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.
- package/built/cli.js +6 -4
- package/built/pxt.js +6 -4
- package/built/pxtblockly.js +1 -1
- package/built/pxtblocks.js +1 -1
- package/built/target.js +1 -1
- package/built/web/main.js +1 -1
- package/built/web/pxtblockly.js +1 -1
- package/built/web/pxtblocks.js +1 -1
- package/built/web/pxtembed.js +1 -1
- package/built/web/rtlsemantic.css +3 -3
- package/built/web/semantic.css +3 -3
- package/package.json +1 -1
- package/theme/image-editor/imageEditor.less +8 -0
- package/theme/tutorial-sidebar.less +4 -4
package/built/web/pxtembed.js
CHANGED
|
@@ -64,4 +64,4 @@ const o=["path.blocklyPath.blockly-ws-search-highlight {","fill: black;","}","pa
|
|
|
64
64
|
* @license
|
|
65
65
|
* Copyright 2020 Google LLC
|
|
66
66
|
* SPDX-License-Identifier: Apache-2.0
|
|
67
|
-
*/}])})),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(e){!function(t){function n(t,n){return e.worker.getWorker(e.webConfig.workerjs).opAsync(t,n)}t.workerOpAsync=n;let o={};function r(e,t){e.push.apply(e,t)}function i(e){if(!e)throw new Error("Assertion failure")}class s{constructor(e,t,n,o,r){this.link=e,this.type=t,this.parentType=n,this.childType=o,this.isArrayType=r}}let a;function l(e){return e.link?l(e.link):e}function c(e,t){let n=l(e),o=l(t);if(i(null==n.link&&null==o.link),n==o)return;if(n.childType&&o.childType){const e=n.childType;n.childType=null,c(e,o.childType)}else n.childType&&!o.childType&&(o.childType=n.childType);if(n.parentType&&o.parentType){const e=n.parentType;n.parentType=null,c(e,o.parentType)}else!n.parentType||o.parentType||o.type||(o.parentType=n.parentType);let r=function(e,t){if(null==e||"Array"===e&&y(t))return t;if(null==t||"Array"===t&&y(e))return e;if(e==t)return e;throw new Error("cannot mix "+e+" with "+t)}(n.type,o.type);e.link=o,n.link=o,n.isArrayType=o.isArrayType,e.type=null,t.type=r}function u(e,t=!1){return new s(null,e,null,null,t)}t.Point=s,function(e){e[e.None=0]="None",e[e.Argument=1]="Argument",e[e.Assigned=2]="Assigned",e[e.Implicit=3]="Implicit"}(a=t.BlockDeclarationType||(t.BlockDeclarationType={}));const d=u("number"),p=u("boolean"),g=u("string"),h=u("void");function f(e){if(!e)return u(e);switch(e.toLowerCase()){case"number":return d;case"boolean":return p;case"string":return g;case"void":return h;default:return u(e)}}function _(e,t){if(i(null!=t),function(e){return"placeholder"==e.type||e.type===pxtc.TS_OUTPUT_TYPE}(t))return t.p||(t.p=u(null)),l(t.p);if("variables_get"==t.type)return l(L(e,t,t.getField("VAR").getText()).type);if("function_call_output"==t.type)return function(e,t){const n=t.getField("function_name").getText();return m(e,n)}(e,t);if(!t.outputConnection)return f(h.type);const n=t.outputConnection.check_&&t.outputConnection.check_.length?t.outputConnection.check_[0]:"T";if("Array"===n){if(t.outputConnection.check_.length>1)return f(t.outputConnection.check_[1]);let n;if("lists_create_with"==t.type){if(t.inputList&&t.inputList.length)for(const o of t.inputList)if(o.connection&&o.connection.targetBlock()){let t=l(_(e,o.connection.targetBlock()));if(t){if(t.parentType)return t.parentType;n=t.type?f(t.type+"[]"):u(null),C(n,t);break}}}else"argument_reporter_array"==t.type&&(n||(n=f("any[]")));return n&&(n.isArrayType=!0),n||u(null,!0)}if("T"===n){const n=e.stdCallTable[t.type],o="lists_index_get"===t.type;if(o||n&&n.comp.thisParameter){let r;if(r=o?t.inputList.find((e=>"LIST"===e.name)):t.inputList.find((e=>e.name===n.comp.thisParameter.definitionName)),r.connection&&r.connection.targetBlock()){const t=_(e,r.connection.targetBlock());if(t.childType)return t.childType;const n=y(t.type)&&"Array"!==t.type?u(t.type.substr(0,t.type.length-2)):u(null);return C(t,n),n}}return u(null)}return f(n)}function m(t,n){if(!t.userFunctionReturnValues[n]){const o=Blockly.Functions.getDefinition(n,t.workspace);let r=u("void");if(me(o,!0))r=u("any");else{const i=[];for(const e of o.getDescendants(!1))"function_return"===e.type&&(k(t,e,"RETURN_VALUE"),i.push(_(t,v(e,"RETURN_VALUE"))));if(i.length)try{const e=u(null);for(const t of i)c(e,t);r=e}catch(i){t.diagnostics.push({blockId:o.id,message:e.Util.lf("Function '{0}' has an invalid return type",n)}),r=u("any")}}t.userFunctionReturnValues[n]=r}return t.userFunctionReturnValues[n]}function y(e){return e&&(-1!==e.indexOf("[]")||"Array"==e)}function k(e,t,n,r){const i=t.getInputTargetBlock(n);i?i.type!==pxtc.TS_OUTPUT_TYPE||i.p||(i.p=u(null)):(o[t.id]||(o[t.id]={}),o[t.id][n]||(o[t.id][n]=function(e,t,n){return{type:"placeholder",p:u(n||null),workspace:e.workspace,parentBlock_:t}}(e,t,r)))}function b(e){return"pxt_controls_for"==e.type||"pxt_controls_for_of"==e.type?v(e,"VAR"):e}function v(e,t){const n=e.getInputTargetBlock(t);return n||o[e.id]&&o[e.id][t]}function T(){o={}}function E(e,t,n,o){k(e,t,n);try{c(_(e,v(t,n)),o)}catch(e){}}function S(e,t,n){function o(e){return e.name?e.connection&&e.connection.check_&&e.connection.check_.length?e.connection.check_[0]:"T":void 0}function r(e,n){let r=e.inputList.filter((e=>"T"===o(e)));if(r.length){const o=v(e,r[0].name);if(o){const r=_(t,o),i=r.type?f(_(t,o).type+"[]"):f(null);return C(i,r),E(t,e,n,i),!0}}return!1}e&&e.filter((e=>e.isEnabled())).forEach((e=>{try{switch(e.type){case"math_op2":E(t,e,"x",f(d.type)),E(t,e,"y",f(d.type));break;case"math_op3":E(t,e,"x",f(d.type));break;case"math_arithmetic":case"logic_compare":switch(e.getFieldValue("OP")){case"ADD":case"MINUS":case"MULTIPLY":case"DIVIDE":case"LT":case"LTE":case"GT":case"GTE":case"POWER":E(t,e,"A",f(d.type)),E(t,e,"B",f(d.type));break;case"AND":case"OR":k(t,e,"A",p.type),k(t,e,"B",p.type);break;case"EQ":case"NEQ":k(t,e,"A"),k(t,e,"B");let n=_(t,v(e,"A")),o=_(t,v(e,"B"));try{c(n,o)}catch(e){}}break;case"logic_operation":k(t,e,"A",p.type),k(t,e,"B",p.type);break;case"logic_negate":k(t,e,"BOOL",p.type);break;case"controls_if":for(let n=0;n<=e.elseifCount_;++n)k(t,e,"IF"+n,p.type);break;case"pxt_controls_for":case"controls_simple_for":E(t,e,"TO",f(d.type));break;case"pxt_controls_for_of":case"controls_for_of":const n=_(t,v(e,"LIST"));C(n,L(t,e,b(e).getField("VAR").getText()).type);break;case"variables_set":case"variables_change":let i=L(t,e,e.getField("VAR").getText()).type;k(t,e,"VALUE");let s=v(e,"VALUE");if(s){let e=function(e,t){var n,o;return(null===(o=null===(n=t.outputConnection)||void 0===n?void 0:n.check_)||void 0===o?void 0:o.length)&&"Array"!==t.outputConnection.check_[0]&&"T"!==t.outputConnection.check_[0]?t.outputConnection.check_.map((e=>f(e))):[_(e,t)]}(t,s);const n=l(i);if(n.type&&e.slice(1).some((e=>e.type===n.type)))i.link=l(e[0]);else try{c(i,e[0])}catch(e){}}break;case"controls_repeat_ext":E(t,e,"TIMES",f(d.type));break;case"device_while":k(t,e,"COND",p.type);break;case"lists_index_get":E(t,e,"LIST",f("Array")),E(t,e,"INDEX",f(d.type));const a=_(t,v(e,"LIST"));C(a,_(t,e));break;case"lists_index_set":E(t,e,"LIST",f("Array")),k(t,e,"VALUE"),r(e,"LIST"),E(t,e,"INDEX",f(d.type));break;case"function_definition":m(t,e.getField("function_name").getText());break;case"function_call":case"function_call_output":e.getArguments().forEach((n=>{E(t,e,n.id,f(n.type))}));break;case pxtc.TS_RETURN_STATEMENT_TYPE:k(t,e,"RETURN_VALUE");break;case pxtc.PAUSE_UNTIL_TYPE:E(t,e,"PREDICATE",p);break;default:if(e.type in t.stdCallTable){const n=t.stdCallTable[e.type];if("ENUM_GET"===n.attrs.shim||"KIND_GET"===n.attrs.shim)return;ie(n,re(e)).forEach(((i,s)=>{const a=n.isExtensionMethod&&0===s;if(i.definitionName&&!e.getFieldValue(i.definitionName)){let n=e.inputList.find((e=>e.name==i.definitionName));if(n&&n.connection&&n.connection.check_){if(a&&"Array"===o(n)){if(r(e,i.definitionName))return}for(let o=0;o<n.connection.check_.length;o++)try{let r=n.connection.check_[o];E(t,e,i.definitionName,f(r));break}catch(e){}}}}))}}}catch(n){const o=n.block||e;o.setWarningText(n+""),t.errors.push(o)}})),t.allVariables.forEach((e=>{null==x(e.type).type&&c(e.type,f(e.type.isArrayType?"number[]":d.type))}))}function C(e,t){const n=l(e),o=l(t);n.childType?c(n.childType,o):n.type||(n.childType=o),o.parentType?c(o.parentType,n):o.type||(o.parentType=n),y(n.type)&&(n.isArrayType=!0)}function x(e,t=[]){const n=l(e);if(-1===t.indexOf(n)&&(t.push(n),!n.type||"Array"===n.type)){if(n.parentType){const e=x(n.parentType,t);if(e.type&&"Array"!==e.type)return y(e.type)?n.type=e.type.substr(0,e.type.length-2):n.type=e.type,n}if(n.childType){const e=x(n.childType,t);if(e.type)return n.type=e.type+"[]",n}}return n}function B(e){let t=e.getFieldValue("math_number_minmax"===e.type?"SLIDER":"NUM");const n=parseFloat(t);return function(e,t){isFinite(e)&&!isNaN(e)||function(e,t){let n=new Error(e);throw n.block=t,n}(lf("Number entered is either too large or too small"),t)}(n,e),n}function A(e,n,o){return t.H.mkNumberLiteral(B(n))}let I={ADD:"+",MINUS:"-",MULTIPLY:"*",DIVIDE:"/",LT:"<",LTE:"<=",GT:">",GTE:">=",AND:"&&",OR:"||",EQ:"==",NEQ:"!=",POWER:"**"};function D(e,n,o){const r=M(n.getFieldValue("NAME"),e,!0);return t.mkStmt(t.mkText(r+"()"))}function N(e,n,o,r){const i=M(n.getField("function_name").getText(),e,!0),s=!n.getInputsInline(),a=n.getArguments().map((e=>({actualName:e.name,definitionName:e.id}))).map((t=>V(e,n,t,o))),l=t.H.stdCall(i,a,s);return r?t.mkStmt(l):l}function w(e,n,o){const r=v(n,"RETURN_VALUE");return r&&"placeholder"!=r.type?t.mkStmt(t.mkText("return "),P(e,r,o)):t.mkStmt(t.mkText("return"))}function R(e){const n=e.getContent();return t.Helpers.mkMultiComment(n.trim())}function O(e){if(null==e.type&&(c(e,f(d.type)),e=l(e)),y(e.type)||e.isArrayType)return t.mkText("[]");switch(e.type){case"boolean":return t.H.mkBooleanLiteral(!1);case"number":return t.H.mkNumberLiteral(0);case"string":return t.H.mkStringLiteral("");default:return t.mkText("null")}}function P(n,o,r){let s;if(i(null!=o),n.stats[o.type]=(n.stats[o.type]||0)+1,ne(o,r),"placeholder"!=o.type&&o.isEnabled&&o.isEnabled())switch(o.type){case"math_number":case"math_integer":case"math_whole_number":case"math_number_minmax":s=A(0,o);break;case"math_op2":s=function(e,n,o){let r=n.getFieldValue("op"),i=P(e,v(n,"x"),o),s=P(e,v(n,"y"),o);return t.H.mathCall(r,[i,s])}(n,o,r);break;case"math_op3":s=function(e,n,o){let r=P(e,v(n,"x"),o);return t.H.mathCall("abs",[r])}(n,o,r);break;case"math_arithmetic":case"logic_compare":case"logic_operation":s=function(e,n,o){let r=n.getFieldValue("OP"),s=v(n,"A"),a=v(n,"B"),l=[P(e,s,o),P(e,a,o)],c=_(e,s).type;if(c==g.type){if("EQ"==r)return t.H.mkSimpleCall("==",l);if("NEQ"==r)return t.H.mkSimpleCall("!=",l)}else if(c==p.type)return t.H.mkSimpleCall(I[r],l);return i(r in I),t.H.mkSimpleCall(I[r],l)}(n,o,r);break;case"math_modulo":s=function(e,n,o){let r=v(n,"DIVIDEND"),i=v(n,"DIVISOR"),s=[P(e,r,o),P(e,i,o)];return t.H.mkSimpleCall("%",s)}(n,o,r);break;case"logic_boolean":s=function(e,n,o){return t.H.mkBooleanLiteral("TRUE"==n.getFieldValue("BOOL"))}(0,o);break;case"logic_negate":s=function(e,n,o){let r=P(e,v(n,"BOOL"),o);return t.mkPrefix("!",[t.H.mkParenthesizedExpression(r)])}(n,o,r);break;case"variables_get":s=function(e,n){const o=n.getField("VAR").getText();let r=L(e,n,o);if(!r)return t.mkText(o);r.firstReference||(r.firstReference=n);return i(null!=r&&null!=r.type),t.mkText(r.escapedName)}(n,o);break;case"text":s=function(e,n,o){return t.H.mkStringLiteral(n.getFieldValue("TEXT"))}(0,o);break;case"text_join":s=function(e,n,o){let r,i=0;for(;;){const s=v(n,"ADD"+i);if(i++,!s){if(i<n.inputList.length)continue;break}const a=P(e,s,o);r=r?t.H.mkSimpleCall("+",[r,a]):0===s.type.indexOf("text")?a:t.H.mkSimpleCall("+",[t.H.mkStringLiteral(""),a])}return r||t.H.mkStringLiteral("")}(n,o,r);break;case"lists_create_with":s=function(e,n,o){let r=n.inputList.map((t=>t.connection&&t.connection.targetBlock()?P(e,t.connection.targetBlock(),o):void 0)).filter((e=>!!e));return t.H.mkArrayLiteral(r,!n.getInputsInline())}(n,o,r);break;case"lists_index_get":s=function(e,n,o){const r=P(e,v(n,"LIST"),o),i=P(e,v(n,"INDEX"),o);return t.mkGroup([r,t.mkText("["),i,t.mkText("]")])}(n,o,r);break;case"lists_index_set":s=function(e,n,o){const r=v(n,"LIST"),i=P(e,r,o),s=P(e,v(n,"INDEX"),o),a=P(e,v(n,"VALUE"),o),l=t.mkGroup([i,t.mkText("["),s,t.mkText("] = "),a]);return"lists_create_with"===r.type?X(l):l}(n,o,r);break;case"math_js_op":case"math_js_round":s=function(e,n,o){const r=n.getFieldValue("OP"),i=[P(e,v(n,"ARG0"),o)];return n.getInput("ARG1")&&i.push(P(e,v(n,"ARG1"),o)),t.H.mathCall(r,i)}(n,o,r);break;case pxtc.TS_OUTPUT_TYPE:s=function(e,n,o){return t.mkText(n.getFieldValue("EXPRESSION").trim())}(0,o);break;case"argument_reporter_boolean":case"argument_reporter_number":case"argument_reporter_string":case"argument_reporter_array":case"argument_reporter_custom":s=function(e,n,o){const r=M(n.getFieldValue("VALUE"),e);return t.mkText(r)}(n,o);break;case"function_call_output":s=N(n,o,r,!1);break;default:let a=n.stdCallTable[o.type];a?s=a.imageLiteral?j(n,o,a.imageLiteral,a.imageLiteralColumns,a.imageLiteralRows,a.namespace,a.f,ie(a,re(o)).map((e=>V(n,o,e,r)))):G(n,o,a,r):(e.reportError("blocks","unable to compile expression",{details:o.type}),s=O(_(n,o)))}else{if("Array"===l(_(n,o)).type){let e="lists_index_get"===o.parentBlock_.type;if(!e){const t=n.stdCallTable[o.parentBlock_.type];e=t&&t.isExpression}const r=t.mkText("[0]");s=e?r:X(r)}else s=O(_(n,o))}return s.id=o.id,s}function L(e,t,n){return de(n,e.idToScope[t.id])}function M(e,t,n=!1){if(!e)return"_";if(n){if(t.renames.oldToNewFunctions[e])return t.renames.oldToNewFunctions[e]}else if(t.renames.oldToNew[e])return t.renames.oldToNew[e];let o=ts.pxtc.escapeIdentifier(e);if(t.renames.takenNames[o]){let e=2;for(;t.renames.takenNames[o+e];)e++;o+=e}return n?(t.renames.oldToNewFunctions[e]=o,t.renames.takenNames[o]=!0):t.renames.oldToNew[e]=o,o}function F(e,n,o){let r=v(n,"VALUE"),i=L(e,n,n.getField("VAR").getText());let s=e.idToScope[n.id].declaredVars[i.name]===i&&!i.firstReference&&!i.alreadyDeclared;s&&pe(n,(t=>{if("variables_get"===t.type){L(e,t,t.getField("VAR").getText())===i&&(s=!1)}}),!0);let l=P(e,r,o),c=i.escapedName+" = ";if(i.isAssigned=!0,s){i.alreadyDeclared=a.Assigned;const t=x(i.type);if(c=`let ${i.escapedName} = `,t){const n=x(_(e,r));t.type!==n.type&&(c=`let ${i.escapedName}: ${t.type} = `)}}else i.firstReference||(i.firstReference=n);return t.mkStmt(t.mkText(c),l)}function U(e,n,o){let r=v(n,"VALUE"),i=L(e,n,n.getField("VAR").getText()),s=P(e,r,o),a=t.mkText(i.escapedName);return t.mkStmt(t.mkInfix(a,"+=",s))}function H(n,o,r){const i=n.stdCallTable[o.type];return i.imageLiteral?t.mkStmt(j(n,o,i.imageLiteral,i.imageLiteralColumns,i.imageLiteralRows,i.namespace,i.f,ie(i,re(o)).map((e=>V(n,o,e,r))))):i.hasHandler?function(n,o,r,i,s,a){const l=i.map((e=>V(n,o,e,a))),c=v(o,"HANDLER"),u=$(n,c);e.appTarget.compile&&e.appTarget.compile.emptyEventHandlerComments&&0===u.children.length&&u.children.unshift(t.mkStmt(t.mkText(`// ${pxtc.HANDLER_COMMENT}`)));let d;if(K(o)&&o.mutation.getMutationType()===t.MutatorTypes.ObjectDestructuringMutator)d=o.mutation.compileMutation(n,a);else if(r.comp.handlerArgs.length){let e=function(e,t,n){return se(e,t).map((t=>L(n,e,t[0]).escapedName))}(o,r,n);d=t.mkText(`function (${e.join(", ")})`)}return W(n,s,r.f,l,u,d,r.isExtensionMethod)}(n,o,i,function(e,t){return ie(e,re(t)).filter((e=>!!e.definitionName))}(i,o),i.namespace,r):t.mkStmt(G(n,o,i,r))}function V(n,o,r,i,s=!1){let a=o.getFieldValue(r.definitionName);if(null!=a){const i=o.getField(r.definitionName);if(i instanceof pxtblockly.FieldTextInput)return t.H.mkStringLiteral(a);if(i instanceof pxtblockly.FieldTilemap&&!i.isGreyBlock){const o=e.react.getTilemapProject(),r=i.getValue();if(r.startsWith("tilemap`"))return t.mkText(r);if(n.options.emitTilemapLiterals)try{const n=e.sprite.decodeTilemap(r,"typescript",o);if(n){const[e]=o.createNewTilemapFromData(n);return t.mkText(`tilemap\`${e}\``)}}catch(n){}}const s=n.blocksInfo.apis.byQName[r.type];if(s&&s.attributes.emitAsConstant)for(const e of Object.keys(n.blocksInfo.apis.byQName)){const o=n.blocksInfo.apis.byQName[e];if(o&&o.attributes&&o.attributes.enumIdentity===a)return t.mkText(e)}let l=t.mkText(a);return l.canIndentInside="string"==typeof a&&a.indexOf("\n")>=0,l}{k(n,o,r.definitionName);const e=v(o,r.definitionName);return s&&"lists_create_with"===e.type?X(P(n,e,i)):r.shadowOptions&&r.shadowOptions.toString&&_(n,e)!==g?t.H.mkSimpleCall("+",[t.H.mkStringLiteral(""),t.H.mkParenthesizedExpression(P(n,e,i))]):P(n,e,i)}}function G(e,n,o,r){let i;if(K(n)&&n.mutation.getMutationType()===t.MutatorTypes.RestParameterMutator)i=n.mutation.compileMutation(e,r).children;else{if("ENUM_GET"===o.attrs.shim){const e=o.attrs.enumName,r=n.getFieldValue("MEMBER").replace(/^\d+/,"");return t.H.mkPropertyAccess(r,t.mkText(e))}if("KIND_GET"===o.attrs.shim){const r=e.kinds.filter((e=>e.blockId===o.attrs.blockId))[0];return t.H.mkPropertyAccess(n.getFieldValue("MEMBER"),t.mkText(r.name))}i=ie(o,re(n)).map(((t,i)=>V(e,n,t,r,o.isExtensionMethod&&0===i&&!o.isExpression)))}let s=o.namespace,a=o.f;if(o.attrs.blockAliasFor){const t=e.blocksInfo.apis.byQName[o.attrs.blockAliasFor];t&&(a=t.name,s=t.namespace)}const l=!n.getInputsInline();if(o.isIdentity)return i[0];if(o.property)return t.H.mkPropertyAccess(a,i[0]);if("@get@"==a)return t.H.mkPropertyAccess(i[1].op.replace(/.*\./,""),i[0]);if("@set@"==a)return t.H.mkAssign(t.H.mkPropertyAccess(i[1].op.replace(/.*\./,"").replace(/@set/,""),i[0]),i[2]);if("@change@"==a)return t.H.mkSimpleCall("+=",[t.H.mkPropertyAccess(i[1].op.replace(/.*\./,"").replace(/@set/,""),i[0]),i[2]]);if(o.isExtensionMethod){if(o.attrs.defaultInstance){let s;K(n)&&n.mutation.getMutationType()===t.MutatorTypes.DefaultInstanceMutator&&(s=n.mutation.compileMutation(e,r)),s?i.unshift(s):i.unshift(t.mkText(o.attrs.defaultInstance))}return t.H.extensionCall(a,i,l)}return s?t.H.namespaceCall(s,a,i,l):t.H.stdCall(a,i,l)}function W(e,n,o,r,i,s,a=!1){let l;return i.noFinalNewline=!0,l=s?t.mkGroup([s,i]):t.mkGroup([t.mkText("function ()"),i]),a?t.mkStmt(t.H.extensionCall(o,r.concat([l]),!1)):n?t.mkStmt(t.H.namespaceCall(n,o,r.concat([l]),!1)):t.mkStmt(t.H.mkCall(o,r.concat([l]),!1))}function K(e){return!!e.mutation}function j(e,n,o,r,i,s,a,l){l=void 0===l?[]:l;let c="\n";i=i||5,r=(r||5)*o;let u=n.getFieldValue("LEDS");u=u.replace(/[ `\n]+/g,"");for(let e=0;e<i;++e){for(let t=0;t<r;++t)t>0&&(c+=" "),c+="#"===u[e*r+t]?"#":".";c+="\n"}let d=t.H.mkStringLiteral(c);return d.canIndentInside=!0,t.H.namespaceCall(s,a,[d].concat(l),!1)}function z(n,o){let i;const s=[];switch(n.stats[o.type]=(n.stats[o.type]||0)+1,ne(o,s),o.type){case"controls_if":i=function(e,n,o){let i=[];for(let s=0;s<=n.elseifCount_;++s){let a=P(e,v(n,"IF"+s),o),l=$(e,v(n,"DO"+s)),c=t.mkText("if (");s>0&&(c=t.mkText("else if ("),c.glueToBlock=t.GlueMode.WithSpace),r(i,[c,a,t.mkText(")"),l])}if(n.elseCount_){let o=t.mkText("else");o.glueToBlock=t.GlueMode.WithSpace,r(i,[o,$(e,v(n,"ELSE"))])}return i}(n,o,s);break;case"pxt_controls_for":case"controls_for":case"controls_simple_for":i=function(e,n,o){let r=v(n,"TO"),i=v(n,"DO"),s=v(n,"BY"),a=v(n,"FROM"),l=!s||s.type.match(/^math_number/)&&1==B(s),c=L(e,n,b(n).getField("VAR").getText());return[t.mkText("for (let "+c.escapedName+" = "),a?P(e,a,o):t.mkText("0"),t.mkText("; "),t.mkInfix(t.mkText(c.escapedName),"<=",P(e,r,o)),t.mkText("; "),l?t.mkText(c.escapedName+"++"):t.mkInfix(t.mkText(c.escapedName),"+=",P(e,s,o)),t.mkText(")"),$(e,i)]}(n,o,s);break;case"pxt_controls_for_of":case"controls_for_of":i=function(e,n,o){let r=v(n,"LIST"),i=v(n,"DO"),s=L(e,n,b(n).getField("VAR").getText());return[t.mkText("for (let "+s.escapedName+" of "),P(e,r,o),t.mkText(")"),$(e,i)]}(n,o,s);break;case"variables_set":i=[F(n,o,s)];break;case"variables_change":i=[U(n,o,s)];break;case"controls_repeat_ext":i=function(e,n,o){let r=P(e,v(n,"TIMES"),o),i=$(e,v(n,"DO")),s="index";for(let t=2;L(e,n,s);t++)s="index"+t;return[t.mkText("for (let "+s+" = 0; "),t.mkInfix(t.mkText(s),"<",r),t.mkText("; "+s+"++)"),i]}(n,o,s);break;case"device_while":i=function(e,n,o){let r=P(e,v(n,"COND"),o),i=$(e,v(n,"DO"));return[t.mkText("while ("),r,t.mkText(")"),i]}(n,o,s);break;case"procedures_defnoreturn":i=function(e,n,o){const r=M(n.getFieldValue("NAME"),e,!0),i=v(n,"STACK");return[t.mkText("function "+r+"() "),$(e,i)]}(n,o);break;case"function_definition":i=function(e,n,o){const r=M(n.getField("function_name").getText(),e,!0),i=v(n,"STACK"),s=n.getArguments().map((t=>"Array"==t.type?`${M(t.name,e)}: any[]`:`${M(t.name,e)}: ${t.type}`)),a=me(n,!1);return[t.mkText(`function ${r} (${s.join(", ")})${a?": any":""}`),$(e,i)]}(n,o);break;case"procedures_callnoreturn":i=[D(n,o)];break;case"function_call":i=[N(n,o,s,!0)];break;case pxtc.TS_RETURN_STATEMENT_TYPE:i=[w(n,o,s)];break;case ts.pxtc.ON_START_TYPE:i=function(n,o){const r=$(n,v(o,"HANDLER"));return e.appTarget.compile&&e.appTarget.compile.onStartText&&r&&r.children&&r.children.unshift(t.mkStmt(t.mkText(`// ${pxtc.ON_START_COMMENT}\n`))),r}(n,o).children;break;case pxtc.TS_STATEMENT_TYPE:i=function(e,n){return n.getLines().map((e=>t.mkText(e+"\n")))}(0,o);break;case pxtc.PAUSE_UNTIL_TYPE:i=function(n,o,r){const i=e.appTarget.runtime&&e.appTarget.runtime.pauseUntilBlock;e.Util.assert(!!i,"target has block enabled");const s=i.namespace,a=i.callName||"pauseUntil",l=V(n,o,{definitionName:"PREDICATE",actualName:"PREDICATE"},r),c=[t.mkGroup([t.mkText("() => "),l])];return s?[t.mkStmt(t.H.namespaceCall(s,a,c,!1))]:[t.mkStmt(t.H.mkCall(a,c,!1,!1))]}(n,o,s);break;case pxtc.TS_DEBUGGER_TYPE:i=function(e,n){if("1"==n.getFieldValue("ON_OFF"))return[t.mkText("debugger;\n")];return[]}(0,o);break;case pxtc.TS_BREAK_TYPE:i=[t.mkText("break;\n")];break;case pxtc.TS_CONTINUE_TYPE:i=[t.mkText("continue;\n")];break;default:i=n.stdCallTable[o.type]?[H(n,o,s)]:[t.mkStmt(P(n,o,s))]}let a=i[i.length-1];return a&&!a.id&&(a.id=o.id),s.length&&function(e,n){const o=[];for(const n of e)for(const e of n.split("\n"))o.push(t.mkText(`// ${e}`)),o.push(t.mkNewLine());for(const e of o.reverse())n.unshift(e)}(s,i),i.forEach((n=>{!(n.type===t.NT.Block||n.type===t.NT.Prefix&&e.Util.startsWith(n.op,"//"))||o.type==pxtc.ON_START_TYPE&&n.id||(n.id=o.id)})),i}function $(e,n){let o=[],i=n;for(;n;)n.isEnabled()&&r(o,z(e,n)),n=n.getNextBlock();return i&&e.blockDeclarations[i.id]&&e.blockDeclarations[i.id].filter((e=>!e.alreadyDeclared)).forEach((t=>{o.unshift(oe(t,e.blocksInfo)),t.alreadyDeclared=a.Implicit})),t.mkBlock(o)}function X(e){const n=t.mkStmt(t.mkText(";"));return n.glueToBlock=t.GlueMode.NoSpace,t.mkGroup([n,e])}function Y(t,n,o={}){let r=function(e,t){return{workspace:e,options:t,stdCallTable:{},userFunctionReturnValues:{},diagnostics:[],errors:[],renames:{oldToNew:{},takenNames:{},oldToNewFunctions:{}},stats:{},enums:[],kinds:[],idToScope:{},blockDeclarations:{},allVariables:[],blocksInfo:null}}(t,o);return r.blocksInfo=n,n&&(Object.keys(n.apis.byQName).forEach((e=>{const t=n.apis.byQName[e];!t.pkg||6!==t.kind&&3!==t.kind&&5!==t.kind&&4!==t.kind||(r.renames.takenNames[t.qName]=!0)})),n.enumsByName&&Object.keys(n.enumsByName).forEach((e=>r.enums.push(n.enumsByName[e]))),n.kindsByName&&Object.keys(n.kindsByName).forEach((e=>r.kinds.push(n.kindsByName[e]))),n.blocks.forEach((t=>{if(r.stdCallTable[t.attributes.blockId])return void e.reportError("blocks","function already defined",{details:t.attributes.blockId,qualifiedName:t.qName,packageName:t.pkg});r.renames.takenNames[t.namespace]=!0;const n=e.blocks.compileInfo(t),o=!!n.thisParameter;r.stdCallTable[t.attributes.blockId]={namespace:t.namespace,f:t.name,comp:n,attrs:t.attributes,isExtensionMethod:o,isExpression:t.retType&&"void"!==t.retType,imageLiteral:t.attributes.imageLiteral,imageLiteralColumns:t.attributes.imageLiteralColumns,imageLiteralRows:t.attributes.imageLiteralRows,hasHandler:e.blocks.hasHandler(t),property:!t.parameters,isIdentity:"TD_ID"==t.attributes.shim}})),t.getTopBlocks(!1).filter(fe).forEach((e=>{M("procedures_defnoreturn"===e.type?e.getFieldValue("NAME"):e.getField("function_name").getText(),r,!0)}))),r}function J(e,t){if(e.type===ts.pxtc.ON_START_TYPE)return 0;const n=t.stdCallTable[e.type],o=Z(t,e),r=1+ts.pxtc.Util.codalHash16(o);return n&&n.attrs.afterOnStart?r:-r}function q(n,o,i){try{let s=o.getAllBlocks(!1);e.react.getTilemapProject&&e.react.getTilemapProject().removeInactiveBlockAssets(s.map((e=>e.id)));let l=o.getTopBlocks(!0);l=l.sort(((e,t)=>J(e,n)-J(t,n))),function(e,t,n){t.forEach((e=>e.setEnabled(!0)));const o={};function r(e,t){o[e]?ee(t,!1):(ee(t,!0),o[e]=t)}n.forEach((t=>{const n=e.stdCallTable[t.type];if(t.type==ts.pxtc.ON_START_TYPE)r(ts.pxtc.ON_START_TYPE,t);else{if(fe(t)||n&&n.attrs.blockAllowMultiple&&!n.attrs.handlerStatement)return;if(n&&n.hasHandler&&!n.attrs.handlerStatement){r(n.attrs.blockHandlerKey||Z(e,t),t)}else{let e=t;for(;e;)ee(t,!1),e=e.getNextBlock()}}}))}(n,s,l),s=s.filter((e=>e.isEnabled())),l=l.filter((e=>e.isEnabled())),function(e,t){let n,o=1;e.forEach((e=>{if(e.type===ts.pxtc.ON_START_TYPE){const o=e.getInputTargetBlock("HANDLER");o&&(n={firstStatement:o,declaredVars:{},referencedVars:[],children:[],assignedVars:[]},r(o,n,t))}})),n||(n={firstStatement:null,declaredVars:{},referencedVars:[],children:[],assignedVars:[]});return e.forEach((e=>{e.type!==ts.pxtc.ON_START_TYPE&&r(e,n,t)})),Object.keys(n.declaredVars).forEach((e=>{const t=n.declaredVars[e];delete n.declaredVars[e];(ue(n,t.id)||n).declaredVars[e]=t})),ge(n,t),ce(n,t),n;function r(e,t,n){if(n.idToScope[e.id]=t,"variables_get"===e.type){const n=i(e.getField("VAR").getText(),t);t.referencedVars.push(n.id)}else if("variables_set"===e.type||"variables_change"===e.type){const n=i(e.getField("VAR").getText(),t);t.assignedVars.push(n.id),t.referencedVars.push(n.id)}else if(e.type===pxtc.TS_STATEMENT_TYPE){const n=e.declaredVariables;if(n){n.split(",").forEach((e=>{i(e,t).alreadyDeclared=a.Argument}))}}if(function(e){return e.inputList.some((e=>e.type===Blockly.NEXT_STATEMENT))}(e)){const i=function(e,t){switch(e.type){case"pxt_controls_for":case"controls_simple_for":return[[b(e).getField("VAR").getText(),d]];case"pxt_controls_for_of":case"controls_for_of":return[[b(e).getField("VAR").getText(),u(null)]]}if(K(e)){const t=e.mutation.getDeclaredVariables();if(t)return Object.keys(t).map((e=>[e,u(t[e])]))}let n=t.stdCallTable[e.type];if(n&&n.comp.handlerArgs.length)return se(e,n);return[]}(e,n).map((e=>({name:e[0],type:e[1],id:o++})));let s=t;i.length&&(s={parent:t,firstStatement:e,declaredVars:{},referencedVars:[],assignedVars:[],children:[]},i.forEach((e=>{e.alreadyDeclared=a.Assigned,s.declaredVars[e.name]=e})),n.idToScope[e.id]=s),t!==s&&t.children.push(s),pe(e,(e=>{r(e,s,n)})),function(e,t){e.inputList.filter((e=>e.type===Blockly.NEXT_STATEMENT)).forEach((e=>{e.connection&&e.connection.targetBlock()&&t(e.connection.targetBlock())}))}(e,(e=>{const t={parent:s,firstStatement:e,declaredVars:{},referencedVars:[],assignedVars:[],children:[]};s.children.push(t),r(e,t,n)}))}else pe(e,(e=>{r(e,t,n)}));e.nextConnection&&e.nextConnection.targetBlock()&&r(e.nextConnection.targetBlock(),t,n)}function i(e,t){return t.declaredVars[e]?t.declaredVars[e]:t.parent?i(e,t.parent):(t.declaredVars[e]={name:e,type:u(null),id:o++},t.declaredVars[e])}}(l,n),S(s,n);const c=[],p=function(e,t){if(!e.length||e.some((e=>!e.rendered)))return{orphans:t,idToComments:{}};const n=e.map((e=>{const t=e.getBoundingRectangle(),n=e.getHeightWidth();return{id:e.id,x:t.left,y:t.top,width:n.width,height:n.height}})),o={orphans:[],idToComments:{}},r=20;for(const e of t){const t=e.getBoundingRectangle(),i=e.getHeightWidth(),s=t.left,a=t.top;let l;for(const e of n)(he(s,a,i.width,i.height,e)||!l&&he(s-r,a-r,i.width+2*r,i.height+2*r,e))&&(l=e);l?(o.idToComments[l.id]||(o.idToComments[l.id]=[]),o.idToComments[l.id].push(e)):o.orphans.push(e)}return o}(l,o.getTopComments(!0));p.orphans.forEach((e=>r(c,R(e).children))),l.forEach((e=>{if(p.idToComments[e.id]&&p.idToComments[e.id].forEach((e=>{r(c,R(e).children)})),e.type==ts.pxtc.ON_START_TYPE)r(c,z(n,e));else{const o=t.mkBlock(z(n,e));o.type==t.NT.Block?r(c,o.children):c.push(o)}}));const g=[];n.enums.forEach((e=>{const n=o.getVariablesOfType(e.name);if(n&&n.length){const o=n.map((e=>{const t=/^(\d+)([^0-9].*)$/.exec(e.name);return t?[t[2],parseInt(t[1])]:[e.name,-1]}));o.sort(((e,t)=>e[1]-t[1]));const r=[];let i=-1;o.forEach((([n,o],s)=>{let a;if(e.isBitMask){const e=Math.log2(o);e>=0&&Math.floor(e)===e&&(a=t.H.mkAssign(t.mkText(n),t.H.mkSimpleCall("<<",[t.H.mkNumberLiteral(1),t.H.mkNumberLiteral(e)])))}else if(e.isHash){const e=ts.pxtc.Util.codalHash16(n.toLowerCase());a=t.H.mkAssign(t.mkText(n),t.H.mkNumberLiteral(e))}a||(a=o===i+1?t.mkText(n):t.H.mkAssign(t.mkText(n),t.H.mkNumberLiteral(o))),r.push(a),i=o}));const s=t.mkCommaSep(r,!0);s.glueToBlock=t.GlueMode.NoSpace,g.push(t.mkGroup([t.mkText(`enum ${e.name}`),t.mkBlock([s])]))}})),n.kinds.forEach((e=>{const n=o.getVariablesOfType("KIND_"+e.name);if(n&&n.length){const o=n.map((e=>e.name)).filter((t=>-1===e.initialMembers.indexOf(t)));o.length&&g.push(t.mkGroup([t.mkText(`namespace ${e.name}`),t.mkBlock(o.map((n=>t.mkStmt(t.mkText(`export const ${n} = ${e.name}.${e.createFunctionName}()`)))))]))}}));const h=n.allVariables.filter((e=>!e.alreadyDeclared)).map((e=>oe(e,i)));return n.allVariables.filter((e=>e.alreadyDeclared===a.Implicit&&!e.isAssigned)).forEach((e=>{const t=x(e.type);"string"===t.type||"number"===t.type||"boolean"===t.type||y(t.type)||n.diagnostics.push({blockId:e.firstReference&&e.firstReference.id,message:lf("Variable '{0}' is never assigned",e.name)})})),[g.concat(h.concat(c)),n.diagnostics]}catch(e){let t=e.block;if(!t)throw e;t.setWarningText(e+""),n.errors.push(t)}finally{T()}return[null,null]}function Z(e,t){if(t.type==ts.pxtc.ON_START_TYPE)return JSON.stringify({name:ts.pxtc.ON_START_TYPE});if(t.type==ts.pxtc.FUNCTION_DEFINITION_TYPE)return JSON.stringify({type:"function",name:t.getFieldValue("function_name")});return JSON.stringify(Q(t)).replace(/"id"\s*:\s*"[^"]+"/g,"")}function Q(e){const t=[],n=[];for(const o of e.inputList){for(const e of o.fieldRow)e.name&&t.push(e.getText());o.type===Blockly.INPUT_VALUE&&(o.connection.targetBlock()?n.push(Q(o.connection.targetBlock())):n.push(null))}return{type:e.type,fields:t,inputs:n}}function ee(e,t){e.setEnabled(t);const n=e.getDescendants(!1);for(const e of n)e.setEnabled(t)}function te(e,o,r){let i=t.flattenNode(o);return n("format",{format:{input:i.output,pos:1}}).then((()=>({source:i.output,sourceMap:i.sourceMap,stats:e.stats,diagnostics:r||[]})))}function ne(e,t){var n;const o=null===(n=e.getCommentText)||void 0===n?void 0:n.call(e);o&&t.push(o)}function oe(e,n){const o=x(e.type);let r;r="Array"===o.type?t.mkText("[]"):O(o);let i="";if("null"==r.op||"[]"==r.op){let e=o.type;"Array"!==e&&"null[]"!==e||(e="number[]");let s=n.apis.byQName[e];s&&s.attributes.autoCreate?r=t.mkText(s.attributes.autoCreate+"()"):i=": "+e}return t.mkStmt(t.mkText("let "+e.escapedName+i+" = "),r)}function re(e){if(e.mutationToDom){const t=e.mutationToDom();if(t.hasAttribute("_expanded")){const e=parseInt(t.getAttribute("_expanded"));return isNaN(e)?0:Math.max(e,0)}}return 0}function ie({comp:e},t){const n=[];return e.thisParameter&&n.push(e.thisParameter),e.parameters.forEach((e=>{e.isOptional&&t>0?(n.push(e),--t):e.isOptional||n.push(e)})),n}function se(e,t){let n=[];if(t.attrs.draggableParameters)for(let o=0;o<t.comp.handlerArgs.length;o++){const r=t.comp.handlerArgs[o];let i;const s=v(e,"HANDLER_DRAG_PARAM_"+r.name);if(i="reporter"===t.attrs.draggableParameters?s&&s.getFieldValue("VALUE"):s&&s.getField("VAR").getText(),null===i)break;n.push([i,u(r.type)])}else for(let o=0;o<t.comp.handlerArgs.length;o++){const r=t.comp.handlerArgs[o],i=e.getField("HANDLER_"+r.name),s=i&&i.getText();if(null===s)break;n.push([s,u(r.type)])}return n}function ae(e,t){if(-1!==e.referencedVars.indexOf(t))return!0;for(const n of e.children)if(ae(n,t))return!0;return!1}function le(e,t){if(-1!==e.assignedVars.indexOf(t))return!0;for(const n of e.children)if(le(n,t))return!0;return!1}function ce(e,t){for(const t of Object.keys(e.declaredVars)){const o=e.declaredVars[t];o.escapedName||(o.escapedName=n(t))}function n(n){if(!n)return"_";let r=ts.pxtc.escapeIdentifier(n);if(t.renames.takenNames[r]||o(r,e,n)){let i=2;for(;t.renames.takenNames[r+i]||o(r+i,e,n);)i++;r+=i}return r}function o(e,t,n){if(t){for(const o of Object.keys(t.declaredVars)){const r=t.declaredVars[o];if((n!==r.name||r.name!==r.escapedName)&&r.escapedName===e)return!0}return o(e,t.parent,n)}return!1}e.children.forEach((e=>ce(e,t)))}function ue(e,t){let n;if(-1!==e.referencedVars.indexOf(t))return e;for(const o of e.children)if(ae(o,t)){if(le(o,t))return e;if(n)return e;n=o}return n?ue(n,t):void 0}function de(e,t){return t&&t.declaredVars[e]?t.declaredVars[e]:t&&t.parent?de(e,t.parent):null}function pe(e,t,n=!1){e.inputList.filter((e=>e.type===Blockly.INPUT_VALUE)).forEach((e=>{e.connection&&e.connection.targetBlock()&&(t(e.connection.targetBlock()),n&&pe(e.connection.targetBlock(),t,n))}))}function ge(e,t){const n=Object.keys(e.declaredVars);if(n.length){const o=n.map((t=>e.declaredVars[t]));e.firstStatement&&(t.blockDeclarations[e.firstStatement.id]=o.concat(t.blockDeclarations[e.firstStatement.id]||[])),o.forEach((e=>t.allVariables.push(e)))}e.children.forEach((e=>ge(e,t)))}function he(e,t,n,o,r){const i=a(e,r.x,r.x+r.width)||a(r.x,e,e+n),s=a(t,r.y,r.y+r.height)||a(r.y,t,t+o);return i&&s;function a(e,t,n){return e>=t&&e<=n}}function fe(e){return"procedures_defnoreturn"===e.type||"function_definition"===e.type}function _e(e){return e.getField("function_name").getText()}function me(e,t){const n=_e(e),o={};return function e(r){let i;i=t?r.getDescendants(!1).filter((e=>"function_return"==e.type)).map((e=>v(e,"RETURN_VALUE"))).filter((e=>e&&"function_call_output"===e.type)):r.getDescendants(!1).filter((e=>"function_call_output"==e.type));for(const t of i){const r=_e(t);if(r===n)return!0;if(!o[r]&&(o[r]=!0,e(Blockly.Functions.getDefinition(r,t.workspace))))return!0}return!1}(e)}t.compileExpression=P,t.escapeVarName=M,t.mkEnv=Y,t.compileBlockAsync=function(e,t){const n=e.workspace,o=Y(n,t);S(n&&n.getAllBlocks(!1),o);const r=z(o,e);return T(),te(o,r)},t.callKey=Z,t.findBlockIdByPosition=function(e,t){if(!t)return;let n,o;for(let r=0;r<e.length;++r){let i=e[r];i.startPos<=t.start&&i.endPos>=t.start+t.length&&(!n||o>i.endPos-i.startPos)&&(n=i,o=i.endPos-i.startPos)}return n?n.id:void 0},t.findBlockIdByLine=function(e,t){if(!t)return;let n,o;for(let r=0;r<e.length;++r){let i=e[r];i.startLine<=t.start&&i.endLine>t.start+t.length&&(!n||o>i.endLine-i.startLine)&&(n=i,o=i.endLine-i.startLine)}return n?n.id:void 0},t.compileAsync=function(e,t,n={}){const o=Y(e,t,n),[r,i]=q(o,e,t);return te(o,r,i)}}(e.blocks||(e.blocks={}))}(pxt||(pxt={})),function(e){!function(t){let n={};function o(e,t,o){null==n[e]&&(n[e]={field:t,validator:o})}t.initFieldEditors=function(){o("text",pxtblockly.FieldTextInput),o("note",pxtblockly.FieldNote),o("gridpicker",pxtblockly.FieldGridPicker),o("textdropdown",pxtblockly.FieldTextDropdown),o("numberdropdown",pxtblockly.FieldNumberDropdown),o("imagedropdown",pxtblockly.FieldImageDropdown),o("colorwheel",pxtblockly.FieldColorWheel),o("toggle",pxtblockly.FieldToggle),o("toggleonoff",pxtblockly.FieldToggleOnOff),o("toggleyesno",pxtblockly.FieldToggleYesNo),o("toggleupdown",pxtblockly.FieldToggleUpDown),o("toggledownup",pxtblockly.FieldToggleDownUp),o("togglehighlow",pxtblockly.FieldToggleHighLow),o("togglewinlose",pxtblockly.FieldToggleWinLose),o("colornumber",pxtblockly.FieldColorNumber),o("images",pxtblockly.FieldImages),o("sprite",pxtblockly.FieldSpriteEditor),o("animation",pxtblockly.FieldAnimationEditor),o("tilemap",pxtblockly.FieldTilemap),o("tileset",pxtblockly.FieldTileset),o("speed",pxtblockly.FieldSpeed),o("turnratio",pxtblockly.FieldTurnRatio),o("protractor",pxtblockly.FieldProtractor),o("position",pxtblockly.FieldPosition),o("melody",pxtblockly.FieldCustomMelody)},t.registerFieldEditor=o,t.createFieldEditor=function(t,o,r){if(null==n[t])return console.error(`Field editor ${t} not registered`),null;r||(r={}),e.Util.assert(null==r.lightMode,"lightMode is a reserved parameter for custom fields"),r.lightMode=e.options.light;let i=n[t];return new i.field(o,r,i.validator)}}(e.blocks||(e.blocks={}))}(pxt||(pxt={})),function(e){!function(t){t.needsDecompiledDiff=function(e,t){if(!e||!t)return!1;const n={};if(e.replace(/id="([^"]+)"/g,((e,t)=>(n[t]=!0,""))),!Object.keys(n).length)return!1;let o=0,r=0;return t.replace(/id="([^"]+)"/g,((e,t)=>(o++,n[t]&&r++,""))),o>0&&0==r},t.diffXml=function(t,n,r){return o(e.blocks.loadWorkspaceXml(t,!0),e.blocks.loadWorkspaceXml(n,!0),r)};const n="#d0d0d0";function o(o,s,a){try{return Blockly.Events.disable(),function(o,s,a){e.tickEvent("blocks.diff",{started:1}),a=a||{};const l=r();if(!o)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=e.Util.toDictionary(o.getTopBlocks(!1),(e=>i(e,!0)));s.getTopBlocks(!1).forEach((e=>{const t=i(e,!0),n=o.getBlockById(e.id)||c[t];if(n){t==i(n,!0)&&(l("fast unmodified top ",e.id),e.dispose(!1),n.dispose(!1))}}));const u=o.getAllBlocks(!1).filter((e=>e.isEnabled())),d=o.getTopBlocks(!1).filter((e=>e.isEnabled())),p=s.getAllBlocks(!1).filter((e=>e.isEnabled()));if(l("blocks",p.map((e=>e.toDevString()))),l(p),0==u.length&&0==p.length)return e.tickEvent("blocks.diff",{moves:1}),{ws:void 0,message:lf("Some blocks were moved or changed."),added:0,deleted:0,modified:1};const g=d.filter((e=>!s.getBlockById(e.id))),h=u.filter((e=>!s.getBlockById(e.id))),f=p.filter((e=>!o.getBlockById(e.id))),_=e.blocks.initRenderingWorkspace(),m=e.blocks.saveWorkspaceXml(s,!0);e.blocks.domToWorkspaceNoEvents(Blockly.Xml.textToDom(m),_),_.getAllBlocks(!1).filter((e=>!e.isEnabled())).forEach((e=>{l("disabled ",e.toDevString()),e.dispose(!1)}));const y=e.Util.toDictionary(_.getAllBlocks(!1),(e=>e.id));l("todo blocks",y),D("start"),a.hideDeletedTopBlocks||(g.forEach((e=>{l(`deleted top ${e.toDevString()}`),A(e);const t=x(e);A(t),t.setEnabled(!1)})),D("deleted top"));f.map((e=>_.getBlockById(e.id))).filter((e=>!!e)).forEach((e=>{l(`added ${e.toDevString()}`),A(e)})),D("added");const k={};if(!a.hideDeletedBlocks){const e=h.filter((e=>!(y[e.id]||C(e)||e.outputConnection&&e.outputConnection.isConnected())));e.forEach((e=>{const t=x(e);k[e.id]=t.id,l(`deleted block ${e.toDevString()}->${t.toDevString()}`)})),e.forEach((e=>E(e)))}let b=0;if(e.Util.values(y).filter((e=>N(e))).forEach((e=>{l(`moved ${e.toDevString()}`),delete y[e.id],S(e),b++})),D("moved"),e.Util.values(y).filter((e=>w(e))).forEach((e=>{l(`changed ${e.toDevString()}`),delete y[e.id],S(e),b++})),D("changed"),_.getTopBlocks(!1).forEach((e=>{I(e)||(l(`unmodified top ${e.toDevString()}`),delete y[e.id],e.dispose(!1))})),D("cleaned"),e.Util.values(y).filter((e=>!!_.getBlockById(e.id))).forEach((e=>{R(e)})),D("unmodified"),!_.getAllBlocks(!1).length)return e.tickEvent("blocks.diff",{missed:1}),{ws:_,message:lf("Some blocks were changed."),deleted:h.length,added:f.length,modified:b};_.resize(),Blockly.svgResize(_);const v=e.blocks.renderWorkspace(a.renderOptions||{emPixels:20,layout:t.BlockLayout.Flow,aspectRatio:.5,useViewWidth:!0}),T={ws:_,svg:v,deleted:h.length,added:f.length,modified:b};return e.tickEvent("blocks.diff",{deleted:T.deleted,added:T.added,modified:T.modified}),T;function E(e){l(`stitching ${e.toDevString()}->${k[e.id]}`);const t=_.getBlockById(k[e.id]);t.setEnabled(!1),S(t),A(t);const n=e.getPreviousBlock();if(n){const o=_.getBlockById(k[n.id])||_.getBlockById(n.id);if(l(`previous ${e.id}->${t.toDevString()}: ${o.toDevString()}`),o)if(o.nextConnection)t.previousConnection.connect(o.nextConnection);else{const e=o.inputList.slice().reverse().find((e=>e.connection&&e.connection.type==Blockly.NEXT_STATEMENT));e&&t.previousConnection.connect(e.connection)}}const o=e.getNextBlock();if(o){const n=_.getBlockById(k[o.id])||_.getBlockById(o.id);n&&(l(`next ${e.id}->${t.toDevString()}: ${n.toDevString()}`),t.nextConnection.connect(n.previousConnection))}}function S(e){e.__pxt_used=!0}function C(e){return!!e.__pxt_used}function x(e){const t=Blockly.Xml.blockToDom(e,!1),n=Blockly.Xml.domToBlock(t,_);return n.nextConnection&&n.nextConnection.targetConnection&&n.nextConnection.disconnect(),n.previousConnection&&n.previousConnection.targetConnection&&n.previousConnection.disconnect(),n}function B(e){e.rendered=!1,e.inputList.forEach((t=>t.fieldRow.forEach((t=>{t.init(),t.borderRect_&&(t.borderRect_.setAttribute("fill",e.getColour()),t.borderRect_.setAttribute("stroke",e.getColourTertiary()))}))))}function A(e){e.getDescendants(!1).forEach((e=>{delete y[e.id],S(e)}))}function I(e){return!!e.getDescendants(!1).find((e=>C(e)))}function D(t){l(`${t}:`,e.Util.values(y).map((e=>e.toDevString())))}function N(e){const t=o.getBlockById(e.id);if(!t)return!1;const n=e.getPreviousBlock();if(n&&!y[n.id])return!1;const r=e.getNextBlock();if(r&&!y[r.id])return!1;const i=t.getPreviousBlock();if(!i&&!n)return!1;if(!!i!=!!n||i.id!=n.id)return!0;const s=t.getNextBlock();return!(!s&&!r)&&(!!s!=!!r||s.id!=r.id)}function w(e){let t=o.getBlockById(e.id);if(!t)return!1;const n=i(t),r=i(e);return n!=r&&(l(`old ${t.toDevString()}`,n),l(`new ${e.toDevString()}`,r),!0)}function R(e){e.setColour(n),B(e),a.statementsOnly&&(e.inputList||[]).map((e=>e.type==Blockly.INPUT_VALUE&&e.connection&&e.connection.targetBlock())).filter((e=>!!e)).forEach((e=>R(e)))}}(o,s,a)}catch(t){return e.reportException(t),{ws:void 0,message:lf("Oops, we could not diff those blocks."),error:t,deleted:0,added:0,modified:0}}finally{Blockly.Events.enable()}}function r(){return e.options.debug||window&&/diffdbg=1/.test(window.location.href)?console.log:(e,...t)=>{}}function i(e,t){const n=Blockly.Xml.blockToDom(e,!0);return s(n),a(n,(e=>{s(e),t||("next"==e.localName||"statement"==e.localName||"shadow"==e.localName)&&e.remove()})),Blockly.Xml.domToText(n)}function s(e){e.removeAttribute("id"),e.removeAttribute("x"),e.removeAttribute("y"),e.removeAttribute("deletable"),e.removeAttribute("editable"),e.removeAttribute("movable")}function a(t,n){if(t){n(t);for(const o of e.Util.toArray(t.children))a(o,n)}}t.mergeXml=function(e,t,n){return e==t?n:n==t?e:void 0},t.decompiledDiffAsync=function(t,n,i,s,a={}){const l=r(),c=n.outfiles[e.MAIN_BLOCKS];let u=s.outfiles[e.MAIN_BLOCKS];l(c),l(u);const d=e.diff.compute(t,i,{ignoreWhitespace:!0,full:!0});l(d);const p={};let g=0,h=0;d.forEach(((t,o)=>{const r=t[0],i=t.substr(2);let a=i.length;switch(r){case"-":g+=a+1;break;case"+":h+=a+1;break;default:const o=/^\s+/.exec(i);if(o){const e=o[0].length;g+=e,h+=e,a-=e}const r=e.blocks.findBlockIdByPosition(s.blockSourceMap,{start:h,length:a});if(r&&!p[r]){const o=e.blocks.findBlockIdByPosition(n.blockSourceMap,{start:g,length:a});o&&(l(t),l(`id ${g}:${i.length}>${o} ==> ${h}:${i.length}>${r}`),p[r]=o,u=u.replace(r,o))}g+=a+1,h+=a+1}}));const f=e.blocks.loadWorkspaceXml(c,!0),_=e.blocks.loadWorkspaceXml(u,!0);return a.statementsOnly=!0,o(f,_,a)}}(e.blocks||(e.blocks={}))}(pxt||(pxt={})),function(e){!function(t){function n(e,t){const n=[];for(let o=0;o<e.childNodes.length;o++){const r=e.childNodes.item(o);r.tagName===t&&n.push(r)}return n}function o(e,t){return r(e,"block","type",t).concat(r(e,"shadow","type",t))}function r(t,n,o,r){return e.Util.toArray(t.getElementsByTagName(n)).filter((e=>e.getAttribute(o)===r))}function i(e,t,n,o){const i=r(e,t,n,o);return i.length?i[0]:void 0}function s(e,n,o){var r;let s=o.getAttribute("type"),a=Blockly.Blocks[s],l=t.blockSymbol(s);if(!l||!a)return;let c=t.compileInfo(l);null===(r=l.parameters)||void 0===r||r.forEach(((t,r)=>{let s=e.apis.byQName[t.type];if(s&&6==s.kind){let e=i(o,"field","name",c.actualNameToParam[t.name].definitionName);if(e){let t=n[s.name+"."+e.textContent];t&&(e.textContent=t)}}}))}t.domToWorkspaceNoEvents=function(t,n){e.tickEvent("blocks.domtow");let o=[];try{Blockly.Events.disable(),o=Blockly.Xml.domToWorkspace(t,n),function(e){e.getAllBlocks(!1).filter((e=>!!e.getCommentText())).forEach((t=>{var n,o;const r=t.getCommentText();if(/@highlight/.test(r)){const i=r.replace(/@highlight/g,"").trim();t.setCommentText(i||null),null===(o=(n=e).highlightBlock)||void 0===o||o.call(n,t.id)}}))}(n)}catch(t){e.reportException(t)}finally{Blockly.Events.enable()}return o},t.clearWithoutEvents=function(t){if(e.tickEvent("blocks.clear"),t)try{Blockly.Events.disable(),t.clear(),t.clearUndo()}finally{Blockly.Events.enable()}},t.saveWorkspaceXml=function(e,t){const n=Blockly.Xml.workspaceToDom(e,!t);return Blockly.Xml.domToText(n)},t.saveBlocksXml=function(e,t){return e.getTopBlocks(!1).map((e=>Blockly.Xml.domToText(Blockly.Xml.blockToDom(e,!t))))},t.getDirectChildren=n,t.getBlocksWithType=o,t.getChildrenWithAttr=r,t.getFirstChildWithAttr=i,t.loadBlocksXml=function(e,t){let n=Blockly.Xml.textToDom(t),o=Blockly.Xml.domToBlock(n,e);if(e.getMetrics){let t=e.getMetrics(),n=o.getHeightWidth();o.moveBy(t.viewLeft+t.viewWidth/2-n.width/2,t.viewTop+t.viewHeight/2-n.height/2)}},t.loadWorkspaceXml=function(t,n=!1){const o=new Blockly.Workspace;try{const n=Blockly.Xml.textToDom(t);return e.blocks.domToWorkspaceNoEvents(n,o),o}catch(t){return n||e.reportException(t),null}},t.importXml=function(i,a,l,c=!1){try{e.blocks.initializeAndInject(l);const c=(new DOMParser).parseFromString(a,"application/xml"),d=e.patching.computePatches(i);d&&(d.filter((e=>"blockId"==e.type)).forEach((t=>Object.keys(t.map).forEach((n=>{o(c,n).forEach((o=>{o.setAttribute("type",t.map[n]),e.debug(`patched block ${n} -> ${t.map[n]}`)}))})))),d.filter((e=>"blockValue"==e.type)).forEach((t=>Object.keys(t.map).forEach((r=>{const i=r.split("."),s=i[0];i[1];o(c,s).reduce(((e,t)=>e.concat(n(t,"value"))),[]).forEach((n=>{n.setAttribute("name",t.map[r]),e.debug(`patched block value ${r} -> ${t.map[r]}`)}))})))),d.filter((e=>"userenum"==e.type)).forEach((t=>Object.keys(t.map).forEach((n=>{r(c,"variable","type",n).forEach((o=>{o.setAttribute("type",t.map[n]),e.debug(`patched enum variable type ${n} -> ${t.map[n]}`)}))})))));const p=n(c.children.item(0),"shadow");for(const e of p){const t=c.createElement("block");e.getAttributeNames().forEach((n=>t.setAttribute(n,e.getAttribute(n))));for(let n=0;n<e.childNodes.length;n++)t.appendChild(e.childNodes.item(n));e.replaceWith(t)}const g={};Object.keys(l.apis.byQName).forEach((e=>{let t=l.apis.byQName[e];7==t.kind&&(g[t.namespace+"."+(t.attributes.blockImportId||t.attributes.block||t.attributes.blockId||t.name)]=t.namespace+"."+t.name)}));const h=c.getElementsByTagName("block");for(let e=0;e<h.length;++e)s(l,g,h[e]);return function(n,r){const i=o(n,ts.pxtc.ON_START_TYPE);let s=i.length?i[0]:void 0;if(s)return void s.removeAttribute("deletable");let a=[];const l=r.blocksById;let c,u=n.firstElementChild;for(;u;){const o=u.nextElementSibling,r=u.getAttribute("type");if(!u.getAttribute("disabled")&&!u.getElementsByTagName("statement").length&&(e.blocks.buildinBlockStatements[r]||l[r]&&"void"==l[r].retType&&!t.hasArrowFunction(l[r])))if(c){const e=n.ownerDocument.createElement("next");e.appendChild(u),c.appendChild(e),u.removeAttribute("x"),u.removeAttribute("y"),c=u}else c=n.ownerDocument.createElement("statement"),c.setAttribute("name","HANDLER"),s||(s=n.ownerDocument.createElement("block"),s.setAttribute("type",ts.pxtc.ON_START_TYPE),a.push(s)),s.appendChild(c),c.appendChild(u),u.removeAttribute("x"),u.removeAttribute("y"),c=u;u=o}a.forEach((e=>n.appendChild(e)))}(c.documentElement,l),u=c.documentElement,e.U.toArray(u.querySelectorAll("block[type=procedures_defnoreturn]")).forEach((e=>{e.setAttribute("type","function_definition"),e.querySelector("field[name=NAME]").setAttribute("name","function_name")})),e.U.toArray(u.querySelectorAll("block[type=procedures_callnoreturn]")).forEach((e=>{e.setAttribute("type","function_call"),e.querySelector("field[name=NAME]").setAttribute("name","function_name")})),e.blocks.extensionBlocklyPatch&&e.blocks.extensionBlocklyPatch(i,c.documentElement),(new XMLSerializer).serializeToString(c)}catch(t){return c||e.reportException(t),a}var u}}(e.blocks||(e.blocks={}))}(pxt||(pxt={})),function(e){var t;(function(n){n.patchBlocksFromOldWorkspace=function(t,n,o){const r=e.blocks.loadWorkspaceXml(o,!0);return function(t,n,o){let r,i;n.getTopBlocks(!1).filter((e=>e.isEnabled())).forEach((s=>{const a=s.xy_;if(a&&0!=a.x&&0!=a.y){r||(r=e.blocks.mkEnv(n,t),i={},o.getTopBlocks(!1).forEach((t=>{const n=e.blocks.callKey(r,t),o=i[n]||[];o.push(t),i[n]=o})));const l=e.blocks.callKey(r,s),c=(i[l]||[]).shift();c&&(c.xy_=a.clone())}}))}(t,n,r),function(t,n){const o=Blockly.Xml.workspaceToDom(t,!0),r=Blockly.Xml.workspaceToDom(n,!0);return e.Util.toArray(o.childNodes).filter((e=>e.nodeType==Node.ELEMENT_NODE&&"block"==e.localName&&"true"==e.getAttribute("disabled"))).forEach((e=>r.appendChild(r.ownerDocument.importNode(e,!0)))),Blockly.Xml.domToText(r)}(n,r)},n.splitSvg=function(t,n,o=18){const r=n.getTopComments(!0),i=n.getTopBlocks(!0);if(r.length+i.length<2)return t;const s=document.createElement("div");function a(n,r,i,a,l,c){const u=t.cloneNode(!0),d=u.querySelector(`g.blocklyWorkspace > g.${n}`),p=u.querySelector(`g.blocklyWorkspace > g.${r}`),g=e.Util.toArray(d.querySelectorAll(`g.blocklyWorkspace > g.${n} > ${c?"."+c:"g[transform]"}`)),h=g.splice(i,1)[0];if(!h)return void e.log("missing block, did block failed to load?");g.filter((e=>e!=h)).forEach((e=>{e.parentNode.removeChild(e)})),d.removeAttribute("transform"),p.parentNode.removeChild(p),h.setAttribute("transform",`translate(${l.x}, ${l.y})`);const f=a.width/o+"em",_=a.height/o+"em";u.setAttribute("viewBox",`0 0 ${a.width} ${a.height}`),u.style.width=f,u.style.height=_,u.setAttribute("width",f),u.setAttribute("height",_),s.appendChild(u)}return s.className=`blocks-svg-list ${n.getInjectionDiv().className}`,r.forEach(((e,t)=>a("blocklyBubbleCanvas","blocklyBlockCanvas",t,e.getHeightWidth(),{x:0,y:0},"blocklyComment"))),i.forEach(((e,t)=>{const n=e.getHeightWidth(),r={x:0,y:0};e.getStartHat()&&(n.height+=o,r.y+=o),a("blocklyBlockCanvas","blocklyBubbleCanvas",t,n,r)})),s},n.verticalAlign=function(e,t){let n=0;e.getTopComments(!0).forEach((e=>{e.moveBy(0,n),n+=e.getHeightWidth().height,n+=t})),e.getTopBlocks(!0).forEach(((e,o)=>{e.getStartHat()&&(n+=t),e.moveBy(0,n),n+=e.getHeightWidth().height,n+=t}))},n.setCollapsedAll=function(e,t){e.getTopBlocks(!1).filter((e=>e.isEnabled())).forEach((e=>e.setCollapsed(t)))};const o=20;function r(t,n,o){let r;o&&(r={target:e.appTarget.id,versions:e.appTarget.versions,xml:e.blocks.saveBlocksXml(t).map((t=>e.Util.htmlEscape(t)))});const i=0|n||4;return a(t,i).then((t=>t?e.BrowserUtils.encodeToPngAsync(t.xml,{width:t.width,height:t.height,pixelDensity:i,text:o?JSON.stringify(r,null,2):null}):Promise.resolve(void 0))).catch((t=>{e.reportException(t)}))}n.flow=function(e,t){if(t){if(t.useViewWidth){const t=e.getMetrics();if(t.viewHeight>t.viewWidth)return f(e.getTopComments(!0),e.getTopBlocks(!0),void 0,t.viewWidth),void e.scroll(o,20)}f(e.getTopComments(!0),e.getTopBlocks(!0),t.ratio)}else f(e.getTopComments(!0),e.getTopBlocks(!0));e.scroll(o,20)},n.screenshotEnabled=function(){return!e.BrowserUtils.isIE()&&!e.BrowserUtils.isUwpEdge()},n.screenshotAsync=function(e,t,n){return r(e,t,n)},n.toPngAsync=r;const i="http://www.w3.org/1999/xlink",s=12e7;function a(e,t){if(!e)return Promise.resolve(void 0);const n=e.getBlocksBoundingBox(),o=e.getParentSvg().cloneNode(!0);u(o);let r=n.right-n.left,i=n.bottom-n.top,a=1;const l=r*i*Math.pow(t,2);return l>s&&(a=Math.sqrt(s/l)),d(o,n.left,n.top,r,i,a)}function l(e){return c((new XMLSerializer).serializeToString(e))}function c(e){return e.replace(new RegExp(" ","g")," ")}function u(t){e.BrowserUtils.removeClass(t,"blocklySvg"),e.BrowserUtils.addClass(t,"blocklyPreview pxt-renderer classic-theme"),e.U.toArray(t.querySelectorAll(".blocklyMainBackground,.blocklyScrollbarBackground")).forEach((e=>{e&&e.parentNode.removeChild(e)})),e.U.toArray(t.querySelectorAll(".blocklyConnectionIndicator,.blocklyInputConnectionIndicator")).forEach((e=>{e&&e.parentNode.removeChild(e)})),t.removeAttribute("width"),t.removeAttribute("height"),e.U.toArray(t.querySelectorAll(".blocklyBlockCanvas,.blocklyBubbleCanvas")).forEach((e=>e.removeAttribute("transform")));const n=new DOMParser;return e.U.toArray(t.querySelectorAll(".blocklyCommentTextarea")).forEach((t=>{const o=n.parseFromString("<!doctype html><body>"+e.docs.html2Quote(t.value),"text/html");t.textContent=o.body.textContent})),t}function d(t,n,o,r,s,a){if(!t.childNodes[0])return Promise.resolve(void 0);t.removeAttribute("width"),t.removeAttribute("height"),t.removeAttribute("transform");let c=Math.round(r*(a||1)),u=Math.round(s*(a||1));const d=l(t).replace(/^\s*<svg[^>]+>/i,"").replace(/<\/svg>\s*$/i,""),f=`<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="${i}" width="${c}" height="${u}" viewBox="${n} ${o} ${r} ${s}" class="pxt-renderer">${d}</svg>`,_=(new DOMParser).parseFromString(f,"image/svg+xml"),m=_.createElementNS("http://www.w3.org/1999/xhtml","style"),y=e.Util.isUserLanguageRtl(),k=document.getElementById(`style-${y?"rtl":""}blockly.css`).href,b=e.Util.toArray(document.head.getElementsByTagName("link")).filter((t=>e.Util.endsWith(t.getAttribute("href"),"semantic.css")))[0].href;return Promise.all([e.BrowserUtils.loadAjaxAsync(k),e.BrowserUtils.loadAjaxAsync(b)]).then((t=>{var n,o;const r=e.Util.toArray(document.head.querySelectorAll("style")).filter((e=>/\.blocklySvg/.test(e.innerText)))[0];t.unshift((null===(n=document.getElementById("blockly-common-style"))||void 0===n?void 0:n.innerText)||""),t.unshift((null===(o=document.getElementById("blockly-renderer-style-pxt"))||void 0===o?void 0:o.innerText)||"");const s=(r?r.innerText:"")+"\n\n"+t.map((e=>e+"\n\n"));return m.appendChild(_.createCDATASection(s)),_.documentElement.insertBefore(m,_.documentElement.firstElementChild),function(t){g||(g={});const n=t.getElementsByTagName("image"),o=e.Util.toArray(n).filter((e=>{const t=e.getAttributeNS(i,"href");return t&&!/^data:/.test(t)})).map((e=>e)).map((t=>{const n=t.getAttributeNS(i,"href");let o=g[n];return(o?Promise.resolve(g[n]):e.BrowserUtils.loadImageAsync(t.getAttributeNS(i,"href")).then((e=>{const t=document.createElement("canvas"),r=t.getContext("2d");let i=e.width,s=e.height;return t.width=i,t.height=s,r.drawImage(e,0,0,i,s,0,0,t.width,t.height),g[n]=o=t.toDataURL("image/png"),o})).catch((t=>(e.debug(`svg render: failed to load ${n}`),"")))).then((e=>{t.setAttributeNS(i,"href",e)}))}));return Promise.all(o).then((()=>{}))}(_).then((()=>function(t){if(h||(h={}),!e.BrowserUtils.isEdge())return Promise.resolve();const n=t.getElementsByTagName("image"),o=e.Util.toArray(n).filter((e=>/^data:image\/svg\+xml/.test(e.getAttributeNS(i,"href")))).map((e=>e)).map((t=>{const n=t.getAttributeNS(i,"href"),o=parseInt(t.getAttribute("width").replace(/[^0-9]/g,"")),r=parseInt(t.getAttribute("height").replace(/[^0-9]/g,""));let s=h[n];return(s?Promise.resolve(s):e.BrowserUtils.encodeToPngAsync(n,{width:o,height:r,pixelDensity:2})).then((e=>{h[n]=e,t.setAttributeNS(i,"href",e)}))}));return Promise.all(o).then((()=>{}))}(_))).then((()=>({width:c,height:u,svg:l(_).replace('<style xmlns="http://www.w3.org/1999/xhtml">',"<style>"),xml:p(_),css:s})))}))}function p(e){const t=(new XMLSerializer).serializeToString(e);return"data:image/svg+xml;base64,"+ts.pxtc.encodeBase64(unescape(encodeURIComponent(t)))}let g,h;function f(e,n,r=1.62,i){const s=[],a={};let l;e.forEach((e=>{const t=e.data;null!=t&&(a[t]=e)})),n.sort(((e,t)=>e.isEnabled()===t.isEnabled()?e.type===t.type?0:"function_definition"===e.type?1:"function_definition"===t.type?-1:e.type.localeCompare(t.type):e.isEnabled()?-1:1)),n.forEach((e=>{const n=t.getBlockData(e).commentRefs;if(n.length){const t=[];for(let e=0;e<n.length;e++){const o=a[n[e]];o&&(t.push(_(o)),delete a[n[e]])}if(t.length)return void s.push({value:e,width:-1,height:-1,children:t})}const o=_(e);!l&&e.isEnabled()&&e.type===pxtc.ON_START_TYPE?l=o:s.push(o)})),l&&s.unshift(l),Object.keys(a).sort(((e,t)=>e.length===t.length?e>t?-1:1:e.length>t.length?-1:1)).forEach((e=>{a[e]&&s.push(_(a[e]))})),e.forEach((e=>{null==e.data&&s.push(_(e))}));let c,u=0;for(let e=0;e<s.length;e++){const t=s[e];if(t.children){const e=t.value.getHeightWidth();t.x=0,t.y=0;let n=e.width+13,o=0;for(let e=0;e<t.children.length;e++){const r=t.children[e];r.x=n,r.y=o,o+=r.height+13,t.width=Math.max(t.width,n+r.width)}t.height=Math.max(o-13,e.height)}u+=(t.height+13)*(t.width+13)}c=i>o?i-o:Math.sqrt(u)*r;let d=o,p=20,g=0;for(let e=0;e<s.length;e++){const t=s[e];if(t.children){h(t,d+t.x,p+t.y);for(let e=0;e<t.children.length;e++){const n=t.children[e];h(n,d+n.x,p+n.y)}}else h(t,d,p);d+=t.width+45,g=Math.max(g,p+t.height+45),d>c&&(d=o,p=g)}function h(e,t,n){const o=e.value.getBoundingRectangle();e.value.moveBy(t-o.left,n-o.top)}}function _(e){const t=e.getHeightWidth();return{value:e,height:t.height,width:t.width}}n.toSvgAsync=a,n.serializeNode=l,n.serializeSvgString=c,n.cleanUpBlocklySvg=u,n.blocklyToSvgAsync=d,n.documentToSvg=p})((t=e.blocks||(e.blocks={})).layout||(t.layout={}))}(pxt||(pxt={})),function(e){!function(t){const n={string:{field:"TEXT",block:"text",defaultValue:""},number:{field:"NUM",block:"math_number",defaultValue:"0"},boolean:{field:"BOOL",block:"logic_boolean",defaultValue:"false"},Array:{field:"VAR",block:"variables_get",defaultValue:"list"}};function o(e){let t=/^(?:Array<(.+)>)|(?:(.+)\[\])|(?:\[.+\])$/.exec(e);return t?t[1]?t[1]:t[2]:void 0}t.optionalDummyInputPrefix="0_optional_dummy",t.optionalInputWithFieldPrefix="0_optional_field",t.isArrayType=o,t.isTupleType=function(e){let t=/^\[(.+)\]$/.exec(e);return t?t[1].split(/,\s*/):void 0};const r=/^(string|number|boolean)$/;let i,s;function a(){return i||(i={},Object.keys(Blockly.Blocks).forEach((e=>i[e]={block:Blockly.Blocks[e]}))),i}t.builtinBlocks=a,t.buildinBlockStatements={controls_if:!0,controls_for:!0,pxt_controls_for:!0,controls_simple_for:!0,controls_repeat_ext:!0,pxt_controls_for_of:!0,controls_for_of:!0,variables_set:!0,variables_change:!0,device_while:!0};let l={};function c(e,t,r,i){let s;if(i=i||t.defaultValue,!(r=r||t.shadowBlockId)&&t.range&&(r="math_number_minmax"),s=i&&'"'==i.slice(0,1)?JSON.parse(i):i,"number"==t.type&&"value"==r){const e=document.createElement("field");return e.setAttribute("name",t.definitionName),e.appendChild(document.createTextNode("0")),e}const a="variables_get"==r,l="text"==r,c=document.createElement("value");c.setAttribute("name",t.definitionName);const d=o(t.type),p=document.createElement(a||d?"block":"shadow");c.appendChild(p);const g=n[d||t.type];if(p.setAttribute("type",r||(d?"lists_create_with":g&&g.block||t.type)),p.setAttribute("colour",Blockly.Colours.textField),d){if(g&&!r){let e;switch(d){case"number":e=["0","1"];break;case"string":e=["a","b","c"];break;case"boolean":e=["FALSE","FALSE","FALSE"]}return u(p,g.block,g.field,e),c}if(r&&s)return u(p,s),c}if(!g||r&&g.block!==r&&"math_number_minmax"!==r){if(s){const n=document.createElement("field");if(n.textContent=s,a)n.setAttribute("name","VAR"),p.appendChild(n);else if(l)n.setAttribute("name","TEXT"),p.appendChild(n);else if(r){const t=e.blocksById[r];if(t&&t.attributes._def&&t.attributes._def.parameters.length){const e=t.attributes._def.parameters[0];n.setAttribute("name",e.name),p.appendChild(n)}}else n.setAttribute("name",t.definitionName),p.appendChild(n)}}else{const e=document.createElement("field");let n,o;switch(p.appendChild(e),r){case"variables_get":n="VAR";break;case"math_number_minmax":n="SLIDER";break;default:n=g.field}e.setAttribute("name",n),o="boolean"==t.type?document.createTextNode((s||g.defaultValue).toUpperCase()):document.createTextNode(s||g.defaultValue),e.appendChild(o)}let h;return t.range&&(h=document.createElement("mutation"),h.setAttribute("min",t.range.min.toString()),h.setAttribute("max",t.range.max.toString()),h.setAttribute("label",t.actualName.charAt(0).toUpperCase()+t.actualName.slice(1)),t.fieldOptions&&(t.fieldOptions.step&&h.setAttribute("step",t.fieldOptions.step),t.fieldOptions.color&&h.setAttribute("color",t.fieldOptions.color),t.fieldOptions.precision&&h.setAttribute("precision",t.fieldOptions.precision))),t.fieldOptions&&(h||(h=document.createElement("mutation")),h.setAttribute("customfield",JSON.stringify(t.fieldOptions))),h&&p.appendChild(h),c}function u(e,t,n,o){const r=o?o.length:2,i=document.createElement("mutation");i.setAttribute("items",""+r),i.setAttribute("horizontalafter",""+r),e.appendChild(i);for(let i=0;i<r;i++){const r=document.createElement("value");r.setAttribute("name","ADD"+i);const s=document.createElement("shadow");if(s.setAttribute("type",t),n){const e=document.createElement("field");e.setAttribute("name",n),o&&e.appendChild(document.createTextNode(o[i])),s.appendChild(e)}r.appendChild(s),e.appendChild(r)}}function d(t,n,o,r){const i=p(t,e.toolbox.convertColor(n),o,r);return i.setAttribute("web-class","blocklyFlyoutHeading"),i}function p(t,n,o,r){let i=Blockly.utils.xml.createElement("label");return i.setAttribute("text",t),n&&i.setAttribute("web-icon-color",e.toolbox.convertColor(n)),o&&(1===o.length?(i.setAttribute("web-icon",o),r&&i.setAttribute("web-icon-class",r)):i.setAttribute("web-icon-class",`blocklyFlyoutIcon${t}`)),i}function g(t,n,i){let s=document.createElement("block");if(s.setAttribute("type",n.attributes.blockId),n.attributes.blockGap?s.setAttribute("gap",n.attributes.blockGap):e.appTarget.appTheme&&e.appTarget.appTheme.defaultBlockGap&&s.setAttribute("gap",e.appTarget.appTheme.defaultBlockGap.toString()),i.thisParameter){const e=i.thisParameter;s.appendChild(c(t,e,e.shadowBlockId||"variables_get",e.defaultValue||e.definitionName))}return n.parameters&&(i.parameters.filter((e=>!e.isOptional&&(r.test(e.type)||r.test(o(e.type))||e.shadowBlockId||e.defaultValue))).forEach((e=>{s.appendChild(c(t,e))})),n.attributes.draggableParameters?i.handlerArgs.forEach((t=>{const o="reporter"===n.attributes.draggableParameters,r=document.createElement("value");r.setAttribute("name","HANDLER_DRAG_PARAM_"+t.name);const i=o?e.blocks.reporterTypeForArgType(t.type):"variables_get_reporter",a=document.createElement("shadow");if(a.setAttribute("type",i),o&&"argument_reporter_custom"===i){const e=document.createElement("mutation");e.setAttribute("typename",t.type),a.appendChild(e)}const l=document.createElement("field");l.setAttribute("name",o?"VALUE":"VAR"),l.textContent=e.Util.htmlEscape(t.name),a.appendChild(l),r.appendChild(a),s.appendChild(r)})):i.handlerArgs.forEach((e=>{const t=document.createElement("field");t.setAttribute("name","HANDLER_"+e.name),t.textContent=e.name,s.appendChild(t)}))),s}function h(n){return s=n,Blockly.pxtBlocklyUtils.whitelistDraggableBlockTypes(n.blocks.filter((e=>e.attributes.duplicateShadowOnDrag)).map((e=>e.attributes.blockId))),n.blocks.map((o=>{const r=t.compileInfo(o),i=g(n,o,r);if(o.attributes.blockBuiltin){e.Util.assert(!!a()[o.attributes.blockId]);const t=a()[o.attributes.blockId];t.symbol=o,t.block.codeCard=_(o,i)}else!function(n,o,r,i){let s=o.attributes.blockId;if(a()[s])return e.reportError("blocks","trying to override builtin block",{details:s}),!1;let c=JSON.stringify(o);if(l[s]&&l[s].hash==c)return!0;if(Blockly.Blocks[o.attributes.blockId])return console.error("duplicate block definition: "+s),!1;let u={hash:c,fn:o,block:{codeCard:_(o,i),init:function(){!function(n,o,r,i){var s;const a=(r.attributes.blockNamespace||r.namespace).split(".")[0],l=1==r.kind||2==r.kind,c=o.apis.byQName[a],u=r.attributes.blockNamespace&&c&&c.attributes.color||r.attributes.color||c&&c.attributes.color||e.toolbox.getNamespaceColor(a)||255;if(r.attributes.help){const e=r.attributes.help.replace(/^\//,"");/^github:/.test(e)?n.setHelpUrl(e):"none"!==e&&n.setHelpUrl("/reference/"+e)}else if(r.pkg&&!e.appTarget.bundledpkgs[r.pkg]){let e=r.qName.toLowerCase().split(".");e[0]==r.pkg&&e.shift(),n.setHelpUrl(`/pkg/${r.pkg}#${encodeURIComponent(e.join("-"))}`)}n.setColour(u);let d=Blockly.OUTPUT_SHAPE_ROUND;"boolean"==r.retType&&(d=Blockly.OUTPUT_SHAPE_HEXAGONAL);n.setOutputShape(d),r.attributes.undeletable&&n.setDeletable(!1);h(r.attributes._def);let p=!1;if(r.attributes.mutate)t.addMutation(n,r,r.attributes.mutate);else if(r.attributes.defaultInstance)t.addMutation(n,r,t.MutatorTypes.DefaultInstanceMutator);else if(r.attributes._expandedDef&&"disabled"!==r.attributes.expandableArgumentMode){const e="toggle"===r.attributes.expandableArgumentMode;t.initExpandableBlock(o,n,r.attributes._expandedDef,i,e,(()=>h(r.attributes._expandedDef,!0)))}else if(i.handlerArgs.length)if(p=!0,r.attributes.optionalVariableArgs)t.initVariableArgsBlock(n,i.handlerArgs);else if(r.attributes.draggableParameters)i.handlerArgs.filter((e=>!e.inBlockDef)).forEach((e=>{const t=n.appendValueInput("HANDLER_DRAG_PARAM_"+e.name);"reporter"==r.attributes.draggableParameters?t.setCheck(b(e.type,o)):t.setCheck("Variable")}));else{let e=n.appendDummyInput();i.handlerArgs.filter((e=>!e.inBlockDef)).forEach((t=>{e.appendField(new Blockly.FieldVariable(t.name),"HANDLER_"+t.name)}))}if(t.appendMutation(n,{mutationToDom:e=>(n.inputList.forEach((t=>{t.fieldRow.forEach((t=>{if(t.isFieldCustom_&&t.saveOptions){const n=t.saveOptions();n&&e.setAttribute("customfield",JSON.stringify(n))}}))})),e),domToMutation:e=>{n.inputList.forEach((t=>{t.fieldRow.forEach((t=>{if(t.isFieldCustom_&&t.restoreOptions){const n=JSON.parse(e.getAttribute("customfield"));n&&t.restoreOptions(n)}}))}))}}),r.attributes.imageLiteral){const e=(r.attributes.imageLiteralColumns||5)*r.attributes.imageLiteral,t=r.attributes.imageLiteralRows||5,o=r.attributes.imageLiteralScale;n.appendDummyInput().appendField(new pxtblockly.FieldMatrix("",{columns:e,rows:t,scale:o}),"LEDS")}"external"===r.attributes.inlineInputMode?n.setInputsInline(!1):"inline"===r.attributes.inlineInputMode?n.setInputsInline(!0):n.setInputsInline(!r.parameters||r.parameters.length<4&&!r.attributes.imageLiteral);((null===(s=r.parameters)||void 0===s?void 0:s.find((e=>pxtc.parameterTypeIsArrowFunction(e))))||p)&&(n.appendStatementInput("HANDLER").setCheck(null),n.setInputsInline(!0));v(n,r.retType,o);const g=m(r);function h(s,a=!1){let c=0,d=!a&&!!i.thisParameter;const p=function(e){const t=[];let n=[];return e.parts.forEach((e=>{switch(e.kind){case"break":o();break;case"param":n.push(e),o();break;case"image":case"label":n.push(e)}})),o(),t;function o(){n.length&&(t.push(n),n=[])}}(s),g=new e.ImageConverter;"ENUM_GET"!==r.attributes.shim&&"KIND_GET"!==r.attributes.shim||!(i.parameters.length>1||i.thisParameter)?(p.forEach((s=>{const p=[];let h,f,_,m=!1;if(s.forEach((n=>{if("param"!==n.kind){const t=function(t){if("image"===t.kind)return function(t){let n=I[t];if(!n)return void e.log(`missing jres icon ${t}`);return new Blockly.FieldImage(n,40,40,"",null,e.Util.isUserLanguageRtl())}(t.uri);const n=function(e){if(" "===e)return"";if(e.length>1){const t=" "==e.charAt(0),n=" "==e.charAt(e.length-1);if(t||n)return e.substring(t?1:0,n?e.length-1:e.length)}return e}(t.text);if(!n)return;return t.cssClass?new Blockly.FieldLabel(n,t.cssClass):t.style.length?new pxtblockly.FieldStyledLabel(n,{bold:-1!==t.style.indexOf("bold"),italics:-1!==t.style.indexOf("italics"),blocksInfo:void 0}):new Blockly.FieldLabel(n,void 0)}(n);t&&p.push({field:t})}else{if("ENUM_GET"===r.attributes.shim)return e.U.assert(!!r.attributes.enumName,"Trying to create an ENUM_GET block without a valid enum name"),void p.push({name:"MEMBER",field:new pxtblockly.FieldUserEnum(o.enumsByName[r.attributes.enumName])});if("KIND_GET"===r.attributes.shim)return void p.push({name:"MEMBER",field:new pxtblockly.FieldKind(o.kindsByName[r.attributes.kindNamespace||r.attributes.blockNamespace||r.namespace])});{let c=function(e,t,n=!1){if(e.ref){const n="this"===e.name?t.thisParameter:t.actualNameToParam[e.name];if(!n){let n;if(t.handlerArgs.forEach((t=>{t.name===e.name&&(n=t)})),n)return n}return n}return n?t.thisParameter:t.definitionNameToParam[e.name]}(n,i,d);if(d=!1,!c)return void console.error("block "+r.attributes.blockId+": unknown parameter "+n.name+(n.ref?` (${n.ref})`:""));if(!c.definitionName)return h="HANDLER_DRAG_PARAM_"+c.name,void(f="reporter"===r.attributes.draggableParameters?b(c.type,o):"Variable");let _=e.U.lookup(o.apis.byQName,c.type);m=!0;const y=c.definitionName,k=c.actualName;let v=_&&6==_.kind,T=_&&!!_.attributes.fixedInstances&&!c.shadowBlockId,E=!!r.attributes.constantShim,S="@combined@"==c.type,C=c.fieldEditor,x=y.charAt(0).toUpperCase()+y.slice(1),B=c.type;if(v||T||E||S){let n;v?(s=o.apis,a=c.type,n=e.Util.values(s.byQName).filter((e=>e.namespace===a&&!e.attributes.blockHidden))):n=T?N(o.apis,_.qName):S?r.combinedProperties.map((t=>e.U.lookup(o.apis.byQName,t))):function(t,n){return e.Util.values(t.byQName).filter((e=>e.attributes.blockIdentity===n))}(o.apis,r.qName),0==n.length&&console.error(`no instances of ${_.qName} found`);const i=n.map((t=>{let n=t.attributes.block||t.attributes.blockId||t.name,o=t.attributes.blockCombine;return t.attributes.jresURL&&!t.attributes.iconURL&&e.U.startsWith(t.attributes.jresURL,"data:image/x-mkcd-f")&&(t.attributes.iconURL=g.convert(t.attributes.jresURL)),o&&(n=n.replace(/@set/,"")),[t.attributes.iconURL||t.attributes.blockImage?{src:t.attributes.iconURL||e.Util.pathJoin(e.webConfig.commitCdnUrl,`blocks/${t.namespace.toLowerCase()}/${t.name.toLowerCase()}.png`),alt:n,width:36,height:36,value:t.name}:n,t.namespace+"."+t.name]}));if(c.defaultValue){let e=-1;if(i.some(((t,n)=>t[1]===c.defaultValue&&(e=n,!0))),e>-1){const t=i.splice(e,1)[0];i.unshift(t)}}if(C){let n=r.attributes.paramDefl[k]||"";const s={data:i,colour:u,label:x,type:B,blocksInfo:o};e.Util.jsonMergeFrom(s,r.attributes.paramFieldEditorOptions&&r.attributes.paramFieldEditorOptions[k]||{}),p.push(D(t.createFieldEditor(C,n,s),y))}else p.push(D(new Blockly.FieldDropdown(i),y))}else if(C){const n=r.attributes.paramDefl[c.actualName]||"",i={colour:u,label:x,type:B,blocksInfo:o};e.Util.jsonMergeFrom(i,r.attributes.paramFieldEditorOptions&&r.attributes.paramFieldEditorOptions[c.actualName]||{}),p.push(D(t.createFieldEditor(C,n,i),c.definitionName))}else h=y,l&&"this"===n.name?f=c.type:"number"==c.type&&c.shadowBlockId&&"value"==c.shadowBlockId?(h=void 0,p.push(D(new Blockly.FieldNumber("0"),y))):f="string"==c.type&&c.shadowOptions&&c.shadowOptions.toString?null:b(c.type,o)}}var s,a})),h)_=n.appendValueInput(h),_.setAlign(Blockly.ALIGN_LEFT);else if(a){const e=m?t.optionalInputWithFieldPrefix:t.optionalDummyInputPrefix;_=n.appendDummyInput(e+c++)}else _=n.appendDummyInput();f&&_.setCheck(f),p.forEach((e=>_.appendField(e.field,e.name)))})),g.logTime()):console.warn(`Enum blocks may only have 1 parameter but ${r.attributes.blockId} has ${i.parameters.length}`)}n.setPreviousStatement(!(g&&!r.attributes.handlerStatement)&&"void"==r.retType),n.setNextStatement(!(g&&!r.attributes.handlerStatement)&&"void"==r.retType),n.setTooltip(/^__/.test(r.namespace)?"":r.attributes.jsDoc)}(this,n,o,r)}}};e.Util.isTranslationMode()&&e.blocks.promptTranslateBlock&&(u.block.customContextMenu=t=>{o.attributes.translationId&&t.push({enabled:!0,text:lf("Translate this block"),callback:function(){e.blocks.promptTranslateBlock(s,[o.attributes.translationId])}})});l[s]=u,Blockly.Blocks[s]=u.block}(n,o,r,i);return o}))}function f(e){return e.outerHTML.replace(/^<\?[^>]*>/,"")}function _(e,t){return{name:e.namespace+"."+e.name,shortName:e.name,description:e.attributes.jsDoc,url:e.attributes.help?"reference/"+e.attributes.help.replace(/^\//,""):void 0,blocksXml:`<xml xmlns="http://www.w3.org/1999/xhtml">${f(t)}</xml>`}}function m(e){var t;return!!(null===(t=e.parameters)||void 0===t?void 0:t.some((e=>pxtc.parameterTypeIsArrowFunction(e))))}t.blockSymbol=function(e){let t=l[e];return t?t.fn:void 0},t.createShadowValue=c,t.createFlyoutHeadingLabel=d,t.createFlyoutGroupLabel=function(e,t,n,o){const r=p(e,void 0,t);return r.setAttribute("web-class","blocklyFlyoutGroup"),r.setAttribute("web-line","1.5"),n&&r.setAttribute("web-line-width",n),o&&(r.setAttribute("web-help-button","true"),r.setAttribute("callbackKey",o)),r},t.createFlyoutButton=function(e,t){let n=Blockly.utils.xml.createElement("button");return n.setAttribute("text",t),n.setAttribute("callbackKey",e),n},t.createToolboxBlock=g,t.injectBlocks=h,t.hasArrowFunction=m,t.cleanBlocks=function(){e.debug("removing all custom blocks");for(const e in l)x(l[e].fn)},t.initializeAndInject=function(e){k(),h(e)},t.initialize=function(e){k(),function(e){I={};const t=e.apis.jres;if(!t)return;Object.keys(t).forEach((e=>{const n=t[e];n&&n.icon&&(I[e]=n.icon)}))}(e)};let y=!1;function k(){y||(y=!0,goog.provide("Blockly.Blocks.device"),goog.require("Blockly.Blocks"),Blockly.FieldCheckbox.CHECK_CHAR="■",Blockly.Constants.ADD_START_HATS=!!e.appTarget.appTheme.blockHats,t.initFieldEditors(),function(){const n=Blockly.Msg;n.DUPLICATE_BLOCK=lf("{id:block}Duplicate"),n.DUPLICATE_COMMENT=lf("Duplicate Comment"),n.REMOVE_COMMENT=lf("Remove Comment"),n.ADD_COMMENT=lf("Add Comment"),n.EXTERNAL_INPUTS=lf("External Inputs"),n.INLINE_INPUTS=lf("Inline Inputs"),n.EXPAND_BLOCK=lf("Expand Block"),n.COLLAPSE_BLOCK=lf("Collapse Block"),n.ENABLE_BLOCK=lf("Enable Block"),n.DISABLE_BLOCK=lf("Disable Block"),n.DELETE_BLOCK=lf("Delete Block"),n.DELETE_X_BLOCKS=lf("Delete Blocks"),n.DELETE_ALL_BLOCKS=lf("Delete All Blocks"),n.HELP=lf("Help"),Blockly.BlockSvg.prototype.showHelp=function(){const t=goog.isFunction(this.helpUrl)?this.helpUrl():this.helpUrl;t&&(e.blocks.openHelpUrl||window.open)(t)},Blockly.WorkspaceSvg.prototype.configureContextMenu=function(o,r){if(this.options.readOnly||this.isFlyout)return;o.length=0;let i=this.getTopBlocks(!0),s=Blockly.utils.genUid(),a=this.getTopComments(),l=this;const c=!(this.options.debugMode||this.options.readOnly);if(this.options.comments&&!e.BrowserUtils.isIE()){const e=Blockly.ContextMenu.workspaceCommentOption(l,r);e.enabled=e.enabled&&c,o.push(e)}let u=Blockly.WorkspaceSvg.buildDeleteList_(i),d=0;for(let e=0;e<u.length;e++)u[e].isShadow()||d++;const p=10;function g(){Blockly.Events.setGroup(s);let e=u.shift();e&&(e.workspace?(e.dispose(!1,!0),setTimeout(g,p)):g()),Blockly.Events.setGroup(!1)}const h={text:1==d?n.DELETE_BLOCK:n.DELETE_ALL_BLOCKS,enabled:d>0&&c,callback:()=>{e.tickEvent("blocks.context.delete",void 0,{interactiveConsent:!0}),d<2?g():Blockly.confirm(lf("Delete all {0} blocks?",d),(e=>{e&&g()}))}};o.push(h);const f={text:lf("Format Code"),enabled:c,callback:()=>{e.tickEvent("blocks.context.format",void 0,{interactiveConsent:!0}),e.blocks.layout.flow(this,{useViewWidth:!0})}};if(o.push(f),e.appTarget.appTheme.blocksCollapsing){const t={text:lf("Collapse Blocks"),enabled:i.length&&i.find((e=>e.isEnabled()&&!e.isCollapsed()))&&c,callback:()=>{e.tickEvent("blocks.context.collapse",void 0,{interactiveConsent:!0}),e.blocks.layout.setCollapsedAll(this,!0)}};o.push(t);const n={text:lf("Expand Blocks"),enabled:i.length&&i.find((e=>e.isEnabled()&&e.isCollapsed()))&&c,callback:()=>{e.tickEvent("blocks.context.expand",void 0,{interactiveConsent:!0}),e.blocks.layout.setCollapsedAll(this,!1)}};o.push(n)}if(e.blocks.layout.screenshotEnabled()){const t={text:lf("Snapshot"),enabled:i.length>0||a.length>0,callback:()=>{var t;e.tickEvent("blocks.context.screenshot",void 0,{interactiveConsent:!0}),e.blocks.layout.screenshotAsync(this,null,null===(t=e.appTarget.appTheme)||void 0===t?void 0:t.embedBlocksInSnapshot).then((t=>{e.BrowserUtils.isSafari()&&(t=t.replace(/^data:image\/[^;]/,"data:application/octet-stream")),e.BrowserUtils.browserDownloadDataUri(t,`${e.appTarget.nickname||e.appTarget.id}-${lf("screenshot")}.png`)}))}};o.push(t)}e.appTarget.appTheme.workspaceSearch&&o.push({text:lf("Find..."),enabled:i.length>0,callback:()=>{var t,n;e.tickEvent("blocks.context.workspacesearch",void 0,{interactiveConsent:!0}),null===(n=null===(t=this.getComponentManager())||void 0===t?void 0:t.getComponent("workspaceSearch"))||void 0===n||n.open()}}),t.onShowContextMenu&&t.onShowContextMenu(this,o)},Blockly.Constants.Logic.LOGIC_COMPARE_ONCHANGE_MIXIN.onchange=function(){}}(),function(){const t=e.blocks.getBlockDefinition(ts.pxtc.ON_START_TYPE);if(Blockly.Blocks[ts.pxtc.ON_START_TYPE]={init:function(){this.jsonInit({message0:t.block.message0,args0:[{type:"input_dummy"},{type:"input_statement",name:"HANDLER"}],colour:(e.appTarget.runtime?e.appTarget.runtime.onStartColor:"")||e.toolbox.getNamespaceColor("loops")}),S(this,ts.pxtc.ON_START_TYPE,t.name,t.tooltip,t.url,String((e.appTarget.runtime?e.appTarget.runtime.onStartColor:"")||e.toolbox.getNamespaceColor("loops")),void 0,void 0,!!e.appTarget.runtime&&e.appTarget.runtime.onStartUnDeletable)}},Blockly.Blocks[pxtc.TS_STATEMENT_TYPE]={init:function(){let t,n,o=this;o.setColour("#717171"),o.setPreviousStatement(!0),o.setNextStatement(!0),o.setInputsInline(!1),o.domToMutation=e=>{const t=parseInt(e.getAttribute("numlines"));o.declaredVariables=e.getAttribute("declaredvars"),n=[];for(let o=0;o<t;o++){const t=e.getAttribute("line"+o);n.push(t)}o.setPythonEnabled(!1)},o.mutationToDom=()=>{let e=document.createElement("mutation");return n&&(n.forEach(((t,n)=>e.setAttribute("line"+n,t))),e.setAttribute("numlines",n.length.toString())),o.declaredVariables&&e.setAttribute("declaredvars",this.declaredVariables),e},o.setPythonEnabled=r=>{if(t!==r){for(;o.inputList.length;)o.removeInput(o.inputList[0].name);t=r,r?(o.appendDummyInput().appendField(e.Util.lf("<python code>"),"LINE0"),o.setTooltip(lf("A Python statement that could not be converted to blocks"))):(n.forEach(((e,t)=>{o.appendDummyInput().appendField(e,"LINE"+t)})),o.setTooltip(lf("A JavaScript statement that could not be converted to blocks")))}},o.getLines=()=>n,o.setEditable(!1),S(this,pxtc.TS_STATEMENT_TYPE,lf("JavaScript statement"),lf("A JavaScript statement that could not be converted to blocks"),"/blocks/javascript-blocks","#717171")}},Blockly.Blocks[pxtc.TS_OUTPUT_TYPE]={init:function(){let e=this;e.setColour("#717171"),e.setPreviousStatement(!1),e.setNextStatement(!1),e.setOutput(!0),e.setEditable(!1),e.appendDummyInput().appendField(new pxtblockly.FieldTsExpression(""),"EXPRESSION"),e.setPythonEnabled=t=>{e.getField("EXPRESSION").setPythonEnabled(t),t?e.setTooltip(lf("A Python expression that could not be converted to blocks")):e.setTooltip(lf("A JavaScript expression that could not be converted to blocks"))},S(e,pxtc.TS_OUTPUT_TYPE,lf("JavaScript expression"),lf("A JavaScript expression that could not be converted to blocks"),"/blocks/javascript-blocks","#717171")}},e.appTarget.runtime&&e.appTarget.runtime.pauseUntilBlock){const t=e.appTarget.runtime.pauseUntilBlock,n=e.blocks.getBlockDefinition(ts.pxtc.PAUSE_UNTIL_TYPE);Blockly.Blocks[pxtc.PAUSE_UNTIL_TYPE]={init:function(){const o=t.color||e.toolbox.getNamespaceColor("loops");this.jsonInit({message0:n.block.message0,args0:[{type:"input_value",name:"PREDICATE",check:"Boolean"}],inputsInline:!0,previousStatement:null,nextStatement:null,colour:o}),S(this,ts.pxtc.PAUSE_UNTIL_TYPE,n.name,n.tooltip,n.url,o,void 0,void 0,!1)}}}const n="pxt_controls_for_of",o=e.blocks.getBlockDefinition(n);Blockly.Blocks[n]={init:function(){this.jsonInit({message0:o.block.message0,args0:[{type:"input_value",name:"VAR",variable:o.block.variable,check:"Variable"},{type:"input_value",name:"LIST",check:["Array","String"]}],previousStatement:null,nextStatement:null,colour:e.toolbox.blockColors.loops,inputsInline:!0}),this.appendStatementInput("DO").appendField(o.block.appendField);let t=this;S(this,n,o.name,(function(){return e.U.rlf(o.tooltip,t.getInputTargetBlock("VAR")?t.getInputTargetBlock("VAR").getField("VAR").getText():"")}),o.url,String(e.toolbox.getNamespaceColor("loops")))}};const r="controls_for_of",i=e.blocks.getBlockDefinition(r);Blockly.Blocks[r]={init:function(){this.jsonInit({message0:i.block.message0,args0:[{type:"field_variable",name:"VAR",variable:i.block.variable},{type:"input_value",name:"LIST",check:"Array"}],previousStatement:null,nextStatement:null,colour:e.toolbox.blockColors.loops,inputsInline:!0}),this.appendStatementInput("DO").appendField(i.block.appendField);let t=this;S(this,r,i.name,(function(){return e.U.rlf(i.tooltip,t.getField("VAR").getText())}),i.url,String(e.toolbox.getNamespaceColor("loops")))}};const s="lists_index_get",a=e.blocks.getBlockDefinition(s);Blockly.Blocks.lists_index_get={init:function(){this.jsonInit({message0:a.block.message0,args0:[{type:"input_value",name:"LIST",check:"Array"},{type:"input_value",name:"INDEX",check:"Number"}],colour:e.toolbox.blockColors.arrays,outputShape:Blockly.OUTPUT_SHAPE_ROUND,inputsInline:!0}),this.setPreviousStatement(!1),this.setNextStatement(!1),this.setOutput(!0),T(this,s)}};const l="lists_index_set",c=e.blocks.getBlockDefinition(l);Blockly.Blocks[l]={init:function(){this.jsonInit({message0:c.block.message0,args0:[{type:"input_value",name:"LIST",check:"Array"},{type:"input_value",name:"INDEX",check:"Number"},{type:"input_value",name:"VALUE",check:null}],previousStatement:null,nextStatement:null,colour:e.toolbox.blockColors.arrays,inputsInline:!0}),T(this,l)}}}(),function(){const n="math_op2",o=e.blocks.getBlockDefinition(n),r=o.tooltip;Blockly.Blocks[n]={init:function(){this.jsonInit({message0:lf("%1 of %2 and %3"),args0:[{type:"field_dropdown",name:"op",options:[[lf("{id:op}min"),"min"],[lf("{id:op}max"),"max"]]},{type:"input_value",name:"x",check:"Number"},{type:"input_value",name:"y",check:"Number"}],inputsInline:!0,output:"Number",outputShape:Blockly.OUTPUT_SHAPE_ROUND,colour:e.toolbox.getNamespaceColor("math")});S(this,n,o.name,(function(e){return r[e.getFieldValue("op")]}),o.url,e.toolbox.getNamespaceColor(o.category))}};const i="math_op3",s=e.blocks.getBlockDefinition(i);Blockly.Blocks[i]={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:e.toolbox.getNamespaceColor("math")}),T(this,i)}};["math_number","math_integer","math_whole_number","math_number_minmax"].forEach((t=>{const n=e.blocks.getBlockDefinition(t);C(t,n.name,n.tooltip,n.url,Blockly.Colours.textField,Blockly.Colours.textField,Blockly.Colours.textField)}));const a=Blockly.Msg,l="math_arithmetic",c=e.blocks.getBlockDefinition(l),u=c.tooltip;a.MATH_ADDITION_SYMBOL=c.block.MATH_ADDITION_SYMBOL,a.MATH_SUBTRACTION_SYMBOL=c.block.MATH_SUBTRACTION_SYMBOL,a.MATH_MULTIPLICATION_SYMBOL=c.block.MATH_MULTIPLICATION_SYMBOL,a.MATH_DIVISION_SYMBOL=c.block.MATH_DIVISION_SYMBOL,a.MATH_POWER_SYMBOL=c.block.MATH_POWER_SYMBOL,C(l,c.name,(function(e){return u[e.getFieldValue("OP")]}),c.url,e.toolbox.getNamespaceColor(c.category));const d="math_modulo",p=e.blocks.getBlockDefinition(d);a.MATH_MODULO_TITLE=p.block.MATH_MODULO_TITLE,E(d),t.initMathOpBlock(),t.initMathRoundBlock()}(),function(){Blockly.FieldVariable.prototype.getVariableTypes_=()=>[""];let t=lf("{id:var}item");Blockly.Variables.flyoutCategory=function(t){let n=[];if(!e.appTarget.appTheme.hideFlyoutHeadings){let t=d(lf("Variables"),e.toolbox.getNamespaceColor("variables"),e.toolbox.getNamespaceIcon("variables"));n.push(t)}let o=document.createElement("button");o.setAttribute("text",lf("Make a Variable...")),o.setAttribute("callbackKey","CREATE_VARIABLE"),t.registerButtonCallback("CREATE_VARIABLE",(function(e){Blockly.Variables.createVariable(e.getTargetWorkspace())})),n.push(o);let r=Blockly.Variables.flyoutCategoryBlocks(t);return n=n.concat(r),n},Blockly.Variables.flyoutCategoryBlocks=function(e){let t=e.getVariablesOfType(""),n=[];if(t.length>0){let e=t[t.length-1];t.sort(Blockly.VariableModel.compareByName);for(let e=0;e<t.length;e++){const o=t[e];if(Blockly.Blocks.variables_get){let e='<xml><block type="variables_get" gap="8">'+Blockly.Variables.generateVariableFieldXmlString(o)+"</block></xml>",t=Blockly.Xml.textToDom(e).firstChild;n.push(t)}}if(n[n.length-1].setAttribute("gap","24"),Blockly.Blocks.variables_set){let t='<xml><block type="variables_set" gap="'+(Blockly.Blocks.variables_change?8:24)+'">'+Blockly.Variables.generateVariableFieldXmlString(e)+"</block></xml>",o=Blockly.Xml.textToDom(t).firstChild;{let e=goog.dom.createDom("value");e.setAttribute("name","VALUE");let t=goog.dom.createDom("shadow");t.setAttribute("type","math_number"),e.appendChild(t);let n=goog.dom.createDom("field");n.setAttribute("name","NUM"),n.appendChild(document.createTextNode("0")),t.appendChild(n),o.appendChild(e)}n.push(o)}if(Blockly.Blocks.variables_change){let t='<xml><block type="variables_change" gap="'+(Blockly.Blocks.variables_get?20:8)+'">'+Blockly.Variables.generateVariableFieldXmlString(e)+"</block></xml>",o=Blockly.Xml.textToDom(t).firstChild;{let e=goog.dom.createDom("value");e.setAttribute("name","VALUE");let t=goog.dom.createDom("shadow");t.setAttribute("type","math_number"),e.appendChild(t);let n=goog.dom.createDom("field");n.setAttribute("name","NUM"),n.appendChild(document.createTextNode("1")),t.appendChild(n),o.appendChild(e)}n.push(o)}}return n};const n=Blockly.Msg,o="variables_get",r=e.blocks.getBlockDefinition(o);n.VARIABLES_GET_CREATE_SET=r.block.VARIABLES_GET_CREATE_SET,E(o);E("variables_get_reporter"),n.RENAME_VARIABLE=lf("Rename variable..."),n.DELETE_VARIABLE=lf('Delete the "%1" variable'),n.DELETE_VARIABLE_CONFIRMATION=lf('Delete %1 uses of the "%2" variable?'),n.NEW_VARIABLE_DROPDOWN=lf("New variable...");const i="variables_set",s=e.blocks.getBlockDefinition(i);n.VARIABLES_SET=s.block.VARIABLES_SET,n.VARIABLES_DEFAULT_NAME=t,n.VARIABLES_SET_CREATE_GET=lf("Create 'get %1'"),E(i);const a="variables_change",l=e.blocks.getBlockDefinition(a);Blockly.Blocks[a]={init:function(){this.jsonInit({message0:l.block.message0,args0:[{type:"field_variable",name:"VAR",variable:t},{type:"input_value",name:"VALUE",check:"Number"}],inputsInline:!0,previousStatement:null,nextStatement:null,colour:e.toolbox.getNamespaceColor("variables")}),T(this,a)},customContextMenu:function(e){if(!this.inDebugWorkspace()){let t={enabled:this.workspace.remainingCapacity()>0},n=this.getField("VAR").getText();t.text=lf("Create 'get {0}'",n);let o=goog.dom.createDom("field",null,n);o.setAttribute("name","VAR");let r=goog.dom.createDom("block",null,o);r.setAttribute("type","variables_get"),t.callback=Blockly.ContextMenu.callbackFactory(this,r),e.push(t)}}},n.NEW_VARIABLE_TITLE=lf("New variable name:"),n.RENAME_VARIABLE_TITLE=lf("Rename all '%1' variables to:")}(),function(){const n=Blockly.Msg;n.FUNCTION_CREATE_NEW=lf("Make a Function..."),n.FUNCTION_WARNING_DUPLICATE_ARG=lf("Functions cannot use the same argument name more than once."),n.FUNCTION_WARNING_ARG_NAME_IS_FUNCTION_NAME=lf("Argument names must not be the same as the function name."),n.FUNCTION_WARNING_EMPTY_NAME=lf("Function and argument names cannot be empty."),n.FUNCTIONS_DEFAULT_FUNCTION_NAME=lf("doSomething"),n.FUNCTIONS_DEFAULT_BOOLEAN_ARG_NAME=lf("bool"),n.FUNCTIONS_DEFAULT_STRING_ARG_NAME=lf("text"),n.FUNCTIONS_DEFAULT_NUMBER_ARG_NAME=lf("num"),n.FUNCTIONS_DEFAULT_CUSTOM_ARG_NAME=lf("arg"),n.PROCEDURES_HUE=e.toolbox.getNamespaceColor("functions"),n.REPORTERS_HUE=e.toolbox.getNamespaceColor("variables");const o="procedures_defnoreturn",r=e.blocks.getBlockDefinition(o);n.PROCEDURES_DEFNORETURN_TITLE=r.block.PROCEDURES_DEFNORETURN_TITLE,n.PROCEDURE_ALREADY_EXISTS=r.block.PROCEDURE_ALREADY_EXISTS,Blockly.Blocks.procedures_defnoreturn.init=function(){let t=new Blockly.FieldTextInput("",Blockly.Procedures.rename);this.appendDummyInput().appendField(Blockly.Msg.PROCEDURES_DEFNORETURN_TITLE).appendField(t,"NAME").appendField("","PARAMS"),this.setColour(e.toolbox.getNamespaceColor("functions")),this.arguments_=[],this.argumentVarModels_=[],this.setStartHat(!0),this.setStatements_(!0),this.statementConnection_=null},E(o);const i="procedures_callnoreturn",a=e.blocks.getBlockDefinition(i);n.PROCEDURES_CALLRETURN_TOOLTIP=r.tooltip.toString(),Blockly.Blocks.procedures_callnoreturn={init:function(){let t=new pxtblockly.FieldProcedure("");this.appendDummyInput("TOPROW").appendField(a.block.PROCEDURES_CALLNORETURN_TITLE).appendField(t,"NAME"),this.setPreviousStatement(!0),this.setNextStatement(!0),this.setColour(e.toolbox.getNamespaceColor("functions")),this.arguments_=[],this.quarkConnections_={},this.quarkIds_=null},getProcedureCall:function(){return this.getFieldValue("NAME")},renameProcedure:function(e,t){Blockly.Names.equals(e,this.getProcedureCall())&&this.setFieldValue(t,"NAME")},onchange:function(t){if(this.workspace&&!this.workspace.isFlyout&&!this.isInsertionMarker())if(t.type==Blockly.Events.CREATE&&-1!=t.ids.indexOf(this.id)){let n=this.getProcedureCall(),o=Blockly.Procedures.getDefinition(n,this.workspace);if(!o||o.type==this.defType_&&JSON.stringify(o.arguments_)==JSON.stringify(this.arguments_)||(o=null),!o){Blockly.Events.setGroup(t.group);let n=Blockly.utils.xml.createElement("xml"),o=Blockly.utils.xml.createElement("block");o.setAttribute("type",this.defType_);let r=this.getRelativeToSurfaceXY(),i=r.x+Blockly.SNAP_RADIUS*(this.RTL?-1:1),s=r.y+2*Blockly.SNAP_RADIUS;o.setAttribute("x",i),o.setAttribute("y",s);let a=Blockly.utils.xml.createElement("field");a.setAttribute("name","NAME"),a.appendChild(document.createTextNode(this.getProcedureCall())),o.appendChild(a),n.appendChild(o),e.blocks.domToWorkspaceNoEvents(n,this.workspace),Blockly.Events.setGroup(!1)}}else if(t.type==Blockly.Events.DELETE){let e=this.getProcedureCall();Blockly.Procedures.getDefinition(e,this.workspace)||(Blockly.Events.setGroup(t.group),this.dispose(!0,!1),Blockly.Events.setGroup(!1))}},mutationToDom:function(){const e=document.createElement("mutation");return e.setAttribute("name",this.getProcedureCall()),e},domToMutation:function(e){const t=e.getAttribute("name");this.renameProcedure(this.getProcedureCall(),t)},customContextMenu:function(e){let t={enabled:!0};t.text=Blockly.Msg.PROCEDURES_HIGHLIGHT_DEF;let n=this.getProcedureCall(),o=this.workspace;t.callback=function(){let e=Blockly.Procedures.getDefinition(n,o);e&&e.select()},e.push(t)},defType_:"procedures_defnoreturn"},E(i);const l="function_definition",c=e.blocks.getBlockDefinition(l);n.FUNCTIONS_EDIT_OPTION=c.block.FUNCTIONS_EDIT_OPTION,E(l);const u="function_call",p=e.blocks.getBlockDefinition(u);n.FUNCTIONS_CALL_TITLE=p.block.FUNCTIONS_CALL_TITLE,n.FUNCTIONS_GO_TO_DEFINITION_OPTION=p.block.FUNCTIONS_GO_TO_DEFINITION_OPTION,E(u),E("function_call_output");const g="function_return";Blockly.Blocks[g]={init:function(){t.initReturnStatement(this)},onchange:function(e){const t=this;if(!t.workspace||t.workspace.isFlyout)return;const n=e.type===Blockly.Events.BLOCK_CREATE&&-1!=e.ids.indexOf(t.id),o=e.type===Blockly.Events.END_DRAG&&-1!=e.allNestedIds.indexOf(t.id);if(n||o){const n=t.getRootBlock();if(n.type===g||null!=n.previousConnection)return;n.type!==l&&(Blockly.Events.setGroup(e.group),t.previousConnection.disconnect(),Blockly.Events.setGroup(!1))}}},E(g),Blockly.Procedures.flyoutCategory=function(t){let n=[];if(!e.appTarget.appTheme.hideFlyoutHeadings){let t=d(lf("Functions"),e.toolbox.getNamespaceColor("functions"),e.toolbox.getNamespaceIcon("functions"),"blocklyFlyoutIconfunctions");n.push(t)}const o=lf("Make a Function..."),r=lf("New function name:");let i=Blockly.utils.xml.createElement("button");i.setAttribute("text",o),i.setAttribute("callbackKey","CREATE_FUNCTION");let s=n=>{let o=t.getTopBlocks(!0)[0],r=10,i=10;if(o){let e=o.getRelativeToSurfaceXY();r=e.x+Blockly.SNAP_RADIUS*(o.RTL?-1:1),i=e.y+2*Blockly.SNAP_RADIUS}let s=Blockly.utils.xml.createElement("xml"),a=Blockly.utils.xml.createElement("block");a.setAttribute("type","procedures_defnoreturn"),a.setAttribute("x",String(r)),a.setAttribute("y",String(i));let l=Blockly.utils.xml.createElement("field");l.setAttribute("name","NAME"),l.appendChild(document.createTextNode(n)),a.appendChild(l),s.appendChild(a);let c=e.blocks.domToWorkspaceNoEvents(s,t);Blockly.hideChaff();let u=t.getBlockById(c[0]);u.select(),t.centerOnBlock(u.id)};function a(t,o){for(let r=0;r<t.length;r++){let i=t[r][0],s=(t[r][1],Blockly.utils.xml.createElement("block"));s.setAttribute("type",o),s.setAttribute("gap","16"),s.setAttribute("colour",e.toolbox.getNamespaceColor("functions"));let a=goog.dom.createDom("field",null,i);a.setAttribute("name","NAME"),s.appendChild(a),n.push(s)}}return t.registerButtonCallback("CREATE_FUNCTION",(function(n){let i=n=>{Blockly.prompt(r,n,(function(n){e.tickEvent("blocks.makeafunction"),n&&(n=n.replace(/[\s\xa0]+/g," ").replace(/^ | $/g,""))==o&&(n=null),n&&(t.getVariable(n)?Blockly.alert(Blockly.Msg.VARIABLE_ALREADY_EXISTS.replace("%1",n.toLowerCase()),(function(){i(n)})):Blockly.Procedures.isLegalName_(n,t)?s(n):Blockly.alert(Blockly.Msg.PROCEDURE_ALREADY_EXISTS.replace("%1",n.toLowerCase()),(function(){i(n)})))}))};i("doSomething")})),n.push(i),a(Blockly.Procedures.allProcedures(t)[0],"procedures_callnoreturn"),n};const h=Blockly.Functions.flyoutCategory;Blockly.Functions.flyoutCategory=t=>{const n=h(t);if(n.length>1){let e=A();n.splice(1,0,e)}const o=Blockly.Functions.getAllFunctionDefinitionBlocks(t).filter((e=>e.getDescendants(!1).some((e=>"function_return"===e.type&&e.getInputTargetBlock("RETURN_VALUE"))))).map((e=>e.getField("function_name").getText())),r=d(lf("Functions"),e.toolbox.getNamespaceColor("functions"),e.toolbox.getNamespaceIcon("functions"),"blocklyFlyoutIconfunctions");n.unshift(r);const i=[];for(const e of n)if(i.push(e),"function_call"===e.getAttribute("type")){const t=e.children.item(0);if(t){const n=t.getAttribute("name");if(o.some((e=>e===n))){const t=e.cloneNode(!0);t.setAttribute("type","function_call_output"),i.push(t)}}}return i};const f={number:e.blocks.defaultIconForArgType("number"),boolean:e.blocks.defaultIconForArgType("boolean"),string:e.blocks.defaultIconForArgType("string"),Array:e.blocks.defaultIconForArgType("Array")},_={},m=e.appTarget.runtime&&e.appTarget.runtime.functionsOptions;m&&m.extraFunctionEditorTypes&&m.extraFunctionEditorTypes.forEach((t=>{f[t.typeName]=t.icon||e.blocks.defaultIconForArgType(),t.defaultName&&(_[t.typeName]=t.defaultName)}));Blockly.PXTBlockly.FunctionUtils.argumentIcons=f,Blockly.PXTBlockly.FunctionUtils.argumentDefaultNames=_,Blockly.Blocks.argument_reporter_custom&&(Blockly.Blocks.argument_reporter_custom.domToMutation=function(e){const t=e.getAttribute("typename");this.typeName_=t,v(this,t,s)});const y=Blockly.Functions.makeCreateCallOption;Blockly.Msg.FUNCTIONS_CREATE_CALL_OPTION="",Blockly.Functions.makeCreateCallOption=function(t){let n=y(t),o=t.getField("function_name").getText();return n.text=e.Util.lf("Create 'call {0}'",o),n}}(),function(){const t=Blockly.Msg,n="lists_create_with",o=e.blocks.getBlockDefinition(n);t.LISTS_CREATE_EMPTY_TITLE=o.block.LISTS_CREATE_EMPTY_TITLE,t.LISTS_CREATE_WITH_INPUT_WITH=o.block.LISTS_CREATE_WITH_INPUT_WITH,t.LISTS_CREATE_WITH_CONTAINER_TITLE_ADD=o.block.LISTS_CREATE_WITH_CONTAINER_TITLE_ADD,t.LISTS_CREATE_WITH_ITEM_TITLE=o.block.LISTS_CREATE_WITH_ITEM_TITLE,E(n);const r="lists_length",i=e.blocks.getBlockDefinition(r);t.LISTS_LENGTH_TITLE=i.block.LISTS_LENGTH_TITLE,Blockly.Blocks[r].init=function(){this.jsonInit({message0:t.LISTS_LENGTH_TITLE,args0:[{type:"input_value",name:"VALUE",check:["Array"]}],output:"Number",outputShape:Blockly.OUTPUT_SHAPE_ROUND})},E(r)}(),function(){const t=Blockly.Msg,n="controls_repeat_ext",o=e.blocks.getBlockDefinition(n);t.CONTROLS_REPEAT_TITLE=o.block.CONTROLS_REPEAT_TITLE,t.CONTROLS_REPEAT_INPUT_DO=o.block.CONTROLS_REPEAT_INPUT_DO,E(n);const r="device_while",i=e.blocks.getBlockDefinition(r);Blockly.Blocks[r]={init:function(){this.jsonInit({message0:i.block.message0,args0:[{type:"input_value",name:"COND",check:"Boolean"}],previousStatement:null,nextStatement:null,colour:e.toolbox.getNamespaceColor("loops")}),this.appendStatementInput("DO").appendField(i.block.appendField),T(this,r)}};const s="pxt_controls_for",a=e.blocks.getBlockDefinition(s);Blockly.Blocks[s]={init:function(){this.jsonInit({message0:a.block.message0,args0:[{type:"input_value",name:"VAR",variable:a.block.variable,check:"Variable"},{type:"input_value",name:"TO",check:"Number"}],previousStatement:null,nextStatement:null,colour:e.toolbox.getNamespaceColor("loops"),inputsInline:!0}),this.appendStatementInput("DO").appendField(a.block.appendField);let t=this;S(this,s,a.name,(function(){return e.U.rlf(a.tooltip,t.getInputTargetBlock("VAR")?t.getInputTargetBlock("VAR").getField("VAR").getText():"")}),a.url,String(e.toolbox.getNamespaceColor("loops")))},getVars:function(){return[this.getField("VAR").getText()]},renameVar:function(e,t){const n=this.getField("VAR");Blockly.Names.equals(e,n.getText())&&n.setValue(t)}};const l="controls_simple_for",c=e.blocks.getBlockDefinition(l);Blockly.Blocks[l]={init:function(){this.jsonInit({message0:c.block.message0,args0:[{type:"field_variable",name:"VAR",variable:c.block.variable},{type:"input_value",name:"TO",check:"Number"}],previousStatement:null,nextStatement:null,colour:e.toolbox.getNamespaceColor("loops"),inputsInline:!0}),this.appendStatementInput("DO").appendField(c.block.appendField);let t=this;S(this,l,c.name,(function(){return e.U.rlf(c.tooltip,t.getField("VAR").getText())}),c.url,String(e.toolbox.getNamespaceColor("loops")))},getVars:function(){return[this.getField("VAR").getText()]},renameVar:function(e,t){const n=this.getField("VAR");Blockly.Names.equals(e,n.getText())&&n.setValue(t)},customContextMenu:function(e){if(!this.isCollapsed()&&!this.inDebugWorkspace()){let t={enabled:!0},n=this.getField("VAR").getText();t.text=lf("Create 'get {0}'",n);let o=goog.dom.createDom("field",null,n);o.setAttribute("name","VAR");let r=goog.dom.createDom("block",null,o);r.setAttribute("type","variables_get"),t.callback=Blockly.ContextMenu.callbackFactory(this,r),e.push(t)}}};const u=e.blocks.getBlockDefinition(ts.pxtc.TS_BREAK_TYPE);Blockly.Blocks[pxtc.TS_BREAK_TYPE]={init:function(){const t=e.toolbox.getNamespaceColor("loops");this.jsonInit({message0:u.block.message0,inputsInline:!0,previousStatement:null,nextStatement:null,colour:t}),S(this,ts.pxtc.TS_BREAK_TYPE,u.name,u.tooltip,u.url,t,void 0,void 0,!1)}};const d=e.blocks.getBlockDefinition(ts.pxtc.TS_CONTINUE_TYPE);Blockly.Blocks[pxtc.TS_CONTINUE_TYPE]={init:function(){const t=e.toolbox.getNamespaceColor("loops");this.jsonInit({message0:d.block.message0,inputsInline:!0,previousStatement:null,nextStatement:null,colour:t}),S(this,ts.pxtc.TS_CONTINUE_TYPE,d.name,d.tooltip,d.url,t,void 0,void 0,!1)}};const p="#cccccc";Blockly.Blocks[pxtc.COLLAPSED_BLOCK]={init:function(){this.jsonInit({message0:"...",inputsInline:!0,previousStatement:null,nextStatement:null,colour:p}),S(this,ts.pxtc.COLLAPSED_BLOCK,"...",lf("a few blocks"),void 0,p,void 0,void 0,!1)}}}(),function(){const t=Blockly.Msg,n="controls_if",o=e.blocks.getBlockDefinition(n),r=o.tooltip;t.CONTROLS_IF_MSG_IF=o.block.CONTROLS_IF_MSG_IF,t.CONTROLS_IF_MSG_THEN=o.block.CONTROLS_IF_MSG_THEN,t.CONTROLS_IF_MSG_ELSE=o.block.CONTROLS_IF_MSG_ELSE,t.CONTROLS_IF_MSG_ELSEIF=o.block.CONTROLS_IF_MSG_ELSEIF,t.CONTROLS_IF_TOOLTIP_1=r.CONTROLS_IF_TOOLTIP_1,t.CONTROLS_IF_TOOLTIP_2=r.CONTROLS_IF_TOOLTIP_2,t.CONTROLS_IF_TOOLTIP_3=r.CONTROLS_IF_TOOLTIP_3,t.CONTROLS_IF_TOOLTIP_4=r.CONTROLS_IF_TOOLTIP_4,E(n);const i="logic_compare",s=e.blocks.getBlockDefinition(i).tooltip;t.LOGIC_COMPARE_TOOLTIP_EQ=s.LOGIC_COMPARE_TOOLTIP_EQ,t.LOGIC_COMPARE_TOOLTIP_NEQ=s.LOGIC_COMPARE_TOOLTIP_NEQ,t.LOGIC_COMPARE_TOOLTIP_LT=s.LOGIC_COMPARE_TOOLTIP_LT,t.LOGIC_COMPARE_TOOLTIP_LTE=s.LOGIC_COMPARE_TOOLTIP_LTE,t.LOGIC_COMPARE_TOOLTIP_GT=s.LOGIC_COMPARE_TOOLTIP_GT,t.LOGIC_COMPARE_TOOLTIP_GTE=s.LOGIC_COMPARE_TOOLTIP_GTE,E(i);const a="logic_operation",l=e.blocks.getBlockDefinition(a),c=l.tooltip;t.LOGIC_OPERATION_AND=l.block.LOGIC_OPERATION_AND,t.LOGIC_OPERATION_OR=l.block.LOGIC_OPERATION_OR,t.LOGIC_OPERATION_TOOLTIP_AND=c.LOGIC_OPERATION_TOOLTIP_AND,t.LOGIC_OPERATION_TOOLTIP_OR=c.LOGIC_OPERATION_TOOLTIP_OR,E(a);const u="logic_negate",d=e.blocks.getBlockDefinition(u);t.LOGIC_NEGATE_TITLE=d.block.LOGIC_NEGATE_TITLE,E(u);const p="logic_boolean",g=e.blocks.getBlockDefinition(p);t.LOGIC_BOOLEAN_TRUE=g.block.LOGIC_BOOLEAN_TRUE,t.LOGIC_BOOLEAN_FALSE=g.block.LOGIC_BOOLEAN_FALSE,E(p)}(),function(){const t=e.blocks.getBlockDefinition("text");C("text",t.name,t.tooltip,t.url,Blockly.Colours.textField,Blockly.Colours.textField,Blockly.Colours.textField);const n=Blockly.Msg,o="text_length",r=e.blocks.getBlockDefinition(o);n.TEXT_LENGTH_TITLE=r.block.TEXT_LENGTH_TITLE,Blockly.Blocks[o].init=function(){this.jsonInit({message0:n.TEXT_LENGTH_TITLE,args0:[{type:"input_value",name:"VALUE",check:["String"]}],output:"Number",outputShape:Blockly.OUTPUT_SHAPE_ROUND})},E(o);const i="text_join",s=e.blocks.getBlockDefinition(i);n.TEXT_JOIN_TITLE_CREATEWITH=s.block.TEXT_JOIN_TITLE_CREATEWITH,E(i)}(),function(){const t=(e,t)=>Math.abs(t-(e.left+e.width/2)),n=Blockly.BlockDragger.prototype.drag;Blockly.BlockDragger.prototype.drag=function(o,r){const i=document.getElementsByClassName("blocklyToolboxDiv")[0],s=document.getElementsByClassName("blocklyTreeRoot")[0]||document.getElementsByClassName("blocklyFlyout")[0],a=document.getElementById("blocklyTrashIcon");if(s&&a){const n=t(s.getBoundingClientRect(),o.clientX);if(n<200){const t=n/200;a.style.opacity=""+(1-t),a.style.display="block",i&&(s.style.opacity=`${t}`,n<50&&e.BrowserUtils.addClass(i,"blocklyToolboxDeleting"))}else a.style.display="none",s.style.opacity="1",i&&e.BrowserUtils.removeClass(i,"blocklyToolboxDeleting")}return n.call(this,o,r)};const o=Blockly.BlockDragger.prototype.endDrag;Blockly.BlockDragger.prototype.endDrag=function(t,n){o.call(this,t,n);const r=document.getElementsByClassName("blocklyToolboxDiv")[0],i=document.getElementsByClassName("blocklyTreeRoot")[0]||document.getElementsByClassName("blocklyFlyout")[0],s=document.getElementById("blocklyTrashIcon");s&&i&&(s.style.display="none",i.style.opacity="1",r&&e.BrowserUtils.removeClass(r,"blocklyToolboxDeleting"))}}(),Blockly.Blocks[pxtc.TS_DEBUGGER_TYPE]={init:function(){let t=this;t.setColour(e.toolbox.getNamespaceColor("debug")),t.setPreviousStatement(!0),t.setNextStatement(!0),t.setInputsInline(!1),t.appendDummyInput("ON_OFF").appendField(new Blockly.FieldLabel(lf("breakpoint"),void 0),"DEBUGGER").appendField(new pxtblockly.FieldBreakpoint("1",{type:"number"}),"ON_OFF"),S(this,pxtc.TS_DEBUGGER_TYPE,lf("Debugger statement"),lf("A debugger statement invokes any available debugging functionality"),"/javascript/debugger",e.toolbox.getNamespaceColor("debug"))}},Blockly.Msg.WORKSPACE_COMMENT_DEFAULT_TEXT="",function(){const t=e=>{if(e.disabled)return lf("This block is disabled and will not run. Attach this block to an event to enable it.");let t=e.tooltip;for(;goog.isFunction(t);)t=t(e);return t};Blockly.Tooltip.show_=function(){const n=Blockly.Tooltip;if(n.poisonedElement_=n.element_,!Blockly.Tooltip.DIV)return;goog.dom.removeChildren(Blockly.Tooltip.DIV);function o(){let e=n.element_.RTL,t=goog.dom.getViewportSize(),o=Blockly.Tooltip.DIV;o.style.direction=e?"rtl":"ltr",o.style.display="block",Blockly.Tooltip.visible=!0;let r=n.lastX_;e?r-=Blockly.Tooltip.OFFSET_X+o.offsetWidth:r+=Blockly.Tooltip.OFFSET_X;let i=n.lastY_+Blockly.Tooltip.OFFSET_Y;i+o.offsetHeight>t.height+window.scrollY&&(i-=o.offsetHeight+2*Blockly.Tooltip.OFFSET_Y),e?r=Math.max(Blockly.Tooltip.MARGINS-window.scrollX,r):r+o.offsetWidth>t.width+window.scrollX-2*Blockly.Tooltip.MARGINS&&(r=t.width-o.offsetWidth-2*Blockly.Tooltip.MARGINS),o.style.top=i+"px",o.style.left=r+"px"}if(n.element_.codeCard){const r=e.docs.codeCard.render({header:t(n.element_)});Blockly.Tooltip.DIV.appendChild(r),o()}else{let e=t(n.element_);e=Blockly.utils._string.wrap(e,Blockly.Tooltip.LIMIT);let r=e.split("\n");for(let e=0;e<r.length;e++){let t=document.createElement("div");t.appendChild(document.createTextNode(r[e])),Blockly.Tooltip.DIV.appendChild(t)}o()}}}(),Blockly.Block.prototype.setEnabled=function(e){if(this.disabled==e){let t=Blockly.Events.recordUndo;Blockly.Events.recordUndo=!1,Blockly.Events.fire(new Blockly.Events.BlockChange(this,"disabled",null,this.disabled,!e)),Blockly.Events.recordUndo=t,this.disabled=!e}})}function b(e,t){const n=e.split(/\s*\|\s*/),r=[];for(const e of n)switch(e){case"number":r.push("Number");break;case"string":r.push("String");break;case"boolean":r.push("Boolean");break;case"T":case"any":return null;case"void":return;default:if(o(e)){if(n.length>1)return null;r.push("Array")}const i=t.apis.byQName[e];i&&i.extendsTypes&&0<i.extendsTypes.length?r.push(...i.extendsTypes):r.push(e)}return r}function v(e,t,n){const o=b(t,n);(o||null===o)&&e.setOutput(!0,o)}function T(t,n){const o=e.blocks.getBlockDefinition(n);S(t,n,o.name,o.tooltip,o.url,e.toolbox.getNamespaceColor(o.category))}function E(t){const n=e.blocks.getBlockDefinition(t);C(t,n.name,n.tooltip,n.url,e.toolbox.getNamespaceColor(n.category))}function S(n,o,r,i,s,a,l,c,u){!i||"string"!=typeof i&&"function"!=typeof i||n.setTooltip(i),s&&n.setHelpUrl(s),a&&n.setColour(a,l,c),u&&n.setDeletable(!1);let d=document.getElementById("blocklyToolboxDefinition"),p=d?t.getFirstChildWithAttr(d,"block","type",o):void 0;n.codeCard={header:r,name:r,software:1,description:goog.isFunction(i)?i(n):i,blocksXml:p?'<xml xmlns="http://www.w3.org/1999/xhtml">'+(f(p)||`<block type="${o}"></block>`)+"</xml>":void 0,url:s},e.Util.isTranslationMode()&&e.blocks.promptTranslateBlock&&(n.customContextMenu=t=>{const r=e.blocks.getBlockDefinition(n.type);r&&r.translationIds&&t.push({enabled:!0,text:lf("Translate this block"),callback:function(){e.blocks.promptTranslateBlock(o,r.translationIds)}})})}function C(e,t,n,o,r,i,s){let a=Blockly.Blocks[e],l=a.init;l&&(a.init=function(){l.call(this);S(this,e,t,n,o,r,i,s)})}function x(e){delete Blockly.Blocks[e.attributes.blockId],delete l[e.attributes.blockId]}function B(t,n,o,r){const i=document.createElement(r?"shadow":"block");i.setAttribute("type",e.Util.htmlEscape(t));const s=document.createElement("field");return s.setAttribute("name",e.Util.htmlEscape(n)),s.textContent=e.Util.htmlEscape(o),i.appendChild(s),i}function A(){const e=document.createElement("block");e.setAttribute("type","function_return");const t=document.createElement("value");t.setAttribute("name","RETURN_VALUE"),e.appendChild(t);const n=B("math_number","NUM","0",!0);return t.appendChild(n),e}t.installHelpResources=C,t.onShowContextMenu=void 0,t.mkPredicateBlock=function(e){const t=document.createElement("block");t.setAttribute("type",e);const n=document.createElement("value");n.setAttribute("name","PREDICATE"),t.appendChild(n);const o=B("logic_boolean","BOOL","TRUE",!0);return n.appendChild(o),t},t.mkFieldBlock=B,t.mkReturnStatementBlock=A;let I={};function D(e,t){return{field:e,name:t}}function N(t,n){return e.Util.values(t.byQName).filter((e=>4===e.kind&&e.attributes.fixedInstance&&function(e,t,n){if(t==n)return!0;let o=e.byQName[t];return!(!o||!o.extendsTypes)&&o.extendsTypes.indexOf(n)>=0}(t,e.retType,n)))}function w(e){return e.data?/^(?:\d+;?)+$/.test(e.data)?{commentRefs:e.data.split(";"),fieldData:{}}:JSON.parse(e.data):{commentRefs:[],fieldData:{}}}function R(e,t){e.data=JSON.stringify(t)}t.getFixedInstanceDropdownValues=N,t.generateIcons=function(t){const n=new e.ImageConverter;t.forEach((t=>{t.attributes.jresURL&&!t.attributes.iconURL&&e.U.startsWith(t.attributes.jresURL,"data:image/x-mkcd-f")&&(t.attributes.iconURL=n.convert(t.attributes.jresURL))}))},t.setVarFieldValue=function(e,t,n){const o=e.getField(t),r=e.workspace.getAllVariables();let i=!1;if(r&&r.length)for(let e=0;e<r.length;e++){const t=r[e];t.name===n&&(o.setValue(t.getId()),i=!0)}if(!i){o.initModel();const e=o.getVariable();e.name=n,o.setValue(e.getId())}},t.getBlockData=w,t.setBlockData=R,t.setBlockDataForField=function(e,t,n){const o=w(e);o.fieldData[t]=n,R(e,o)},t.getBlockDataForField=function(e,t){return w(e).fieldData[t]};class O extends WorkspaceSearch{createDom_(){super.createDom_(),this.addEvent_(this.workspace_.getInjectionDiv(),"click",this,(e=>{this.htmlDiv_.contains(e.target)||this.close()}))}highlightSearchGroup_(e){e.forEach((e=>{const t=e.pathObject.svgPath;Blockly.utils.dom.addClass(t,"blockly-ws-search-highlight-pxt")}))}unhighlightSearchGroup_(e){e.forEach((e=>{const t=e.pathObject.svgPath;Blockly.utils.dom.removeClass(t,"blockly-ws-search-highlight-pxt")}))}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")}}t.PxtWorkspaceSearch=O}(e.blocks||(e.blocks={}))}(pxt||(pxt={})),function(e){!function(t){let n;!function(e){e.ObjectDestructuringMutator="objectdestructuring",e.RestParameterMutator="restparameter",e.DefaultInstanceMutator="defaultinstance"}(n=t.MutatorTypes||(t.MutatorTypes={})),t.addMutation=function(e,t,o){let a;switch(o){case n.ObjectDestructuringMutator:if(!t.parameters||t.parameters.length<1)console.error("Destructuring mutations require at least one parameter");else{let e=!1;for(const n of t.parameters)if(-1!==n.type.indexOf("=>")){if(!n.properties||0===n.properties.length)return void console.error("Destructuring mutations only supported for functions with an event parameter that has multiple properties");e=!0}if(!e)return void console.error("Destructuring mutations must have an event parameter")}a=new r(e,t);break;case n.RestParameterMutator:a=new i(e,t);break;case n.DefaultInstanceMutator:a=new s(e,t);break;default:return void console.warn("Ignoring unknown mutation type: "+o)}e.mutationToDom=a.mutationToDom.bind(a),e.domToMutation=a.domToMutation.bind(a),e.compose=a.compose.bind(a),e.decompose=a.decompose.bind(a),e.mutation=a},t.mutateToolboxBlock=function(e,t,o){const a=document.createElement("mutation");switch(t){case n.ObjectDestructuringMutator:a.setAttribute(r.propertiesAttributeName,o);break;case n.RestParameterMutator:a.setAttribute(i.countAttributeName,o);break;case n.DefaultInstanceMutator:a.setAttribute(s.attributeName,o);default:return void console.warn("Ignoring unknown mutation type: "+t)}e.appendChild(a)};class o{constructor(e,t){this.info=t,this.block=e,this.topBlockType=this.block.type+"_mutator";const n=this.getSubBlockNames();this.initializeMutatorTopBlock(),this.initializeMutatorSubBlocks(n);const o=n.map((e=>e.type));this.block.setMutator(new Blockly.Mutator(o))}compose(e){const t=e.getDescendants(!1).map((e=>({type:e.type,name:e.inputList[0].name})));t.shift(),this.updateBlock(t)}decompose(e){const t=e.newBlock(this.topBlockType);t.initSvg();for(const n of t.inputList)if(n.name===o.mutatorStatmentInput){let t=n.connection;this.getVisibleBlockTypes().forEach((n=>{const o=e.newBlock(n);o.initSvg(),t.connect(o.previousConnection),t=o.nextConnection}));break}return t}compileMutation(e,t){}getDeclaredVariables(){}isDeclaredByMutation(e){return!1}initializeMutatorSubBlock(e,t,n){e.appendDummyInput(t).appendField(t),e.setColour(n),e.setNextStatement(!0),e.setPreviousStatement(!0)}initializeMutatorTopBlock(){const e=this.info.attributes.mutateText,t=this.block.getColour();Blockly.Blocks[this.topBlockType]=Blockly.Blocks[this.topBlockType]||{init:function(){const n=this;n.appendDummyInput().appendField(e),n.setColour(t),n.appendStatementInput(o.mutatorStatmentInput)}}}initializeMutatorSubBlocks(e){const t=this.block.getColour(),n=this.initializeMutatorSubBlock.bind(this);e.forEach((e=>{Blockly.Blocks[e.type]=Blockly.Blocks[e.type]||{init:function(){n(this,e.name,t)}}}))}}o.mutatorStatmentInput="PROPERTIES",o.mutatedVariableInputName="properties";class r extends o{constructor(e,t){super(e,t),this.currentlyVisible=[],this.parameterRenames={},this.prefix=this.info.attributes.mutatePrefix,this.block.appendDummyInput(o.mutatedVariableInputName),this.block.appendStatementInput("HANDLER").setCheck("null")}getMutationType(){return n.ObjectDestructuringMutator}compileMutation(e,n){if(!this.info.attributes.mutatePropertyEnum&&!this.parameters.length)return;const o=`function ({ ${this.parameters.map((n=>{const o=this.block.getField(n),r=o&&o.getText(),i=t.escapeVarName(n,e);return r!==n?(this.parameterRenames[n]=r,`${n}: ${t.escapeVarName(r,e)}`):i})).join(", ")} })`;return this.info.attributes.mutatePropertyEnum?t.mkText(` [${this.parameters.map((e=>`${this.info.attributes.mutatePropertyEnum}.${e}`)).join(", ")}],${o}`):t.mkText(o)}getDeclaredVariables(){const e={};return this.parameters.forEach((t=>{e[this.getVarFieldValue(t)]=this.parameterTypes[t]})),e}isDeclaredByMutation(e){return this.parameters.some((t=>this.getVarFieldValue(t)===e))}mutationToDom(){const t=document.createElement("mutation"),n=this.parameters.map((t=>{const n=this.getVarFieldValue(t);return n!==t&&(this.parameterRenames[t]=e.Util.htmlEscape(n)),e.Util.htmlEscape(t)})).join(",");t.setAttribute(r.propertiesAttributeName,n);for(const e in this.parameterRenames)e===this.parameterRenames[e]&&delete this.parameterRenames[e];return t.setAttribute(r.renameAttributeName,JSON.stringify(this.parameterRenames)),t}domToMutation(e){const t=e.getAttribute(r.propertiesAttributeName);if(t){const n=t.split(","),o=[];if(void 0===this.paramIndex&&(this.paramIndex=this.getParameterIndex()),n.forEach((e=>{const t=e.split(":");this.info.parameters[this.paramIndex].properties.some((e=>e.name===t[0]))&&o.push({property:t[0],newName:t[1]})})),this.parameterRenames=void 0,e.hasAttribute(r.renameAttributeName))try{this.parameterRenames=JSON.parse(e.getAttribute(r.renameAttributeName))}catch(e){console.warn("Ignoring invalid rename map in saved block mutation")}this.parameterRenames=this.parameterRenames||{},this.parameters=[],o.forEach((e=>{this.parameters.push(e.property),e.newName&&e.newName!==e.property&&(this.parameterRenames[e.property]=e.newName)})),this.updateVisibleProperties(),o.filter((e=>!!e.newName)).forEach((e=>this.setVarFieldValue(e.property,e.newName)))}}getVarFieldValue(e){const t=this.block.getField(e);return t&&t.getText()}setVarFieldValue(e,n){this.block.getField(e);this.block.getField(e)&&t.setVarFieldValue(this.block,e,n)}updateBlock(e){this.parameters=[],e.forEach((e=>{-1===this.parameters.indexOf(e.name)&&this.parameters.push(e.name)})),this.updateVisibleProperties()}getSubBlockNames(){return this.parameters=[],this.parameterTypes={},void 0===this.paramIndex&&(this.paramIndex=this.getParameterIndex()),this.info.parameters[this.paramIndex].properties.map((e=>(this.parameterTypes[e.name]=e.type,{type:this.propertyId(e.name),name:e.name})))}getVisibleBlockTypes(){return this.currentlyVisible.map((e=>this.propertyId(e)))}updateVisibleProperties(){if(e.Util.listsEqual(this.currentlyVisible,this.parameters))return;const t=this.block.inputList.find((e=>e.name===o.mutatedVariableInputName));this.prefix&&0===this.currentlyVisible.length&&t.appendField(this.prefix,r.prefixLabel),this.currentlyVisible.forEach((e=>{if(-1===this.parameters.indexOf(e)){const n=this.getVarFieldValue(e);n!==e&&(this.parameterRenames[e]=n),t.removeField(e)}})),this.parameters.forEach((e=>{if(-1===this.currentlyVisible.indexOf(e)){const n=this.parameterRenames[e]||e;t.appendField(new Blockly.FieldVariable(n),e)}})),this.prefix&&0===this.parameters.length&&t.removeField(r.prefixLabel),this.currentlyVisible=this.parameters}propertyId(e){return this.block.type+"_"+e}getParameterIndex(){for(let e=0;e<this.info.parameters.length;e++)if(-1!==this.info.parameters[e].type.indexOf("=>"))return e}}r.propertiesAttributeName="callbackproperties",r.renameAttributeName="renamemap",r.prefixLabel="0prefix_label_";class i extends o{constructor(){super(...arguments),this.count=0}getMutationType(){return n.RestParameterMutator}compileMutation(e,n){const o=[];return this.forEachInput((r=>o.push(t.compileExpression(e,r,n)))),t.mkGroup(o)}mutationToDom(){const e=document.createElement("mutation");return e.setAttribute(i.countAttributeName,this.count.toString()),e}domToMutation(e){const t=e.getAttribute(i.countAttributeName);if(t){try{this.count=parseInt(t)}catch(e){return}for(let e=0;e<this.count;e++)this.addNumberField(!1,e)}}updateBlock(e){if(e){const t=Math.abs(this.count-e.length);if(this.count<e.length)for(let e=0;e<t;e++)this.addNumberField(!0,this.count);else if(this.count>e.length)for(let e=0;e<t;e++)this.removeNumberField()}}getSubBlockNames(){return[{name:"Value",type:i.entryTypeName}]}getVisibleBlockTypes(){const e=[];return this.forEachInput((()=>e.push(i.entryTypeName))),e}addNumberField(e,t){const n=this.block.appendValueInput(i.valueInputPrefix+t).setCheck("Number");if(e){const e=this.block.workspace.newBlock("math_number");e.initSvg(),e.setShadow(!0),n.connection.connect(e.outputConnection),this.block.workspace.render(),this.count++}}removeNumberField(){this.count>0&&this.block.removeInput(i.valueInputPrefix+(this.count-1)),this.count--}forEachInput(e){for(let t=0;t<this.count;t++)e(this.block.getInputTargetBlock(i.valueInputPrefix+t),t)}}i.countAttributeName="count",i.entryTypeName="entry",i.valueInputPrefix="value_input_";class s extends o{constructor(){super(...arguments),this.showing=!1}getMutationType(){return n.DefaultInstanceMutator}compileMutation(e,n){if(this.showing){const o=this.block.getInputTargetBlock(s.instanceInputName);if(o)return t.compileExpression(e,o,n)}}mutationToDom(){const e=document.createElement("mutation");return e.setAttribute(s.attributeName,this.showing?"true":"false"),e}domToMutation(e){const t=e.getAttribute(s.attributeName);t?this.updateShape("true"===t):this.updateShape(!1)}updateBlock(e){this.updateShape(!(!e||!e.length))}getSubBlockNames(){return[{name:"Instance",type:s.instanceSubBlockType}]}getVisibleBlockTypes(){const e=[];return this.showing&&e.push(s.instanceSubBlockType),e}updateShape(e){this.showing!==e&&(e&&!this.block.getInputTargetBlock(s.instanceInputName)?this.block.appendValueInput(s.instanceInputName):this.block.removeInput(s.instanceInputName),this.showing=e)}}s.attributeName="showing",s.instanceInputName="__instance__",s.instanceSubBlockType="instance"}(e.blocks||(e.blocks={}))}(pxt||(pxt={})),function(e){!function(t){let n,o,r;function i(){return n||(o=document.createElement("div"),o.style.position="absolute",o.style.top="0",o.style.left="0",o.style.width="1px",o.style.height="1px",document.body.appendChild(o),n=Blockly.inject(o,{move:{scrollbars:!1},readOnly:!0,sounds:!1,media:e.webConfig.commitCdnUrl+"blockly/media/",rtl:e.Util.isUserLanguageRtl(),renderer:"pxt"})),e.blocks.clearWithoutEvents(n),n}function s(){n&&n.dispose(),n=void 0}function a(t={emPixels:18,layout:r.Align}){switch(t.splitSvg?r.Align:t.layout||r.Flow){case r.Align:e.blocks.layout.verticalAlign(n,t.emPixels||18);break;case r.Flow:e.blocks.layout.flow(n,{ratio:t.aspectRatio,useViewWidth:t.useViewWidth});break;case r.Clean:n.cleanUp_&&n.cleanUp_()}let i=n.getMetrics();const s=o.querySelectorAll("svg")[0].cloneNode(!0);return e.blocks.layout.cleanUpBlocklySvg(s),e.U.toArray(s.querySelectorAll(".blocklyBlockCanvas,.blocklyBubbleCanvas")).forEach((e=>e.setAttribute("transform",`translate(${-i.contentLeft}, ${-i.contentTop}) scale(1)`))),s.setAttribute("viewBox",`0 0 ${i.contentWidth} ${i.contentHeight}`),t.emPixels&&(s.style.width=i.contentWidth/t.emPixels+"em",s.style.height=i.contentHeight/t.emPixels+"em"),t.splitSvg?e.blocks.layout.splitSvg(s,n,t.emPixels):s}!function(e){e[e.None=0]="None",e[e.Align=1]="Align",e[e.Clean=3]="Clean",e[e.Flow=4]="Flow"}(r=t.BlockLayout||(t.BlockLayout={})),t.initRenderingWorkspace=i,t.cleanRenderingWorkspace=s,t.renderWorkspace=a,t.render=function(t,o={emPixels:18,layout:r.Align}){i();try{let r=t||'<xml xmlns="http://www.w3.org/1999/xhtml"></xml>',i=Blockly.Xml.textToDom(r);return e.blocks.domToWorkspaceNoEvents(i,n),a(o)}catch(t){return void e.reportException(t)}finally{s()}},t.blocksMetrics=function(e){const t=e.getTopBlocks(!1);if(!t.length)return{width:0,height:0};let n;return t.forEach((e=>{const t=e.getBoundingRectangle();n?(n.l=Math.min(n.l,t.left),n.r=Math.max(n.r,t.right),n.t=Math.min(n.t,t.top),n.b=Math.min(n.b,t.bottom)):n={l:t.left,r:t.right,t:t.top,b:t.bottom}})),{width:n.r-n.l,height:n.b-n.t}}}(e.blocks||(e.blocks={}))}(pxt||(pxt={})),function(e){!function(e){function t(e,t){let o=[];for(const r in e.children){const i=e.children[r];if("block"===i.tagName)if(t){const e=i.getAttribute("type");e&&e===t&&o.push(i)}else o.push(i);else{const e=n(i);e&&(o=o.concat(e))}}return o}function n(e,n){let o=t(e,n);return o.length?o[0]:null}e.findRootBlocks=t,e.findRootBlock=n}(e.blocks||(e.blocks={}))}(pxt||(pxt={})),function(e){!function(t){!function(t){t.render=function(t,n={}){const o=t.url?/^[^:]+:\/\//.test(t.url)?t.url:"/"+t.url.replace(/^\.?\/?/,""):t.youTubeId?`https://youtu.be/${t.youTubeId}`:void 0,r=!!o,i=(e,t,n="div",o="")=>{let r=document.createElement(n);return t&&(r.className=t),e&&e.appendChild(r),o&&r.appendChild(document.createTextNode(o+"")),r};let s=i(null,"ui "+(t.style||"card")+" "+(t.color||"")+(r?" link":""),r?"a":"div");if(s.setAttribute("role","option"),s.setAttribute("aria-selected","true"),r){const e=s;e.href=o,/^https?:\/\//.test(o)&&(e.target="_blank")}if(!n.hideHeader&&t.header){let e=i(s,"ui content "+(t.responsive?" tall desktop only":""));t.header&&i(e,"description","span",t.header)}const a=(n.shortName?t.shortName:"")||t.name;let l=i(s,"ui image"+(t.responsive?" tall landscape only":""));if(t.label){let e=document.createElement("label");e.className=`ui ${t.labelClass?t.labelClass:"orange right ribbon"} label`,e.textContent=t.label,l.appendChild(e)}if(t.blocksXml){const n=e.blocks.render(t.blocksXml);if(n){let e=i(l,"");e.setAttribute("style","width:100%; min-height:10em"),e.appendChild(n)}else console.error("failed to render blocks"),e.debug(t.blocksXml)}if(t.typeScript){let e=document.createElement("pre");e.appendChild(document.createTextNode(t.typeScript)),l.appendChild(e)}if(t.imageUrl||(t.youTubeId?`https://img.youtube.com/vi/${t.youTubeId}/0.jpg`:void 0)){let e=document.createElement("div");e.className="ui imagewrapper";let n=document.createElement("div");n.className="ui cardimage",n.style.backgroundImage=`url("${t.imageUrl}")`,n.title=a,n.setAttribute("role","presentation"),e.appendChild(n),l.appendChild(e)}if("file"==t.cardType){let e=i(s,"ui fileimage");l.appendChild(e)}if(a||t.description){let e=i(s,"ui content");if(a&&(s.setAttribute("aria-label",a),i(e,"header","div",a)),t.description){const n=i(e,"ui description"),o=t.description.split(".")[0]+".";n.appendChild(document.createTextNode(o))}}if(t.time){let n=i(s,"meta");if(t.time){i(n,"date","span").appendChild(document.createTextNode(e.Util.timeSince(t.time)))}}if(t.extracontent){i(s,"extra content","div").appendChild(document.createTextNode(t.extracontent))}return s}}(t.codeCard||(t.codeCard={}))}(e.docs||(e.docs={}))}(pxt||(pxt={})),function(e){!function(t){function n(e,t){const n=e,o=n.mutationToDom,r=n.domToMutation;n.mutationToDom=()=>{const e=o?o():document.createElement("mutation");return t.mutationToDom(e)},n.domToMutation=e=>{r&&r(e),t.domToMutation(e)}}t.appendMutation=n,t.initVariableArgsBlock=function(e,o){let r=0,i=0,s=e.appendDummyInput(),a=()=>{if(r!==i){if(r>i){const t=r-i;for(let n=0;n<t;n++){const t=o[i+n];s.insertFieldAt(s.fieldRow.length-1,new pxtblockly.FieldArgumentVariable(t.name),"HANDLER_"+t.name);const r=e;(null==r?void 0:r.initSvg)&&r.initSvg()}}else{let e=i-r;for(let t=0;t<e;t++){const e=o[i-t-1];s.removeField("HANDLER_"+e.name)}}r>=o.length?s.removeField("_HANDLER_ADD"):i>=o.length&&l(),i=r}};function l(){s.appendField(new Blockly.FieldImage(e.ADD_IMAGE_DATAURI,24,24,lf("Add argument"),(()=>{r=Math.min(r+1,o.length),a()}),!1),"_HANDLER_ADD")}Blockly.Extensions.apply("inline-svgs",e,!1),l(),n(e,{mutationToDom:t=>{t.setAttribute("numArgs",r.toString());for(let n=0;n<r;n++){const r=e.getField("HANDLER_"+o[n].name);let i=r&&r.getText();t.setAttribute("arg"+n,i)}return t},domToMutation:n=>{let i=parseInt(n.getAttribute("numargs"));r=Math.min(isNaN(i)?0:i,o.length),a();for(let i=0;i<r;i++){const r=n.getAttribute("arg"+i),s="HANDLER_"+o[i].name;e.getField(s)&&t.setVarFieldValue(e,s,r)}}})},t.initExpandableBlock=function(r,i,s,a,l,c){const u="0_add_button",d="0_rem_button",p="_expanded",g="_input_init",h=s.parameters.map((e=>e.name)),f=s.parameters.length,_=l?f:1,m=new o(i);function y(n,o=!1,l=!1){const c=E(n);if(!l&&!o&&c===m.getNumber(p))return;m.setValue(p,c);const u=c;if(!m.getBoolean(g)&&u>0&&(T(),!i.rendered))return;let d=0;for(let n=0;n<i.inputList.length;n++){const o=i.inputList[n];if(e.Util.startsWith(o.name,t.optionalDummyInputPrefix))S(o,d<u||u===f);else if(e.Util.startsWith(o.name,t.optionalInputWithFieldPrefix)||-1!==h.indexOf(o.name)){const e=d<u;if(S(o,e),e&&o.connection&&!o.connection.isConnected()&&!i.isInsertionMarker()){const e=a.definitionNameToParam[s.parameters[d].name];let n=t.createShadowValue(r,e);"value"===n.tagName.toLowerCase()&&(n=n.firstElementChild),Blockly.Events.disable();try{const e=Blockly.Xml.domToBlock(n,i.workspace);e&&o.connection.connect(e.outputConnection)}catch(e){}Blockly.Events.enable()}++d}}b(),o||i.render()}function k(e,t,n,o){i.appendDummyInput(e).appendField(new Blockly.FieldImage(t,24,24,n,(()=>y(o)),!1))}function b(){const e=m.getNumber(p),t=e!==f,n=0!==e,o=!!i.getInput(d),r=!!i.getInput(u);t||i.removeInput(u,!0),n||i.removeInput(d,!0),n&&!o&&k(d,i.REMOVE_IMAGE_DATAURI,lf("Hide optional arguments"),-1*_),t&&(r&&i.inputList.findIndex((e=>e.name===u))!==i.inputList.length-1?(i.removeInput(u,!0),v()):r||v())}function v(){k(u,i.ADD_IMAGE_DATAURI,lf("Reveal optional arguments"),_)}function T(){m.setValue(g,!0),c(),b()}function E(e){return Math.min(Math.max(m.getNumber(p)+e,0),f)}function S(e,t){if(i.rendered){e.setVisible(t).forEach((e=>{e.render()}))}}m.setEventsEnabled(!1),m.setValue(p,0),m.setValue(g,!1),m.setEventsEnabled(!0),Blockly.Extensions.apply("inline-svgs",i,!1),v(),n(i,{mutationToDom:e=>(e.setAttribute(p,m.getString(p)),e.setAttribute(g,m.getString(g)),e),domToMutation:e=>{if(m.setEventsEnabled(!1),e.hasAttribute(g)&&"true"==e.getAttribute(g)&&!m.getBoolean(g)&&(m.setValue(g,!0),T()),e.hasAttribute(p)){const t=parseInt(e.getAttribute(p));if(!isNaN(t)){const e=t-(m.getNumber(p)||0);m.getBoolean(g)?i.rendered||i.isInsertionMarker()?y(e,!0,i.isInsertionMarker()):m.setValue(p,E(e)):y(e,!0)}}m.setEventsEnabled(!0)}}),setTimeout((()=>{i.rendered&&!i.workspace.isDragging()&&y(0,void 0,!0)}),1)},t.initReturnStatement=function(t){const n=e.blocks.getBlockDefinition("function_return"),o="0_add_button",r="0_rem_button";Blockly.Extensions.apply("inline-svgs",t,!1);let i,s=!0;function a(){const a=t.getInput("RETURN_VALUE");if(s){if(!a){for(;t.getInput("");)t.removeInput("");t.jsonInit({message0:n.block.message_with_value,args0:[{type:"input_value",name:"RETURN_VALUE",check:null}],previousStatement:null,colour:e.toolbox.getNamespaceColor("functions")})}if(t.getInput(o)&&t.removeInput(o),t.getInput(r)||u(r,t.REMOVE_IMAGE_DATAURI,lf("Remove return value")),i){const e=t.workspace.getBlockById(i);e&&e.outputConnection&&!e.outputConnection.targetBlock()&&t.getInput("RETURN_VALUE").connection.connect(e.outputConnection),i=void 0}}else{if(a){const o=a.connection.targetBlock();o&&(o.isShadow()&&o.setShadow(!1),a.connection.disconnect(),i=o.id),t.removeInput("RETURN_VALUE"),t.jsonInit({message0:n.block.message_no_value,args0:[],previousStatement:null,colour:e.toolbox.getNamespaceColor("functions")})}t.getInput(r)&&t.removeInput(r),t.getInput(o)||u(o,t.ADD_IMAGE_DATAURI,lf("Add return value"))}t.setInputsInline(!0)}function l(){return Blockly.Xml.domToText(t.mutationToDom())}function c(e,n){e!==n&&Blockly.Events.fire(new Blockly.Events.BlockChange(t,"mutation",null,e,n))}function u(e,n,o){t.appendDummyInput(e).appendField(new Blockly.FieldImage(n,24,24,o,(()=>{const e=l();s=!s;const t=l();c(e,t),a();c(t,l())}),!1))}a(),t.domToMutation=e=>{e.hasAttribute("last_connected_id")&&(i=e.getAttribute("last_connected_id")),s="true"!==e.getAttribute("no_return_value"),a()},t.mutationToDom=()=>{const e=document.createElement("mutation");return function(e,t){e.setAttribute("no_return_value",t?"false":"true")}(e,!!t.getInput("RETURN_VALUE")),i&&e.setAttribute("last_connected_id",i),e}};class o{constructor(e,t){this.block=e,this.fireEvents=!0,this.state=t||{}}setValue(e,t){if(this.fireEvents&&this.block.mutationToDom){const n=this.block.mutationToDom();this.state[e]=t.toString();const o=this.block.mutationToDom();Object.keys(this.state).forEach((e=>{n.getAttribute(e)!==this.state[e]&&o.setAttribute(e,this.state[e])}));const r=Blockly.Xml.domToText(n),i=Blockly.Xml.domToText(o);r!=i&&Blockly.Events.fire(new Blockly.Events.BlockChange(this.block,"mutation",null,r,i))}else this.state[e]=t.toString()}getNumber(e){return parseInt(this.state[e])}getBoolean(e){return"false"!=this.state[e]}getString(e){return this.state[e]}setEventsEnabled(e){this.fireEvents=e}}}(e.blocks||(e.blocks={}))}(pxt||(pxt={})),function(e){!function(t){const n=e.blocks.MATH_FUNCTIONS.unary.concat(e.blocks.MATH_FUNCTIONS.binary).concat(e.blocks.MATH_FUNCTIONS.infix);let o;t.initMathOpBlock=function(){const r="math_js_op",i=e.blocks.getBlockDefinition(r);function s(e,t){const n=e.appendValueInput("ARG"+(t?1:0));n.setCheck("Number"),t&&(n.connection.setShadowDom(function(){if(!o){o=document.createElement("shadow"),o.setAttribute("type","math_number");const e=document.createElement("field");e.setAttribute("name","NUM"),e.textContent="0",o.appendChild(e)}return o}()),n.connection.respawnShadow_())}function a(e,t){let n=!!e.getInput("ARG1");t?(n&&e.moveInputBefore("op_dropdown","ARG1"),e.moveInputBefore("ARG0","op_dropdown")):(n&&e.moveInputBefore("ARG0","ARG1"),e.moveInputBefore("op_dropdown","ARG0"))}Blockly.Blocks[r]={init:function(){const o=this;o.setPreviousStatement(!1),o.setNextStatement(!1),o.setOutput(!0,"Number"),o.setOutputShape(Blockly.OUTPUT_SHAPE_ROUND),o.setInputsInline(!0);o.appendDummyInput("op_dropdown").appendField(new Blockly.FieldDropdown(n.map((e=>[i.block[e],e])),(t=>function(t,n){!function(t){return-1!==e.blocks.MATH_FUNCTIONS.unary.indexOf(t)}(n)?t.getInput("ARG1")||s(t,!0):t.removeInput("ARG1",!0);a(t,function(t){return-1!==e.blocks.MATH_FUNCTIONS.infix.indexOf(t)}(n))}(o,t))),"OP"),s(o,!1),t.appendMutation(o,{mutationToDom:e=>{let t;for(let e=0;e<o.inputList.length;e++){const n=o.inputList[e];if("op_dropdown"===n.name){t=!1;break}if("ARG0"===n.name){t=!0;break}}return e.setAttribute("op-type",(o.getInput("ARG1")?t?"infix":"binary":"unary").toString()),e},domToMutation:e=>{if(e.hasAttribute("op-type")){const t=e.getAttribute("op-type");"unary"!=t&&s(o,!0),a(o,"infix"===t)}}})}},t.installHelpResources(r,i.name,(function(e){return i.tooltip[e.getFieldValue("OP")]}),i.url,e.toolbox.getNamespaceColor(i.category))}}(e.blocks||(e.blocks={}))}(pxt||(pxt={})),function(e){!function(t){const n=e.blocks.ROUNDING_FUNCTIONS;t.initMathRoundBlock=function(){const o="math_js_round",r=e.blocks.getBlockDefinition(o);Blockly.Blocks[o]={init:function(){const e=this;e.setPreviousStatement(!1),e.setNextStatement(!1),e.setOutput(!0,"Number"),e.setOutputShape(Blockly.OUTPUT_SHAPE_ROUND),e.setInputsInline(!0);e.appendDummyInput("round_dropdown").appendField(new Blockly.FieldDropdown(n.map((e=>[r.block[e],e])),(e=>{})),"OP"),function(e){e.appendValueInput("ARG0").setCheck("Number")}(e)}},t.installHelpResources(o,r.name,(function(e){return r.tooltip[e.getFieldValue("OP")]}),r.url,e.toolbox.getNamespaceColor(r.category))}}(e.blocks||(e.blocks={}))}(pxt||(pxt={})),function(e){class t extends Blockly.Field{constructor(e,t,n){super(e,n),this.SERIALIZABLE=!0,this.options=t,e&&!this.valueText&&(this.valueText=e)}init(){super.init(),this.onInit()}dispose(){this.onDispose()}getValue(){return this.valueText}doValueUpdate_(e){null!==e&&(this.valueText=this.loaded?this.onValueChanged(e):e)}getDisplayText_(){return this.valueText}onLoadedIntoWorkspace(){this.loaded||(this.loaded=!0,this.valueText=this.onValueChanged(this.valueText))}isInitialized(){return!!this.fieldGroup_}getBlockData(){return pxt.blocks.getBlockDataForField(this.sourceBlock_,this.name)}setBlockData(e){pxt.blocks.setBlockDataForField(this.sourceBlock_,this.name,e)}}e.FieldBase=t}(pxtblockly||(pxtblockly={})),function(e){var t=pxt.svgUtil;const n=32;class o extends e.FieldBase{constructor(e,t,n){super(e,t,n),this.pendingEdit=!1,this.isEmpty=!1,this.assetChangeListener=()=>{if(this.pendingEdit)return;const e=this.getBlockData();e&&(this.asset=pxt.react.getTilemapProject().lookupAsset(this.getAssetType(),e)),this.redrawPreview()},this.lightMode=t.lightMode,this.params=this.parseFieldOptions(t),this.blocksInfo=t.blocksInfo}onInit(){this.redrawPreview()}onValueChanged(e){return this.parseValueText(e),this.redrawPreview(),this.getValueText()}showEditor_(){if(this.isGreyBlock)return;const t=Object.assign({},this.params);let n;switch(t.blocksInfo=this.blocksInfo,this.asset.type){case"tile":case"image":n="image-editor",t.temporaryAssets=e.getTemporaryAssets(this.sourceBlock_.workspace,"image");break;case"animation":n="animation-editor",t.temporaryAssets=e.getTemporaryAssets(this.sourceBlock_.workspace,"image").concat(e.getTemporaryAssets(this.sourceBlock_.workspace,"animation"));break;case"tilemap":n="tilemap-editor";const o=pxt.react.getTilemapProject();pxt.sprite.addMissingTilemapTilesAndReferences(o,this.asset)}const o=pxt.react.getFieldEditorView(n,this.asset,t);this.undoRedoState&&o.restorePersistentData(this.undoRedoState),pxt.react.getTilemapProject().pushUndo(),o.onHide((()=>{var e;const t=o.getResult(),n=pxt.react.getTilemapProject();if(t){const s=this.getValue();if(pxt.assetEquals(this.asset,t))return;const a=r(this.asset)?null:this.asset.id;let l=r(t)?null:t.id;a||l!==this.sourceBlock_.id||(t.id=n.generateNewID(t.type),l=t.id),this.pendingEdit=!0,(null===(e=t.meta)||void 0===e?void 0:e.displayName)&&this.disposeOfTemporaryAsset(),this.asset=t;const c=n.revision();if(this.onEditorClose(this.asset),this.updateAssetListener(),this.updateAssetMeta(),this.redrawPreview(),this.undoRedoState=o.getPersistentData(),this.sourceBlock_&&Blockly.Events.isEnabled()){const e=new i(this.sourceBlock_,"field",this.name,s,this.getValue(),c,n.revision());a!==l&&(e.oldAssetId=a,e.newAssetId=l),Blockly.Events.fire(e)}this.pendingEdit=!1}})),o.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 e=pxt.Util.htmlUnescape(this.valueText);return e.substr(0,e.indexOf("("))+"(...)"}return""}updateEditable(){if(this.isGreyBlock&&this.fieldGroup_){const e=this.fieldGroup_;Blockly.utils.dom.removeClass(e,"blocklyNonEditableText"),Blockly.utils.dom.removeClass(e,"blocklyEditableText"),e.style.cursor=""}else super.updateEditable()}getValue(){return this.isGreyBlock?pxt.Util.htmlUnescape(this.valueText):this.getValueText()}onDispose(){var e;(null===(e=this.sourceBlock_)||void 0===e?void 0:e.workspace)&&!this.sourceBlock_.workspace.rendered&&this.disposeOfTemporaryAsset(),pxt.react.getTilemapProject().removeChangeListener(this.getAssetType(),this.assetChangeListener)}disposeOfTemporaryAsset(){this.isTemporaryAsset()&&(pxt.react.getTilemapProject().removeAsset(this.asset),this.setBlockData(null),this.asset=void 0)}clearTemporaryAssetData(){this.isTemporaryAsset()&&this.setBlockData(null)}isTemporaryAsset(){return r(this.asset)}getAsset(){return this.asset}updateAsset(e){this.asset=e,this.setValue(this.getValue())}onEditorClose(e){}redrawPreview(){if(!this.fieldGroup_)return;if(pxsim.U.clear(this.fieldGroup_),this.isGreyBlock)return this.createTextElement_(),this.render_(),void this.updateEditable();const o=(new t.Rect).at(5,1).size(40,40).setClass("blocklySpriteField").stroke("#898989",1).corner(4);if(this.fieldGroup_.appendChild(o.el),this.asset){let o;switch(this.asset.type){case"image":case"tile":o=e.bitmapToImageURI(pxt.sprite.Bitmap.fromData(this.asset.bitmap),n,this.lightMode);break;case"animation":o=e.bitmapToImageURI(pxt.sprite.Bitmap.fromData(this.asset.frames[0]),n,this.lightMode);break;case"tilemap":o=e.tilemapToImageURI(this.asset.data,n,this.lightMode)}const r=(new t.Image).src(o).at(9,5).size(n,n);this.fieldGroup_.appendChild(r.el)}}parseValueText(e){if(e=pxt.Util.htmlUnescape(e),this.sourceBlock_&&!this.sourceBlock_.isInFlyout){const t=pxt.react.getTilemapProject(),n=this.getBlockData(),o=t.lookupAsset(this.getAssetType(),n);!o||e&&this.isEmpty?(this.setBlockData(null),this.asset&&this.sourceBlock_&&this.asset.meta.blockIDs&&(this.asset.meta.blockIDs=this.asset.meta.blockIDs.filter((e=>e!==this.sourceBlock_.id)),this.isTemporaryAsset()||t.updateAsset(this.asset)),this.isEmpty=!e,this.asset=this.createNewAsset(e)):this.asset=o,this.updateAssetMeta(),this.updateAssetListener()}}parseFieldOptions(e){const t={initWidth:16,initHeight:16,disableResize:!1,lightMode:!1};return e?(e.disableResize&&(t.disableResize="true"===e.disableResize.toLowerCase()||"1"===e.disableResize),t.initWidth=n(e.initWidth,t.initWidth),t.initHeight=n(e.initHeight,t.initHeight),t.lightMode=e.lightMode,t):t;function n(e,t){const n=parseInt(e);return isNaN(n)?t:n}}updateAssetMeta(){if(this.asset){if(this.asset.meta||(this.asset.meta={}),this.asset.meta.blockIDs||(this.asset.meta.blockIDs=[]),this.sourceBlock_){if(-1===this.asset.meta.blockIDs.indexOf(this.sourceBlock_.id)){const e=this.asset.meta.blockIDs;e.length&&this.isTemporaryAsset()&&e.some((e=>this.sourceBlock_.workspace.getBlockById(e)))&&(this.asset=pxt.cloneAsset(this.asset),this.asset.meta.blockIDs=[]),this.asset.meta.blockIDs.push(this.sourceBlock_.id)}this.setBlockData(this.asset.id)}this.isTemporaryAsset()?this.asset.meta.temporaryInfo={blockId:this.sourceBlock_.id,fieldName:this.name}:pxt.react.getTilemapProject().updateAsset(this.asset)}}updateAssetListener(){pxt.react.getTilemapProject().removeChangeListener(this.getAssetType(),this.assetChangeListener),this.asset&&!this.isTemporaryAsset()&&pxt.react.getTilemapProject().addChangeListener(this.asset,this.assetChangeListener)}}function r(e){return e&&!e.meta.displayName}e.FieldAssetEditor=o;class i extends Blockly.Events.BlockChange{constructor(e,t,n,o,r,i,s){super(e,t,n,o,r),this.oldRevision=i,this.newRevision=s,this.fieldName=n}isNull(){return this.oldRevision===this.newRevision&&super.isNull()}run(e){if(this.newAssetId||this.oldAssetId){const t=this.getEventWorkspace_().getBlockById(this.blockId);e?pxt.blocks.setBlockDataForField(t,this.fieldName,this.newAssetId):pxt.blocks.setBlockDataForField(t,this.fieldName,this.oldAssetId)}e?(pxt.react.getTilemapProject().redo(),super.run(e)):(pxt.react.getTilemapProject().undo(),super.run(e));const t=this.getEventWorkspace_(),n=new i(t.getBlockById(this.blockId),"tilemap-revision","revision",null,pxt.react.getTilemapProject().revision(),0,0);n.recordUndo=!1,Blockly.Events.fire(n)}}e.BlocklyTilemapChange=i}(pxtblockly||(pxtblockly={})),function(e){var t=pxt.svgUtil;const n=32;class o extends e.FieldAssetEditor{constructor(){super(...arguments),this.onMouseEnter=()=>{if(this.animateRef||!this.asset)return;const e=this.getParentInterval()||this.asset.interval,t=e>50?e:50;let n=0;this.animateRef=setInterval((()=>{this.preview&&this.frames[n]&&this.preview.src(this.frames[n]),n=(n+1)%this.frames.length}),t)},this.onMouseLeave=()=>{this.animateRef&&clearInterval(this.animateRef),this.animateRef=void 0,this.preview&&this.frames[0]&&this.preview.src(this.frames[0])}}initView(){this.sourceBlock_.getSvgRoot().addEventListener("mouseenter",this.onMouseEnter),this.sourceBlock_.getSvgRoot().addEventListener("mouseleave",this.onMouseLeave)}showEditor_(){this.asset&&(this.asset.interval=this.getParentInterval()||this.asset.interval),super.showEditor_()}render_(){super.render_(),this.size_.height=42,this.size_.width=80}getAssetType(){return"animation"}createNewAsset(e){const t=pxt.react.getTilemapProject();if(e){const o=pxt.lookupProjectAssetByTSReference(e,t);if(o)return o;const r=-1===(n=e).indexOf("[")?null:(n=n.replace(/[\[\]]/gm,"")).split(",").map((e=>pxt.sprite.imageLiteralToBitmap(e).data())).filter((e=>e.height&&e.width));if(r&&r.length){return{internalID:-1,id:this.sourceBlock_.id,type:"animation",frames:r,interval:this.getParentInterval(),meta:{}}}const i=t.lookupAssetByName("animation",e.trim());if(i)return i}var n;return{internalID:-1,id:this.sourceBlock_.id,type:"animation",frames:[new pxt.sprite.Bitmap(this.params.initWidth,this.params.initHeight).data()],interval:500,meta:{}}}onEditorClose(e){this.setParentInterval(e.interval)}getValueText(){return this.asset?this.isTemporaryAsset()?"["+this.asset.frames.map((e=>pxt.sprite.bitmapToImageLiteral(pxt.sprite.Bitmap.fromData(e),"typescript"))).join(",")+"]":pxt.getTSReferenceForAsset(this.asset):"[]"}redrawPreview(){if(!this.fieldGroup_)return;pxsim.U.clear(this.fieldGroup_);const o=(new t.Rect).at(35,1).size(40,40).corner(4).setClass("blocklyAnimationField");this.fieldGroup_.appendChild(o.el);const r=new t.Text("").at(5,26).fill(this.sourceBlock_.getColourSecondary()).setClass("semanticIcon");this.fieldGroup_.appendChild(r.el),this.asset&&(this.frames=this.asset.frames.map((t=>e.bitmapToImageURI(pxt.sprite.Bitmap.fromData(t),n,this.lightMode))),this.preview=(new t.Image).src(this.frames[0]).at(39,5).size(n,n),this.fieldGroup_.appendChild(this.preview.el))}getParentIntervalBlock(){const e=this.sourceBlock_;if(e.parentBlock_){const t=e.parentBlock_;for(const e of t.inputList)if("frameInterval"===e.name)return e.connection.targetBlock()}}setParentInterval(e){const t=this.getParentIntervalBlock();if(t){const n=r(t);n&&t.setFieldValue(String(e),n)}}getParentInterval(){const e=this.getParentIntervalBlock();if(e){const t=r(e);if(t)return Number(e.getFieldValue(t))}return 100}parseFieldOptions(e){return function(e){const t={initWidth:16,initHeight:16,disableResize:!1,lightMode:!1};if(!e)return t;t.lightMode=e.lightMode,e.filter&&(t.filter=e.filter);return t.initWidth=n(e.initWidth,t.initWidth),t.initHeight=n(e.initHeight,t.initHeight),t;function n(e,t){const n=parseInt(e);return isNaN(n)?t:n}}(e)}}function r(e){return"math_number_minmax"===e.type?"SLIDER":"math_number"===(t=e.type)||"math_integer"===t||"math_whole_number"===t?"NUM":"timePicker"===e.type?"ms":null;var t}e.FieldAnimationEditor=o}(pxtblockly||(pxtblockly={})),function(e){class t extends Blockly.FieldVariable{constructor(e){super(e),this.menuGenerator_=this.dropdownCreate}dropdownCreate(){return Blockly.FieldVariable.dropdownCreate.call(this).filter((e=>e[1]!=Blockly.DELETE_VARIABLE_ID))}}e.FieldArgumentVariable=t}(pxtblockly||(pxtblockly={})),function(e){class t extends Blockly.FieldNumber{constructor(e,t,n){super(e,void 0,void 0,void 0,n),this.isFieldCustom_=!0,this.CURSOR="pointer",this.params=t,this.setValue(e),this.addArgType("toggle"),this.type_=t.type}initView(){if(!this.fieldGroup_)return;null!==this.getArgTypes()&&(this.sourceBlock_.isShadow()?this.sourceBlock_.svgGroup_.setAttribute("data-argument-type",this.getArgTypes()):this.fieldGroup_.setAttribute("data-argument-type",this.getArgTypes()));const e=this.getSize();this.checkElement_=Blockly.utils.dom.createSvgElement("g",{class:"blocklyToggle "+(this.state_?"blocklyToggleOnBreakpoint":"blocklyToggleOffBreakpoint"),transform:`translate(8, ${e.height/2})`},this.fieldGroup_),this.toggleThumb_=Blockly.utils.dom.createSvgElement("polygon",{class:"blocklyToggleRect",points:"50,5 100,5 125,30 125,80 100,105 50,105 25,80 25,30"},this.checkElement_);let t=this.sourceBlock_.RTL?-e.width/2:e.width/2;this.textElement_=Blockly.utils.dom.createSvgElement("text",{class:"blocklyText",x:t,dy:"0.6ex",y:e.height/2},this.fieldGroup_),this.switchToggle(this.state_),this.setValue(this.getValue()),this.markDirty()}updateSize_(){this.size_.width=30}getValue(){return this.toVal(this.state_)}setValue(e){let t=this.fromVal(e);this.state_!==t&&(this.sourceBlock_&&Blockly.Events.isEnabled()&&Blockly.Events.fire(new Blockly.Events.BlockChange(this.sourceBlock_,"field",this.name,this.state_,t)),this.state_=t,this.switchToggle(this.state_))}switchToggle(e){this.checkElement_&&(this.updateSize_(),e?(pxt.BrowserUtils.addClass(this.checkElement_,"blocklyToggleOnBreakpoint"),pxt.BrowserUtils.removeClass(this.checkElement_,"blocklyToggleOffBreakpoint")):(pxt.BrowserUtils.removeClass(this.checkElement_,"blocklyToggleOnBreakpoint"),pxt.BrowserUtils.addClass(this.checkElement_,"blocklyToggleOffBreakpoint")),this.checkElement_.setAttribute("transform","translate(-7, -1) scale(0.3)"))}updateDisplay_(e){super.updateDisplay_(e),this.textElement_&&pxt.BrowserUtils.addClass(this.textElement_,"blocklyToggleText")}render_(){this.visible_&&this.textElement_&&(goog.dom.removeChildren(this.textElement_),this.updateSize_())}showEditor_(){let e=!this.state_;null!==e&&this.setValue(this.toVal(e))}toVal(e){return"number"==this.type_?String(e?"1":"0"):String(e?"true":"false")}fromVal(e){return"string"==typeof e?"1"==e||"TRUE"==e.toUpperCase():!!e}}e.FieldBreakpoint=t}(pxtblockly||(pxtblockly={})),function(e){class t extends Blockly.FieldSlider{constructor(e,t,n){super(String(e),"0","255","1","10","Color",n),this.isFieldCustom_=!0,this.params=t,this.params.min&&(this.min_=parseFloat(this.params.min)),this.params.max&&(this.max_=parseFloat(this.params.max)),this.params.label&&(this.labelText_=this.params.label),this.params.channel&&(this.channel_=this.params.channel)}setBackground_(e){let t=this.createColourStops_().join(",");goog.style.setStyle(e,"background","-moz-linear-gradient(left, "+t+")"),goog.style.setStyle(e,"background","-webkit-linear-gradient(left, "+t+")"),goog.style.setStyle(e,"background","-o-linear-gradient(left, "+t+")"),goog.style.setStyle(e,"background","-ms-linear-gradient(left, "+t+")"),goog.style.setStyle(e,"background","linear-gradient(left, "+t+")"),this.params.sliderWidth&&goog.style.setStyle(e,"width",`${this.params.sliderWidth}px`)}setReadout_(e,t){const n=this.colorWheel(parseInt(t),this.channel_),o=document.createElement("span");o.className="blocklyColorReadout",o.style.backgroundColor=`${n}`,pxsim.U.clear(e),e.appendChild(o)}createColourStops_(){let e=[];for(let t=0;t<=255;t+=20)e.push(this.colorWheel(t,this.channel_));return e}colorWheel(e,t){return"hsvfast"==t?this.hsvFast(e,255,255):(e=255-e)<85?this.hex(3*e,255,255-3*e):e<170?(e-=85,this.hex(255,255-3*e,3*e)):(e-=170,this.hex(255-3*e,3*e,255))}hsvFast(e,t,n){let o=e%255>>0;o<0&&(o+=255),o=192*o/255>>0;let r,i,s,a=n*(255-t)/255>>0,l=n-a,c=o/64>>0,u=o%64>>0,d=(u*l/63.75>>0)+a,p=((63-u)*l/63.75>>0)+a;return c?1==c?(r=a,i=p,s=d):(r=d,i=a,s=p):(r=p,i=d,s=a),this.hex(r,i,s)}hex(e,t,n){return`#${this.componentToHex(255&e)}${this.componentToHex(255&t)}${this.componentToHex(255&n)}`}componentToHex(e){let t=e.toString(16);return 1==t.length?"0"+t:t}}e.FieldColorWheel=t}(pxtblockly||(pxtblockly={})),function(e){class t extends Blockly.FieldColour{constructor(e,t,n){if(super(e,n),this.isFieldCustom_=!0,this.valueMode_="rgb",t.colours)this.setColours(JSON.parse(t.colours));else if(pxt.appTarget.runtime&&pxt.appTarget.runtime.palette){let e,t=pxt.Util.clone(pxt.appTarget.runtime.palette);t[0]="#dedede",pxt.appTarget.runtime.paletteNames&&(e=pxt.Util.clone(pxt.appTarget.runtime.paletteNames),e[0]=lf("transparent")),this.setColours(t,e)}this.setValue(this.getColours_()[0]),t.columns&&this.setColumns(parseInt(t.columns)),t.className&&(this.className_=t.className),t.valueMode&&(this.valueMode_=t.valueMode)}applyColour(){var e,t,n,o,r,i;this.borderRect_?this.borderRect_.style.fill=this.value_:this.sourceBlock_&&(null===(n=null===(t=null===(e=this.sourceBlock_)||void 0===e?void 0:e.pathObject)||void 0===t?void 0:t.svgPath)||void 0===n||n.setAttribute("fill",this.value_),null===(i=null===(r=null===(o=this.sourceBlock_)||void 0===o?void 0:o.pathObject)||void 0===r?void 0:r.svgPath)||void 0===i||i.setAttribute("stroke","#fff"))}doClassValidation_(e){return"string"!=typeof e?null:n(e,this.getColours_())}getValue(e){if(e)return this.value_;switch(this.valueMode_){case"hex":return`"${this.value_}"`;case"rgb":return this.value_.indexOf("#")>-1?`0x${this.value_.replace(/^#/,"")}`:this.value_;case"index":if(!this.value_)return"-1";const e=this.getColours_();for(let t=0;t<e.length;t++)if(this.value_.toUpperCase()===e[t].toUpperCase())return t+""}return this.value_}doValueUpdate_(e){this.value_=n(e,this.getColours_()),this.applyColour()}showEditor_(){super.showEditor_(),this.className_&&this.picker_&&pxt.BrowserUtils.addClass(this.picker_,this.className_)}getColours_(){return this.colours_}}function n(e,t){if(e){const n=/Colors\.([a-zA-Z]+)/.exec(e),o=/(0x|#)([0-9a-fA-F]+)/.exec(e);if(n)switch(n[1].toLocaleLowerCase()){case"red":return"#FF0000";case"orange":return"#FF7F00";case"yellow":return"#FFFF00";case"green":return"#00FF00";case"blue":return"#0000FF";case"indigo":return"#4B0082";case"violet":return"#8A2BE2";case"purple":return"#A033E5";case"pink":return"#FF007F";case"white":return"#FFFFFF";case"black":return"#000000";default:return e}else if(o){const e=o[2];if(3===e.length){let t="#";for(let n=0;n<e.length;n++){const o=e.charAt(n);t+=o+o}return t}if(6===e.length)return"#"+e}if(t){const n=parseInt(e);return isNaN(n)||null==t[n]?t[0]:t[n]}}return e}e.FieldColorNumber=t}(pxtblockly||(pxtblockly={})),function(e){class t extends Blockly.FieldDropdown{constructor(t,n,o){super(n.data),this.isFieldCustom_=!0,this.buttonClick_=function(e){let t=e.target.getAttribute("data-value");null!==t&&(this.setValue(t),this.closeModal_&&(this.close(),this.closeModal_=!1))},this.buttonClickAndClose_=function(e){this.closeModal_=!0,this.buttonClick_(e)},this.columns_=parseInt(n.columns)||4,this.maxRows_=parseInt(n.maxRows)||0,this.width_=parseInt(n.width)||200,this.backgroundColour_=e.parseColour(n.colour),this.borderColour_=pxt.toolbox.fadeColor(this.backgroundColour_,.4,!1);let r={xOffset:parseInt(n.tooltipsXOffset)||15,yOffset:parseInt(n.tooltipsYOffset)||-10};this.tooltipConfig_=r,this.hasSearchBar_=!!n.hasSearchBar||!1,this.hideRect_=!!n.hideRect||!1}dispose(){super.dispose(),this.disposeTooltip(),this.disposeIntersectionObserver()}createTooltip_(){this.gridTooltip_||(this.gridTooltip_=document.createElement("div"),this.gridTooltip_.className="goog-tooltip blocklyGridPickerTooltip",this.gridTooltip_.style.position="absolute",this.gridTooltip_.style.display="none",this.gridTooltip_.style.visibility="hidden",document.body.appendChild(this.gridTooltip_))}populateTableContainer(e,t,n){pxsim.U.removeChildren(t),0==e.length&&(this.firstItem_=void 0);for(let n=0;n<e.length/this.columns_;n++){let o=this.populateRow(n,e,t);t.appendChild(o)}}populateRow(e,n,o){const r=this.columns_,i=document.createElement("div");i.className="blocklyGridPickerRow";for(let s=r*e;s<Math.min(r*e+r,n.length);s++){let e=n[s][0];const r=n[s][1],a=document.createElement("div");a.className="goog-menuitem goog-option",a.setAttribute("id",":"+s),a.setAttribute("role","menuitem"),a.style.userSelect="none",a.title=e.alt||e,a.setAttribute("data-value",r);const l=document.createElement("div");l.setAttribute("class","goog-menuitem-content"),l.title=e.alt||e,l.setAttribute("data-value",r);const c="object"==typeof e;let u=this.backgroundColour_;if(r==this.getValue()&&(a.setAttribute("aria-selected","true"),pxt.BrowserUtils.addClass(a,"goog-option-selected"),u=this.sourceBlock_.getColourTertiary(),this.selectedItemDom=a,c&&!this.shouldShowTooltips()&&this.updateSelectedBar_(e,r)),a.style.backgroundColor=u,a.style.borderColor=this.borderColour_,c){const n=new Image(e.width,e.height);n.setAttribute("draggable","false"),"IntersectionObserver"in window?(n.src=t.DEFAULT_IMG,n.setAttribute("data-src",e.src),this.observer.observe(n)):n.src=e.src,n.alt=e.alt||"",n.setAttribute("data-value",r),l.appendChild(n)}else l.textContent=e;if(this.shouldShowTooltips()){Blockly.bindEvent_(a,"click",this,this.buttonClickAndClose_);const e=this.sourceBlock_.RTL?-this.tooltipConfig_.xOffset:this.tooltipConfig_.xOffset,t=this.tooltipConfig_.yOffset;Blockly.bindEvent_(a,"mousemove",this,(n=>{if(c){this.gridTooltip_.style.top=`${n.clientY+t}px`,this.gridTooltip_.style.left=`${n.clientX+e}px`;const o=document.elementFromPoint(n.clientX,n.clientY),r=o.title||o.alt;this.gridTooltip_.textContent=r,this.gridTooltip_.style.visibility=r?"visible":"hidden",this.gridTooltip_.style.display=r?"":"none"}pxt.BrowserUtils.addClass(a,"goog-menuitem-highlight"),o.setAttribute("aria-activedescendant",a.id)})),Blockly.bindEvent_(a,"mouseout",this,(e=>{c&&(this.gridTooltip_.style.visibility="hidden",this.gridTooltip_.style.display="none"),pxt.BrowserUtils.removeClass(a,"goog-menuitem-highlight"),o.removeAttribute("aria-activedescendant")}))}else c?(this.selectedBar_.style.display="",Blockly.bindEvent_(a,"click",this,(t=>{if(this.closeModal_)this.buttonClick_(t);else{const t=o.getElementsByClassName("goog-menuitem-highlight");for(let e=0;e<t.length;e++)pxt.BrowserUtils.removeClass(t[e],"goog-menuitem-highlight");pxt.BrowserUtils.addClass(a,"goog-menuitem-highlight"),this.updateSelectedBar_(e,r)}}))):(Blockly.bindEvent_(a,"click",this,this.buttonClickAndClose_),Blockly.bindEvent_(a,"mouseup",this,this.buttonClickAndClose_));a.appendChild(l),i.appendChild(a),0==s&&(this.firstItem_=a)}return i}shouldShowRect_(){return!this.hideRect_&&!this.sourceBlock_.isShadow()}doClassValidation_(e){return e}close(){this.disposeTooltip(),Blockly.WidgetDiv.hideIfOwner(this),Blockly.Events.setGroup(!1)}getFirstItem(){return this.firstItem_}highlightFirstItem(e){let t=e.childNodes;if(t.length&&t[0].childNodes){for(let e=0;e<t.length;++e){let n=t[e].childNodes.length;for(let o=0;o<n;++o){const n=t[e].childNodes[o];pxt.BrowserUtils.removeClass(n,"goog-menuitem-highlight"),pxt.BrowserUtils.removeClass(n,"goog-option-selected")}}t[0].childNodes[0].className+=" goog-menuitem-highlight"}}highlightAndScrollSelected(e,t){this.selectedItemDom&&goog.style.scrollIntoContainerView(this.selectedItemDom,t,!0)}showEditor_(){Blockly.WidgetDiv.show(this,this.sourceBlock_.RTL,(()=>{this.onClose_()})),this.setupIntersectionObserver_(),this.createTooltip_();const e=document.createElement("div");this.positionMenu_(e)}positionMenu_(e){const t=Blockly.utils.getViewportBBox(),n=this.getAnchorDimensions_(),{paddingContainer:o,scrollContainer:r}=this.createWidget_(e),i={width:o.offsetWidth,height:o.offsetHeight},s=goog.dom.getViewportSize();this.width_>s.width&&(this.width_=s.width),e.style.width=this.width_+"px";let a=0;if(this.hasSearchBar_&&(a+=50),this.selectedBar_&&(a+=50),this.maxRows_){let t=e.children[0].offsetHeight*(this.maxRows_+.3);s.height<t+a&&(t=s.height-a),i.height>t&&(r.style.overflowY="auto",goog.style.setHeight(r,t),i.height=t)}i.height+=a,this.sourceBlock_.RTL&&Blockly.utils.uiMenu.adjustBBoxesForRTL(t,n,i),Blockly.WidgetDiv.positionWithAnchor(t,n,i,this.sourceBlock_.RTL),this.highlightAndScrollSelected(e,r)}shouldShowTooltips(){return!pxt.BrowserUtils.isMobile()}getAnchorDimensions_(){const e=this.getScaledBBox();return this.sourceBlock_.RTL?e.right+=Blockly.FieldDropdown.CHECKMARK_OVERHANG:e.left-=Blockly.FieldDropdown.CHECKMARK_OVERHANG,e}createWidget_(e){const t=Blockly.WidgetDiv.DIV,n=this.getOptions();e.setAttribute("role","menu"),e.setAttribute("aria-haspopup","true");const o=document.createElement("div"),r=document.createElement("div");if(r.style.border=`solid 1px ${this.borderColour_}`,e.style.backgroundColor=this.backgroundColour_,o.style.backgroundColor=this.backgroundColour_,r.style.backgroundColor=this.backgroundColour_,e.className="blocklyGridPickerMenu",o.className="blocklyGridPickerScroller",r.className="blocklyGridPickerPadder",r.appendChild(o),o.appendChild(e),t.appendChild(r),this.hasSearchBar_){const t=this.createSearchBar_(e,o,n);r.insertBefore(t,r.childNodes[0])}return this.shouldShowTooltips()||(this.selectedBar_=this.createSelectedBar_(),r.appendChild(this.selectedBar_)),this.populateTableContainer(n,e,o),{paddingContainer:r,scrollContainer:o}}createSearchBar_(e,t,n){const o=document.createElement("div");o.setAttribute("class","ui fluid icon input");const r=document.createElement("i");r.setAttribute("class","search icon");const i=document.createElement("input");return i.setAttribute("type","search"),i.setAttribute("id","search-bar"),i.setAttribute("class","blocklyGridPickerSearchBar"),i.setAttribute("placeholder",pxt.Util.lf("Search")),i.addEventListener("click",(()=>{i.focus(),i.setSelectionRange(0,i.value.length)})),i.addEventListener("keyup",pxt.Util.debounce((()=>{let o=i.value,r=new RegExp(o,"i"),s=n.filter((e=>{const t=e[0].alt,n=e[1];return t?r.test(t):r.test(n)}));this.populateTableContainer.bind(this)(s,e,t),o?this.highlightFirstItem(e):this.highlightAndScrollSelected(e,t),this.gridTooltip_.style.visibility="hidden",this.gridTooltip_.style.display="none"}),300,!1)),i.addEventListener("keyup",(t=>{if(13==t.which){const t=e.childNodes[0];if(t){const e=t.childNodes[0];e&&(this.closeModal_=!0,e.click())}}})),o.appendChild(i),o.appendChild(r),o}createSelectedBar_(){const e=document.createElement("div");e.setAttribute("class","blocklyGridPickerSelectedBar"),e.style.display="none";const n=document.createElement("div"),o=document.createElement("div");o.className="blocklyGridPickerSelectedImage",n.appendChild(o),this.selectedImg_=document.createElement("img"),this.selectedImg_.setAttribute("width","30px"),this.selectedImg_.setAttribute("height","30px"),this.selectedImg_.setAttribute("draggable","false"),this.selectedImg_.style.display="none",this.selectedImg_.src=t.DEFAULT_IMG,o.appendChild(this.selectedImg_),this.selectedBarText_=document.createElement("span"),this.selectedBarText_.className="blocklyGridPickerTooltip",n.appendChild(this.selectedBarText_);const r=document.createElement("div"),i=document.createElement("div");i.className="ui buttons mini",r.appendChild(i);const s=document.createElement("button");s.className="ui button icon green";const a=document.createElement("i");a.className="icon check",s.appendChild(a),Blockly.bindEvent_(s,"click",this,(()=>{this.setValue(this.selectedBarValue_),this.close()}));const l=document.createElement("button");l.className="ui button icon red";const c=document.createElement("i");return c.className="icon cancel",l.appendChild(c),Blockly.bindEvent_(l,"click",this,(()=>{this.close()})),i.appendChild(s),i.appendChild(l),e.appendChild(n),e.appendChild(r),e}updateSelectedBar_(e,t){e.src&&(this.selectedImg_.src=e.src,this.selectedImg_.style.display=""),this.selectedImg_.alt=e.alt||e,this.selectedBarText_.textContent=e.alt||e,this.selectedBarValue_=t}setupIntersectionObserver_(){if(!("IntersectionObserver"in window))return;this.disposeIntersectionObserver();this.observer=new IntersectionObserver((e=>{e.forEach((e=>{e.intersectionRatio>0&&(this.observer.unobserve(e.target),(e=>{const t=e.getAttribute("data-src");t&&(e.src=t,e.removeAttribute("data-src"))})(e.target))}))}),{rootMargin:"20px 0px",threshold:.01})}disposeIntersectionObserver(){this.observer&&(this.observer=null)}disposeTooltip(){this.gridTooltip_&&(pxsim.U.remove(this.gridTooltip_),this.gridTooltip_=null)}onClose_(){this.disposeTooltip()}}t.DEFAULT_IMG="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==",e.FieldGridPicker=t}(pxtblockly||(pxtblockly={})),function(e){class t extends Blockly.FieldDropdown{constructor(t,n,o){super(n.data),this.isFieldCustom_=!0,this.buttonClick_=function(e){let t=e.target.getAttribute("data-value");t&&(this.setValue(t),Blockly.DropDownDiv.hide())},this.columns_=parseInt(n.columns),this.maxRows_=parseInt(n.maxRows)||0,this.width_=parseInt(n.width)||300,this.backgroundColour_=e.parseColour(n.colour),this.borderColour_=pxt.toolbox.fadeColor(this.backgroundColour_,.4,!1)}showEditor_(){if(Blockly.DropDownDiv.hideIfOwner(this))return;Blockly.DropDownDiv.hideWithoutAnimation(),Blockly.DropDownDiv.clearContent();let e=Blockly.DropDownDiv.getContentDiv(),t=document.createElement("div");t.setAttribute("role","menu"),t.setAttribute("aria-haspopup","true");const n=this.getOptions();let o=0;for(let e=0;e<n.length;e++){let r=n[e][0];const i=n[e][1];if("placeholder"==r.type){let e=document.createElement("span");e.setAttribute("class","blocklyDropDownPlaceholder"),e.style.width=r.width+"px",e.style.height=r.height+"px",t.appendChild(e);continue}let s=document.createElement("button");s.setAttribute("id",":"+e),s.setAttribute("role","menuitem"),s.setAttribute("class","blocklyDropDownButton"),s.title=r.alt;let a=r.height;this.columns_?(a=this.width_/this.columns_-8,s.style.width=a+"px",s.style.height=a+"px"):(s.style.width=r.width+"px",s.style.height=r.height+"px"),a>o&&(o=a);let l=this.backgroundColour_;i==this.getValue()&&(l=this.sourceBlock_.getColourTertiary(),s.setAttribute("aria-selected","true")),s.style.backgroundColor=l,s.style.borderColor=this.borderColour_,Blockly.bindEvent_(s,"click",this,this.buttonClick_),Blockly.bindEvent_(s,"mouseover",s,(function(){this.setAttribute("class","blocklyDropDownButton blocklyDropDownButtonHover"),t.setAttribute("aria-activedescendant",this.id)})),Blockly.bindEvent_(s,"mouseout",s,(function(){this.setAttribute("class","blocklyDropDownButton"),t.removeAttribute("aria-activedescendant")}));let c=document.createElement("img");c.src=r.src,s.setAttribute("data-value",i),c.setAttribute("data-value",i),s.appendChild(c),t.appendChild(s)}t.style.width=this.width_+"px",e.appendChild(t),this.maxRows_&&(e.style.maxHeight=(this.maxRows_+.4)*(o+8)+"px"),pxt.BrowserUtils.isFirefox()&&(e.style.paddingRight="20px"),Blockly.DropDownDiv.setColour(this.backgroundColour_,this.borderColour_),Blockly.DropDownDiv.showPositionedByField(this,this.onHide_.bind(this));let r=this.sourceBlock_;this.savedPrimary_=null==r?void 0:r.getColour(),(null==r?void 0:r.isShadow())?r.setColour(r.getColourTertiary()):this.borderRect_&&this.borderRect_.setAttribute("fill",r.getColourTertiary())}onHide_(){let e=Blockly.DropDownDiv.getContentDiv();e.removeAttribute("role"),e.removeAttribute("aria-haspopup"),e.removeAttribute("aria-activedescendant"),e.style.width="",e.style.paddingRight="",e.style.maxHeight="";let t=this.sourceBlock_;(null==t?void 0:t.isShadow())?this.sourceBlock_.setColour(this.savedPrimary_):this.borderRect_&&this.borderRect_.setAttribute("fill",this.savedPrimary_)}}e.FieldImageDropdown=t}(pxtblockly||(pxtblockly={})),function(e){class t extends e.FieldImageDropdown{constructor(e,t,n){super(e,t,n),this.isFieldCustom_=!0,this.shouldSort_=t.sort,this.addLabel_=!!t.addLabel}showEditor_(){if(Blockly.DropDownDiv.hideIfOwner(this))return;let e=this.sourceBlock_;Blockly.DropDownDiv.hideWithoutAnimation(),Blockly.DropDownDiv.clearContent();let t=Blockly.DropDownDiv.getContentDiv(),n=document.createElement("div");n.setAttribute("role","menu"),n.setAttribute("aria-haspopup","true");const o=this.getOptions();this.shouldSort_&&o.sort();for(let t=0;t<o.length;t++){const r=o[t][0],i=o[t][1];if("placeholder"==r.type){let e=document.createElement("span");e.setAttribute("class","blocklyDropDownPlaceholder"),e.style.width=r.width+"px",e.style.height=r.height+"px",n.appendChild(e);continue}let s=document.createElement("button");s.setAttribute("id",":"+t),s.setAttribute("role","menuitem"),s.setAttribute("class","blocklyDropDownButton"),s.title=r.alt,this.columns_?s.style.width=this.width_/this.columns_-8+"px":(s.style.width=r.width+"px",s.style.height=r.height+"px");let a=e.getColour();i==this.getValue()&&(a=e.getColourTertiary(),s.setAttribute("aria-selected","true")),s.style.backgroundColor=a,s.style.borderColor=e.getColourTertiary(),Blockly.bindEvent_(s,"click",this,this.buttonClick_),Blockly.bindEvent_(s,"mouseover",s,(function(){this.setAttribute("class","blocklyDropDownButton blocklyDropDownButtonHover"),n.setAttribute("aria-activedescendant",this.id)})),Blockly.bindEvent_(s,"mouseout",s,(function(){this.setAttribute("class","blocklyDropDownButton"),n.removeAttribute("aria-activedescendant")}));let l=document.createElement("img");if(l.src=r.src,s.setAttribute("data-value",i),l.setAttribute("data-value",i),s.appendChild(l),this.addLabel_){const e=this.createTextNode_(r.alt);e.setAttribute("data-value",i),s.appendChild(e)}n.appendChild(s)}n.style.width=this.width_+"px",t.appendChild(n),Blockly.DropDownDiv.setColour(e.getColour(),e.getColourTertiary()),Blockly.DropDownDiv.showPositionedByField(this,this.onHideCallback.bind(this)),this.savedPrimary_=null==e?void 0:e.getColour(),(null==e?void 0:e.isShadow())?e.setColour(e.style.colourTertiary):this.borderRect_&&this.borderRect_.setAttribute("fill",e.style.colourTertiary)}onHideCallback(){let e=this.sourceBlock_;(null==e?void 0:e.isShadow())?e.setColour(this.savedPrimary_):this.borderRect_&&this.borderRect_.setAttribute("fill",this.savedPrimary_)}createTextNode_(e){const t=document.createElement("span");return t.setAttribute("class","blocklyDropdownTextLabel"),t.textContent=e,t}}e.FieldImages=t}(pxtblockly||(pxtblockly={})),function(e){class t extends Blockly.FieldDropdown{constructor(e){super(function(e){return function(){const t=[],n=this;if(n.sourceBlock_&&n.sourceBlock_.workspace){n.sourceBlock_.workspace.getVariablesOfType(i(e.name)).forEach((e=>{t.push([e.name,e.name])}))}else e.initialMembers.forEach((e=>t.push([e,e])));return t.push([lf("Add a new {0}...",e.memberName),"CREATE"]),t}}(e)),this.opts=e}initView(){super.initView()}onItemSelected_(e,t){"CREATE"===t.getValue()?n(this.sourceBlock_.workspace,this.opts,lf("New {0}:",this.opts.memberName),(e=>e&&this.setValue(e))):super.onItemSelected_(e,t)}doClassValidation_(e){var t;return(null===(t=this.opts)||void 0===t?void 0:t.initialMembers)&&!this.opts.initialMembers.find((t=>t==e))&&this.getOptions(),super.doClassValidation_(e)}getOptions(e){return this.initVariables(),super.getOptions(e)}initVariables(){if(this.sourceBlock_&&this.sourceBlock_.workspace){const e=this.sourceBlock_.workspace,t=o(e,this.opts.name);this.opts.initialMembers.forEach((n=>{-1===t.indexOf(n)&&r(e,this.opts,n)})),"CREATE"===this.getValue()&&this.opts.initialMembers.length&&this.setValue(this.opts.initialMembers[0])}}}function n(e,t,i,s){Blockly.prompt(i,null,(a=>{if(a){let l=!1;if(pxtc.isIdentifierStart(a.charCodeAt(0),2)){l=!0;for(let e=1;e<a.length;e++)pxtc.isIdentifierPart(a.charCodeAt(e),2)||(l=!1)}if(!l)return void Blockly.alert(lf("Names must start with a letter and can only contain letters, numbers, '$', and '_'."),(()=>n(e,t,i,s)));if(pxt.blocks.isReservedWord(a))return void Blockly.alert(lf("'{0}' is a reserved word and cannot be used.",a),(()=>n(e,t,i,s)));const c=o(e,t.name);for(let o=0;o<c.length;o++){if(c[o]===a)return void Blockly.alert(lf("A {0} named '{1}' already exists.",t.memberName,a),(()=>n(e,t,i,s)))}a===t.createFunctionName&&Blockly.alert(lf("'{0}' is a reserved name.",t.createFunctionName),(()=>n(e,t,i,s))),s(r(e,t,a))}}),{placeholder:t.promptHint})}function o(e,t){const n=e.getVariablesOfType(i(t));return n&&n.length?n.map((e=>e.name)):[]}function r(e,t,n){return Blockly.Variables.getOrCreateVariablePackage(e,null,n,i(t.name)),n}function i(e){return"KIND_"+e}e.FieldKind=t}(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,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxt,pxt,pxt;!function(e){e[e.None=0]="None",e[e.Number=1]="Number",e[e.Letter=2]="Letter"}(LabelMode||(LabelMode={})),function(e){class t extends Blockly.Field{constructor(e,t,n){if(super(e,n),this.isFieldCustom_=!0,this.SERIALIZABLE=!0,this.onColor="#FFFFFF",this.scale=1,this.matrixWidth=5,this.matrixHeight=5,this.yAxisLabel=LabelMode.None,this.xAxisLabel=LabelMode.None,this.cellState=[],this.cells=[],this.dontHandleMouseEvent_=e=>{e.stopPropagation(),e.preventDefault()},this.clearLedDragHandler=e=>{const t=this.sourceBlock_.getSvgRoot();pxsim.pointerEvents.down.forEach((e=>t.removeEventListener(e,this.dontHandleMouseEvent_))),t.removeEventListener(pxsim.pointerEvents.move,this.dontHandleMouseEvent_),document.removeEventListener(pxsim.pointerEvents.up,this.clearLedDragHandler),document.removeEventListener(pxsim.pointerEvents.leave,this.clearLedDragHandler),Blockly.Touch.clearTouchIdentifier(),this.elt.removeEventListener(pxsim.pointerEvents.move,this.handleRootMouseMoveListener),e.stopPropagation(),e.preventDefault()},this.toggleRect=(e,t)=>{this.cellState[e][t]=this.currentDragState_,this.updateValue()},this.handleRootMouseMoveListener=e=>{let t,n;e.changedTouches&&1==e.changedTouches.length?(t=e.changedTouches[0].clientX,n=e.changedTouches[0].clientY):(t=e.clientX,n=e.clientY);const o=document.elementFromPoint(t,n);if(!o)return;const r=o.getAttribute("data-x"),i=o.getAttribute("data-y");null!=r&&null!=i&&this.toggleRect(parseInt(r),parseInt(i))},this.params=t,void 0!==this.params.rows){let e=parseInt(this.params.rows);isNaN(e)||(this.matrixHeight=e)}if(void 0!==this.params.columns){let e=parseInt(this.params.columns);isNaN(e)||(this.matrixWidth=e)}void 0!==this.params.onColor&&(this.onColor=this.params.onColor),void 0!==this.params.offColor&&(this.offColor=this.params.offColor),void 0!==this.params.scale?this.scale=Math.max(.6,Math.min(2,Number(this.params.scale))):Math.max(this.matrixWidth,this.matrixHeight)>15?this.scale=.85:Math.max(this.matrixWidth,this.matrixHeight)>10&&(this.scale=.9)}showEditor_(){}initMatrix(){if(!this.sourceBlock_.isInsertionMarker()){this.elt=pxsim.svg.parseString('<svg xmlns="http://www.w3.org/2000/svg" id="field-matrix" />');for(let e=0;e<this.matrixWidth;e++){this.cellState.push([]),this.cells.push([]);for(let t=0;t<this.matrixHeight;t++)this.cellState[e].push(!1)}this.restoreStateFromString();for(let e=0;e<this.matrixWidth;e++)for(let t=0;t<this.matrixHeight;t++)this.createCell(e,t);if(this.updateValue(),this.xAxisLabel!==LabelMode.None){const e=this.scale*this.matrixHeight*(t.CELL_WIDTH+t.CELL_VERTICAL_MARGIN)+2*t.CELL_VERTICAL_MARGIN+t.BOTTOM_MARGIN,n=pxsim.svg.child(this.elt,"g",{transform:`translate(0 ${e})`});for(let e=0;e<this.matrixWidth;e++){const o=this.getYAxisWidth()+this.scale*e*(t.CELL_WIDTH+t.CELL_HORIZONTAL_MARGIN)+t.CELL_WIDTH/2+t.CELL_HORIZONTAL_MARGIN/2;pxsim.svg.child(n,"text",{x:o,class:"blocklyText"}).textContent=this.getLabel(e,this.xAxisLabel)}}if(this.yAxisLabel!==LabelMode.None){const e=pxsim.svg.child(this.elt,"g",{});for(let n=0;n<this.matrixHeight;n++){const o=this.scale*n*(t.CELL_WIDTH+t.CELL_VERTICAL_MARGIN)+t.CELL_WIDTH/2+2*t.CELL_VERTICAL_MARGIN;pxsim.svg.child(e,"text",{x:0,y:o,class:"blocklyText"}).textContent=this.getLabel(n,this.yAxisLabel)}}this.fieldGroup_.replaceChild(this.elt,this.fieldGroup_.firstChild)}}getLabel(e,t){switch(t){case LabelMode.Letter:return String.fromCharCode(e+65);default:return(e+1).toString()}}createCell(e,n){const o=this.scale*e*(t.CELL_WIDTH+t.CELL_HORIZONTAL_MARGIN)+t.CELL_HORIZONTAL_MARGIN+this.getYAxisWidth(),r=this.scale*n*(t.CELL_WIDTH+t.CELL_VERTICAL_MARGIN)+t.CELL_VERTICAL_MARGIN,i=pxsim.svg.child(this.elt,"g",{transform:`translate(${o} ${r})`}),s=pxsim.svg.child(i,"rect",{class:"blocklyLed"+(this.cellState[e][n]?"On":"Off"),cursor:"pointer",width:this.scale*t.CELL_WIDTH,height:this.scale*t.CELL_WIDTH,fill:this.getColor(e,n),"data-x":e,"data-y":n,rx:Math.max(2,this.scale*t.CELL_CORNER_RADIUS)});this.cells[e][n]=s,this.sourceBlock_.workspace.isFlyout||pxsim.pointerEvents.down.forEach((t=>s.addEventListener(t,(t=>{const o=this.sourceBlock_.getSvgRoot();this.currentDragState_=!this.cellState[e][n],Blockly.hideChaff(),this.sourceBlock_.select(),this.toggleRect(e,n),pxsim.pointerEvents.down.forEach((e=>o.addEventListener(e,this.dontHandleMouseEvent_))),o.addEventListener(pxsim.pointerEvents.move,this.dontHandleMouseEvent_),document.addEventListener(pxsim.pointerEvents.up,this.clearLedDragHandler),document.addEventListener(pxsim.pointerEvents.leave,this.clearLedDragHandler),this.elt.addEventListener(pxsim.pointerEvents.move,this.handleRootMouseMoveListener),t.stopPropagation(),t.preventDefault()}),!1)))}getColor(e,n){return this.cellState[e][n]?this.onColor:this.offColor||t.DEFAULT_OFF_COLOR}getOpacity(e,t){return this.cellState[e][t]?"1.0":"0.2"}updateCell(e,t){const n=this.cells[e][t];n.setAttribute("fill",this.getColor(e,t)),n.setAttribute("fill-opacity",this.getOpacity(e,t)),n.setAttribute("class","blocklyLed"+(this.cellState[e][t]?"On":"Off"))}setValue(e,t=!0){if(super.setValue(String(e)),this.elt){t&&this.restoreStateFromString();for(let e=0;e<this.matrixWidth;e++)for(let t=0;t<this.matrixHeight;t++)this.updateCell(e,t)}}render_(){this.visible_?(this.elt||this.initMatrix(),this.size_.height=this.scale*Number(this.matrixHeight)*(t.CELL_WIDTH+t.CELL_VERTICAL_MARGIN)+2*t.CELL_VERTICAL_MARGIN+t.BOTTOM_MARGIN+this.getXAxisHeight(),this.size_.width=this.scale*Number(this.matrixWidth)*(t.CELL_WIDTH+t.CELL_HORIZONTAL_MARGIN)+this.getYAxisWidth()):this.markDirty()}getValue(){let e=function(e){const t=(e=(e||"").trim()).charAt(0);if(t===e.charAt(e.length-1)&&-1!==o.indexOf(t))return e.substr(1,e.length-2).trim();return e}(this.value_);return`\`\n${t.TAB}${e}\n${t.TAB}\``}restoreStateFromString(){let e=this.value_;if(e){const o=e.split("\n").filter((e=>rowRegex.test(e)));for(let e=0;e<o.length&&e<this.matrixHeight;e++){let r=0;const i=o[e];for(let o=0;o<i.length&&r<this.matrixWidth;o++)"."===(t=i[o])||"_"===t||"0"===t?(this.cellState[r][e]=!1,r++):n(i[o])&&(this.cellState[r][e]=!0,r++)}}var t}updateValue(){let e="";for(let n=0;n<this.matrixHeight;n++){for(let t=0;t<this.matrixWidth;t++)e+=(this.cellState[t][n]?"#":".")+" ";e+="\n"+t.TAB}this.setValue(e,!1)}getYAxisWidth(){return this.yAxisLabel===LabelMode.None?0:t.Y_AXIS_WIDTH}getXAxisHeight(){return this.xAxisLabel===LabelMode.None?0:t.X_AXIS_HEIGHT}}function n(e){return"#"===e||"*"===e||"1"===e}t.CELL_WIDTH=25,t.CELL_HORIZONTAL_MARGIN=7,t.CELL_VERTICAL_MARGIN=5,t.CELL_CORNER_RADIUS=5,t.BOTTOM_MARGIN=9,t.Y_AXIS_WIDTH=9,t.X_AXIS_HEIGHT=10,t.TAB=" ",t.DEFAULT_OFF_COLOR="#000000",e.FieldMatrix=t;const o=["'",'"',"`"]}(pxtblockly||(pxtblockly={})),function(e){var t=pxt.svgUtil;e.HEADER_HEIGHT=50,e.TOTAL_WIDTH=300;class n extends Blockly.Field{constructor(e,t,n){super(e,n),this.isFieldCustom_=!0,this.SERIALIZABLE=!0,this.soundingKeys=0,this.numRow=8,this.numCol=8,this.tempo=120,this.isPlaying=!1,this.timeouts=[],this.params=t,this.createMelodyIfDoesntExist()}init(){super.init(),this.onInit()}showEditor_(){Blockly.DropDownDiv.hideWithoutAnimation(),Blockly.DropDownDiv.clearContent(),Blockly.DropDownDiv.setColour(this.getDropdownBackgroundColour(),this.getDropdownBorderColour());let e=Blockly.DropDownDiv.getContentDiv();pxt.BrowserUtils.addClass(e,"melody-content-div"),pxt.BrowserUtils.addClass(e.parentElement,"melody-editor-dropdown"),this.gallery=new pxtmelody.MelodyGallery,this.renderEditor(e),this.prevString=this.getValue(),Blockly.Events.fire(new Blockly.Events.Ui(this.sourceBlock_,"melody-editor",!1,!0)),Blockly.DropDownDiv.showPositionedByBlock(this,this.sourceBlock_,(()=>{this.onEditorClose(),pxt.BrowserUtils.removeClass(e,"melody-content-div"),pxt.BrowserUtils.removeClass(e.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_(e){null==e||""==e||'""'==e||this.stringRep&&this.stringRep===e||(this.stringRep=e,this.parseTypeScriptValue(e),super.doValueUpdate_(this.getValue()))}getText_(){return this.invalidString?pxt.Util.lf("Invalid Input"):this.getValue()}onInit(){this.render_(),this.createMelodyIfDoesntExist(),this.invalidString||(this.fieldGroup_||(this.fieldGroup_=Blockly.utils.dom.createSvgElement("g",{},null)),this.visible_||(this.fieldGroup_.style.display="none"),this.sourceBlock_.getSvgRoot().appendChild(this.fieldGroup_),this.updateFieldLabel())}render_(){super.render_(),this.invalidString||(this.size_.width=n.MUSIC_ICON_WIDTH+(n.COLOR_BLOCK_WIDTH+n.COLOR_BLOCK_SPACING)*this.numCol),this.sourceBlock_.setColour("#ffffff")}renderEditor(n){let o=this.getDropdownBackgroundColour(),r=this.getDropdownBorderColour();this.topDiv=document.createElement("div"),pxt.BrowserUtils.addClass(this.topDiv,"melody-top-bar-div"),this.root=new t.SVG(this.topDiv).id("melody-editor-header-controls"),this.toggle=new i(this.root,{leftText:lf("Editor"),rightText:lf("Gallery"),baseColor:o}),this.toggle.onStateChange((e=>{e?this.hideGallery():this.showGallery()})),this.toggle.layout(),this.toggle.translate((e.TOTAL_WIDTH-this.toggle.width())/2,0),n.appendChild(this.topDiv),n.appendChild(this.gallery.getElement()),this.editorDiv=document.createElement("div"),pxt.BrowserUtils.addClass(this.editorDiv,"melody-editor-div"),this.editorDiv.style.setProperty("background-color",r),this.gridDiv=this.createGridDisplay(),this.editorDiv.appendChild(this.gridDiv),this.bottomDiv=document.createElement("div"),pxt.BrowserUtils.addClass(this.bottomDiv,"melody-bottom-bar-div"),this.doneButton=document.createElement("button"),pxt.BrowserUtils.addClass(this.doneButton,"melody-confirm-button"),this.doneButton.innerText=lf("Done"),this.doneButton.addEventListener("click",(()=>this.onDone())),this.doneButton.style.setProperty("background-color",o),this.playButton=document.createElement("button"),this.playButton.id="melody-play-button",this.playButton.addEventListener("click",(()=>this.togglePlay())),this.playIcon=document.createElement("i"),this.playIcon.id="melody-play-icon",pxt.BrowserUtils.addClass(this.playIcon,"play icon"),this.playButton.appendChild(this.playIcon),this.tempoInput=document.createElement("input"),pxt.BrowserUtils.addClass(this.tempoInput,"ui input"),this.tempoInput.type="number",this.tempoInput.title=lf("tempo"),this.tempoInput.id="melody-tempo-input",this.tempoInput.addEventListener("input",(()=>this.setTempo(+this.tempoInput.value))),this.syncTempoField(!0),this.bottomDiv.appendChild(this.tempoInput),this.bottomDiv.appendChild(this.playButton),this.bottomDiv.appendChild(this.doneButton),this.editorDiv.appendChild(this.bottomDiv),n.appendChild(this.editorDiv)}onEditorClose(){this.stopMelody(),this.gallery&&this.gallery.stopMelody(),this.clearDomReferences(),this.sourceBlock_&&Blockly.Events.isEnabled()&&this.getValue()!==this.prevString&&Blockly.Events.fire(new Blockly.Events.BlockChange(this.sourceBlock_,"field",this.name,this.prevString,this.getValue())),this.prevString=void 0}onDone(){Blockly.DropDownDiv.hideIfOwner(this),this.onEditorClose()}clearDomReferences(){this.topDiv=null,this.editorDiv=null,this.gridDiv=null,this.bottomDiv=null,this.doneButton=null,this.playButton=null,this.playIcon=null,this.tempoInput=null,this.elt=null,this.cells=null,this.toggle=null,this.root=null,this.gallery.clearDomReferences()}getTypeScriptValue(){return this.invalidString?this.invalidString:this.melody?'"'+this.melody.getStringRepresentation()+'"':""}parseTypeScriptValue(e){let t=e;try{e=(e=e.slice(1,-1)).trim(),this.createMelodyIfDoesntExist();let t=e.split(" ");t.forEach((e=>{if(!this.isValidNote(e))throw new Error(lf("Invalid note '{0}'. Notes can be C D E F G A B C5",e))})),this.melody.resetMelody();for(let e=0;e<t.length;e++)if("-"!=t[e]){let n=pxtmelody.noteToRow(t[e]);this.melody.updateMelody(n,e)}this.updateFieldLabel()}catch(e){pxt.log(e),this.invalidString=t}}isValidNote(e){switch(e){case"C":case"D":case"E":case"F":case"G":case"A":case"B":case"C5":case"-":return!0}return!1}getPreviewWidth(){return this.updateSize_(),this.size_.width}getPreviewHeight(){var e;return(null===(e=this.getConstants())||void 0===e?void 0:e.FIELD_BORDER_RECT_HEIGHT)||16}getDropdownBackgroundColour(){return this.sourceBlock_.parentBlock_?this.sourceBlock_.parentBlock_.getColour():"#3D3D3D"}getDropdownBorderColour(){return this.sourceBlock_.parentBlock_?this.sourceBlock_.parentBlock_.getColourTertiary():"#2A2A2A"}updateFieldLabel(){if(!this.fieldGroup_)return;pxsim.U.clear(this.fieldGroup_);let e=s("").appendClass("melody-editor-field-icon").at(6,15);this.fieldGroup_.appendChild(e.el);let o=this.melody.getStringRepresentation().trim().split(" ");for(let e=0;e<o.length;e++){let r=pxtmelody.getColorClass(pxtmelody.noteToRow(o[e]));const i=(new t.Rect).at((n.COLOR_BLOCK_WIDTH+n.COLOR_BLOCK_SPACING)*e+n.COLOR_BLOCK_X,n.COLOR_BLOCK_Y).size(n.COLOR_BLOCK_WIDTH,n.COLOR_BLOCK_HEIGHT).stroke("#898989",1).corners(3,2);pxt.BrowserUtils.addClass(i.el,r),this.fieldGroup_.appendChild(i.el)}}setTempo(e){(isNaN(e)||e<=0)&&this.tempoInput?this.tempoInput.value=this.tempo+"":this.tempo!=e&&(this.tempo=e,this.melody&&this.melody.setTempo(this.tempo),this.tempoInput&&(this.tempoInput.value=this.tempo+""),this.syncTempoField(!1))}syncTempoField(e){const t=this.sourceBlock_;if(t.parentBlock_){const n=t.parentBlock_;for(const t of n.inputList)if("tempo"===t.name){const n=t.connection.targetBlock();n&&(e?n.getFieldValue("SLIDER")?(this.tempoInput.value=n.getFieldValue("SLIDER"),this.tempo=+this.tempoInput.value):this.tempoInput.value=this.tempo+"":("math_number_minmax"===n.type?n.setFieldValue(this.tempoInput.value,"SLIDER"):n.setFieldValue(this.tempoInput.value,"NUM"),this.tempoInput.focus()));break}}}getDuration(){return 6e4/this.tempo}createMelodyIfDoesntExist(){return!this.melody&&(this.melody=new pxtmelody.MelodyArray,!0)}onNoteSelect(e,t){this.invalidString=null,this.melody.updateMelody(e,t),this.melody.getValue(e,t)&&!this.isPlaying&&this.playNote(e,t),this.updateGrid(),this.updateFieldLabel()}updateGrid(){for(let e=0;e<this.numRow;e++){const t=pxtmelody.getColorClass(e);for(let n=0;n<this.numCol;n++){const o=this.cells[e][n];this.melody.getValue(e,n)?(pxt.BrowserUtils.removeClass(o,"melody-default"),pxt.BrowserUtils.addClass(o,t)):(pxt.BrowserUtils.addClass(o,"melody-default"),pxt.BrowserUtils.removeClass(o,t))}}}playNote(e,t){let n=++this.soundingKeys;this.isPlaying?(this.timeouts.push(setTimeout((()=>{this.playToneCore(e)}),t*this.getDuration())),this.timeouts.push(setTimeout((()=>{pxt.AudioContextManager.stop()}),(t+1)*this.getDuration()))):(this.playToneCore(e),this.timeouts.push(setTimeout((()=>{this.soundingKeys==n&&pxt.AudioContextManager.stop()}),this.getDuration())))}queueToneForColumn(e,t,n){const o=setTimeout((()=>{++this.soundingKeys,pxt.AudioContextManager.stop();for(let t=0;t<this.numRow;t++)this.melody.getValue(t,e)&&this.playToneCore(t);this.highlightColumn(e,!0),this.timeouts=this.timeouts.filter((e=>e!==o))}),t),r=setTimeout((()=>{this.timeouts=this.timeouts.filter((e=>e!==r)),this.highlightColumn(e,!1)}),t+n);this.timeouts.push(o),this.timeouts.push(r)}playToneCore(e){let t=0;switch(e){case 0:t=523;break;case 1:t=494;break;case 2:t=440;break;case 3:t=392;break;case 4:t=349;break;case 5:t=330;break;case 6:t=294;break;case 7:t=262}pxt.AudioContextManager.tone(t)}highlightColumn(e,t){this.cells.map((t=>t[e])).forEach((e=>{t?pxt.BrowserUtils.addClass(e,"playing"):pxt.BrowserUtils.removeClass(e,"playing")}))}createGridDisplay(){n.VIEWBOX_WIDTH=(n.CELL_WIDTH+n.CELL_VERTICAL_MARGIN)*this.numCol+n.CELL_VERTICAL_MARGIN,pxt.BrowserUtils.isEdge()&&(n.VIEWBOX_WIDTH+=37),n.VIEWBOX_HEIGHT=(n.CELL_WIDTH+n.CELL_HORIZONTAL_MARGIN)*this.numRow+n.CELL_HORIZONTAL_MARGIN,this.elt=pxsim.svg.parseString(`<svg xmlns="http://www.w3.org/2000/svg" class="melody-grid-div" viewBox="0 0 ${n.VIEWBOX_WIDTH} ${n.VIEWBOX_HEIGHT}"/>`),this.cells=[];for(let e=0;e<this.numRow;e++)this.cells.push([]);for(let e=0;e<this.numRow;e++)for(let t=0;t<this.numCol;t++)this.createCell(e,t);return this.elt}createCell(e,t){const o=e*(n.CELL_WIDTH+n.CELL_HORIZONTAL_MARGIN)+n.CELL_HORIZONTAL_MARGIN,r=t*(n.CELL_WIDTH+n.CELL_VERTICAL_MARGIN)+n.CELL_VERTICAL_MARGIN,i=pxsim.svg.child(this.elt,"g",{transform:`translate(${r} ${o})`}),s=pxsim.svg.child(i,"rect",{cursor:"pointer",width:n.CELL_WIDTH,height:n.CELL_WIDTH,stroke:"white","data-x":e,"data-y":t,rx:n.CELL_CORNER_RADIUS});this.melody.getValue(e,t)?pxt.BrowserUtils.addClass(s,pxtmelody.getColorClass(e)):pxt.BrowserUtils.addClass(s,"melody-default"),this.sourceBlock_.workspace.isFlyout||(pxsim.pointerEvents.down.forEach((n=>s.addEventListener(n,(n=>{this.onNoteSelect(e,t),n.stopPropagation(),n.preventDefault()}),!1))),this.cells[e][t]=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 e=0;e<this.numCol;e++)this.queueToneForColumn(e,e*this.getDuration(),this.getDuration());this.timeouts.push(setTimeout((()=>this.playMelody()),this.numCol*this.getDuration()))}else this.stopMelody()}stopMelody(){if(this.isPlaying){for(;this.timeouts.length;)clearTimeout(this.timeouts.shift());pxt.AudioContextManager.stop(),this.isPlaying=!1,this.cells.forEach((e=>e.forEach((e=>pxt.BrowserUtils.removeClass(e,"playing")))))}}showGallery(){this.stopMelody(),this.updatePlayButton(),this.gallery.show((e=>{e&&(this.melody.parseNotes(e),this.gallery.hide(),this.toggle.toggle(),this.updateFieldLabel(),this.updateGrid())}))}hideGallery(){this.gallery.hide()}}n.CELL_WIDTH=25,n.CELL_HORIZONTAL_MARGIN=7,n.CELL_VERTICAL_MARGIN=5,n.CELL_CORNER_RADIUS=5,n.COLOR_BLOCK_WIDTH=10,n.COLOR_BLOCK_HEIGHT=20,n.COLOR_BLOCK_X=20,n.COLOR_BLOCK_Y=5,n.COLOR_BLOCK_SPACING=2,n.MUSIC_ICON_WIDTH=20,e.FieldCustomMelody=n;const o=200,r=40;class i{constructor(e,t){this.props=function(e){e.baseColor||(e.baseColor="#e95153");e.backgroundColor||(e.backgroundColor="rgba(52,73,94,.2)");e.borderColor||(e.borderColor="rgba(52,73,94,.4)");e.selectedTextColor||(e.selectedTextColor=e.baseColor);e.unselectedTextColor||(e.unselectedTextColor="hsla(0,0%,100%,.9)");e.switchColor||(e.switchColor="#ffffff");return e}(t),this.root=e.group(),this.buildDom(),this.isLeft=!0}buildDom(){this.root.style().content("\n .toggle-left {\n transform: translateX(0px);\n animation: mvleft 0.2s 0s ease;\n }\n\n .toggle-right {\n transform: translateX(100px);\n animation: mvright 0.2s 0s ease;\n }\n\n @keyframes mvright {\n 0% {\n transform: translateX(0px);\n }\n 100% {\n transform: translateX(100px);\n }\n }\n\n @keyframes mvleft {\n 0% {\n transform: translateX(100px);\n }\n 100% {\n transform: translateX(0px);\n }\n }\n ");this.root.def().create("clipPath","sprite-editor-toggle-border").clipPathUnits(!0).draw("rect").at(0,0).corners(.02,.1).size(1,1),this.root.draw("rect").size(o,r).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(e=!1){this.isLeft?(this.switch.removeClass("toggle-left"),this.switch.appendClass("toggle-right"),this.leftText.fill(this.props.unselectedTextColor),this.rightText.fill(this.props.selectedTextColor)):(this.switch.removeClass("toggle-right"),this.switch.appendClass("toggle-left"),this.leftText.fill(this.props.selectedTextColor),this.rightText.fill(this.props.unselectedTextColor)),this.isLeft=!this.isLeft,!e&&this.changeHandler&&this.changeHandler(this.isLeft)}onStateChange(e){this.changeHandler=e}layout(){this.leftText.moveTo(51,20),this.rightText.moveTo(149,20)}translate(e,t){this.root.translate(e,t)}height(){return r}width(){return o}}function s(e){return new t.Text(e).anchor("middle").setAttribute("dominant-baseline","middle").setAttribute("dy",pxt.BrowserUtils.isIE()||pxt.BrowserUtils.isEdge()?"0.3em":"0.1em")}}(pxtblockly||(pxtblockly={})),function(e){let t;!function(e){e[e.C=262]="C",e[e.CSharp=277]="CSharp",e[e.D=294]="D",e[e.Eb=311]="Eb",e[e.E=330]="E",e[e.F=349]="F",e[e.FSharp=370]="FSharp",e[e.G=392]="G",e[e.GSharp=415]="GSharp",e[e.A=440]="A",e[e.Bb=466]="Bb",e[e.B=494]="B",e[e.C3=131]="C3",e[e.CSharp3=139]="CSharp3",e[e.D3=147]="D3",e[e.Eb3=156]="Eb3",e[e.E3=165]="E3",e[e.F3=175]="F3",e[e.FSharp3=185]="FSharp3",e[e.G3=196]="G3",e[e.GSharp3=208]="GSharp3",e[e.A3=220]="A3",e[e.Bb3=233]="Bb3",e[e.B3=247]="B3",e[e.C4=262]="C4",e[e.CSharp4=277]="CSharp4",e[e.D4=294]="D4",e[e.Eb4=311]="Eb4",e[e.E4=330]="E4",e[e.F4=349]="F4",e[e.FSharp4=370]="FSharp4",e[e.G4=392]="G4",e[e.GSharp4=415]="GSharp4",e[e.A4=440]="A4",e[e.Bb4=466]="Bb4",e[e.B4=494]="B4",e[e.C5=523]="C5",e[e.CSharp5=555]="CSharp5",e[e.D5=587]="D5",e[e.Eb5=622]="Eb5",e[e.E5=659]="E5",e[e.F5=698]="F5",e[e.FSharp5=740]="FSharp5",e[e.G5=784]="G5",e[e.GSharp5=831]="GSharp5",e[e.A5=880]="A5",e[e.Bb5=932]="Bb5",e[e.B5=988]="B5",e[e.C6=1047]="C6",e[e.CSharp6=1109]="CSharp6",e[e.D6=1175]="D6",e[e.Eb6=1245]="Eb6",e[e.E6=1319]="E6",e[e.F6=1397]="F6",e[e.FSharp6=1480]="FSharp6",e[e.G6=1568]="G6",e[e.GSharp6=1568]="GSharp6",e[e.A6=1760]="A6",e[e.Bb6=1865]="Bb6",e[e.B6=1976]="B6",e[e.C7=2093]="C7"}(t||(t={}));class n extends Blockly.FieldNumber{constructor(t,n,o){super(null,0,null,null,o),this.isFieldCustom_=!0,this.SERIALIZABLE=!0,this.isTextValid_=!0,this.nKeys_=36,this.minNote_=28,this.maxNote_=63,this.eps=2,this.setSpellcheck(!1),this.prepareNotes(),this.isExpanded=!1,this.currentPage=0,this.totalPlayCount=0,n.editorColour&&(this.primaryColour=e.parseColour(n.editorColour),this.borderColour=Blockly.utils.colour.darken(this.primaryColour,.2));const r=parseInt(n.eps);!Number.isNaN(r)&&r>=0&&(this.eps=r);const i=parseInt(n.minNote)||this.minNote_,s=parseInt(n.maxNote)||this.maxNote_;i>=28&&s<=75&&s>i&&(this.minNote_=i,this.maxNote_=s,this.nKeys_=this.maxNote_-this.minNote_+1),this.setValue(t)}doClassValidation_(e){const n=/^Note\.(.+)$/.exec(e),o=n&&n.length>1?n[1]:null;if(null===(e=t[o]?t[o]:String(parseFloat(e||"0"))))return null;const r=parseFloat(e||"0");if(isNaN(r)||r<0)return null;const i=Math.floor(r)!=r;return""+r.toFixed(i?2:0)}getValue(){return this.value_+""}doValueUpdate_(e){isNaN(Number(e))||Number(e)<0||(this.sourceBlock_&&Blockly.Events.isEnabled()&&this.value_!=e&&Blockly.Events.fire(new Blockly.Events.Change(this.sourceBlock_,"field",this.name,this.value_,e)),this.value_=e,this.refreshText())}getText(){if(this.isExpanded)return""+this.value_;{const e=+this.value_;for(let t=0;t<this.nKeys_;t++)if(Math.abs(this.getKeyFreq(t)-e)<this.eps)return this.getKeyName(t);let t=e.toString();return isNaN(e)||(t+=" Hz"),t}}refreshText(){this.forceRerender()}onHtmlInputChange_(e){super.onHtmlInputChange_(e),Blockly.DropDownDiv.hideWithoutAnimation(),this.htmlInput_.focus()}onFinishEditing_(e){this.refreshText()}onHide(){this.isExpanded=!1,this.refreshText()}showEditor_(e){this.isExpanded=!0,this.updateColor(),Blockly.DropDownDiv.hideWithoutAnimation(),Blockly.DropDownDiv.clearContent();const t=pxt.BrowserUtils.isMobile()||pxt.BrowserUtils.isIOS();n.superClass_.showEditor_.call(this,e,t,t),this.refreshText(),Blockly.Events.setGroup(!0),this.piano=[],this.currentSelectedKey=void 0;const r=this.nKeys_-this.nKeys_/n.notesPerOctave*n.blackKeysPerOctave,i=n.notesPerOctave-n.blackKeysPerOctave;let s=n.keyWidth*r,a=n.keyHeight+n.labelHeight;const l=window.innerWidth<s;l&&(s=i*n.keyWidth,a=n.keyHeight+n.labelHeight+n.prevNextHeight);const c=o("blocklyPianoDiv",`width: ${s}px;\n height: ${a}px;`);Blockly.DropDownDiv.getContentDiv().appendChild(c),this.noteLabel=o("blocklyNoteLabel",`top: ${n.keyHeight}px;\n width: ${s}px;\n background-color: ${this.primaryColour};\n border-color: ${this.primaryColour};`),c.appendChild(this.noteLabel),this.noteLabel.textContent="-";let u=0;for(let e=0;e<this.nKeys_;e++){const t=Math.floor(e/n.notesPerOctave);let o=this.getPosition(e);l&&e>=n.notesPerOctave&&(o-=i*t*n.keyWidth);const r=this.getKeyDiv(e,o);this.piano.push(r),c.appendChild(r),Math.abs(this.getKeyFreq(e)-Number(this.getValue()))<this.eps&&(pxt.BrowserUtils.addClass(r,"selected"),this.currentSelectedKey=r,u=t)}l&&(this.setPage(u),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(e,t){const n=++this.totalPlayCount;this.currentSelectedKey!==e&&(this.currentSelectedKey&&pxt.BrowserUtils.removeClass(this.currentSelectedKey,"selected"),pxt.BrowserUtils.addClass(e,"selected"),this.setValue(t)),this.currentSelectedKey=e,this.htmlInput_.value=this.getText(),pxt.AudioContextManager.tone(t),setTimeout((()=>{this.totalPlayCount==n&&pxt.AudioContextManager.stop()}),300)}dispose(){Blockly.DropDownDiv.hideIfOwner(this),super.dispose()}updateColor(){if(this.sourceBlock_.parentBlock_&&(this.sourceBlock_.isShadow()||1===(e=this.sourceBlock_).inputList.length&&1===e.inputList[0].fieldRow.length)){let e=this.sourceBlock_.parentBlock_;this.primaryColour=e.getColour(),this.borderColour=e.getColourTertiary()}else this.primaryColour="#3D3D3D",this.borderColour="#2A2A2A";var e}setPage(e){const t=this.nKeys_/n.notesPerOctave;e=Math.max(Math.min(e,t-1),0),this.noteLabel.textContent=`Octave #${e+1}`;const o=e*n.notesPerOctave;for(let e=0;e<this.piano.length;++e){const t=e>=o&&e<o+n.notesPerOctave;this.piano[e].style.display=t?"block":"none"}this.currentPage=e}getNextPrevDiv(e,t){const r=e?0:t/2,i=o("blocklyNotePrevNext",`top: ${n.keyHeight+n.labelHeight}px;\n left: ${r}px;\n width: ${Math.ceil(t/2)}px;\n ${e?"border-left-color":"border-right-color"}: ${this.primaryColour};\n background-color: ${this.primaryColour};\n border-bottom-color: ${this.primaryColour};`);return pxt.BrowserUtils.pointerEvents.down.forEach((t=>{Blockly.bindEventWithChecks_(i,t,this,(()=>this.setPage(e?this.currentPage-1:this.currentPage+1)),!0)})),i.textContent=e?"<":">",i}getKeyDiv(e,t){const n=o("blocklyNote "+(this.isWhite(e)?"":"black"),`width: ${this.getKeyWidth(e)}px;\n height: ${this.getKeyHeight(e)}px;\n left: ${t}px;\n border-color: ${this.primaryColour};`);return pxt.BrowserUtils.pointerEvents.down.forEach((t=>{Blockly.bindEventWithChecks_(n,t,this,(()=>this.playKey(n,this.getKeyFreq(e))),!0)})),Blockly.bindEventWithChecks_(n,"mouseover",this,(()=>this.noteLabel.textContent=this.getKeyName(e)),!0),n}isWhite(e){switch(e%12){case 1:case 3:case 6:case 8:case 10:return!1;default:return!0}}getKeyWidth(e){return this.isWhite(e)?n.keyWidth:n.keyWidth/2}getKeyHeight(e){return this.isWhite(e)?n.keyHeight:n.keyHeight/2}getKeyFreq(e){return this.getKeyNoteData(e).freq}getKeyName(e){const t=this.getKeyNoteData(e);let o=t.prefixedName;return this.nKeys_<=n.notesPerOctave?o=t.name:this.minNote_>=28&&this.maxNote_<=63&&(o=t.altPrefixedName||o),o}getKeyNoteData(e){return n.Notes[e+this.minNote_]}getPosition(e){const t=(e-Math.floor((e+1)/n.notesPerOctave*n.blackKeysPerOctave))*n.keyWidth;return this.isWhite(e)?t:t-n.keyWidth/4}prepareNotes(){n.Notes||(n.Notes={28:{name:lf("{id:note}C"),prefixedName:lf("Low C"),freq:131},29:{name:lf("C#"),prefixedName:lf("Low C#"),freq:139},30:{name:lf("{id:note}D"),prefixedName:lf("Low D"),freq:147},31:{name:lf("D#"),prefixedName:lf("Low D#"),freq:156},32:{name:lf("{id:note}E"),prefixedName:lf("Low E"),freq:165},33:{name:lf("{id:note}F"),prefixedName:lf("Low F"),freq:175},34:{name:lf("F#"),prefixedName:lf("Low F#"),freq:185},35:{name:lf("{id:note}G"),prefixedName:lf("Low G"),freq:196},36:{name:lf("G#"),prefixedName:lf("Low G#"),freq:208},37:{name:lf("{id:note}A"),prefixedName:lf("Low A"),freq:220},38:{name:lf("A#"),prefixedName:lf("Low A#"),freq:233},39:{name:lf("{id:note}B"),prefixedName:lf("Low B"),freq:247},40:{name:lf("{id:note}C"),prefixedName:lf("Middle C"),freq:262},41:{name:lf("C#"),prefixedName:lf("Middle C#"),freq:277},42:{name:lf("{id:note}D"),prefixedName:lf("Middle D"),freq:294},43:{name:lf("D#"),prefixedName:lf("Middle D#"),freq:311},44:{name:lf("{id:note}E"),prefixedName:lf("Middle E"),freq:330},45:{name:lf("{id:note}F"),prefixedName:lf("Middle F"),freq:349},46:{name:lf("F#"),prefixedName:lf("Middle F#"),freq:370},47:{name:lf("{id:note}G"),prefixedName:lf("Middle G"),freq:392},48:{name:lf("G#"),prefixedName:lf("Middle G#"),freq:415},49:{name:lf("{id:note}A"),prefixedName:lf("Middle A"),freq:440},50:{name:lf("A#"),prefixedName:lf("Middle A#"),freq:466},51:{name:lf("{id:note}B"),prefixedName:lf("Middle B"),freq:494},52:{name:lf("{id:note}C"),prefixedName:lf("Tenor C"),altPrefixedName:lf("High C"),freq:523},53:{name:lf("C#"),prefixedName:lf("Tenor C#"),altPrefixedName:lf("High C#"),freq:554},54:{name:lf("{id:note}D"),prefixedName:lf("Tenor D"),altPrefixedName:lf("High D"),freq:587},55:{name:lf("D#"),prefixedName:lf("Tenor D#"),altPrefixedName:lf("High D#"),freq:622},56:{name:lf("{id:note}E"),prefixedName:lf("Tenor E"),altPrefixedName:lf("High E"),freq:659},57:{name:lf("{id:note}F"),prefixedName:lf("Tenor F"),altPrefixedName:lf("High F"),freq:698},58:{name:lf("F#"),prefixedName:lf("Tenor F#"),altPrefixedName:lf("High F#"),freq:740},59:{name:lf("{id:note}G"),prefixedName:lf("Tenor G"),altPrefixedName:lf("High G"),freq:784},60:{name:lf("G#"),prefixedName:lf("Tenor G#"),altPrefixedName:lf("High G#"),freq:831},61:{name:lf("{id:note}A"),prefixedName:lf("Tenor A"),altPrefixedName:lf("High A"),freq:880},62:{name:lf("A#"),prefixedName:lf("Tenor A#"),altPrefixedName:lf("High A#"),freq:932},63:{name:lf("{id:note}B"),prefixedName:lf("Tenor B"),altPrefixedName:lf("High B"),freq:988},64:{name:lf("{id:note}C"),prefixedName:lf("High C"),freq:1046},65:{name:lf("C#"),prefixedName:lf("High C#"),freq:1109},66:{name:lf("{id:note}D"),prefixedName:lf("High D"),freq:1175},67:{name:lf("D#"),prefixedName:lf("High D#"),freq:1245},68:{name:lf("{id:note}E"),prefixedName:lf("High E"),freq:1319},69:{name:lf("{id:note}F"),prefixedName:lf("High F"),freq:1397},70:{name:lf("F#"),prefixedName:lf("High F#"),freq:1478},71:{name:lf("{id:note}G"),prefixedName:lf("High G"),freq:1568},72:{name:lf("G#"),prefixedName:lf("High G#"),freq:1661},73:{name:lf("{id:note}A"),prefixedName:lf("High A"),freq:1760},74:{name:lf("A#"),prefixedName:lf("High A#"),freq:1865},75:{name:lf("{id:note}B"),prefixedName:lf("High B"),freq:1976}})}}function o(e,t){const n=document.createElement("div");return pxt.BrowserUtils.addClass(n,e),n.setAttribute("style",t.replace(/\s+/g," ")),n}n.keyWidth=22,n.keyHeight=90,n.labelHeight=24,n.prevNextHeight=20,n.notesPerOctave=12,n.blackKeysPerOctave=5,e.FieldNote=n}(pxtblockly||(pxtblockly={})),function(e){class t extends Blockly.FieldNumberDropdown{constructor(e,t,n){super(e,t.data,t.min,t.max,t.precision,n),this.isFieldCustom_=!0}getOptions(){let e;return this.menuGenerator_&&(e=JSON.parse(this.menuGenerator_).map((e=>"object"==typeof e?e:[String(e),String(e)]))),e}}e.FieldNumberDropdown=t}(pxtblockly||(pxtblockly={})),function(e){class t extends Blockly.FieldSlider{constructor(e,t,n){super(e,"0","100","1","100","Value",n),this.isFieldCustom_=!0,this.params=t,this.params.screenHeight||(this.params.screenHeight=120),this.params.screenWidth||(this.params.screenWidth=160),this.params.xInputName||(this.params.xInputName="x"),this.params.yInputName||(this.params.yInputName="y"),this.params.min&&(this.min_=parseInt(this.params.min)),this.params.max&&(this.max_=parseInt(this.params.max))}showEditor_(e){this.getFieldByName(this.params.xInputName)===this&&(this.max_=this.params.screenWidth,this.labelText_=this.params.xInputName);this.getFieldByName(this.params.yInputName)===this&&(this.max_=this.params.screenHeight,this.labelText_=this.params.yInputName),super.showEditor_(e),this.renderScreenPicker()}doValueUpdate_(e){super.doValueUpdate_(e),this.resetCrosshair&&this.resetCrosshair()}renderScreenPicker(){let e=Blockly.DropDownDiv.getContentDiv();this.selectorDiv_=document.createElement("div"),this.selectorDiv_.className="blocklyCanvasOverlayOuter",e.appendChild(this.selectorDiv_);const t=document.createElement("div");t.className="blocklyCanvasOverlayDiv",this.selectorDiv_.appendChild(t);const n=document.createElement("div");n.className="cross-x",t.appendChild(n);const o=document.createElement("div");o.className="cross-y",t.appendChild(o);const r=document.createElement("div");r.className="label",t.appendChild(r);const i=1.5*this.params.screenWidth,s=1.5*this.params.screenHeight;t.style.height=s+"px",t.style.width=i+"px";const a=e.getElementsByClassName("goog-slider-horizontal")[0];if(a){a.style.width=i+"px";const e=parseFloat(this.getValue());!isNaN(e)&&e>this.getMin()&&(this.setValue(e-1+""),this.setValue(e+""))}const l=(e,t)=>{e=Math.round(Math.max(0,Math.min(i,e))),t=Math.round(Math.max(0,Math.min(s,t))),n.style.top=t+"px",o.style.left=e+"px",e=Math.round(Math.max(0,Math.min(this.params.screenWidth,e/i*this.params.screenWidth))),t=Math.round(Math.max(0,Math.min(this.params.screenHeight,t/s*this.params.screenHeight))),isNaN(e)?r.textContent=`${this.params.yInputName}=${t}`:isNaN(t)?r.textContent=`${this.params.xInputName}=${e}`:r.textContent=`${this.params.xInputName}=${e} ${this.params.yInputName}=${t}`;const a=r.getBoundingClientRect();e>this.params.screenWidth/2?r.style.left=e*(i/this.params.screenWidth)-a.width-8+"px":r.style.left=e*(i/this.params.screenWidth)+4+"px",t>this.params.screenHeight/2?r.style.top=t*(s/this.params.screenHeight)-a.height-6+"px":r.style.top=t*(s/this.params.screenHeight)+"px"};this.resetCrosshair=()=>{const{currentX:e,currentY:t}=this.getXY();l(e/this.params.screenWidth*i,t/this.params.screenHeight*s)},this.resetCrosshair(),Blockly.bindEvent_(this.selectorDiv_,"mousemove",this,(e=>{const n=t.getBoundingClientRect(),o=e.clientX-n.left,r=e.clientY-n.top;l(o,r)})),Blockly.bindEvent_(this.selectorDiv_,"mouseleave",this,this.resetCrosshair),Blockly.bindEvent_(this.selectorDiv_,"click",this,(e=>{const n=t.getBoundingClientRect(),o=e.clientX-n.left,r=e.clientY-n.top,a=Math.round(o/i*this.params.screenWidth),l=Math.round(r/s*this.params.screenHeight);this.close(),this.setXY(a,l)}))}resizeHandler(){this.close()}setXY(e,t){const n=this.getFieldByName(this.params.xInputName);n&&"number"==typeof n.getValue()&&n.setValue(String(e));const o=this.getFieldByName(this.params.yInputName);o&&"number"==typeof o.getValue()&&o.setValue(String(t))}getFieldByName(e){const t=this.sourceBlock_.parentBlock_;if(t)for(let n=0;n<t.inputList.length;n++){const o=t.inputList[n];if(o.name===e)return this.getTargetField(o)}}getXY(){let e,t;const n=this.getFieldByName(this.params.xInputName);n&&(e=n.getValue());const o=this.getFieldByName(this.params.yInputName);return o&&(t=o.getValue()),{currentX:parseInt(e),currentY:parseInt(t)}}getTargetField(e){const t=e.connection.targetBlock();if(!t)return null;const n=t.inputList[0];if(!n)return null;return n.fieldRow[0]}widgetDispose_(){Blockly.FieldNumber.superClass_.widgetDispose_.call(this),this.close(!0)}close(e){e||(Blockly.WidgetDiv.hideIfOwner(this),Blockly.DropDownDiv.hideIfOwner(this)),window.removeEventListener("resize",this.resizeHandler),this.resetCrosshair=void 0,this.selectorDiv_&&(goog.dom.removeNode(this.selectorDiv_),this.selectorDiv_=void 0)}}e.FieldPosition=t}(pxtblockly||(pxtblockly={})),function(e){class t extends Blockly.FieldDropdown{constructor(e,t){super([["Temp","Temp"]],t),this.setValue(e||"")}getOptions(){return this.dropdownCreate()}init(){this.fieldGroup_||super.init.call(this)}setSourceBlock(e){goog.asserts.assert(!e.isShadow(),"Procedure fields are not allowed to exist on shadow blocks."),super.setSourceBlock.call(this,e)}dropdownCreate(){let e=[];if(this.sourceBlock_&&this.sourceBlock_.workspace){let t=this.sourceBlock_.workspace.getAllBlocks(!1);for(let n=0;n<t.length;n++)if(t[n].getProcedureDef){let o=t[n].getProcedureDef();e.push(o[0])}}let t=this.getValue();t&&-1==e.indexOf(t)&&e.push(t),e.sort(goog.string.caseInsensitiveCompare),e.length||e.push("Temp");let n=[];for(let t=0;t<e.length;t++)n[t]=[e[t],e[t]];return n}onItemSelected(e,t){let n=t.getValue();null!==n&&this.setValue(n)}}e.FieldProcedure=t}(pxtblockly||(pxtblockly={})),function(e){class t extends Blockly.FieldSlider{constructor(e,t,n){super(String(e),"0","180","1","15",lf("Angle"),n),this.isFieldCustom_=!0,this.params=t}createLabelDom_(e){const t=document.createElement("div");this.circleSVG=document.createElementNS("http://www.w3.org/2000/svg","svg"),pxsim.svg.hydrate(this.circleSVG,{viewBox:"0 0 200 100",width:"170"}),t.appendChild(this.circleSVG);pxsim.svg.child(this.circleSVG,"circle",{"stroke-dasharray":"565.48","stroke-dashoffset":"0",cx:100,cy:100,r:"90",style:"fill:transparent; transition: stroke-dashoffset 0.1s linear;",stroke:"#a8aaa8","stroke-width":"1rem"});this.circleBar=pxsim.svg.child(this.circleSVG,"circle",{"stroke-dasharray":"565.48","stroke-dashoffset":"0",cx:100,cy:100,r:"90",style:"fill:transparent; transition: stroke-dashoffset 0.1s linear;",stroke:"#f12a21","stroke-width":"1rem"}),this.reporter=pxsim.svg.child(this.circleSVG,"text",{x:100,y:80,"text-anchor":"middle","dominant-baseline":"middle",style:"font-size: 50px",class:"sim-text inverted number"});const n=document.createElement("span");return n.setAttribute("class","blocklyFieldSliderReadout"),[t,n]}setReadout_(e,t){this.updateAngle(parseFloat(t)),this.reporter.textContent=`${t}°`}updateAngle(e){const t=(180-(e=Math.max(0,Math.min(180,e))))/180*Math.PI*90;this.circleBar.setAttribute("stroke-dashoffset",`${t}`)}}e.FieldProtractor=t}(pxtblockly||(pxtblockly={})),function(e){class t extends Blockly.FieldSlider{constructor(e,t,n){super(String(e),"-100","100","1","10","Speed",n),this.isFieldCustom_=!0,this.params=t,this.params.min&&(this.min_=parseFloat(this.params.min)),this.params.max&&(this.max_=parseFloat(this.params.max)),this.params.label&&(this.labelText_=this.params.label),this.params.format||(this.params.format="{0}%")}createLabelDom_(e){const t=document.createElement("div");this.speedSVG=document.createElementNS("http://www.w3.org/2000/svg","svg"),pxsim.svg.hydrate(this.speedSVG,{viewBox:"0 0 200 100",width:"170"}),t.appendChild(this.speedSVG);pxsim.svg.child(this.speedSVG,"circle",{"stroke-dasharray":"565.48","stroke-dashoffset":"0",cx:100,cy:100,r:"90",style:"fill:transparent; transition: stroke-dashoffset 0.1s linear;",stroke:"#a8aaa8","stroke-width":"1rem"});this.circleBar=pxsim.svg.child(this.speedSVG,"circle",{"stroke-dasharray":"565.48","stroke-dashoffset":"0",cx:100,cy:100,r:"90",style:"fill:transparent; transition: stroke-dashoffset 0.1s linear;",stroke:"#f12a21","stroke-width":"1rem"}),this.reporter=pxsim.svg.child(this.speedSVG,"text",{x:100,y:80,"text-anchor":"middle","dominant-baseline":"middle",style:`font-size: ${Math.max(14,50-5*(this.params.format.length-4))}px`,class:"sim-text inverted number"});const n=document.createElement("span");return n.setAttribute("class","blocklyFieldSliderReadout"),[t,n]}setReadout_(e,t){this.updateSpeed(parseFloat(t)),this.reporter.textContent=ts.pxtc.U.rlf(this.params.format,t)}updateSpeed(e){let t=this.sign(e);e=Math.abs(e)/100*50+50,-1==t&&(e=50-e);let n=(100-e)/100*(180*Math.PI);this.circleBar.setAttribute("stroke-dashoffset",`${n}`)}sign(e){return e?e<0?-1:1:0}}e.FieldSpeed=t}(pxtblockly||(pxtblockly={})),function(e){class t extends e.FieldAssetEditor{getAssetType(){return"image"}createNewAsset(e){const t=pxt.react.getTilemapProject();if(e){const n=pxt.lookupProjectAssetByTSReference(e,t);if(n)return n}if(this.getBlockData())return t.lookupAsset("image",this.getBlockData());const n=e?pxt.sprite.imageLiteralToBitmap(e):new pxt.sprite.Bitmap(this.params.initWidth,this.params.initHeight);if(!n)return this.isGreyBlock=!0,void(this.valueText=e);const o=n.data();return{internalID:-1,id:this.sourceBlock_.id,type:"image",jresData:pxt.sprite.base64EncodeBitmap(o),meta:{},bitmap:o}}getValueText(){return this.asset&&!this.isTemporaryAsset()?pxt.getTSReferenceForAsset(this.asset):pxt.sprite.bitmapToImageLiteral(this.asset&&pxt.sprite.Bitmap.fromData(this.asset.bitmap),"typescript")}parseFieldOptions(e){return function(e){const t={initColor:1,initWidth:16,initHeight:16,disableResize:!1,lightMode:!1};if(!e)return t;if(t.lightMode=e.lightMode,e.sizes){const n=e.sizes.split(";"),o=[];for(let e=0;e<n.length;e++){const t=n[e].split(",");if(2!==t.length)continue;let r=parseInt(t[0]),i=parseInt(t[1]);if(isNaN(r)||isNaN(i))continue;const s=pxt.appTarget.runtime&&pxt.appTarget.runtime.screenSize;r<0&&s&&(r=s.width),i<0&&s&&(i=s.height),o.push([r,i])}o.length>0&&(t.initWidth=o[0][0],t.initHeight=o[0][1])}e.filter&&(t.filter=e.filter);e.disableResize&&(t.disableResize="true"===e.disableResize.toLowerCase()||"1"===e.disableResize);return t.initColor=n(e.initColor,t.initColor),t.initWidth=n(e.initWidth,t.initWidth),t.initHeight=n(e.initHeight,t.initHeight),t;function n(e,t){const n=parseInt(e);return isNaN(n)?t:n}}(e)}}e.FieldSpriteEditor=t}(pxtblockly||(pxtblockly={})),function(e){class t extends Blockly.FieldLabel{constructor(e,t,n){super(e,function(e){if(e){if(e.bold&&e.italics)return"blocklyBoldItalicizedText";if(e.bold)return"blocklyBoldText";if(e.italics)return"blocklyItalicizedText"}return}(t)),this.isFieldCustom_=!0}}e.FieldStyledLabel=t}(pxtblockly||(pxtblockly={})),function(e){class t extends Blockly.FieldTextDropdown{constructor(e,t,n){super(e,t.values,n),this.isFieldCustom_=!0}}e.FieldTextDropdown=t}(pxtblockly||(pxtblockly={})),function(e){class t extends Blockly.FieldTextInput{constructor(e,t,n){super(e,n),this.isFieldCustom_=!0}}e.FieldTextInput=t}(pxtblockly||(pxtblockly={})),function(e){class t extends e.FieldAssetEditor{getInitText(){return this.initText}getTileset(){var e;return null===(e=this.asset)||void 0===e?void 0:e.data.tileset}getAssetType(){return"tilemap"}createNewAsset(e=""){e&&(e=e.replace(/`/g,"`"));const t=pxt.react.getTilemapProject(),n=pxt.lookupProjectAssetByTSReference(e,t);if(n)return n;const o=pxt.sprite.decodeTilemap(e,"typescript",t)||t.blankTilemap(this.params.tileWidth,this.params.initWidth,this.params.initHeight);let r;if(function(e){return!!(e&&e.tilemap&&e.tilemap.width&&e.tilemap.height)&&(!(!e.layers||e.layers.width!==e.tilemap.width||e.layers.height!==e.tilemap.height)&&!!e.tileset)}(o)){this.initText=e,this.isGreyBlock=!1;const[n]=t.createNewTilemapFromData(o);r=t.getTilemap(n)}else e.trim()&&(this.isGreyBlock=!0,this.valueText=e);return r}onEditorClose(e){pxt.sprite.updateTilemapReferencesFromResult(pxt.react.getTilemapProject(),e)}getValueText(){return this.isGreyBlock?pxt.Util.htmlUnescape(this.valueText):this.asset?pxt.getTSReferenceForAsset(this.asset):this.getInitText()}parseFieldOptions(e){return function(e){const t={initWidth:16,initHeight:16,disableResize:!1,tileWidth:16,lightMode:!1};if(!e)return t;t.lightMode=e.lightMode,e.filter&&(t.filter=e.filter);if(e.tileWidth)if("number"==typeof e.tileWidth)switch(e.tileWidth){case 8:t.tileWidth=8;break;case 16:t.tileWidth=16;break;case 32:t.tileWidth=32}else{switch(e.tileWidth.trim().toLowerCase()){case"8":case"eight":t.tileWidth=8;break;case"16":case"sixteen":t.tileWidth=16;break;case"32":case"thirtytwo":t.tileWidth=32}}return t.initWidth=n(e.initWidth,t.initWidth),t.initHeight=n(e.initHeight,t.initHeight),t;function n(e,t){const n=parseInt(e);return isNaN(n)?t:n}}(e)}}e.FieldTilemap=t}(pxtblockly||(pxtblockly={})),function(e){const t=32;class n extends e.FieldImages{constructor(t,r,i){super(t,r,i),this.isFieldCustom_=!0,this.menuGenerator_=()=>{var t,r;return(null===(t=this.sourceBlock_)||void 0===t?void 0:t.workspace)&&e.needsTilemapUpgrade(null===(r=this.sourceBlock_)||void 0===r?void 0:r.workspace)?[o()]:n.getReferencedTiles(this.sourceBlock_.workspace)},this.assetChangeListener=()=>{this.doValueUpdate_(this.getValue()),this.forceRerender()},this.blocksInfo=r.blocksInfo}static getReferencedTiles(o){const a=pxt.react.getTilemapProject();if(a.revision()!==n.cachedRevision||o.id!=n.cachedWorkspaceId){n.cachedRevision=a.revision(),n.cachedWorkspaceId=o.id;const l=e.getAllReferencedTiles(o),c=[16,8,32];for(const e of c){const t=a.getProjectTiles(e,16===e);if(t)for(const e of t.tiles)l.find((t=>t.id===e.id))||l.push(e)}let u={};l.sort(((e,t)=>e.id===t.id?0:e.bitmap.width!==t.bitmap.width?e.bitmap.width-t.bitmap.width:e.isProjectTile!==t.isProjectTile?e.isProjectTile?-1:1:(u[e.id]||(u[e.id]=i(e.id)))-(u[t.id]||(u[t.id]=i(t.id)))));const d=n=>i(n.id)<=2?r(n.bitmap.width):e.bitmapToImageURI(pxt.sprite.Bitmap.fromData(n.bitmap),t,!1);n.referencedTiles=l.map((e=>[{src:d(e),width:t,height:t,alt:s(e)},e.id,e]))}return n.referencedTiles}initView(){super.initView(),this.sourceBlock_&&this.sourceBlock_.isInFlyout&&this.setValue(this.getOptions()[0][1])}getValue(){if(this.selectedOption_){let e=this.selectedOption_[2];return e=pxt.react.getTilemapProject().lookupAsset(e.type,e.id),pxt.getTSReferenceForAsset(e)}const e=super.getValue();return"string"==typeof e&&-1===e.indexOf(".")&&-1===e.indexOf("`")?`img\`${e}\``:e}getText(){const e=this.getValue();return"string"==typeof e&&-1!==e.indexOf("`")?e:super.getText()}render_(){if(this.value_&&this.selectedOption_&&this.selectedOption_[1]!==this.value_){const o=pxt.react.getTilemapProject().resolveTile(this.value_);n.cachedRevision=-1,o&&(this.selectedOption_=[{src:e.bitmapToImageURI(pxt.sprite.Bitmap.fromData(o.bitmap),t,!1),width:t,height:t,alt:s(o)},this.value_,o])}super.render_()}doValueUpdate_(e){super.doValueUpdate_(e);const t=this.getOptions(!0);if(e){const n=pxt.parseAssetTSReference(e);n&&(e=n.name),e=e.trim();for(const n of t)if(e===n[2].id||e===n[2].meta.displayName||e===pxt.getShortIDForAsset(n[2]))return this.selectedOption_=n,this.value_=this.getValue(),void this.updateAssetListener();this.selectedOption_=null,this.updateAssetListener()}}getOptions(e){return"function"!=typeof this.menuGenerator_?(this.transparent=o(),[this.transparent]):this.menuGenerator_.call(this)}dispose(){super.dispose(),pxt.react.getTilemapProject().removeChangeListener("tile",this.assetChangeListener)}updateAssetListener(){const e=pxt.react.getTilemapProject();e.removeChangeListener("tile",this.assetChangeListener),this.selectedOption_&&e.addChangeListener(this.selectedOption_[2],this.assetChangeListener)}}function o(){const e=pxt.react.getTilemapProject().getTransparency(16);return[{src:r(16),width:t,height:t,alt:pxt.U.lf("transparency")},e.id,e]}function r(e){const t=document.createElement("canvas"),n=t.getContext("2d");t.width=e,t.height=e,n.fillStyle="#aeaeae",n.fillRect(0,0,e,e),n.fillStyle="#dedede";for(let t=0;t<e;t+=4)for(let o=0;o<e;o+=4)t+o>>2&1&&n.fillRect(t,o,4,4);return t.toDataURL()}function i(e){switch(e){case"myTiles.transparency16":return 1;case"myTiles.transparency8":case"myTiles.transparency32":return 2;default:if(e.startsWith("myTiles.tile")){const t=parseInt(e.slice(12));if(!Number.isNaN(t))return t+2}return 9999999999}}function s(e){return e.meta.displayName||pxt.getShortIDForAsset(e)}e.FieldTileset=n}(pxtblockly||(pxtblockly={})),function(e){class t extends Blockly.FieldNumber{constructor(e,t,n){super(e,void 0,void 0,void 0,n),this.isFieldCustom_=!0,this.CURSOR="pointer",this.params=t,this.setValue(e),this.addArgType("toggle"),this.type_=t.type}initView(){if(!this.fieldGroup_)return;null!==this.getArgTypes()&&(this.sourceBlock_.isShadow()?this.sourceBlock_.svgGroup_.setAttribute("data-argument-type",this.getArgTypes()):this.fieldGroup_.setAttribute("data-argument-type",this.getArgTypes())),!this.sourceBlock_.isShadow()&&this.sourceBlock_.inputList&&this.sourceBlock_.inputList.length>1&&(this.borderRect_=Blockly.utils.dom.createSvgElement("rect",{rx:Blockly.BlockSvg.CORNER_RADIUS,ry:Blockly.BlockSvg.CORNER_RADIUS,x:0,y:0,width:this.size_.width,height:this.size_.height,fill:this.sourceBlock_.getColour(),stroke:this.sourceBlock_.getColourTertiary()},null),this.fieldGroup_.insertBefore(this.borderRect_,this.textElement_));const e=this.getSize();switch(this.checkElement_=Blockly.utils.dom.createSvgElement("g",{class:"blocklyToggle "+(this.state_?"blocklyToggleOn":"blocklyToggleOff"),transform:`translate(8, ${e.height/2})`},this.fieldGroup_),this.getOutputShape()){case Blockly.OUTPUT_SHAPE_HEXAGONAL:this.toggleThumb_=Blockly.utils.dom.createSvgElement("polygon",{class:"blocklyToggleRect",points:"-7,-14 -21,0 -7,14 7,14 21,0 7,-14",cursor:"pointer"},this.checkElement_);break;case Blockly.OUTPUT_SHAPE_ROUND:this.toggleThumb_=Blockly.utils.dom.createSvgElement("rect",{class:"blocklyToggleCircle",x:-6,y:-14,height:28,width:28,rx:14,ry:14,cursor:"pointer"},this.checkElement_);break;case Blockly.OUTPUT_SHAPE_SQUARE:this.toggleThumb_=Blockly.utils.dom.createSvgElement("rect",{class:"blocklyToggleRect",x:-6,y:-14,height:28,width:28,rx:3,ry:3,cursor:"pointer"},this.checkElement_)}let t=this.sourceBlock_.RTL?-e.width/2:e.width/2;this.textElement_=Blockly.utils.dom.createSvgElement("text",{class:"blocklyText",x:t,dy:"0.6ex",y:e.height/2},this.fieldGroup_),this.updateEditable();const n=this.sourceBlock_.getSvgRoot();n.appendChild(this.fieldGroup_),n.querySelector(".blocklyBlockBackground").setAttribute("fill",this.sourceBlock_.getColourTertiary()),this.switchToggle(this.state_),this.setValue(this.getValue()),this.markDirty()}getDisplayText_(){return this.state_?this.getTrueText():this.getFalseText()}getTrueText(){return lf("True")}getFalseText(){return lf("False")}updateSize_(){switch(this.getOutputShape()){case Blockly.OUTPUT_SHAPE_ROUND:this.size_.width=2*this.getInnerWidth()-7;break;case Blockly.OUTPUT_SHAPE_HEXAGONAL:this.size_.width=2*this.getInnerWidth()+8-Math.floor(this.getInnerWidth()/2);break;case Blockly.OUTPUT_SHAPE_SQUARE:this.size_.width=9+2*this.getInnerWidth()}}getInnerWidth(){return 10*this.getMaxLength()}getMaxLength(){return Math.max(this.getTrueText().length,this.getFalseText().length)}getOutputShape(){return this.sourceBlock_.isShadow()?this.sourceBlock_.getOutputShape():Blockly.OUTPUT_SHAPE_SQUARE}doClassValidation_(e){return"boolean"==typeof this.fromVal(e)?e:"false"}applyColour(){let e=this.sourceBlock_.getColourTertiary();this.borderRect_?this.borderRect_.setAttribute("stroke",e):this.sourceBlock_.pathObject.svgPath.setAttribute("fill",e)}getValue(){return this.toVal(this.state_)}doValueUpdate_(e){let t=this.fromVal(e);this.state_!==t&&(this.sourceBlock_&&Blockly.Events.isEnabled()&&Blockly.Events.fire(new Blockly.Events.BlockChange(this.sourceBlock_,"field",this.name,this.state_,t)),this.state_=t,this.switchToggle(this.state_),this.isDirty_=!0)}switchToggle(e){if(this.checkElement_){this.updateSize_();const t=this.getSize(),n=this.getInnerWidth();e?(pxt.BrowserUtils.addClass(this.checkElement_,"blocklyToggleOn"),pxt.BrowserUtils.removeClass(this.checkElement_,"blocklyToggleOff")):(pxt.BrowserUtils.removeClass(this.checkElement_,"blocklyToggleOn"),pxt.BrowserUtils.addClass(this.checkElement_,"blocklyToggleOff"));const o=this.getOutputShape();let r=0,i=0,s=0,a=0;switch(o){case Blockly.OUTPUT_SHAPE_HEXAGONAL:r=n,i=r/2;let e=i/2;s=-i+e,a=-e;const t=-e,l=i;this.toggleThumb_.setAttribute("points",`${t},-14 ${t-14},0 ${t},14 ${l},14 ${l+14},0 ${l},-14`);break;case Blockly.OUTPUT_SHAPE_ROUND:case Blockly.OUTPUT_SHAPE_SQUARE:r=5+n,i=r/2,this.toggleThumb_.setAttribute("width",""+r),this.toggleThumb_.setAttribute("x",`-${i}`),s=a=o==Blockly.OUTPUT_SHAPE_SQUARE?2:-6}this.checkElement_.setAttribute("transform",`translate(${e?a+n+i:i+s}, ${t.height/2})`)}}render_(){if(this.visible_&&this.textElement_){goog.dom.removeChildren(this.textElement_);let e=document.createTextNode(this.getDisplayText_());this.textElement_.appendChild(e),pxt.BrowserUtils.addClass(this.textElement_,"blocklyToggleText"),this.updateSize_();let t=this.size_.width,n=(this.state_?t+t/8:t/2)-t/2;this.textElement_.setAttribute("x",`${n}`)}this.borderRect_&&(this.borderRect_.setAttribute("width",`${this.size_.width}`),this.borderRect_.setAttribute("height",`${this.size_.height}`))}showEditor_(){let e=!this.state_;null!==e&&this.setValue(this.toVal(e))}toVal(e){return"number"==this.type_?String(e?"1":"0"):String(e?"true":"false")}fromVal(e){return"string"==typeof e?"1"==e||"TRUE"==e.toUpperCase():!!e}}e.FieldToggle=t}(pxtblockly||(pxtblockly={})),function(e){class t extends e.FieldToggle{constructor(e,t,n){super(e,t,n),this.isFieldCustom_=!0}getTrueText(){return lf("HIGH")}getFalseText(){return lf("LOW")}}e.FieldToggleHighLow=t}(pxtblockly||(pxtblockly={})),function(e){class t extends e.FieldToggle{constructor(e,t,n){super(e,t,n),this.isFieldCustom_=!0}getTrueText(){return lf("ON")}getFalseText(){return lf("OFF")}}e.FieldToggleOnOff=t}(pxtblockly||(pxtblockly={})),function(e){class t extends e.FieldToggle{constructor(e,t,n){super(e,t,n),this.isFieldCustom_=!0}getTrueText(){return lf("UP")}getFalseText(){return lf("DOWN")}}e.FieldToggleUpDown=t;class n extends e.FieldToggle{constructor(e,t,n){super(e,t,n),this.isFieldCustom_=!0}getTrueText(){return lf("DOWN")}getFalseText(){return lf("UP")}}e.FieldToggleDownUp=n}(pxtblockly||(pxtblockly={})),function(e){class t extends e.FieldToggle{constructor(e,t,n){super(e,t,n),this.isFieldCustom_=!0}getTrueText(){return lf("WIN")}getFalseText(){return lf("LOSE")}}e.FieldToggleWinLose=t}(pxtblockly||(pxtblockly={})),function(e){class t extends e.FieldToggle{constructor(e,t,n){super(e,t,n),this.isFieldCustom_=!0}getTrueText(){return lf("Yes")}getFalseText(){return lf("No")}}e.FieldToggleYesNo=t}(pxtblockly||(pxtblockly={})),function(e){class t extends Blockly.FieldTextInput{constructor(){super(...arguments),this.isFieldCustom_=!0,this.pythonMode=!1}updateEditable(){let e=this.fieldGroup_;this.EDITABLE&&e&&(this.sourceBlock_.isEditable()?(pxt.BrowserUtils.addClass(e,"blocklyEditableText"),pxt.BrowserUtils.removeClass(e,"blocklyGreyExpressionBlockText"),this.fieldGroup_.style.cursor=this.CURSOR):(pxt.BrowserUtils.addClass(e,"blocklyGreyExpressionBlockText"),pxt.BrowserUtils.removeClass(e,"blocklyEditableText"),this.fieldGroup_.style.cursor=""))}setPythonEnabled(e){e!==this.pythonMode&&(this.pythonMode=e,this.forceRerender())}getText(){return this.pythonMode?pxt.Util.lf("<python code>"):this.getValue()}applyColour(){var e;this.sourceBlock_&&(null===(e=this.getConstants())||void 0===e?void 0:e.FULL_BLOCK_FIELDS)&&this.borderRect_&&this.borderRect_.setAttribute("stroke",this.sourceBlock_.style.colourTertiary)}}e.FieldTsExpression=t}(pxtblockly||(pxtblockly={})),function(e){class t extends Blockly.FieldSlider{constructor(e,t,n){super(String(e),"-200","200","1","10","TurnRatio",n),this.isFieldCustom_=!0,this.params=t,this.sliderColor_="#a8aaa8"}createLabelDom_(e){let n=document.createElement("div"),o=Blockly.utils.dom.createSvgElement("svg",{xmlns:"http://www.w3.org/2000/svg","xmlns:html":"http://www.w3.org/1999/xhtml","xmlns:xlink":"http://www.w3.org/1999/xlink",version:"1.1",height:t.HALF+t.HANDLE_RADIUS+10+"px",width:2*t.HALF+"px"},n),r=Blockly.utils.dom.createSvgElement("defs",{},o),i=Blockly.utils.dom.createSvgElement("marker",{id:"head",orient:"auto",markerWidth:"2",markerHeight:"4",refX:"0.1",refY:"1.5"},r);Blockly.utils.dom.createSvgElement("path",{d:"M0,0 V3 L1.5,1.5 Z",fill:"#f12a21"},i);this.reporter_=pxsim.svg.child(o,"text",{x:t.HALF,y:96,"text-anchor":"middle","dominant-baseline":"middle",style:"font-size: 50px",class:"sim-text inverted number"}),this.path_=Blockly.utils.dom.createSvgElement("path",{x1:t.HALF,y1:t.HALF,"marker-end":"url(#head)",style:"fill: none; stroke: #f12a21; stroke-width: 10"},o),this.updateGraph_();let s=document.createElement("span");return s.setAttribute("class","blocklyFieldSliderReadout"),[n,s]}updateGraph_(){if(!this.path_)return;let e=goog.math.clamp(this.getValue()||0,-200,200);const n=e/100,o=Math.max(-1,Math.min(1,n)),r=Math.max(o)*Math.PI/2,i=t.RADIUS-6;let s=t.HALF;const a=t.HALF-22;Math.abs(n)>1&&(s-=(n-(n>0?1:-1))*i/2);const l=.2+.5*Math.abs(o),c=i*l,u=i*Math.sin(Math.PI/2-r),d=i*Math.cos(Math.PI/2-r),p=u-i*l*Math.cos(2*r),g=`M ${s} ${a} C ${s} ${a-c} ${s+(d-i*l*Math.sin(2*r))} ${a-p} ${s+d} ${a-u}`;this.path_.setAttribute("d",g),this.reporter_.textContent=`${e}`}setReadout_(e,t){this.updateGraph_()}}t.HALF=80,t.HANDLE_RADIUS=30,t.RADIUS=t.HALF-t.HANDLE_RADIUS-1,e.FieldTurnRatio=t}(pxtblockly||(pxtblockly={})),function(e){class t extends Blockly.FieldDropdown{constructor(e){super(function(e){return function(){const t=[],n=this;if(n.sourceBlock_&&n.sourceBlock_.workspace){n.sourceBlock_.workspace.getVariablesOfType(e.name).forEach((e=>{const n=e.name.replace(/^\d+/,"");t.push([n,e.name])}))}else e.initialMembers.forEach((e=>t.push([e,e])));return t.push([lf("Add a new {0}...",e.memberName),"CREATE"]),t}}(e)),this.opts=e}init(){super.init(),this.initVariables()}onItemSelected_(e,t){"CREATE"===t.getValue()?n(this.sourceBlock_.workspace,this.opts,lf("New {0}:",this.opts.memberName),(e=>e&&this.setValue(e))):super.onItemSelected_(e,t)}doClassValidation_(e){var t;return(null===(t=this.opts)||void 0===t?void 0:t.initialMembers)&&!this.opts.initialMembers.find((t=>t==e))&&this.getOptions(),super.doClassValidation_(e)}initVariables(){if(this.sourceBlock_&&this.sourceBlock_.workspace){const e=this.sourceBlock_.workspace,t=r(e,this.opts.name);if(this.opts.initialMembers.forEach((n=>{t.some((([e,t])=>e===n))||s(e,this.opts,n)})),"CREATE"===this.getValue()){const t=function(e,t,n){const r=e.getVariablesOfType(t);if(r&&r.length)for(let e=0;e<r.length;e++){const[t]=o(r[e]);if(t===n)return r[e].name}return}(e,this.opts.name,this.opts.initialMembers[0]);t&&this.setValue(t)}}}}function n(e,t,o,i){Blockly.prompt(o,null,(a=>{if(a){let l=!1;if(pxtc.isIdentifierStart(a.charCodeAt(0),2)){l=!0;for(let e=1;e<a.length;e++)pxtc.isIdentifierPart(a.charCodeAt(e),2)||(l=!1)}if(!l)return void Blockly.alert(lf("Names must start with a letter and can only contain letters, numbers, '$', and '_'."),(()=>n(e,t,o,i)));const c=r(e,t.name);for(let r=0;r<c.length;r++){const[s,l]=c[r];if(s===a)return void Blockly.alert(lf("A {0} named '{1}' already exists.",t.memberName,a),(()=>n(e,t,o,i)))}i(s(e,t,a))}}),{placeholder:t.promptHint})}function o(e){const t=/^(\d+)([^0-9].*)$/.exec(e.name);return t?[t[2],parseInt(t[1])]:[e.name,-1]}function r(e,t){const n=e.getVariablesOfType(t);return n&&n.length?n.map(o):[]}function i(e,t){const n=e.map((([e,t])=>t));if(t.isBitMask){for(let e=0;e<n.length;e++){let t=1<<e;if(n.indexOf(t)<0)return t}return 1<<n.length}if(t.isHash)return 0;{const e=t.firstValue||0;for(let t=0;t<n.length;t++)if(n.indexOf(e+t)<0)return e+t;return e+n.length}}function s(e,t,n){const o=i(r(e,t.name),t)+n;return Blockly.Variables.getOrCreateVariablePackage(e,null,o,t.name),o}e.FieldUserEnum=t,e.getNextValue=i}(pxtblockly||(pxtblockly={})),function(e){let t;function n(e,t){const n=e.getVariablesOfType(pxt.sprite.BLOCKLY_TILESET_TYPE);for(const o of n)if(parseInt(o.name.substr(0,o.name.indexOf(";")))===t.projectId){e.deleteVariableById(o.getId());break}}function o(t){return i(t,(t=>t instanceof e.FieldTilemap&&!t.isGreyBlock))}function r(t){return i(t,(t=>t instanceof e.FieldTileset))}function i(e,t){const n=[];return e.getTopBlocks(!1).forEach((e=>o(e))),n;function o(e){for(const r of e.inputList){for(const o of r.fieldRow)t(o)&&n.push({block:e,field:o.name,ref:o});r.connection&&r.connection.targetBlock()&&o(r.connection.targetBlock())}e.nextConnection&&e.nextConnection.targetBlock()&&o(e.nextConnection.targetBlock())}}!function(e){e.hasClass=function(e,t){return pxt.BrowserUtils.containsClass(e,t)},e.addClass=function(e,t){pxt.BrowserUtils.addClass(e,t)},e.removeClass=function(e,t){pxt.BrowserUtils.removeClass(e,t)}}(t=e.svg||(e.svg={})),e.parseColour=function(e){const t=Number(e);return isNaN(t)?goog.isString(e)&&e.match(/^#[0-9a-fA-F]{6}$/)?e:"#000":Blockly.hueToRgb(t)},e.bitmapToImageURI=function(e,t,n){const o=pxt.appTarget.runtime.palette.slice(1),r=document.createElement("canvas");r.width=t,r.height=t;const i=Math.min(t/e.width,t/e.height),s=Math.max(Math.floor(t*(1-e.width/e.height)/2),0),a=Math.max(Math.floor(t*(1-e.height/e.width)/2),0);let l;n?(l=r.getContext("2d",{alpha:!1}),l.fillStyle="#dedede",l.fillRect(0,0,t,t)):l=r.getContext("2d");for(let t=0;t<e.width;t++)for(let r=0;r<e.height;r++){const c=e.get(t,r);c?(l.fillStyle=o[c-1],l.fillRect(s+t*i,a+r*i,i,i)):n&&(l.fillStyle="#dedede",l.fillRect(s+t*i,a+r*i,i,i))}return r.toDataURL()},e.tilemapToImageURI=function(e,t,n){const o=pxt.appTarget.runtime.palette.slice(),r=document.createElement("canvas");r.width=t,r.height=t;const i=Math.min(t/e.tilemap.width,t/e.tilemap.height),s=Math.max(Math.floor(t*(1-e.tilemap.width/e.tilemap.height)/2),0),a=Math.max(Math.floor(t*(1-e.tilemap.height/e.tilemap.width)/2),0);let l;n?(l=r.getContext("2d",{alpha:!1}),l.fillStyle="#dedede",l.fillRect(0,0,t,t)):l=r.getContext("2d");let c=[];for(let t=0;t<e.tilemap.width;t++)for(let r=0;r<e.tilemap.height;r++){const u=e.tilemap.get(t,r);if(u){if(!c[u]){const t=e.tileset.tiles[u];c[u]=t?pxt.sprite.computeAverageColor(pxt.sprite.Bitmap.fromData(t.bitmap),o):"#dedede"}l.fillStyle=c[u],l.fillRect(s+t*i,a+r*i,i,i)}else n&&(l.fillStyle="#dedede",l.fillRect(s+t*i,a+r*i,i,i))}return r.toDataURL()},e.getAllBlocksWithTilemaps=o,e.getAllBlocksWithTilesets=r,e.needsTilemapUpgrade=function(e){return!!e.getVariablesOfType(pxt.sprite.BLOCKLY_TILESET_TYPE).map((e=>pxt.sprite.legacy.blocklyVariableToTile(e.name))).length},e.upgradeTilemapsInWorkspace=function(e,t){const i=e.getVariablesOfType(pxt.sprite.BLOCKLY_TILESET_TYPE).map((e=>pxt.sprite.legacy.blocklyVariableToTile(e.name)));if(i.length)try{Blockly.Events.disable();let s=[];for(const o of i)o.qualifiedName?s[o.projectId]=t.resolveTile(o.qualifiedName):o.data&&(s[o.projectId]=t.createNewTile(o.data,"myTiles.tile"+o.projectId)),n(e,o);const a=o(e);for(const e of a){const n=pxt.sprite.legacy.decodeTilemap(e.ref.getInitText(),"typescript"),o=[],r=new pxt.sprite.TilemapData(n.tilemap,{tileWidth:n.tileset.tileWidth,tiles:n.tileset.tiles.map(((e,n)=>null!=e.projectId?s[e.projectId]:(o[n]||(o[n]=t.resolveTile(e.qualifiedName)),o[n])))},n.layers);e.ref.setValue(pxt.sprite.encodeTilemap(r,"typescript"))}const l=r(e);for(const e of l)e.ref.doValueUpdate_(e.ref.getValue()),e.ref.isDirty_&&e.ref.forceRerender()}finally{Blockly.Events.enable()}},e.getAllReferencedTiles=function(e,t){var n;let i={};const s=o(e),a=pxt.react.getTilemapProject();for(const e of s)if(e.block.id!==t)for(const t of(null===(n=e.ref.getTileset())||void 0===n?void 0:n.tiles)||[])i[t.id]=a.lookupAsset("tile",t.id);const l=a.getAssets("tilemap");for(const e of l)for(const t of e.data.tileset.tiles)i[t.id]=a.lookupAsset("tile",t.id);const c=r(e);for(const e of c){const t=e.ref.getValue(),n=/^\s*assets\s*\.\s*tile\s*`([^`]*)`\s*$/.exec(t);if(n){const e=a.lookupAssetByName("tile",n[1]);e&&!i[e.id]&&(i[e.id]=e)}else i[t]||(i[t]=a.resolveTile(t))}return Object.keys(i).map((e=>i[e])).filter((e=>!!e))},e.getTemporaryAssets=function(t,n){switch(n){case"image":return i(t,(t=>t instanceof e.FieldSpriteEditor&&t.isTemporaryAsset())).map((e=>e.ref.getAsset()));case"animation":return i(t,(t=>t instanceof e.FieldAnimationEditor&&t.isTemporaryAsset())).map((e=>e.ref.getAsset()));default:return[]}}}(pxtblockly||(pxtblockly={})),function(e){!function(t){let n,o,r,i;!function(e){e[e.Stopped=0]="Stopped",e[e.Pending=1]="Pending",e[e.Starting=2]="Starting",e[e.Running=3]="Running"}(n=t.SimState||(t.SimState={})),t.isBlocks=function(t){return e.U.endsWith(t.name,".blocks")},function(e){e.HeaderOnly="errorListHeader",e.Expanded="errorListExpanded"}(o=t.ErrorListState||(t.ErrorListState={})),function(e){e[e.Hidden=0]="Hidden",e[e.Visible=1]="Visible",e[e.Disabled=2]="Disabled"}(r=t.FilterState||(t.FilterState={})),t.initExtensionsAsync=e=>Promise.resolve({}),t.initFieldExtensionsAsync=e=>Promise.resolve({}),t.HELP_IMAGE_URI="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjYiIGhlaWdodD0iMjYiIHZpZXdCb3g9IjAgMCAyNiAyNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPGNpcmNsZSBjeD0iMTMiIGN5PSIxMyIgcj0iMTMiIGZpbGw9IndoaXRlIi8+CjxwYXRoIGQ9Ik0xNy45NTIgOS4xODQwMkMxNy45NTIgMTAuMjU2IDE3LjgxNiAxMS4wNzIgMTcuNTQ0IDExLjYzMkMxNy4yODggMTIuMTkyIDE2Ljc1MiAxMi43OTIgMTUuOTM2IDEzLjQzMkMxNS4xMiAxNC4wNzIgMTQuNTc2IDE0LjU4NCAxNC4zMDQgMTQuOTY4QzE0LjA0OCAxNS4zMzYgMTMuOTIgMTUuNzM2IDEzLjkyIDE2LjE2OFYxNi45NkgxMS44MDhDMTEuNDI0IDE2LjQ2NCAxMS4yMzIgMTUuODQgMTEuMjMyIDE1LjA4OEMxMS4yMzIgMTQuNjg4IDExLjM4NCAxNC4yODggMTEuNjg4IDEzLjg4OEMxMS45OTIgMTMuNDg4IDEyLjUzNiAxMi45NjggMTMuMzIgMTIuMzI4QzE0LjEwNCAxMS42NzIgMTQuNjI0IDExLjE2OCAxNC44OCAxMC44MTZDMTUuMTM2IDEwLjQ0OCAxNS4yNjQgOS45NjgwMiAxNS4yNjQgOS4zNzYwMkMxNS4yNjQgOC4yMDgwMiAxNC40MTYgNy42MjQwMiAxMi43MiA3LjYyNDAyQzExLjc2IDcuNjI0MDIgMTAuNzUyIDcuNzM2MDIgOS42OTYgNy45NjAwMkw5LjE0NCA4LjA4MDAyTDkgNi4wODgwMkMxMC40ODggNS41NjAwMiAxMS44NCA1LjI5NjAyIDEzLjA1NiA1LjI5NjAyQzE0LjczNiA1LjI5NjAyIDE1Ljk2OCA1LjYwODAyIDE2Ljc1MiA2LjIzMjAyQzE3LjU1MiA2Ljg0MDAyIDE3Ljk1MiA3LjgyNDAyIDE3Ljk1MiA5LjE4NDAyWk0xMS40IDIyVjE4LjY0SDE0LjE4NFYyMkgxMS40WiIgZmlsbD0iIzU5NUU3NCIvPgo8L3N2Zz4K",t.initEditorExtensionsAsync=function(){if(!i&&(i=Promise.resolve(),e.appTarget&&e.appTarget.appTheme&&e.appTarget.appTheme.extendFieldEditors)){const t={};i=i.then((()=>e.BrowserUtils.loadBlocklyAsync())).then((()=>e.BrowserUtils.loadScriptAsync("fieldeditors.js"))).then((()=>e.editor.initFieldExtensionsAsync(t))).then((t=>{t.fieldEditors&&t.fieldEditors.forEach((t=>{e.blocks.registerFieldEditor(t.selector,t.editor,t.validator)}))}))}return i}}(e.editor||(e.editor={}))}(pxt||(pxt={})),function(e){!function(t){const n={};function o(e,t,n,o){e.response&&window.parent.postMessage({type:e.type,id:e.id,resp:t,success:n,error:o},"*")}function r(t){return new Promise(((o,r)=>{const i=e.Util.clone(t);i.id=ts.pxtc.Util.guidGen(),t.response&&(n[i.id]={resolve:o,reject:r}),window.parent.postMessage(i,"*"),t.response||o(void 0)}))}t.bindEditorMessages=function(t){const r=(e.appTarget.appTheme.allowParentController||e.shell.isControllerMode())&&e.BrowserUtils.isIFrame(),i=e.appTarget.appTheme.allowPackageExtensions,s=e.appTarget.appTheme.allowSimulatorTelemetry;(r||i||s)&&window.addEventListener("message",(a=>{const l=a.data;if(!l||!/^pxt(host|editor|pkgext|sim)$/.test(l.type))return!1;if("pxtpkgext"===l.type&&i)t().then((e=>{e.handleExtensionRequest(l)}));else if("pxtsim"===l.type&&s){const t=l;"event"===t.action&&(t.category||t.message?e.reportError(t.category,t.message,t.data):e.tickEvent(t.tick,t.data))}else if(r){let r,i=Promise.resolve();if("pxthost"==l.type){const t=n[l.id];t?i=i.then((()=>t.resolve(l))):e.debug(`pxthost: unknown request ${l.id}`)}else"pxteditor"==l.type&&(i=i.then((()=>t().then((t=>{const n=l;switch(e.debug(`pxteditor: ${n.action}`),n.action.toLowerCase()){case"switchjavascript":return Promise.resolve().then((()=>t.openJavaScript()));case"switchpython":return Promise.resolve().then((()=>t.openPython()));case"switchblocks":return Promise.resolve().then((()=>t.openBlocks()));case"startsimulator":return Promise.resolve().then((()=>t.startSimulator()));case"restartsimulator":return Promise.resolve().then((()=>t.restartSimulator()));case"hidesimulator":return Promise.resolve().then((()=>t.collapseSimulator()));case"showsimulator":return Promise.resolve().then((()=>t.expandSimulator()));case"closeflyout":return Promise.resolve().then((()=>t.closeFlyout()));case"unloadproject":return Promise.resolve().then((()=>t.unloadProjectAsync()));case"saveproject":return t.saveProjectAsync();case"redo":return Promise.resolve().then((()=>{const e=t.editor;e&&e.hasRedo()&&e.redo()}));case"undo":return Promise.resolve().then((()=>{const e=t.editor;e&&e.hasUndo()&&e.undo()}));case"setscale":{const e=l;return Promise.resolve().then((()=>t.editor.setScale(e.scale)))}case"stopsimulator":{const e=l;return Promise.resolve().then((()=>t.stopSimulator(e.unload)))}case"newproject":{const e=l;return Promise.resolve().then((()=>t.newProject(e.options)))}case"importproject":{const e=l;return Promise.resolve().then((()=>t.importProjectAsync(e.project,{filters:e.filters,searchBar:e.searchBar})))}case"openheader":{const e=l;return t.openProjectByHeaderIdAsync(e.headerId)}case"startactivity":{const n=l;let o,r=n.path;return/^([jt]s|py|blocks?):/i.test(r)&&(o=/^py:/i.test(r)?e.PYTHON_PROJECT_NAME:/^[jt]s:/i.test(r)?e.JAVASCRIPT_PROJECT_NAME:e.BLOCKS_PROJECT_NAME,r=r.substr(r.indexOf(":")+1)),Promise.resolve().then((()=>t.startActivity({activity:n.activityType,path:r,title:n.title,editor:o,previousProjectHeaderId:n.previousProjectHeaderId,carryoverPreviousCode:n.carryoverPreviousCode})))}case"importtutorial":{const e=l;return Promise.resolve().then((()=>t.importTutorialAsync(e.markdown)))}case"proxytosim":{const e=l;return Promise.resolve().then((()=>t.proxySimulatorMessage(e.content)))}case"renderblocks":{const e=l;return Promise.resolve().then((()=>t.renderBlocksAsync(e))).then((e=>e.xml.then((e=>{r=e.xml}))))}case"renderpython":{const e=l;return Promise.resolve().then((()=>t.renderPythonAsync(e))).then((e=>{r=e.python}))}case"toggletrace":{const e=l;return Promise.resolve().then((()=>t.toggleTrace(e.intervalSpeed)))}case"settracestate":{const e=l;return Promise.resolve().then((()=>t.setTrace(e.enabled,e.intervalSpeed)))}case"setsimulatorfullscreen":{const e=l;return Promise.resolve().then((()=>t.setSimulatorFullScreen(e.enabled)))}case"togglehighcontrast":return Promise.resolve().then((()=>t.toggleHighContrast()));case"sethighcontrast":{const e=l;return Promise.resolve().then((()=>t.setHighContrast(e.on)))}case"togglegreenscreen":return Promise.resolve().then((()=>t.toggleGreenScreen()));case"print":return Promise.resolve().then((()=>t.printCode()));case"pair":return t.pairAsync();case"info":return Promise.resolve().then((()=>{r={versions:e.appTarget.versions,locale:ts.pxtc.Util.userLanguage(),availableLocales:e.appTarget.appTheme.availableLocales}}));case"shareproject":{const e=l;return t.anonymousPublishHeaderByIdAsync(e.headerId).then((e=>{r=e}))}case"savelocalprojectstocloud":{const e=l;return t.saveLocalProjectsToCloudAsync(e.headerIds).then((e=>{r={headerIdMap:e}}))}case"requestprojectcloudstatus":{const e=l;return t.requestProjectCloudStatus(e.headerIds)}case"convertcloudprojectstolocal":{const e=l;return t.convertCloudProjectsToLocal(e.userId)}case"setlanguagerestriction":{const e=l;if("no-blocks"===e.restriction)throw console.warn("no-blocks language restriction is not supported"),new Error("no-blocks language restriction is not supported");return t.setLanguageRestrictionAsync(e.restriction)}}return Promise.resolve()})))));i.then((()=>o(l,r,!0,void 0)),(e=>o(l,r,!1,e)))}return!0}),!1)},t.enableControllerAnalytics=function(){if(!e.appTarget.appTheme.allowParentController||!e.BrowserUtils.isIFrame())return;const t=e.tickEvent;e.tickEvent=function(e,n){t&&t(e,n),r({type:"pxthost",action:"event",tick:e,response:!1,data:n})};const n=e.reportException;e.reportException=function(e,t){n&&n(e,t);try{r({type:"pxthost",action:"event",tick:"error",message:e.message,response:!1,data:t})}catch(e){}};const o=e.reportError;e.reportError=function(e,t,n){o&&o(e,t,n),r({type:"pxthost",action:"event",tick:"error",category:e,message:t,data:n})}},t.shouldPostHostMessages=function(){return e.appTarget.appTheme.allowParentController&&e.BrowserUtils.isIFrame()},t.postHostMessageAsync=r}(e.editor||(e.editor={}))}(pxt||(pxt={})),function(e){!function(t){!function(t){function n(e){return`experiments-${"object"==typeof e?e.id:e}`}function o(){const t=e.savedAppTheme(),n={},o=r();return o.forEach((e=>{const o=i(e);t[e.id]=!!o,o&&(n[e.id]=o?1:0)})),o.length&&Object.keys(n).length&&(e.tickEvent("experiments.loaded",n),e.reloadAppTargetVariant()),e.appTarget.appTheme}function r(){const t=e.appTarget.appTheme.experiments;return t?[{id:"print",name:lf("Print Code"),description:lf("Print the code from the current project"),feedbackUrl:"https://github.com/microsoft/pxt/issues/4740"},{id:"greenScreen",name:lf("Green screen"),description:lf("Display a webcam video stream or a green background behind the code."),feedbackUrl:"https://github.com/microsoft/pxt/issues/4738"},{id:"allowPackageExtensions",name:lf("Editor Extensions"),description:lf("Allow Extensions to add buttons in the editor."),feedbackUrl:"https://github.com/microsoft/pxt/issues/4741"},{id:"instructions",name:lf("Wiring Instructions"),description:lf("Generate step-by-step assembly instructions for breadboard wiring."),feedbackUrl:"https://github.com/microsoft/pxt/issues/4739"},{id:"debugger",name:lf("Debugger"),description:lf("Step through code and inspect variables in the debugger"),feedbackUrl:"https://github.com/microsoft/pxt/issues/4729"},{id:"bluetoothUartConsole",name:"Bluetooth Console",description:lf("Receives UART message through Web Bluetooth"),feedbackUrl:"https://github.com/microsoft/pxt/issues/4796"},{id:"bluetoothPartialFlashing",name:"Bluetooth Download",description:lf("Download code via Web Bluetooth"),feedbackUrl:"https://github.com/microsoft/pxt/issues/4807"},{id:"simScreenshot",name:lf("Simulator Screenshots"),description:lf("Download screenshots of the simulator"),feedbackUrl:"https://github.com/microsoft/pxt/issues/5232"},{id:"python",name:lf("Static Python"),description:lf("Use Static Python to code your device"),feedbackUrl:"https://github.com/microsoft/pxt/issues/5390"},{id:"simGif",name:lf("Simulator Gifs"),description:lf("Download gifs of the simulator"),feedbackUrl:"https://github.com/microsoft/pxt/issues/5297"},{id:"qrCode",name:lf("Shared QR Code"),description:lf("Generate a QR Code form the shared project url"),feedbackUrl:"https://github.com/microsoft/pxt/issues/5456"},{id:"importExtensionFiles",name:lf("Import Extension Files"),description:lf("Import Extensions from compiled project files")},{id:"debugExtensionCode",name:lf("Debug Extension Code"),description:lf("Use the JavaScript debugger to debug extension code")},{id:"snippetBuilder",name:lf("Snippet Builder"),description:lf("Try out the new snippet dialogs.")},{id:"experimentalHw",name:lf("Experimental Hardware"),description:lf("Enable support for hardware marked 'experimental' in the hardware seletion dialog")},{id:"checkForHwVariantWebUSB",name:lf("Detect Hardware with WebUSB"),description:lf("When compiling, use WebUSB to detect hardware configuration.")},{id:"githubEditor",name:lf("GitHub editor"),description:lf("Review, commit and push to GitHub."),feedbackUrl:"https://github.com/microsoft/pxt/issues/6419",enableOnline:!0},{id:"githubCompiledJs",name:lf("GitHub Pages JavaScript"),description:lf("Commit compiled javascript when creating a release"),enableOnline:!0},{id:"blocksCollapsing",name:lf("Collapse blocks"),description:lf("Collapse and expand functions or event blocks")},{id:"tutorialBlocksDiff",name:lf("Tutorial Block Diffs"),description:lf("Automatially render blocks diff in tutorials")},{id:"openProjectNewTab",name:lf("Open in New Tab"),description:lf("Open an editor in a new tab.")},{id:"openProjectNewDependentTab",name:lf("Open in New Connected Tab"),description:lf("Open connected editors in different browser tabs.")},{id:"accessibleBlocks",name:lf("Accessible Blocks"),description:lf("Use the WASD keys to move and modify blocks."),feedbackUrl:"https://github.com/microsoft/pxt/issues/6850"},{id:"errorList",name:lf("Error List"),description:lf("Show an error list panel for JavaScript and Python.")},{id:"blocksErrorList",name:lf("Blocks Error List"),description:lf("Show an error list panel for Blocks")}].filter((n=>t.indexOf(n.id)>-1&&!(e.BrowserUtils.isPxtElectron()&&n.enableOnline))):[]}function i(t){return!!e.storage.getLocal(n(t))}function s(t,r){r!=i(t)&&(r?e.storage.setLocal(n(t),"1"):e.storage.removeLocal(n(t)),o())}t.syncTheme=o,t.all=r,t.clear=function(){r().forEach((t=>e.storage.removeLocal(n(t)))),o()},t.someEnabled=function(){return r().some((e=>i(e)))},t.isEnabled=i,t.toggle=function(e){s(e,!i(e))},t.state=function(){const e={};return r().forEach((t=>e[t.id]=i(t))),JSON.stringify(e)},t.setState=s}(t.experiments||(t.experiments={}))}(e.editor||(e.editor={}))}(pxt||(pxt={})),function(e){!function(t){function n(t){const n=e.appTarget.appTheme.invertedMonaco,o=!(!e.appTarget.appTheme.monacoFieldEditors||!e.appTarget.appTheme.monacoFieldEditors.length),r=e.BrowserUtils.isAndroid();let i=monaco.editor.create(t,{model:null,ariaLabel:e.Util.lf("JavaScript editor"),fontFamily:"'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', 'source-code-pro', 'monospace'",scrollBeyondLastLine:!0,language:"typescript",mouseWheelZoom:!1,wordBasedSuggestions:!0,lineNumbersMinChars:3,formatOnPaste:!0,folding:o,glyphMargin:o||e.appTarget.appTheme.debugger,minimap:{enabled:!1},fixedOverflowWidgets:!0,autoIndent:"full",useTabStops:!0,dragAndDrop:!0,matchBrackets:"always",occurrencesHighlight:!1,quickSuggestionsDelay:200,theme:n?"vs-dark":"vs",renderIndentGuides:!0,accessibilityHelpUrl:"",quickSuggestions:{other:!r,comments:!r,strings:!r},acceptSuggestionOnCommitCharacter:!r,acceptSuggestionOnEnter:r?"off":"on",accessibilitySupport:r?"off":"on"});return i.layout(),i}t.syncModels=function(e,t,n,o){if(o)return;let r=monaco.languages.typescript.typescriptDefaults.getExtraLibs(),i={};e.sortedDeps().forEach((e=>{e.getFiles().forEach((o=>{let r=e.id+"/"+o;if(/\.(ts)$/.test(o)&&r!=n){if(!monaco.languages.typescript.typescriptDefaults.getExtraLibs()[r]){let n=e.readFile(o)||"\n";t[r]=monaco.languages.typescript.typescriptDefaults.addExtraLib(n,r)}i[r]="1"}}))})),Object.keys(r).filter((e=>/\.(ts)$/.test(e)&&!i[e])).forEach((e=>{t[e].dispose()}))},t.initMonacoAsync=function(t){return new Promise(((o,r)=>{if("object"==typeof window.monaco)return void o(n(t));let i=window.MonacoPaths,s=()=>{let r=window.require;r.config({paths:i}),r(["vs/editor/editor.main"],(()=>{monaco.languages.register({id:"asm",extensions:[".asm"]}),monaco.languages.setMonarchTokensProvider("asm",{tokenPostfix:"",keywords:["movs","mov","adds","add","adcs","adr","subs","sbcs","sub","rsbs","muls","cmp","cmn","ands","eors","orrs","bics","mvns","tst","lsls","lsrs","asrs","rors","ldr","ldrh","ldrb","ldrsh","ldrsb","ldm","str","strh","strb","stm","push","pop","cbz","cbnz","b","bl","bx","blx","sxth","sxtb","uxth","uxtb","rev","rev16","revsh","svc","cpsid","cpsie","setend","bkpt","nop","sev","wfe","wfi","yield","beq","bne","bcs","bhs","bcc","blo","bmi","bpl","bvs","bvc","bhi","bls","bge","blt","bgt","ble","bal","r0","r1","r2","r3","r4","r5","r6","r7","r8","r9","r10","r11","r12","r13","r14","r15","pc","sp","lr"],typeKeywords:[".startaddr",".hex",".short",".space",".section",".string",".byte"],operators:[],symbols:/[:\*]+/,escapes:/\\(?:[abfnrtv\\"']|x[0-9A-Fa-f]{1,4}|u[0-9A-Fa-f]{4}|U[0-9A-Fa-f]{8})/,tokenizer:{root:[[/(\.)?[a-z_$\.][\w$]*/,{cases:{"@typeKeywords":"keyword","@keywords":"keyword","@default":"identifier"}}],{include:"@whitespace"},[/[{}()\[\]]/,"@brackets"],[/[<>](?!@symbols)/,"@brackets"],[/@symbols/,{cases:{"@operators":"operator","@default":""}}],[/@\s*[a-zA-Z_\$][\w\$]*/,{token:"annotation"}],[/(#|(0[xX]))?[0-9a-fA-F]+/,"number"],[/[;,.]/,"delimiter"],[/"([^"\\]|\\.)*$/,"string.invalid"],[/"/,{token:"string.quote",bracket:"@open",next:"@string"}],[/'[^\\']'/,"string"],[/(')(@escapes)(')/,["string","string.escape","string"]],[/'/,"string.invalid"]],comment:[],string:[[/[^\\"]+/,"string"],[/@escapes/,"string.escape"],[/\\./,"string.escape.invalid"],[/"/,{token:"string.quote",bracket:"@close",next:"@pop"}]],whitespace:[[/[ \t\r\n]+/,"white"],[/\/\*/,"comment","@comment"],[/;.*$/,"comment"]]}}),monaco.languages.typescript&&(monaco.languages.typescript.typescriptDefaults.setDiagnosticsOptions({noSyntaxValidation:!0,noSemanticValidation:!0}),monaco.languages.typescript.typescriptDefaults.setWorkerOptions({customWorkerPath:e.webConfig.typeScriptWorkerJs}),monaco.languages.typescript.typescriptDefaults.setCompilerOptions({allowUnreachableCode:!0,noImplicitAny:!0,allowJs:!1,allowUnusedLabels:!0,target:monaco.languages.typescript.ScriptTarget.ES5,outDir:"built",rootDir:".",noLib:!0,mouseWheelZoom:!1})),o(n(t))}))};if(window.require)s();else{let e=document.createElement("script");e.type="text/javascript",e.src=i["vs/loader"],e.addEventListener("load",s),document.body.appendChild(e)}}))},t.createEditor=n}(e.vs||(e.vs={}))}(pxt||(pxt={})),function(e){!function(t){t.freshHeader=function(t,n){return{target:e.appTarget.id,targetVersion:e.appTarget.versions.target,name:t,meta:{},editor:e.JAVASCRIPT_PROJECT_NAME,pubId:"",pubCurrent:!1,_rev:null,id:e.U.guidGen(),recentUse:n,modificationTime:n,cloudUserId:null,cloudCurrent:!1,cloudVersion:null,cloudLastSyncTime:0,isDeleted:!1}}}(e.workspace||(e.workspace={}))}(pxt||(pxt={})),function(e){!function(e){const t={};e.registerMonacoFieldEditor=function(e,n){t[e]=n},e.getMonacoFieldEditor=function(e){return t[e]}}(e.editor||(e.editor={}))}(pxt||(pxt={})),function(e){!function(t){t.MonacoReactFieldEditor=class{getId(){return"image-editor"}showEditorAsync(t,n,o){return this.fileType=t,this.editrange=n,this.host=o,this.initAsync().then((()=>{const t=this.textToValue(o.getText(n));return t?(this.fv=e.react.getFieldEditorView(this.getFieldEditorId(),t,this.getOptions()),this.fv.onHide((()=>{this.onClosed()})),this.fv.show(),new Promise(((e,t)=>{this.resolver=e,this.rejecter=t}))):Promise.resolve(null)}))}onClosed(){this.resolver&&(this.resolver({range:this.editrange,replacement:this.resultToText(this.fv.getResult())}),this.editrange=void 0,this.resolver=void 0,this.rejecter=void 0)}dispose(){this.onClosed()}initAsync(){return Promise.resolve()}textToValue(e){return null}resultToText(e){return e+""}getFieldEditorId(){return""}getOptions(){return null}}}(e.editor||(e.editor={}))}(pxt||(pxt={})),function(e){!function(t){const n="image-editor";class o extends t.MonacoReactFieldEditor{textToValue(t){this.isPython=-1===t.indexOf("`");const n=e.parseAssetTSReference(t);if(n){const{type:t,name:o}=n,r=o.trim(),i=e.react.getTilemapProject();this.isAsset=!0;const s=i.lookupAssetByName("image",r);if(s)return s;{const t=i.createNewImage();return r&&!i.isNameTaken("image",r)&&e.validateAssetName(r)&&(t.meta.displayName=r),t}}return{type:"image",id:"",internalID:0,bitmap:e.sprite.imageLiteralToBitmap(t).data(),meta:{},jresData:""}}resultToText(t){var n;if(null===(n=t.meta)||void 0===n?void 0:n.displayName){const n=e.react.getTilemapProject();return t=this.isAsset||n.lookupAsset(t.type,t.id)?n.updateAsset(t):n.createNewProjectImage(t.bitmap,t.meta.displayName),this.isAsset=!0,e.getTSReferenceForAsset(t,this.isPython)}return e.sprite.bitmapToImageLiteral(e.sprite.Bitmap.fromData(t.bitmap),this.isPython?"python":"typescript")}getFieldEditorId(){return"image-editor"}getOptions(){return{initWidth:16,initHeight:16,blocksInfo:this.host.blocksInfo()}}}t.MonacoSpriteEditor=o,t.spriteEditorDefinition={id:n,foldMatches:!0,glyphCssClass:"sprite-editor-glyph sprite-focus-hover",heightInPixels:510,matcher:{searchString:'(?:img|assets\\s*\\.\\s*image)\\s*(?:`|\\(\\s*""")(?:(?:[^(){}:\\[\\]"\';?/,+\\-=*&|^%!`~]|\\n)*)\\s*(?:`|"""\\s*\\))',isRegex:!0,matchCase:!0,matchWholeWord:!1},proto:o},t.registerMonacoFieldEditor(n,t.spriteEditorDefinition)}(e.editor||(e.editor={}))}(pxt||(pxt={})),function(e){!function(t){const n="tilemap-editor";class o extends t.MonacoReactFieldEditor{textToValue(t){const n=this.readTilemap(t),o=e.react.getTilemapProject();return e.sprite.addMissingTilemapTilesAndReferences(o,n),n}readTilemap(t){const n=e.react.getTilemapProject();if(/^\s*tiles\s*\./.test(t)&&(this.isTilemapLiteral=!1,t)){try{return function(e){return{type:"tilemap",id:"",internalID:0,meta:{},data:e}}(e.sprite.decodeTilemap(t,"typescript",n))}catch(e){}return null}this.isTilemapLiteral=!0;const o=/^\s*(tilemap(?:8|16|32)?)\s*(?:`([^`]*)`)|(?:\(\s*"""([^"]*)"""\s*\))\s*$/.exec(t),r=(o[2]||o[3]||"").trim();let i,s;if(this.tilemapLiteral=o[1],r){let e=ts.pxtc.escapeIdentifier(r);i=n.getTilemap(e)}if(!i){let e=16;"tilemap8"===this.tilemapLiteral?e=8:"tilemap32"===this.tilemapLiteral&&(e=32);const[t]=n.createNewTilemap(s,e,16,16);i=n.getTilemap(t),s=t}return i}resultToText(t){const n=e.react.getTilemapProject();return n.pushUndo(),e.sprite.updateTilemapReferencesFromResult(n,t),this.isTilemapLiteral?(n.updateAsset(t),e.getTSReferenceForAsset(t,"python"===this.fileType)):e.sprite.encodeTilemap(t.data,"typescript"===this.fileType?"typescript":"python")}getFieldEditorId(){return"tilemap-editor"}getOptions(){return{initWidth:16,initHeight:16,blocksInfo:this.host.blocksInfo()}}getCreateTilemapRange(){const e=this.editrange.getStartPosition();let t,n=this.editrange.getEndPosition(),o=1;for(;;){t=new monaco.Range(n.lineNumber,n.column,n.lineNumber+1,0);const r=this.host.getText(t);for(let t=0;t<r.length;t++)if("("===r.charAt(t))o++;else if(")"===r.charAt(t)&&(o--,0===o)){const o=new monaco.Position(n.lineNumber,n.column+t+2);return monaco.Range.fromPositions(e,o)}if(n=t.getEndPosition(),n.lineNumber>e.lineNumber+20)return null}}}t.MonacoTilemapEditor=o,t.tilemapEditorDefinition={id:n,foldMatches:!0,alwaysBuildOnClose:!0,glyphCssClass:"sprite-focus-hover ms-Icon ms-Icon--Nav2DMapView",heightInPixels:510,weight:5,matcher:{searchString:'(?:tilemap(?:8|16|32)?\\s*(?:`|\\(""")(?:[ a-zA-Z0-9_]|\\n)*\\s*(?:`|"""\\)))|(?:tiles\\s*\\.\\s*createTilemap\\s*\\([^\\)]+\\))',isRegex:!0,matchCase:!0,matchWholeWord:!1},proto:o},t.registerMonacoFieldEditor(n,t.tilemapEditorDefinition)}(e.editor||(e.editor={}))}(pxt||(pxt={})),function(e){!function(e){let t;e.makeFocusable=function(e){e.setAttribute("focusable","true"),e.setAttribute("tabindex","0")},e.enableKeyboardInteraction=function(e,t,n){t&&e.addEventListener("keydown",(e=>{const n="number"==typeof e.which?e.which:e.keyCode;32!==n&&13!==n||t()})),n&&e.addEventListener("keyup",(e=>{const t="number"==typeof e.which?e.which:e.keyCode;32!==t&&13!==t||n()}))},e.setAria=function(e,t,n){t&&!e.hasAttribute("role")&&e.setAttribute("role",t),n&&!e.hasAttribute("aria-label")&&e.setAttribute("aria-label",n)},e.setLiveContent=function(e){if(!t){let e="position: absolute !important;display: block;visibility: visible;overflow: hidden;width: 1px;height: 1px;margin: -1px;border: 0;padding: 0;clip: rect(0 0 0 0);";t=document.createElement("div"),t.setAttribute("role","status"),t.setAttribute("aria-live","polite"),t.setAttribute("aria-hidden","false"),t.setAttribute("style",e),document.body.appendChild(t)}t.textContent!==e&&(t.textContent=e)}}(e.accessibility||(e.accessibility={}))}(pxsim||(pxsim={})),function(e){const t="blue",n="red",o="orange";const r=e=>(e=>e.reduce(((e,t)=>e+(t?1:0)),0))(e)>0;function i(e,t){let n={};for(let t in e)n[t]=e[t];for(let e in t)n[e]=t[e];return n}function s(t){e.U.assert(!!t,"Invalid pin: "+t);const n=/^(\w+)\.\s*(?:[a-z]*)?([A-Z][A-Z\d_]+)$/.exec(t);return n?n[2]:void 0}function a(e){return"-Z"===e.orientation&&"male"===e.style}e.readPin=s;class l{constructor(t){this.availablePowerPins={top:{fiveVolt:e.mkRange(26,51).map((e=>({type:"breadboard",row:"+",col:`${e}`}))),threeVolt:e.mkRange(26,51).map((e=>({type:"breadboard",row:"+",col:`${e}`}))),ground:e.mkRange(26,51).map((e=>({type:"breadboard",row:"-",col:`${e}`})))},bottom:{fiveVolt:e.mkRange(1,26).map((e=>({type:"breadboard",row:"+",col:`${e}`}))),threeVolt:e.mkRange(1,26).map((e=>({type:"breadboard",row:"+",col:`${e}`}))),ground:e.mkRange(1,26).map((e=>({type:"breadboard",row:"-",col:`${e}`})))}},this.opts=t}allocPartIRs(e,t,n){let o=[];const r=(e,t,o,r)=>{let i=[];for(let t=0;t<e.numberOfPins;t++){let r,s=e.pinDefinitions[t];if("string"==typeof s.target)r=s.target;else{let e=s.target.pinInstantiationIdx;if(!o||void 0===o[e])return void console.log(`error: parts no pin found for PinInstantiationIdx: ${e}. (Is the part missing an ArgumentRole or "trackArgs=" annotations?)`);r=o[e]}let a=e.visual.pinLocations[t],l=n.yOffset+a.y,c=Math.round(l/e.visual.pinDistance),u=l-c*e.visual.pinDistance,d=n.xOffset+a.x,p=Math.round(d/e.visual.pinDistance),g={partRelativeRowIdx:c,partRelativeColIdx:p,xOffset:d-p*e.visual.pinDistance,yOffset:u};i.push({def:s,loc:a,target:r,bbFit:g})}return{name:t,def:e,pins:i,partParams:r||{},bbFit:n}},i=e.instantiations||[];return e.instantiation&&i.push(e.instantiation),i.forEach((n=>{if("singleton"===n.kind)o.push(r(e,t));else if("function"===n.kind){let i=n,a=i.fullyQualifiedName.split(","),l={};a.forEach((e=>{this.opts.fnArgs[e]&&this.opts.fnArgs[e].forEach((e=>{l[e]=1}))}));let c=Object.keys(l);if(!c||!c.length)return void console.log(`error: parts failed to read pin(s) from callsite for: ${a}`);c.forEach((n=>{const l=n.split(",");if(l.length!=i.argumentRoles.length)return void console.log(`error: parts mismatch between number of arguments at callsite (function name: ${a}) vs number of argument roles in part definition (part: ${t}).`);let c=[],u={};l.forEach(((e,t)=>{let n=i.argumentRoles[t];if(void 0!==n.partParameter&&(u[n.partParameter]=e),void 0!==n.pinInstantiationIdx){let t=n.pinInstantiationIdx,o=s(e);c[t]=o}})),o.push(r(e,t,c,u))}))}})),o.filter((e=>!!e))}computePartDimensions(t,n){let o=t.visual.pinLocations,r=t.pinDefinitions,s=t.numberOfPins;e.U.assert(o.length===s,`Mismatch between "numberOfPins" and length of "visual.pinLocations" for "${n}"`),e.U.assert(r.length===s,`Mismatch between "numberOfPins" and length of "pinDefinitions" for "${n}"`),e.U.assert(s>0,`Part "${n}" has no pins`);let a,l,c,u,d=o.map(((e,t)=>{return n={idx:t},o=e,s=r[t],i(i(n,o),s);var n,o,s})).filter((e=>"-Z"===e.orientation)),p=d.length>0,g=t.visual.pinDistance;if(p){let e=d[0],n=Math.ceil(e.x/g),o=Math.ceil(e.y/g);a=n*g-e.x,l=o*g-e.y,c=Math.ceil((a+t.visual.width)/g)+1,u=Math.ceil((l+t.visual.height)/g)+1}else c=Math.ceil(t.visual.width/g),u=Math.ceil(t.visual.height/g),a=c*g-t.visual.width,l=u*g-t.visual.height;return{xOffset:a,yOffset:l,rowCount:u,colCount:c}}allocColumns(t){let n=t.length;let o=e.visuals.BREADBOARD_MID_COLS-t.map((e=>e.colCount)).reduce(((e,t)=>e+t),0);o<=0&&console.log("Not enough breadboard space!");let r=Math.floor(o/(n-1+2)),i=o-r*(n-1),s=Math.floor(i/2),a=(Math.ceil(i/2),1+s);return t.map((e=>{let t=a;return a+=e.colCount+r,t}))}placeParts(t){const n=e.visuals.BREADBOARD_MID_ROWS+2;let o=this.allocColumns(t.map((e=>e.bbFit))),r=t.map((e=>{let t=n-e.bbFit.rowCount,o=Math.floor(t/2);return o>4&&(o=4),o<1&&(o=1),o}));return t.map(((e,t)=>{let n=r[t];return i({startColumnIdx:o[t],startRowIdx:n},e)}))}nextColor(){return(!this.availableWireColors||this.availableWireColors.length<=0)&&(this.availableWireColors=e.visuals.GPIO_WIRE_COLORS.map((e=>e))),this.availableWireColors.pop()}allocWireIRs(r){let s=[],l=r.pins.map(((i,l)=>{let c,u,d=i.target,p=r.startColumnIdx+i.bbFit.partRelativeColIdx,g=e.visuals.getColumnName(p),h=r.startRowIdx+i.bbFit.partRelativeRowIdx;if(h>=7&&(h-=2),a(i.def)){c={type:"breadboard",row:h<5?"j":"a",col:g,style:i.def.style}}else{c={type:"breadboard",row:e.visuals.getRowName(h),col:g,xOffset:i.bbFit.xOffset/r.def.visual.pinDistance,yOffset:i.bbFit.yOffset/r.def.visual.pinDistance,style:i.def.style}}return u="ground"===d?t:"threeVolt"===d?n:"fiveVolt"===d?o:"number"==typeof i.def.colorGroup?s[i.def.colorGroup]?s[i.def.colorGroup]:s[i.def.colorGroup]=this.nextColor():this.nextColor(),{start:c,end:d,color:u,pinIdx:l}}));return i(r,{wires:l})}allocLocation(t,n){if("ground"===t||"threeVolt"===t||"fiveVolt"==t){if("ground"===t&&this.powerUsage.singleGround){return{type:"dalboard",pin:this.getBoardGroundPin()}}if("threeVolt"===t&&this.powerUsage.singleThreeVolt){return{type:"dalboard",pin:this.getBoardThreeVoltPin()}}if("fiveVolt"===t&&this.powerUsage.singleFiveVolt){return{type:"dalboard",pin:this.getBoardFiveVoltPin()}}e.U.assert(!!n.referenceBBPin);let o=this.opts.getBBCoord(n.referenceBBPin),r=[this.availablePowerPins.top.ground[0]||this.availablePowerPins.top.threeVolt[0],this.availablePowerPins.bottom.ground[0]||this.availablePowerPins.bottom.threeVolt[0]].map((e=>this.opts.getBBCoord(e)));r[0]&&r[1]||console.debug(`No more available "${t}" locations!`);let i,s=0==e.visuals.findClosestCoordIdx(o,r);s?"ground"===t?i=this.availablePowerPins.top.ground:"threeVolt"===t?i=this.availablePowerPins.top.threeVolt:"fiveVolt"===t&&(i=this.availablePowerPins.top.fiveVolt):"ground"===t?i=this.availablePowerPins.bottom.ground:"threeVolt"===t?i=this.availablePowerPins.bottom.threeVolt:"fiveVolt"===t&&(i=this.availablePowerPins.bottom.fiveVolt);let a=i.map((e=>this.opts.getBBCoord(e))),l=e.visuals.findClosestCoordIdx(o,a),c=i[l];return s?(this.availablePowerPins.top.ground.splice(l,1),this.availablePowerPins.top.threeVolt.splice(l,1)):(this.availablePowerPins.bottom.ground.splice(l,1),this.availablePowerPins.bottom.threeVolt.splice(l,1)),c}if("breadboard"===t.type)return t;if("MOSI"===t||"MISO"===t||"SCK"===t){return this.opts.boardDef.spiPins||console.debug("No SPI pin mappings found!"),{type:"dalboard",pin:this.opts.boardDef.spiPins[t]}}if("SDA"===t||"SCL"===t){return this.opts.boardDef.i2cPins||console.debug("No I2C pin mappings found!"),{type:"dalboard",pin:this.opts.boardDef.i2cPins[t]}}{e.U.assert("string"==typeof t,"Unknown location type: "+t);let n=t,o=this.opts.boardDef.gpioPinMap[n]||n;return o?{type:"dalboard",pin:o}:void console.debug(`unknown pin location for ${n}`)}}getBoardGroundPin(){let e=this.opts.boardDef.groundPins&&this.opts.boardDef.groundPins[0]||null;return e||console.debug("No available ground pin on board!"),e}getBoardThreeVoltPin(){let e=this.opts.boardDef.threeVoltPins&&this.opts.boardDef.threeVoltPins[0]||null;return e||console.debug("No available 3.3V pin on board!"),e}getBoardFiveVoltPin(){let e=this.opts.boardDef.fiveVoltPins&&this.opts.boardDef.fiveVoltPins[0]||null;return e||console.debug("No available 5V pin on board!"),e}allocPowerWires(e){let r=this.getBoardGroundPin(),i=this.getBoardThreeVoltPin(),s=this.getBoardFiveVoltPin();const a={type:"breadboard",row:"-",col:"26"},l={type:"breadboard",row:"-",col:"1"},c={type:"breadboard",row:"-",col:"50"},u={type:"breadboard",row:"-",col:"25"};let d,p;this.opts.boardDef.attachPowerOnRight?(d=c,p=u):(d=a,p=l);let g=[],h=[],f=[];e.bottomGround&&e.topGround&&g.push({start:this.allocLocation("ground",{referenceBBPin:d}),end:this.allocLocation("ground",{referenceBBPin:p}),color:t}),e.topGround?g.push({start:this.allocLocation("ground",{referenceBBPin:d}),end:{type:"dalboard",pin:r},color:t}):e.bottomGround&&g.push({start:this.allocLocation("ground",{referenceBBPin:p}),end:{type:"dalboard",pin:r},color:t}),e.bottomThreeVolt&&e.bottomGround?h.push({start:this.allocLocation("threeVolt",{referenceBBPin:d}),end:this.allocLocation("threeVolt",{referenceBBPin:p}),color:n}):e.bottomFiveVolt&&e.bottomGround&&f.push({start:this.allocLocation("fiveVolt",{referenceBBPin:d}),end:this.allocLocation("fiveVolt",{referenceBBPin:p}),color:o}),e.topThreeVolt?h.push({start:this.allocLocation("threeVolt",{referenceBBPin:d}),end:{type:"dalboard",pin:i},color:n}):e.bottomThreeVolt&&h.push({start:this.allocLocation("threeVolt",{referenceBBPin:p}),end:{type:"dalboard",pin:i},color:o}),e.topFiveVolt&&!e.topThreeVolt?f.push({start:this.allocLocation("fiveVolt",{referenceBBPin:d}),end:{type:"dalboard",pin:s},color:n}):e.bottomFiveVolt&&!e.bottomThreeVolt&&f.push({start:this.allocLocation("fiveVolt",{referenceBBPin:p}),end:{type:"dalboard",pin:s},color:o});let _=[];g.length>0&&_.push({wireIndices:g.map(((e,t)=>t))});let m=g.length;return h.length>0&&_.push({wireIndices:h.map(((e,t)=>t+m))}),f.length>0&&_.push({wireIndices:h.map(((e,t)=>t+m+h.length))}),{wires:g.concat(h).concat(f),assembly:_}}allocWire(e){const t=[e.start,e.end],n=t.map((e=>"ground"===e||"threeVolt"===e||"fiveVolt"===e));let o=t.map(((e,t)=>n[t]?void 0:this.allocLocation(e,{})));if(o=o.map(((e,n)=>{if(e)return e;const r=o[1-n];return this.allocLocation(t[n],{referenceBBPin:r})})),o[0]&&o[1])return{start:o[0],end:o[1],color:e.color}}allocPart(t){let n=t.pins.filter((e=>a(e.def))).map((n=>{let o=t.startRowIdx+n.bbFit.partRelativeRowIdx;o>=7&&(o-=2);let r=e.visuals.getRowName(o),i=t.startColumnIdx+n.bbFit.partRelativeColIdx;return{type:"breadboard",row:r,col:e.visuals.getColumnName(i)}}));return{name:t.name,visual:t.def.visual,bbFit:t.bbFit,startColumnIdx:t.startColumnIdx,startRowIdx:t.startRowIdx,breadboardConnections:n,params:t.partParams,simulationBehavior:t.def.simulationBehavior}}allocAll(){let e=this.opts.partsList.map((e=>({name:e,def:this.opts.partDefs[e]}))).filter((e=>!!e.def));if(e.length>0){let t=e.map((e=>this.computePartDimensions(e.def,e.name))),n=[];e.forEach(((e,o)=>{let r=t[o],i=this.allocPartIRs(e.def,e.name,r);n=n.concat(i)}));const o=this.placeParts(n).map((e=>this.allocWireIRs(e))),i=o.map((e=>e.wires)).reduce(((e,t)=>e.concat(t)),[]).map((e=>function(e){let t=[e.start,e.end],n=t.map((e=>"ground"===e)),o=t.map((e=>"threeVolt"===e)),i=t.map((e=>"fiveVolt"===e)),s=t.map((e=>function(e){let t=!1;if("string"!=typeof e&&"breadboard"===e.type){let n=e.row;t=0<=["a","b","c","d","e"].indexOf(n)}return t}(e))),a=r(n),l=r(o),c=r(i),u=r(s);return{topGround:a&&!u,topThreeVolt:l&&!u,topFiveVolt:c&&!u,bottomGround:a&&u,bottomThreeVolt:l&&u,bottomFiveVolt:c&&u,singleGround:a,singleThreeVolt:l,singleFiveVolt:c}}(e)));this.powerUsage=function(e){const t=e.reduce(((e,t)=>({topGround:e.topGround||t.topGround,topThreeVolt:e.topThreeVolt||t.topThreeVolt,topFiveVolt:e.topFiveVolt||t.topFiveVolt,bottomGround:e.bottomGround||t.bottomGround,bottomThreeVolt:e.bottomThreeVolt||t.bottomThreeVolt,bottomFiveVolt:e.bottomFiveVolt||t.bottomFiveVolt,singleGround:t.singleGround?null===e.singleGround:e.singleGround,singleThreeVolt:t.singleThreeVolt?null===e.singleThreeVolt:e.singleThreeVolt,singleFiveVolt:t.singleFiveVolt?null===e.singleFiveVolt:e.singleFiveVolt})),{topGround:!1,topThreeVolt:!1,topFiveVolt:!1,bottomGround:!1,bottomThreeVolt:!1,bottomFiveVolt:!1,singleGround:null,singleThreeVolt:null,singleFiveVolt:null});return t.singleGround&&(t.topGround=t.bottomGround=!1),t.singleThreeVolt&&(t.topThreeVolt=t.bottomThreeVolt=!1),t.singleFiveVolt&&(t.topFiveVolt=t.bottomFiveVolt=!1),t}(i);const s=this.allocPowerWires(this.powerUsage),a=o.map(((e,t)=>{const n=this.allocPart(e),o=e.wires.map((e=>this.allocWire(e)));if(o.some((e=>!e)))return;const r=[];e.wires.forEach(((e,t)=>{r[e.pinIdx]=t}));return{part:n,wires:o,assembly:e.def.assembly.map((e=>({part:e.part,wireIndices:(e.pinIndices||[]).map((e=>r[e]))})))}})).filter((e=>!!e)),l=[s].concat(a).filter((e=>e.assembly&&e.assembly.length)),c=!l.some((e=>e.part&&e.part.breadboardConnections&&e.part.breadboardConnections.length>0||e.wires&&e.wires.some((e=>"breadboard"==e.end.type&&"croc"!=e.end.style||"breadboard"==e.start.type&&"croc"!=e.start.style))));return{partsAndWires:l,wires:[],parts:[],hideBreadboard:c}}return{partsAndWires:[],wires:[],parts:[]}}}e.allocateDefinitions=function(e){return new l(e).allocAll()}}(pxsim||(pxsim={})),function(e){!function(e){class t{constructor(e){this.seq=0,this.type=e}}e.Message=t;e.Response=class extends t{constructor(e,t){super("response"),this.request_seq=e.seq,this.command=e.command,t?(this.success=!1,this.message=t):this.success=!0}};class n extends t{constructor(e,t){super("event"),this.event=e,t&&(this.body=t)}}e.Event=n;e.Source=class{constructor(e,t,n=0,o,r){this.name=e,this.path=t,this.sourceReference=n,o&&(this.origin=o),r&&(this.adapterData=r)}};e.Scope=class{constructor(e,t,n=!1){this.name=e,this.variablesReference=t,this.expensive=n}};e.StackFrame=class{constructor(e,t,n,o=0,r=0){this.id=e,this.source=n,this.line=o,this.column=r,this.name=t}};e.Thread=class{constructor(e,t){this.id=e,this.name=t||"Thread #"+e}};e.Variable=class{constructor(e,t,n=0,o,r){this.name=e,this.value=t,this.variablesReference=n,"number"==typeof r&&(this.namedVariables=r),"number"==typeof o&&(this.indexedVariables=o)}};e.Breakpoint=class{constructor(e,t,n,o){this.verified=e;const r=this;"number"==typeof t&&(r.line=t),"number"==typeof n&&(r.column=n),o&&(r.source=o)}};e.Module=class{constructor(e,t){this.id=e,this.name=t}};e.CompletionItem=class{constructor(e,t,n=0){this.label=e,this.start=t,this.length=n}};e.StoppedEvent=class extends n{constructor(e,t,n=null){if(super("stopped"),this.body={reason:e,threadId:t},n){this.body.text=n}}};e.ContinuedEvent=class extends n{constructor(e,t){super("continued"),this.body={threadId:e},"boolean"==typeof t&&(this.body.allThreadsContinued=t)}};e.InitializedEvent=class extends n{constructor(){super("initialized")}};e.TerminatedEvent=class extends n{constructor(e){if(super("terminated"),"boolean"==typeof e){this.body={restart:e}}}};e.OutputEvent=class extends n{constructor(e,t="console",n){super("output"),this.body={category:t,output:e},void 0!==n&&(this.body.data=n)}};e.ThreadEvent=class extends n{constructor(e,t){super("thread"),this.body={reason:e,threadId:t}}};e.BreakpointEvent=class extends n{constructor(e,t){super("breakpoint"),this.body={reason:e,breakpoint:t}}};e.ModuleEvent=class extends n{constructor(e,t){super("module"),this.body={reason:e,module:t}}};class o{constructor(){this._pendingRequests={}}start(e){this._sequence=1,this.host=e,this.host.onData((e=>{if("request"===e.type)this.dispatchRequest(e);else if("response"===e.type){const t=e,n=this._pendingRequests[t.seq];n&&(delete this._pendingRequests[t.seq],n(t))}}))}stop(){this.host&&this.host.close()}sendEvent(e){this.send("event",e)}sendResponse(e){e.seq>0?console.error(`attempt to send more than one response for command ${e.command}`):this.send("response",e)}sendRequest(t,n,o,r){const i={command:t};if(n&&Object.keys(n).length>0&&(i.arguments=n),this.send("request",i),r){this._pendingRequests[i.seq]=r;const t=setTimeout((()=>{clearTimeout(t);const n=this._pendingRequests[i.seq];n&&(delete this._pendingRequests[i.seq],n(new e.Response(i,"timeout")))}),o)}}send(e,t){if(t.type=e,t.seq=this._sequence++,this.host){const e=JSON.stringify(t);this.host.send(e)}}dispatchRequest(e){}}e.ProtocolServer=o;class r extends o{constructor(){super(...arguments),this._debuggerLinesStartAt1=!1,this._debuggerColumnsStartAt1=!1,this._clientLinesStartAt1=!0,this._clientColumnsStartAt1=!0}shutdown(){}dispatchRequest(t){const n=new e.Response(t);try{if("initialize"===t.command){let e=t.arguments;if("boolean"==typeof e.linesStartAt1&&(this._clientLinesStartAt1=e.linesStartAt1),"boolean"==typeof e.columnsStartAt1&&(this._clientColumnsStartAt1=e.columnsStartAt1),"path"!==e.pathFormat)this.sendErrorResponse(n,2018,"debug adapter only supports native paths",null);else{const t=n;t.body={},this.initializeRequest(t,e)}}else"launch"===t.command?this.launchRequest(n,t.arguments):"attach"===t.command?this.attachRequest(n,t.arguments):"disconnect"===t.command?this.disconnectRequest(n,t.arguments):"setBreakpoints"===t.command?this.setBreakPointsRequest(n,t.arguments):"setFunctionBreakpoints"===t.command?this.setFunctionBreakPointsRequest(n,t.arguments):"setExceptionBreakpoints"===t.command?this.setExceptionBreakPointsRequest(n,t.arguments):"configurationDone"===t.command?this.configurationDoneRequest(n,t.arguments):"continue"===t.command?this.continueRequest(n,t.arguments):"next"===t.command?this.nextRequest(n,t.arguments):"stepIn"===t.command?this.stepInRequest(n,t.arguments):"stepOut"===t.command?this.stepOutRequest(n,t.arguments):"stepBack"===t.command?this.stepBackRequest(n,t.arguments):"restartFrame"===t.command?this.restartFrameRequest(n,t.arguments):"goto"===t.command?this.gotoRequest(n,t.arguments):"pause"===t.command?this.pauseRequest(n,t.arguments):"stackTrace"===t.command?this.stackTraceRequest(n,t.arguments):"scopes"===t.command?this.scopesRequest(n,t.arguments):"variables"===t.command?this.variablesRequest(n,t.arguments):"setVariable"===t.command?this.setVariableRequest(n,t.arguments):"source"===t.command?this.sourceRequest(n,t.arguments):"threads"===t.command?this.threadsRequest(n):"evaluate"===t.command?this.evaluateRequest(n,t.arguments):"stepInTargets"===t.command?this.stepInTargetsRequest(n,t.arguments):"gotoTargets"===t.command?this.gotoTargetsRequest(n,t.arguments):"completions"===t.command?this.completionsRequest(n,t.arguments):this.customRequest(t.command,n,t.arguments)}catch(e){this.sendErrorResponse(n,1104,"{_stack}",{_exception:e.message,_stack:e.stack})}}initializeRequest(e,t){e.body.supportsConditionalBreakpoints=!1,e.body.supportsHitConditionalBreakpoints=!1,e.body.supportsFunctionBreakpoints=!1,e.body.supportsConfigurationDoneRequest=!0,e.body.supportsEvaluateForHovers=!1,e.body.supportsStepBack=!1,e.body.supportsSetVariable=!1,e.body.supportsRestartFrame=!1,e.body.supportsStepInTargetsRequest=!1,e.body.supportsGotoTargetsRequest=!1,e.body.supportsCompletionsRequest=!1,this.sendResponse(e)}disconnectRequest(e,t){this.sendResponse(e),this.shutdown()}launchRequest(e,t){this.sendResponse(e)}attachRequest(e,t){this.sendResponse(e)}setBreakPointsRequest(e,t){this.sendResponse(e)}setFunctionBreakPointsRequest(e,t){this.sendResponse(e)}setExceptionBreakPointsRequest(e,t){this.sendResponse(e)}configurationDoneRequest(e,t){this.sendResponse(e)}continueRequest(e,t){this.sendResponse(e)}nextRequest(e,t){this.sendResponse(e)}stepInRequest(e,t){this.sendResponse(e)}stepOutRequest(e,t){this.sendResponse(e)}stepBackRequest(e,t){this.sendResponse(e)}restartFrameRequest(e,t){this.sendResponse(e)}gotoRequest(e,t){this.sendResponse(e)}pauseRequest(e,t){this.sendResponse(e)}sourceRequest(e,t){this.sendResponse(e)}threadsRequest(e){this.sendResponse(e)}stackTraceRequest(e,t){this.sendResponse(e)}scopesRequest(e,t){this.sendResponse(e)}variablesRequest(e,t){this.sendResponse(e)}setVariableRequest(e,t){this.sendResponse(e)}evaluateRequest(e,t){this.sendResponse(e)}stepInTargetsRequest(e,t){this.sendResponse(e)}gotoTargetsRequest(e,t){this.sendResponse(e)}completionsRequest(e,t){this.sendResponse(e)}customRequest(e,t,n){this.sendErrorResponse(t,1014,"unrecognized request",null)}sendErrorResponse(e,t,n,o){let i;"number"==typeof t?(i={id:t,format:n},o&&(i.variables=o),i.showUser=!0):i=t,e.success=!1,r.formatPII(i.format,!0,i.variables),e.body||(e.body={}),e.body.error=i,this.sendResponse(e)}convertClientLineToDebugger(e){return this._debuggerLinesStartAt1?this._clientLinesStartAt1?e:e+1:this._clientLinesStartAt1?e-1:e}convertDebuggerLineToClient(e){return this._debuggerLinesStartAt1?this._clientLinesStartAt1?e:e-1:this._clientLinesStartAt1?e+1:e}convertClientColumnToDebugger(e){return this._debuggerColumnsStartAt1?this._clientColumnsStartAt1?e:e+1:this._clientColumnsStartAt1?e-1:e}convertDebuggerColumnToClient(e){return this._debuggerColumnsStartAt1?this._clientColumnsStartAt1?e:e-1:this._clientColumnsStartAt1?e+1:e}convertClientPathToDebugger(e){return this._clientPathsAreURIs!=this._debuggerPathsAreURIs?this._clientPathsAreURIs?r.uri2path(e):r.path2uri(e):e}convertDebuggerPathToClient(e){return this._debuggerPathsAreURIs!=this._clientPathsAreURIs?this._debuggerPathsAreURIs?r.uri2path(e):r.path2uri(e):e}static path2uri(e){let t=e.replace(/\\/g,"/");return"/"!==t[0]&&(t="/"+t),encodeURI("file://"+t)}static uri2path(e){return e}static formatPII(e,t,n){return e.replace(r._formatPIIRegexp,(function(e,o){return t&&o.length>0&&"_"!==o[0]?e:n[o]&&n.hasOwnProperty(o)?n[o]:e}))}}r._formatPIIRegexp=/{([^}]+)}/g,e.DebugSession=r}(e.protocol||(e.protocol={}))}(pxsim||(pxsim={})),function(e){!function(e){e.injectPolyphils=function(){String.prototype.startsWith||Object.defineProperty(String.prototype,"startsWith",{value:function(e,t){return void 0!==e&&null!=e&&(t=!t||t<0?0:+t,this.substring(t,t+e.length)===e)}}),Array.prototype.fill||Object.defineProperty(Array.prototype,"fill",{writable:!0,enumerable:!0,value:function(e){if(null==this)throw new TypeError("this is null or not defined");let t=Object(this),n=t.length>>>0,o=arguments[1],r=o>>0,i=r<0?Math.max(n+r,0):Math.min(r,n),s=arguments[2],a=void 0===s?n:s>>0,l=a<0?Math.max(n+a,0):Math.min(a,n);for(;i<l;)t[i]=e,i++;return t}}),Array.prototype.find||Object.defineProperty(Array.prototype,"find",{writable:!0,enumerable:!0,value:function(e){if(null==this)throw new TypeError('"this" is null or not defined');let t=Object(this);const n=t.length>>>0;if("function"!=typeof e)throw new TypeError("predicate must be a function");const o=arguments[1];let r=0;for(;r<n;){const n=t[r];if(e.call(o,n,r,t))return n;r++}}}),Uint8Array.prototype.slice||Object.defineProperty(Uint8Array.prototype,"slice",{value:Array.prototype.slice,writable:!0,enumerable:!0}),Uint16Array.prototype.slice||Object.defineProperty(Uint16Array.prototype,"slice",{value:Array.prototype.slice,writable:!0,enumerable:!0}),Uint32Array.prototype.slice||Object.defineProperty(Uint32Array.prototype,"slice",{value:Array.prototype.slice,writable:!0,enumerable:!0}),Uint8Array.prototype.fill||Object.defineProperty(Uint8Array.prototype,"fill",{value:Array.prototype.fill,writable:!0,enumerable:!0}),Uint16Array.prototype.fill||Object.defineProperty(Uint16Array.prototype,"fill",{value:Array.prototype.fill,writable:!0,enumerable:!0}),Uint32Array.prototype.fill||Object.defineProperty(Uint32Array.prototype,"fill",{value:Array.prototype.fill,writable:!0,enumerable:!0}),Uint8Array.prototype.some||Object.defineProperty(Uint8Array.prototype,"some",{value:Array.prototype.some,writable:!0,enumerable:!0}),Uint16Array.prototype.some||Object.defineProperty(Uint16Array.prototype,"some",{value:Array.prototype.some,writable:!0,enumerable:!0}),Uint32Array.prototype.some||Object.defineProperty(Uint32Array.prototype,"some",{value:Array.prototype.some,writable:!0,enumerable:!0}),Uint8Array.prototype.reverse||Object.defineProperty(Uint8Array.prototype,"reverse",{value:Array.prototype.reverse,writable:!0,enumerable:!0}),Uint16Array.prototype.reverse||Object.defineProperty(Uint16Array.prototype,"reverse",{value:Array.prototype.reverse,writable:!0,enumerable:!0}),Uint32Array.prototype.reverse||Object.defineProperty(Uint32Array.prototype,"reverse",{value:Array.prototype.reverse,writable:!0,enumerable:!0}),Math.imul||(Math.imul=function(e,t){const n=65535&e,o=65535&t;return n*o+((e>>>16&65535)*o+n*(t>>>16&65535)<<16>>>0)|0}),"function"!=typeof Object.assign&&Object.defineProperty(Object,"assign",{value:function(e,t){if(null==e)throw new TypeError("Cannot convert undefined or null to object");let n=Object(e);for(let e=1;e<arguments.length;e++){let t=arguments[e];if(null!=t)for(let e in t)Object.prototype.hasOwnProperty.call(t,e)&&(n[e]=t[e])}return n},writable:!0,configurable:!0}),Promise.prototype.finally||(Promise.prototype.finally=Promise.prototype.finally||{finally(e){const t=t=>Promise.resolve(e()).then(t);return this.then((e=>t((()=>e))),(e=>t((()=>Promise.reject(e)))))}}.finally)};function t(e){e=e.replace(/\\/g,"/");const t=[];return e.split("/").forEach((e=>{".."===e&&t.length?t.pop():e&&"."!==e&&t.push(e)})),t}e.Lazy=class{constructor(e){this._func=e,this._evaluated=!1}get value(){return this._evaluated||(this._value=this._func(),this._evaluated=!0),this._value}},e.getNormalizedParts=t,e.normalizePath=function(e){return t(e).join("/")},e.relativePath=function(e,n){const o=t(e),r=t(n);let i=0;for(;o[i]===r[i]&&(i++,i!==o.length&&i!==r.length););const s=o.slice(i),a=r.slice(i);for(let e=0;e<s.length;e++)a.unshift("..");return a.join("/")},e.pathJoin=function(...e){let t="";return e.forEach((e=>{e.replace(/\\/g,"/"),e.lastIndexOf("/")===e.length-1&&(e=e.slice(0,e.length-1)),t+="/"+e})),t},e.toArray=function(e){if(Array.isArray(e))return e;let t=[];for(let n=0;n<e.length;++n)t.push(e[n]);return t}}(e.util||(e.util={}))}(pxsim||(pxsim={})),function(e){e.getWarningMessage=function(t){let n={type:"debugger",subtype:"warning",breakpointIds:[],message:t},o=e.runtime.currFrame;for(;null!=o;)n.breakpointIds.push(o.lastBrkId),o=o.parent;return n};function t(t,n){switch(typeof t){case"string":case"number":case"boolean":return t;case"function":return{text:"(function)",type:"function"};case"undefined":return null;case"object":if(!t)return null;if(t instanceof e.RefObject){n&&(n[t.id]=t);let o=e.RefObject.toDebugString(t),r=o.startsWith("[")?"array":o;return{id:t.id,preview:o,hasFields:null!==t.fields||o.startsWith("["),type:r}}return t._width&&t._height?{text:t._width+"x"+t._height,type:"image"}:{text:"(object)",type:"object"};default:throw new Error}}function n(e,n,r,i){return function(e,r){const s={};for(let o of Object.keys(e))/^__/.test(o)||!/___\d+$/.test(o)||i&&-1===i.indexOf(o)||(s[o]=t(e[o],n));if(e.fields&&r)for(let i of r)i=i.substring(i.lastIndexOf(".")+1),s[i]=t(o(e.vtable.iface[i],e),n);if(e.fields)for(let o of Object.keys(e.fields).filter((e=>!e.startsWith("_"))))s[o]=t(e.fields[o],n);else Array.isArray(e.data)&&e.data.forEach(((e,o)=>{s[o]=t(e,n)}));return s}(e,r)}function o(e,t){let n={pc:0,arg0:t,fn:e,parent:{}};for(;n.fn;)n=n.fn(n);return n.retval}function r(e,o){let r=e.fn?e.fn.info:null;if(r){let i={thisParam:t(e.argL,o),params:[]};if(r.argumentNames){const n=r.argumentNames;i.params=n.map(((n,r)=>({name:n,value:t(e["arg"+r],o)})))}return{locals:n(e,o),funcInfo:r,breakpointId:e.lastBrkId,callLocationId:e.callLocIdx,arguments:i}}}e.BreakpointMap=class{constructor(e){this.fileMap={},this.idMap={},e.forEach((e=>{const[t,n]=e;this.fileMap[n.source.path]||(this.fileMap[n.source.path]=[]),this.fileMap[n.source.path].push(e),this.idMap[t]=n}));for(const e in this.fileMap){const t=this.fileMap[e];this.fileMap[e]=t.sort((([,e],[,t])=>e.line===t.line?t.endLine===e.endLine?e.column-t.column:t.endLine-e.endLine:e.line-t.line))}}getById(e){return this.idMap[e]}verifyBreakpoint(e,t){const n=this.fileMap[e];let o;if(n)for(const[e,r]of n)r.line<=t.line&&r.endLine>=t.line&&(o=[e,r]);return o?(o[1].verified=!0,o):[-1,{verified:!1}]}},e.dumpHeap=n,e.injectEnvironmentGlobals=function(n,o){const r=e.runtime.environmentGlobals;if(!Object.keys(r).length)return;const i=n.environmentGlobals={};Object.keys(r).forEach((n=>i[n]=t(e.runtime.environmentGlobals[n],o)))},e.getBreakpointMsg=function(t,o,i){const s={},a={type:"debugger",subtype:"breakpoint",breakpointId:o,globals:n(e.runtime.globals,s,void 0,i),stackframes:[]};for(;null!=t;){let e=r(t,s);e&&a.stackframes.push(e),t=t.parent}return{msg:a,heap:s}};class i extends e.protocol.DebugSession{constructor(t){super();let n={onDebuggerBreakpoint:e=>this.onDebuggerBreakpoint(e),onDebuggerWarning:e=>this.onDebuggerWarning(e),onDebuggerResume:()=>this.onDebuggerResume(),onStateChanged:e=>this.onStateChanged(e)};this.driver=new e.SimulatorDriver(t,n)}runCode(t,n,o,r,i){this.breakpoints=r,this.projectDir&&this.fixBreakpoints(),this.sendEvent(new e.protocol.InitializedEvent),this.driver.run(t,{parts:n,fnArgs:o,boardDefinition:i})}stopSimulator(e=!1){this.driver.stop(e)}initializeRequest(e,t){e.body.supportsConditionalBreakpoints=!1,e.body.supportsHitConditionalBreakpoints=!1,e.body.supportsFunctionBreakpoints=!1,e.body.supportsEvaluateForHovers=!1,e.body.supportsStepBack=!1,e.body.supportsSetVariable=!1,e.body.supportsRestartFrame=!1,e.body.supportsStepInTargetsRequest=!1,e.body.supportsGotoTargetsRequest=!1,e.body.supportsCompletionsRequest=!1,e.body.supportsConfigurationDoneRequest=!0,this.sendResponse(e)}disconnectRequest(e,t){this.sendResponse(e),this.shutdown()}launchRequest(t,n){this.projectDir||(this.projectDir=e.util.normalizePath(n.projectDir),this.breakpoints&&this.fixBreakpoints()),this.sendResponse(t)}setBreakPointsRequest(t,n){t.body={breakpoints:[]};const o=[];n.breakpoints.forEach((r=>{if(this.breakpoints){const[i,s]=this.breakpoints.verifyBreakpoint(e.util.relativePath(this.projectDir,n.source.path),r);t.body.breakpoints.push(s),s.verified&&o.push(i)}else t.body.breakpoints.push({verified:!1})})),this.driver.setBreakpoints(o),this.sendResponse(t)}continueRequest(t,n){this.driver.resume(e.SimulatorDebuggerCommand.Resume),this.sendResponse(t)}nextRequest(t,n){this.driver.resume(e.SimulatorDebuggerCommand.StepOver),this.sendResponse(t)}stepInRequest(t,n){this.driver.resume(e.SimulatorDebuggerCommand.StepInto),this.sendResponse(t)}stepOutRequest(t,n){this.driver.resume(e.SimulatorDebuggerCommand.StepOut),this.sendResponse(t)}pauseRequest(t,n){this.driver.resume(e.SimulatorDebuggerCommand.Pause),this.sendResponse(t)}threadsRequest(e){e.body={threads:[{id:i.THREAD_ID,name:"main"}]},this.sendResponse(e)}stackTraceRequest(e,t){if(this.lastBreak){const t=this.state.getFrames();e.body={stackFrames:t}}this.sendResponse(e)}scopesRequest(e,t){this.state&&(e.body={scopes:this.state.getScopes(t.frameId)}),this.sendResponse(e)}variablesRequest(e,t){this.state&&(e.body={variables:this.state.getVariables(t.variablesReference)}),this.sendResponse(e)}onDebuggerBreakpoint(t){if(this.lastBreak=t,this.state=new s(this.lastBreak,this.breakpoints,this.projectDir),t.exceptionMessage){const n=t.exceptionMessage.replace(/___\d+/g,"");this.sendEvent(new e.protocol.StoppedEvent("exception",i.THREAD_ID,n))}else this.sendEvent(new e.protocol.StoppedEvent("breakpoint",i.THREAD_ID))}onDebuggerWarning(e){}onDebuggerResume(){this.sendEvent(new e.protocol.ContinuedEvent(i.THREAD_ID,!0))}onStateChanged(t){switch(t){case e.SimulatorState.Paused:break;case e.SimulatorState.Running:this.sendEvent(new e.protocol.ContinuedEvent(i.THREAD_ID,!0));break;case e.SimulatorState.Stopped:this.sendEvent(new e.protocol.TerminatedEvent)}}fixBreakpoints(){for(const t in this.breakpoints.idMap){const n=this.breakpoints.idMap[t];n.source.path=e.util.pathJoin(this.projectDir,n.source.path),n.line=this.convertDebuggerLineToClient(n.line),n.endLine=this.convertDebuggerLineToClient(n.endLine),n.column=this.convertDebuggerColumnToClient(n.column),n.endColumn=this.convertDebuggerColumnToClient(n.endColumn)}}}i.THREAD_ID=1,e.SimDebugSession=i;class s{constructor(e,t,n){this._message=e,this._map=t,this._dir=n,this._currentId=1,this._frames={},this._vars={};const o=this.nextId();this._vars[o]=this.getVariableValues(this._message.globals),this._globalScope={name:"Globals",variablesReference:o,expensive:!1}}getFrames(){return this._message.stackframes.map(((e,t)=>{const n=this._map.getById(e.breakpointId);if(n)return this._frames[e.breakpointId]=e,{id:e.breakpointId,name:e.funcInfo?e.funcInfo.functionName:0===t?"main":"anonymous",line:n.line,column:n.column,endLine:n.endLine,endColumn:n.endLine,source:n.source}})).filter((e=>!!e))}getScopes(e){const t=this._frames[e];if(t){const e=this.nextId();return this._vars[e]=this.getVariableValues(t.locals),[{name:"Locals",variablesReference:e,expensive:!1},this._globalScope]}return[this._globalScope]}getVariables(e){const t=this._vars[e];return t&&t.value||[]}getVariableValues(t){return new e.util.Lazy((()=>{const e=[];for(const n in t){const o=t[n];let r,i=0;null===o?r="null":void 0===o?r="undefined":"object"==typeof o?(r="(object)",i=this.nextId(),this._vars[i]=this.getVariableValues(o)):r=o.toString();const s=n.substr(0,n.lastIndexOf("___"));e.push({name:s,value:r,variablesReference:i})}return e}))}nextId(){return this._currentId++}}}(pxsim||(pxsim={})),function(e){function t(e=0){function t(){try{window.print()}catch(e){}}e?setTimeout(t,e):t()}let n;function o(e,t){r({type:"pxtsim",action:"event",tick:e,data:t})}function r(e){"undefined"!=typeof window&&window.parent&&window.parent!==window&&window.parent.postMessage(e,"*")}function i(){setInterval((()=>{e.Runtime.postMessage({type:"simulator",command:"reload"})}),3e3)}e.print=t,function(n){function r(n){n.origin;let r=n.data||{},i=r.type;if(i)switch(i){case"run":l(r);break;case"instructions":e.instructions.renderInstructions(r);break;case"stop":a();break;case"mute":c(r.mute);break;case"stopsound":e.AudioContextManager.stopAll();break;case"print":t();break;case"recorder":!function(e){if(!s)return;switch(e.action){case"start":s.startRecording(e.width);break;case"stop":s.stopRecording()}}(r);break;case"screenshot":e.Runtime.postScreenshotAsync(r);break;case"custom":e.handleCustomMessage&&e.handleCustomMessage(r);break;case"pxteditor":break;case"debugger":s&&s.handleDebuggerMsg(r);break;case"simulator":let n=r;switch(n.command){case"focus":o("simulator.focus",{timestamp:n.timestamp});break;case"blur":o("simulator.blur",{timestamp:n.timestamp})}default:!function(e){if(!s||s.dead)return;s.board.receiveMessage(e)}(r)}}let s;function a(){s&&(s.kill(),s.board&&s.board.kill())}function l(t){a(),t.mute&&c(t.mute),t.localizedStrings&&e.localization.setLocalizedStrings(t.localizedStrings);const n=new e.Runtime(t);s=n,n.board.initAsync(t).then((()=>{n===s&&n.run((t=>{e.dumpLivePointers(),e.Runtime.postMessage({type:"toplevelcodefinished"})}))}))}function c(t){e.AudioContextManager.mute(t)}n.start=function(){window.addEventListener("message",r,!1),n.frameid=window.location.hash.slice(1),function(){if("serviceWorker"in navigator&&-1!==window.location.href.indexOf("---simulator")&&!e.U.isLocalHost()){const e=window.location.pathname,t=e.substring(1,e.indexOf("---"));navigator.serviceWorker.controller&&navigator.serviceWorker.addEventListener("message",(e=>{const n=e.data;n&&"serviceworker"===n.type&&"activated"===n.state&&n.ref===t&&i()}));const n=window.location.href.replace(/---simulator.*$/,"---simserviceworker");navigator.serviceWorker.register(n).then((function(e){console.log("Simulator ServiceWorker registration successful with scope: ",e.scope)}),(function(e){console.log("Simulator ServiceWorker registration failed: ",e)}))}}(),e.Runtime.postMessage({type:"ready",frameid:n.frameid})},n.stop=a,n.run=l}(n=e.Embed||(e.Embed={})),e.tickEvent=o,e.reportError=function(e,t,n){r({type:"pxtsim",action:"event",tick:"error",category:e,message:t,data:n})},e.reload=i}(pxsim||(pxsim={})),pxsim.util.injectPolyphils(),"undefined"!=typeof window&&window.addEventListener("load",(function(e){pxsim.Embed.start()})),function(e){!function(t){const n=e=>`${e}x`,o=.95,[r,i]=[816*o,1056*o],s=r-86.4,a=i-86.4,[l,c]=[1,1],u=24,d=s/c-48*c,p=`\n .instr-panel {\n margin: 20px;\n padding: 24px;\n border-width: 4px;\n border-color: gray;\n border-style: solid;\n border-radius: 20px;\n display: inline-block;\n width: ${d}px;\n height: ${a/l-48*l}px;\n position: relative;\n overflow: hidden;\n page-break-inside: avoid;\n }\n .board-svg {\n margin: 0 auto;\n display: block;\n position: absolute;\n bottom: 24px;\n left: ${(d-465)/2+u}px;\n }\n .panel-num-outer {\n position: absolute;\n left: -4px;\n top: -4px;\n width: 120px;\n height: 120px;\n border-width: 4px;\n border-style: solid;\n border-color: gray;\n border-radius: 20px 0 20px 0;\n }\n .panel-num {\n margin: 10px 0;\n text-align: center;\n font-size: 80px;\n }\n .cmp-div {\n display: inline-block;\n }\n .reqs-div {\n margin-left: 144px;\n margin-top: 5px;\n }\n .partslist-wire,\n .partslist-cmp {\n margin: 10px;\n }\n .partslist-wire {\n display: inline-block;\n }\n `;function g(t,n){let o=document.createElementNS("http://www.w3.org/2000/svg","svg"),r={l:0,t:0,w:0,h:0},i=document.createElementNS("http://www.w3.org/2000/svg","svg");o.appendChild(i),i.appendChild(t.el);let s={viewBox:`${t.x} ${t.y} ${t.w} ${t.h}`,preserveAspectRatio:"xMidYMid"};r.w=t.w,r.h=t.h;let a=e=>{r.h*=e,r.w*=e,s.width=r.w,s.height=r.h};n.cmpScale&&a(n.cmpScale),n.cmpWidth&&n.cmpWidth<r.w?a(n.cmpWidth/r.w):n.cmpHeight&&n.cmpHeight<r.h&&a(n.cmpHeight/r.h),e.svg.hydrate(i,s);let l=r.l,c=r.t,u=r.w,d=r.h,p=e=>{if(e<r.l){let t=r.l-e;r.l=e,r.w+=t}},g=e=>{let t=r.l+r.w;if(t<e){let n=e-t;r.w+=n}},h=e=>{if(e<r.t){let t=r.t-e;r.t=e,r.h+=t}},f=e=>{let t=r.t+r.h;if(t<e){let n=e-t;r.h+=n}},[_,m]=[-.3,.3];const y=[1.4,1];if(n&&n.top){let t=n.topSize,r=t/y[0],i=t/y[1],[s,a]=[l+u/2,c-3-i/2],d=e.visuals.mkTxt(s,a,t,0,n.top,_,m);e.U.addClass(d,"cmp-lbl"),o.appendChild(d);let f=r*n.top.length;h(a-i/2),p(s-f/2),g(s+f/2)}if(n&&n.bot){let t=n.botSize,r=t/y[0],i=t/y[1],[s,a]=[l+u/2,c+d+3+i/2],h=e.visuals.mkTxt(s,a,t,0,n.bot,_,m);e.U.addClass(h,"cmp-lbl"),o.appendChild(h);let k=r*n.bot.length;f(a+i/2),p(s-k/2),g(s+k/2)}if(n&&n.right){let t=n.rightSize,r=t/y[1],i=t/y[0]*n.right.length,[s,a]=[l+u+5+i/2,c+d/2],p=e.visuals.mkTxt(s,a,t,0,n.right,_,m);e.U.addClass(p,"cmp-lbl"),o.appendChild(p),h(a-r/2),g(s+i/2),f(a+r/2)}if(n&&n.left){let t=n.leftSize,r=t/y[1],i=t/y[0]*n.left.length,[s,a]=[l-5-i/2,c+d/2],u=e.visuals.mkTxt(s,a,t,0,n.left,_,m);e.U.addClass(u,"cmp-lbl"),o.appendChild(u),h(a-r/2),p(s-i/2),f(a+r/2)}let k={viewBox:`${r.l} ${r.t} ${r.w} ${r.h}`,width:1.7*r.w,height:1.7*r.h,preserveAspectRatio:"xMidYMid"};e.svg.hydrate(o,k);let b=document.createElement("div");return b.appendChild(o),b}function h(t,n){let o,r=e.runtime.board;if("wire"==t)o=e.visuals.mkWirePart([0,0],n.wireClr||"red",n.crocClips);else{let n=t;if("string"==typeof n.builtIn){o=(0,r.builtinPartVisuals[n.builtIn])([0,0])}else o=e.visuals.mkGenericPartSVG(n)}return g(o,n)}function f(t,n,o=!1){const r={state:e.runtime.board,boardDef:t.boardDef,forceBreadboardLayout:!0,forceBreadboardRender:t.allAlloc.requiresBreadboard,partDefs:t.cmpDefs,maxWidth:`${n}px`,fnArgs:t.fnArgs,wireframe:o,partsList:[]};let i=new e.visuals.BoardHost(e.visuals.mkBoardView({visual:r.boardDef.visual,boardDef:r.boardDef,wireframe:r.wireframe}),r),s=i.getView();return e.U.addClass(s,"board-svg"),i}function _(){let t=document.createElement("div");return e.U.addClass(t,"instr-panel"),t}function m(t){let o=_();var r;let i=g((r=t.boardDef,e.visuals.mkBoardView({visual:r.visual,boardDef:r}).getView()),{left:n(1),leftSize:30,cmpScale:.17});o.appendChild(i);let s=g(new e.visuals.Breadboard({}).getSVGAndSize(),{left:n(1),leftSize:30,cmpScale:.25});return o.appendChild(s),t.allCmps.forEach((t=>{let r=1;"buttonpair"===t.visual.builtIn&&(r=2);let i=h(t.visual,{left:n(r),leftSize:30,cmpScale:.3});e.U.addClass(i,"partslist-cmp"),o.appendChild(i)})),t.allWireColors.forEach((r=>{let i=t.colorToWires[r].length,s=t.boardDef.pinStyles[r]||"female",a=h("wire",{left:n(i),leftSize:20,wireClr:r,cmpScale:.23,crocClips:"croc"==s});e.U.addClass(a,"partslist-wire"),o.appendChild(a)})),o}function y(t,n){let o=_(),r=f(n,465,!0);!function(t,n,o){let r=t.getView();n>0&&e.U.addClass(r,"grayed");for(let r=0;r<=n;r++){let i=o.stepToCmps[r];i&&i.forEach((o=>{let i=t.addPart(o);r===n&&(o.breadboardConnections.forEach((e=>t.highlightBreadboardPin(e))),e.U.addClass(i.element,"notgrayed"))}));let s=o.stepToWires[r];s&&s.forEach((e=>{let o=t.addWire(e);o&&r===n&&("breadboard"==e.start.type?t.highlightBreadboardPin(e.start):t.highlightBoardPin(e.start.pin),"breadboard"==e.end.type?t.highlightBreadboardPin(e.end):t.highlightBoardPin(e.end.pin),t.highlightWire(o))}))}}(r,t,n),o.appendChild(r.getView());let i=document.createElement("div");e.U.addClass(i,"panel-num-outer"),e.U.addClass(i,"noselect"),o.appendChild(i);let s=document.createElement("div");e.U.addClass(s,"panel-num"),s.textContent=t+1+"",i.appendChild(s);let a=document.createElement("div");e.U.addClass(a,"reqs-div"),o.appendChild(a);let l=n.stepToWires[t]||[],c=e=>{if("breadboard"===e.type){let{row:t,col:n}=e;return`(${t},${n})`}return e.pin};return l.forEach((t=>{let o=!1;"dalboard"==t.end.type&&(o="croc"==n.boardDef.pinStyles[t.end.pin]);let r=h("wire",{top:c(t.end),topSize:10,bot:c(t.start),botSize:10,wireClr:t.color,cmpHeight:40,crocClips:o});e.U.addClass(r,"cmp-div"),a.appendChild(r)})),(n.stepToCmps[t]||[]).forEach((t=>{let n;n="buttonpair"===t.visual.builtIn?[t.breadboardConnections[0],t.breadboardConnections[2]]:[t.breadboardConnections[0]],n.forEach(((n,o)=>{let r;if(n){let{row:e,col:t}=n;r=`(${e},${t})`}else r="";let i=1.5;"buttonpair"===t.visual.builtIn&&(i*=.5);let s=h(t.visual,{top:r,topSize:10,cmpHeight:50,cmpScale:i});e.U.addClass(s,"cmp-div"),a.appendChild(s)}))})),o}function k(t,n){n.boardDef.pinStyles||(n.boardDef.pinStyles={}),n.configData&&e.setConfigData(n.configData.cfg,n.configData.cfgKey);const o={type:"run",code:"",boardDefinition:n.boardDef,partDefinitions:n.partDefinitions};e.runtime=new e.Runtime(o),e.runtime.board=null,e.initCurrentRuntime(o);let r=document.createElement("style");r.textContent+=p,document.head.appendChild(r);const i=n.partDefinitions;let s=new e.visuals.Breadboard({}),a=function(t){let n=e.allocateDefinitions(t),o=[],r=[],i=1;n.partsAndWires.forEach((e=>{let t=e.part,n=e.wires;e.assembly.forEach(((e,s)=>{e.part&&t&&(r[i+s]=[t]),e.wireIndices&&e.wireIndices.length>0&&n&&(o[i+s]=e.wireIndices.map((e=>n[e])))})),i+=e.assembly.length}));let s=i-1,a=n.partsAndWires.map((e=>e.part)).filter((e=>!!e)),l=n.partsAndWires.map((e=>e.wires||[])).reduce(((e,t)=>e.concat(t)),[]),c={},u=[];return l.forEach((e=>{c[e.color]||(c[e.color]=[],u.push(e.color)),c[e.color].push(e)})),{boardDef:t.boardDef,cmpDefs:t.partDefs,fnArgs:t.fnArgs,allAlloc:n,stepToWires:o,stepToCmps:r,allWires:l,allCmps:a,lastStep:s,colorToWires:c,allWireColors:u}}({boardDef:n.boardDef,partDefs:i,partsList:n.parts,fnArgs:n.fnArgs,getBBCoord:s.getCoord.bind(s)});a.allAlloc.requiresBreadboard=!0;!function(e){let t=document.getElementById("front-panel"),n=f(e,400,!1);n.addAll(e.allAlloc),t.appendChild(n.getView())}(a);let l=m(a);t.appendChild(l);for(let e=0;e<=a.lastStep;e++){let n=y(e,a);t.appendChild(n)}n.print&&e.print(2e3)}t.renderParts=k,t.renderInstructions=function(e){document.getElementById("proj-title").innerText=e.options.name||"",k(document.body,e.options)}}(e.instructions||(e.instructions={}))}(pxsim||(pxsim={})),function(e){function t(e,t="sim: check failed"){if(!e)throw new Error(t)}e.quiet=!1,e.check=t,e.title="";let n,o,r,i,s,a={},l={};e.getConfig=function(e){return l.hasOwnProperty(e+"")?l[e+""]:null},e.getConfigKey=function(e){return a.hasOwnProperty(e)?a[e]:null},e.getAllConfigKeys=function(){return Object.keys(a)},e.setConfigKey=function(e,t){a[e]=t},e.setConfig=function(e,t){l[e]=t},e.setConfigData=function(e,t){l=e,a=t},e.getConfigData=function(){return{cfg:l,cfgKey:a}},e.setTitle=function(t){e.title=t};class c{constructor(){e.runtime?this.id=e.runtime.registerLiveObject(this):this.id=0}destroy(){}scan(t){throw e.U.userError("scan not implemented")}gcKey(){throw e.U.userError("gcKey not implemented")}gcSize(){throw e.U.userError("gcSize not implemented")}gcIsStatic(){return!1}print(){e.runtime&&e.runtime.refCountingDebug&&console.log(`RefObject id:${this.id}`)}toDebugString(){return"(object)"}static toAny(e){return e&&e.toAny?e.toAny():e}static toDebugString(e){return null===e?"null":void 0===e?"undefined;":e.vtable&&e.vtable.name?e.vtable.name:e.toDebugString?e.toDebugString():"string"==typeof e?JSON.stringify(e):e.toString()}}e.RefObject=c;class u{constructor(e,t,n){this.func=e,this.caps=t,this.args=n}}e.FnWrapper=u;class d extends c{constructor(){super(...arguments),this.fields={}}scan(e){for(let t of Object.keys(this.fields))e(t,this.fields[t])}gcKey(){return this.vtable.name}gcSize(){return this.vtable.numFields+1}destroy(){this.fields=null,this.vtable=null}print(){e.runtime&&e.runtime.refCountingDebug&&console.log(`RefRecord id:${this.id} (${this.vtable.name})`)}}e.RefRecord=d;class p extends c{constructor(){super(...arguments),this.fields=[]}scan(e){for(let t=0;t<this.fields.length;++t)e("_cap"+t,this.fields[t])}gcKey(){return e.functionName(this.func)}gcSize(){return this.fields.length+3}isRef(e){return t(0<=e&&e<this.fields.length),e<this.len}ldclo(e){return t(0<=(e>>=2)&&e<this.fields.length),this.fields[e]}destroy(){this.fields=null,this.func=null}print(){e.runtime&&e.runtime.refCountingDebug&&console.log(`RefAction id:${this.id} len:${this.fields.length}`)}}e.RefAction=p,function(t){t.seedAddRandom=function(e){},t.mkAction=function(e,t){let n=new p;n.len=e,n.func=t;for(let t=0;t<e;++t)n.fields.push(null);return n},t.runAction=function(t,n){let o=e.getResume();o(t instanceof p?new u(t.func,t.fields,n):new u(t,null,n))};let n={};t.dumpPerfCounters=function(){if(!e.runtime||!e.runtime.perfCounters)return;let t="calls,us,name\n";for(let n of e.runtime.perfCounters){n.lastFew.sort();const e=n.lastFew[n.lastFew.length>>1];t+=`${n.numstops},${n.value},${n.name},${e}\n`}!function(e){let t="";const o=(e,n)=>{t+=e.length>=n?e:(" "+e).slice(-n)},r=e=>o(""+Math.round(e),6),i=(e,n)=>{o(Math.round(n)+"",8),t+=" /",r(e),t+=" =",r(n/e)};for(let o of e.split(/\n/)){if(!o)continue;if(!/^\d/.test(o))continue;const e=o.split(/,/);let l=n[e[2]];l||(n[e[2]]=l={stops:0,us:0,meds:[]}),s=e[2],a=25,t+=s.length>=a?s:(s+" ").slice(0,a);const c=parseInt(e[0]),u=parseInt(e[1]);i(c,u),t+=" |",i(c-l.stops,u-l.us),t+=" ~";const d=parseInt(e[3]);r(d),l.meds.length>10&&l.meds.shift(),l.meds.push(d);const p=l.meds.slice();p.sort(((e,t)=>e-t));const g=p[p.length>>1];t+=" ~~",r(g),l.stops=c,l.us=u,t+="\n"}var s,a;console.log(t)}(t)}}(n=e.pxtcore||(e.pxtcore={}));class g extends c{constructor(){super(...arguments),this.v=void 0}scan(e){e("*",this.v)}gcKey(){return"LOC"}gcSize(){return 2}destroy(){}print(){e.runtime&&e.runtime.refCountingDebug&&console.log(`RefRefLocal id:${this.id} v:${this.v}`)}}e.RefRefLocal=g;class h extends c{constructor(){super(...arguments),this.vtable=e.mkMapVTable(),this.data=[]}scan(e){for(let t of this.data)e(t.key,t.val)}gcKey(){return"{...}"}gcSize(){return 2*this.data.length+4}findIdx(e){e+="";for(let t=0;t<this.data.length;++t)if(this.data[t].key==e)return t;return-1}destroy(){super.destroy();for(let e=0;e<this.data.length;++e)this.data[e].val=0;this.data=[]}print(){e.runtime&&e.runtime.refCountingDebug&&console.log(`RefMap id:${this.id} size:${this.data.length}`)}toAny(){const e={};return this.data.forEach((t=>{e[t.key]=c.toAny(t.val)})),e}}function f(){e.runtime&&e.runtime.dumpLivePointers()}e.RefMap=h,e.dumpLivePointers=f,function(e){e.toString=function(e){return null===e?"null":void 0===e?"undefined":e.toString()},e.toBoolDecr=function(e){return!!e},e.toBool=function(e){return!!e}}(o=e.numops||(e.numops={})),function(e){e.toInt=function(e){return 0|e},e.toFloat=function(e){return e},e.ignore=function(e){return e}}(r=e.langsupp||(e.langsupp={})),function(t){t.ptrOfLiteral=function(e){return e},t.debugMemLeaks=function(){f()},t.templateHash=function(){return 0},t.programHash=function(){return 0},t.programName=function(){return e.title},t.programSize=function(){return 0},t.afterProgramPage=function(){return 0},t.getConfig=function(t,n){let o=e.getConfig(t);return null==o?n:o},t.toInt=function(e){return e>>0},t.toUInt=function(e){return e>>>0},t.toDouble=function(e){return e},t.toFloat=function(e){return e},t.fromInt=function(e){return e},t.fromUInt=function(e){return e},t.fromDouble=function(e){return e},t.fromFloat=function(e){return e},t.fromBool=function(e){return!!e}}(n=e.pxtcore||(e.pxtcore={})),function(n){function o(e,t){if(t+="",e instanceof d){return e.fields[t]}let n=e.findIdx(t);if(!(n<0))return e.data[n].val}function r(e,t,n){if(t+="",e instanceof d){return void(e.fields[t]=n)}let o=e.findIdx(t);o<0?e.data.push({key:t,val:n}):e.data[o].val=n}n.toInt8=function(e){return(255&e)<<24>>24},n.toInt16=function(e){return(65535&e)<<16>>16},n.toInt32=function(e){return 0|e},n.toUInt32=function(e){return e>>>0},n.toUInt8=function(e){return 255&e},n.toUInt16=function(e){return 65535&e},n.nullFix=function(e){return null==e||!1===e?0:!0===e?1:e},n.nullCheck=function(t){null==t&&e.U.userError("Dereferencing null/undefined value.")},n.panic=function(t){e.U.userError("PANIC! Code "+t)},n.stringToBool=function(e){return e?1:0},n.ptrToBool=function(e){return e?1:0},n.emptyToNull=function(e){return""==e?0:e},n.ldlocRef=function(e){return e.v},n.stlocRef=function(e,t){e.v=t},n.mklocRef=function(){return new g},n.stclo=function(e,n,o){return t(0<=n&&n<e.fields.length),t(null===e.fields[n]),e.fields[n]=o,e},n.runtimeWarning=function(t){e.Runtime.postMessage(e.getWarningMessage(t))},n.mkMap=function(){return new h},n.mapGet=function(e,t){return o(e,n.mapKeyNames[t])},n.mapSet=function(e,t,o){return r(e,n.mapKeyNames[t],o)},n.mapGetByString=o,n.mapDeleteByString=function(e,t){e instanceof h||n.panic(923);let o=e.findIdx(t);return o>=0&&e.data.splice(o,1),!0},n.mapSetGeneric=r,n.mapGetGeneric=o,n.mapSetByString=r,n.keysOf=function(t){let n=new e.RefCollection;if(t instanceof h)for(let e of t.data)n.push(e.key);return n}}(i=e.pxtrt||(e.pxtrt={})),function(e){e.mkClassInstance=function(e){t(!!e.methods);let n=new d;return n.vtable=e,n},e.switch_eq=function(e,t){return e==t},e.typeOf=function(e){return typeof e}}(n=e.pxtcore||(e.pxtcore={})),function(t){t.panic=i.panic,t.pause=function(t){let n=e.getResume();e.runtime.schedule((()=>{n()}),t)},t.runInBackground=function(t){e.runtime.runFiberAsync(t)},t.forever=function(t){i.nullCheck(t),function n(){e.runtime.runFiberAsync(t).then((()=>e.U.delay(20))).then(n)}()}}(s=e.thread||(e.thread={}))}(pxsim||(pxsim={})),function(e){class t extends e.RefObject{constructor(){super(),this.data=[]}scan(e){for(let t=0;t<this.data.length;++t)e("["+t+"]",this.data[t])}gcKey(){return"[...]"}gcSize(){return this.data.length+2}toArray(){return this.data.slice(0)}toAny(){return this.data.map((t=>e.RefObject.toAny(t)))}toDebugString(){let t="[";for(let n=0;n<this.data.length;++n){n>0&&(t+=",");let o=e.RefObject.toDebugString(this.data[n]);if(t.length+o.length>100){0==n&&(t+=o.substr(0,100)),t+="...";break}t+=o}return t+="]",t}destroy(){let e=this.data;for(let t=0;t<e.length;++t)e[t]=0;this.data=[]}isValidIndex(e){return e>=0&&e<this.data.length}push(e){this.data.push(e)}pop(){return this.data.pop()}getLength(){return this.data.length}setLength(e){this.data.length=e}getAt(e){return this.data[e]}setAt(e,t){this.data[e]=t}insertAt(e,t){this.data.splice(e,0,t)}removeAt(e){return this.data.splice(e,1)[0]}indexOf(e,t){return this.data.indexOf(e,t)}print(){}}let n,o,r,i,s,a,l,c;e.RefCollection=t,function(n){function o(t,n){if(e.pxtrt.nullCheck(t),t.isValidIndex(n))return t.removeAt(n)}function r(t,n,o){return e.pxtrt.nullCheck(t),t.indexOf(n,o)}n.mk=function(){return new t},n.isArray=function(e){return e instanceof t},n.length=function(t){return e.pxtrt.nullCheck(t),t.getLength()},n.setLength=function(t,n){e.pxtrt.nullCheck(t),t.setLength(n)},n.push=function(t,n){e.pxtrt.nullCheck(t),t.push(n)},n.pop=function(t,n){return e.pxtrt.nullCheck(t),t.pop()},n.getAt=function(t,n){return e.pxtrt.nullCheck(t),t.getAt(n)},n.removeAt=o,n.insertAt=function(t,n,o){e.pxtrt.nullCheck(t),t.insertAt(n,o)},n.setAt=function(t,n,o){e.pxtrt.nullCheck(t),t.setAt(n,o)},n.indexOf=r,n.removeElement=function(t,n){e.pxtrt.nullCheck(t);let i=r(t,n,0);return i>=0?(o(t,i),1):0}}(n=e.Array_||(e.Array_={})),function(e){e.imul=Math.imul||function(e,t){const n=65535&e,o=65535&t;return n*o+((e>>>16&65535)*o+n*(t>>>16&65535)<<16>>>0)|0},e.idiv=function(e,t){return(0|e)/(0|t)|0},e.round=function(e){return Math.round(e)},e.roundWithPrecision=function(e,t){if((t|=0)<=0)return Math.round(e);if(0==e)return 0;let n=0;for(;0==n&&t<21;){const o=Math.pow(10,t++);n=Math.round(e*o+Number.EPSILON)/o}return n},e.ceil=function(e){return Math.ceil(e)},e.floor=function(e){return Math.floor(e)},e.sqrt=function(e){return Math.sqrt(e)},e.pow=function(e,t){return Math.pow(e,t)},e.clz32=function(e){return Math.clz32(e)},e.log=function(e){return Math.log(e)},e.log10=function(e){return Math.log10(e)},e.log2=function(e){return Math.log2(e)},e.exp=function(e){return Math.exp(e)},e.sin=function(e){return Math.sin(e)},e.sinh=function(e){return Math.sinh(e)},e.cos=function(e){return Math.cos(e)},e.cosh=function(e){return Math.cosh(e)},e.tan=function(e){return Math.tan(e)},e.tanh=function(e){return Math.tanh(e)},e.asin=function(e){return Math.asin(e)},e.asinh=function(e){return Math.asinh(e)},e.acos=function(e){return Math.acos(e)},e.acosh=function(e){return Math.acosh(e)},e.atan=function(e){return Math.atan(e)},e.atanh=function(e){return Math.atanh(e)},e.atan2=function(e,t){return Math.atan2(e,t)},e.trunc=function(e){return e>0?Math.floor(e):Math.ceil(e)},e.random=function(){return Math.random()},e.randomRange=function(e,t){if(e==t)return e;if(e>t){let n=e;e=t,t=n}return Math.floor(e)==e&&Math.floor(t)==t?e+Math.floor(Math.random()*(t-e+1)):e+Math.random()*(t-e)}}(o=e.Math_||(e.Math_={})),function(t){function n(t,n){return e.pxtrt.nullFix(t)==e.pxtrt.nullFix(n)}t.lt=function(e,t){return e<t},t.le=function(e,t){return e<=t},t.neq=function(e,t){return!n(e,t)},t.eq=n,t.eqDecr=function(t,n){return e.pxtrt.nullFix(t)==e.pxtrt.nullFix(n)},t.gt=function(e,t){return e>t},t.ge=function(e,t){return e>=t},t.div=function(e,t){return 0|Math.floor(e/t)},t.mod=function(e,t){return e%t},t.bnot=function(e){return~e},t.toString=function(e){return e+""}}(r=e.Number_||(e.Number_={})),function(e){e.adds=function(e,t){return e+t|0},e.subs=function(e,t){return e-t|0},e.divs=function(e,t){return 0|Math.floor(e/t)},e.muls=function(e,t){return o.imul(e,t)},e.ands=function(e,t){return e&t},e.orrs=function(e,t){return e|t},e.eors=function(e,t){return e^t},e.lsls=function(e,t){return e<<t},e.lsrs=function(e,t){return e>>>t},e.asrs=function(e,t){return e>>t},e.bnot=function(e){return~e},e.ignore=function(e){return e}}(i=e.thumb||(e.thumb={})),function(e){function t(e){return e<<16>>16}e.adds=function(e,n){return t(e+n)},e.subs=function(e,n){return t(e-n)},e.divs=function(e,n){return t(Math.floor(e/n))},e.muls=function(e,n){return t(o.imul(e,n))},e.ands=function(e,n){return t(e&n)},e.orrs=function(e,n){return t(e|n)},e.eors=function(e,n){return t(e^n)},e.lsls=function(e,n){return t(e<<n)},e.lsrs=function(e,t){return(65535&e)>>>t},e.asrs=function(e,n){return t(e>>n)},e.bnot=function(e){return~e},e.ignore=function(e){return e}}(s=e.avr||(e.avr={})),function(t){t.stringConv=function(t){const n=e.getResume();t instanceof e.RefRecord&&t.vtable.toStringMethod?e.runtime.runFiberAsync(t.vtable.toStringMethod,t).then((()=>{n(e.runtime.currFrame.retval+"")})):n(t+"")},t.mkEmpty=function(){return""},t.fromCharCode=function(e){return String.fromCharCode(e)},t.toNumber=function(e){return parseFloat(e)},t.concat=function(e,t){return e+t},t.substring=function(t,n,o){return e.pxtrt.nullCheck(t),t.slice(n,n+o)},t.equals=function(e,t){return e==t},t.compare=function(e,t){return e==t?0:e<t?-1:1},t.compareDecr=function(e,t){return e==t?0:e<t?-1:1},t.length=function(e){return e.length},t.substr=function(e,t,n){return e.substr(t,n)},t.charAt=function(e,t){return e.charAt(t)},t.charCodeAt=function(t,n){return e.pxtrt.nullCheck(t),function(t,n){return e.pxtrt.nullCheck(t),0<=n&&n<t.length}(t,n)?t.charCodeAt(n):0},t.indexOf=function(t,n,o){return e.pxtrt.nullCheck(t),null==n?-1:t.indexOf(n,o)},t.lastIndexOf=function(t,n,o){return e.pxtrt.nullCheck(t),null==n?-1:t.lastIndexOf(n,o)},t.includes=function(t,n,o){return e.pxtrt.nullCheck(t),null!=n&&t.includes(n,o)}}(a=e.String_||(e.String_={})),function(e){e.toString=function(e){return e?"true":"false"},e.bang=function(e){return!e}}(l=e.Boolean_||(e.Boolean_={}));class u extends e.RefObject{constructor(e){super(),this.data=e,this.isStatic=!1}scan(e){}gcKey(){return"Buffer"}gcSize(){return 2+(this.data.length+3>>2)}gcIsStatic(){return this.isStatic}print(){}toDebugString(){return c.toHex(this)}}e.RefBuffer=u,function(t){let n;function o(t){let o=function(t){switch(t){case n.Int8LE:return-1;case n.UInt8LE:return 1;case n.Int16LE:return-2;case n.UInt16LE:return 2;case n.Int32LE:return-4;case n.UInt32LE:return 4;case n.Int8BE:return-10;case n.UInt8BE:return 10;case n.Int16BE:return-20;case n.UInt16BE:return 20;case n.Int32BE:return-40;case n.UInt32BE:return 40;case n.Float32LE:return 4;case n.Float32BE:return 40;case n.Float64LE:return 8;case n.Float64BE:return 80;default:throw e.U.userError("bad format")}}(t),r=!1;o<0&&(r=!0,o=-o);let i=!1;return o>=10&&(i=!0,o/=10),{size:o,signed:r,swap:i,isFloat:t>=n.Float32LE}}function r(e){return new u(new Uint8Array(e))}function i(t,n){return e.pxtrt.nullCheck(t),0<=n&&n<t.data.length}function s(e,t){return i(e,t)?e.data[t]:0}function a(t){t.isStatic&&e.U.userError("Writing to read only buffer.")}function l(e,t,n){i(e,t)&&(a(e),e.data[t]=n)}function c(e,t,n=0,o=-1){n<0||n>e.data.length||(o<0&&(o=e.data.length),o=Math.min(o,e.data.length-n),a(e),e.data.fill(t,n,n+o))}function d(e,t,n,o,r){if(n.buffer===e.buffer)d(e,t,n.slice(o,o+r),0,r);else for(let i=0;i<r;++i)e[t+i]=n[o+i]}!function(e){e[e.Int8LE=1]="Int8LE",e[e.UInt8LE=2]="UInt8LE",e[e.Int16LE=3]="Int16LE",e[e.UInt16LE=4]="UInt16LE",e[e.Int32LE=5]="Int32LE",e[e.Int8BE=6]="Int8BE",e[e.UInt8BE=7]="UInt8BE",e[e.Int16BE=8]="Int16BE",e[e.UInt16BE=9]="UInt16BE",e[e.Int32BE=10]="Int32BE",e[e.UInt32LE=11]="UInt32LE",e[e.UInt32BE=12]="UInt32BE",e[e.Float32LE=13]="Float32LE",e[e.Float64LE=14]="Float64LE",e[e.Float32BE=15]="Float32BE",e[e.Float64BE=16]="Float64BE"}(n=t.NumberFormat||(t.NumberFormat={})),t.getNumber=function(e,t,n){let r=o(t);if(r.isFloat){let t=e.data.buffer.slice(n,n+r.size);if(r.swap){new Uint8Array(t).reverse()}return 4==r.size?new Float32Array(t)[0]:new Float64Array(t)[0]}let i=0;for(let t=0;t<r.size;++t){i<<=8;let o=r.swap?n+t:n+r.size-t-1;i|=e.data[o]}if(r.signed){let e=32-8*r.size;i=i<<e>>e}else i>>>=0;return i},t.setNumber=function(e,t,n,r){let i=o(t);if(i.isFloat){let t=new Uint8Array(i.size);4==i.size?new Float32Array(t.buffer)[0]=r:new Float64Array(t.buffer)[0]=r,i.swap&&t.reverse();for(let o=0;o<i.size;++o)e.data[n+o]=t[o]}else for(let t=0;t<i.size;++t){let o=i.swap?n+i.size-t-1:n+t;e.data[o]=255&r,r>>=8}},t.createBuffer=r,t.createBufferFromHex=function(e){let t=r(e.length>>1);for(let n=0;n<e.length;n+=2)t.data[n>>1]=parseInt(e.slice(n,n+2),16);return t.isStatic=!0,t},t.isReadOnly=function(e){return e.isStatic},t.getBytes=function(e){return e.data},t.getUint8=function(e,t){return s(e,t)},t.getByte=s,t.setUint8=function(e,t,n){l(e,t,n)},t.setByte=l,t.length=function(e){return e.data.length},t.fill=c,t.slice=function(e,t,n){return t=Math.min(e.data.length,t),n<0&&(n=e.data.length),n=Math.min(n,e.data.length-t),new u(e.data.slice(t,t+n))},t.toHex=function(e){const t="0123456789abcdef";let n="";for(let o=0;o<e.data.length;++o)n+=t[e.data[o]>>4],n+=t[15&e.data[o]];return n},t.toString=function(t){return e.U.fromUTF8Array(t.data)};const p=-2147483648;t.shift=function(e,t,n,o){o<0&&(o=e.data.length-n),n<0||n+o>e.data.length||n+o<n||0==o||0==t||t==p||0!=o&&0!=t&&t!=p&&(t<=-o||t>=o?c(e,0):(a(e),t<0?(t=-t,d(e.data,n+t,e.data,n,o-t),e.data.fill(0,n,n+t)):(o-=t,d(e.data,n,e.data,n+t,o),e.data.fill(0,n+o,n+o+t))))},t.rotate=function(e,t,n,o){if(o<0&&(o=e.data.length-n),n<0||n+o>e.data.length||n+o<n||0==o||0==t||t==p)return;a(e),t<0&&(t+=o<<8),(t%=o)<0&&(t+=o);let r=e.data,i=t,s=0,l=i,c=o;for(;s!=l;){let e=r[s+n];r[s+++n]=r[l+n],r[l+++n]=e,l==c?l=i:s==i&&(i=l)}},t.write=function(e,t,n,o=0,r=-1){r<0&&(r=n.data.length),o<0||t<0||t>e.data.length||(r=Math.min(n.data.length-o,e.data.length-t))<0||(a(e),d(e.data,t,n.data,o,r))}}(c=e.BufferMethods||(e.BufferMethods={}))}(pxsim||(pxsim={})),function(e){!function(t){t.createBufferFromUTF8=function(t){return new e.RefBuffer(e.U.toUTF8Array(t))}}(e.control||(e.control={}))}(pxsim||(pxsim={})),function(e){!function(e){let t={};e.setLocalizedStrings=function(e){t=e||{}};function n(e,t){return 0==t.length?e:e.replace(/\{([0-9]+)(\:[^\}]+)?\}/g,(function(e,n,i){let s=t[parseInt(n)],a="",l=/^:f(\d*)\.(\d+)/.exec(i);if(l){let e=parseInt(l[2]),t=parseInt(l[1])||0,n=/^0/.test(l[1])?"0":" ",o=s.toFixed(e);if(t>0&&e>0&&(t+=e+1),t>0)for(;o.length<t;)o=n+o;a=o}else a=":x"==i?"0x"+s.toString(16):void 0===s?"(undef)":null===s?"(null)":s.toString?s.toString():s+"";return":a"==i?/^\s*[euioah]/.test(a.toLowerCase())?a="an "+a:/^\s*[bcdfgjklmnpqrstvwxz]/.test(a.toLowerCase())&&(a="a "+a):":s"==i?a=1==s?"":"s":":q"==i?a=o(a):":jq"==i?a=r(a):":uri"==i?a=encodeURIComponent(a).replace(/'/g,"%27").replace(/"/g,"%22"):":url"==i?a=encodeURI(a).replace(/'/g,"%27").replace(/"/g,"%22"):":%"==i&&(a=(100*s).toFixed(1).toString()+"%"),a}))}function o(e){return e?e.replace(/([^\w .!?\-$])/g,(e=>"&#"+e.charCodeAt(0)+";")):e}function r(e){return e.replace(/[^\w .!?\-$]/g,(e=>{let t=e.charCodeAt(0).toString(16);return"\\u"+"0000".substr(0,4-t.length)+t}))}e.lf=function(e,...o){let r=t[e]||e;return r=r.replace(/^\{(id|loc):[^\}]+\}/g,""),n(r,o)},e.fmt_va=n,e.htmlEscape=o,e.jsStringQuote=r}(e.localization||(e.localization={}))}(pxsim||(pxsim={})),function(pxsim){const MIN_MESSAGE_WAIT_MS=200;let tracePauseMs=0,U,pxtcore;!function(e){function t(e){return e.split(/\s+/).filter((e=>!!e))}function n(e){for(;e.firstChild;)e.removeChild(e.firstChild)}let o;e.containsClass=function(e,n){return t(n).every((t=>function(e,t){if(e.classList)return e.classList.contains(t);return!((e.className+"").split(/\s+/).indexOf(t)<0)}(e,t)))},e.addClass=function(e,n){t(n).forEach((t=>function(e,t){if(e.classList)e.classList.add(t);else{(e.className+"").split(/\s+/).indexOf(t)<0&&(e.className.baseVal+=" "+t)}}(e,t)))},e.removeClass=function(e,n){t(n).forEach((t=>function(e,t){e.classList?e.classList.remove(t):e.className.baseVal=(e.className+"").split(/\s+/).filter((e=>e!=t)).join(" ")}(e,t)))},e.remove=function(e){e.parentElement.removeChild(e)},e.removeChildren=n,e.clear=function(e){n(e)},e.assert=function(e,t="Assertion failed"){if(!e)throw new Error(t)},e.repeatMap=function(e,t){e=e||0;let n=[];for(let o=0;o<e;++o)n.push(t(o));return n},e.userError=function(e){let t=new Error(e);throw t.isUserError=!0,t},e.now=function(){return Date.now()},e.perfNowUs=function(){return o||(o="undefined"!=typeof performance?performance.now.bind(performance)||performance.moznow.bind(performance)||performance.msNow.bind(performance)||performance.webkitNow.bind(performance)||performance.oNow.bind(performance):Date.now),1e3*o()};const r=Promise.resolve();async function i(e,t,n){let o=0;const r=[],i=[];for(let s=0;s<e;s++){const e=(async()=>{for(;o<t.length;){const e=o++,r=t[e];i[e]=await n(r)}})();r.push(e)}try{await Promise.all(r)}catch(e){throw o=t.length,e}return i}function s(){return"undefined"!=typeof window&&!!window.pxtElectron}function a(){return"undefined"!=typeof window&&!!window.ipcRenderer}function l(){return s()||a()}function c(){try{return"undefined"!=typeof window&&/^http:\/\/(localhost|127\.0\.0\.1):\d+\//.test(window.location.href)&&!/nolocalhost=1/.test(window.location.href)}catch(e){return!1}}e.nextTick=function(e){r.then(e)},e.delay=async function(e,t){const n=await t;return await new Promise((t=>setTimeout((()=>t()),e))),n},e.promiseMapAll=function(e,t){return Promise.all(e.map((e=>t(e))))},e.promiseMapAllSeries=function(e,t){return i(1,e,t)},e.promisePoolAsync=i,e.promiseTimeout=async function(e,t,n){let o,r;const i=new Promise(((t,i)=>{r=t,o=setTimeout((()=>{r=void 0,clearTimeout(o),i(n||`Promise timed out after ${e}ms`)}),e)}));return Promise.race([t,i]).then((e=>(r&&(clearTimeout(o),r()),e)))},e.stringToUint8Array=function(e){let t=e.length,n=new Uint8Array(t);for(let o=0;o<t;++o)n[o]=255&e.charCodeAt(o);return n},e.uint8ArrayToString=function(e){let t=e.length,n="";for(let o=0;o<t;++o)n+=String.fromCharCode(e[o]);return n},e.fromUTF8=function(e){if(!e)return"";let t="";for(let n=0;n<e.length;++n){let o=255&e.charCodeAt(n);t+=37==o||o>127?"%"+o.toString(16):e.charAt(n)}return decodeURIComponent(t)},e.toUTF8=function(e,t){let n="";if(!e)return n;for(let o=0;o<e.length;++o){let r=e.charCodeAt(o);if(r<=127)n+=e.charAt(o);else if(r<=2047)n+=String.fromCharCode(192|r>>6,128|63&r);else{if(!t&&55296<=r&&r<=56319){let t=e.charCodeAt(++o);isNaN(t)||(r=65536+(r-55296<<10)+(t-56320))}n+=r<=65535?String.fromCharCode(224|r>>12,128|r>>6&63,128|63&r):String.fromCharCode(240|r>>18,128|r>>12&63,128|r>>6&63,128|63&r)}}return n},e.toUTF8Array=function(e){return(new TextEncoder).encode(e)},e.fromUTF8Array=function(e){return(new TextDecoder).decode(e)},e.isPxtElectron=s,e.isIpcRenderer=a,e.isElectron=l,e.isLocalHost=c,e.isLocalHostDev=function(){return c()&&!l()},e.unique=function(e,t){let n=[],o={};return e.forEach((e=>{let r=t(e);o.hasOwnProperty(r)||(o[r]=null,n.push(e))})),n}}(U=pxsim.U||(pxsim.U={}));class BreakLoopException{}function getResume(){return pxsim.runtime.getResume()}pxsim.BreakLoopException=BreakLoopException,function(e){function t(e){let t=pxsim.runtime.currTryFrame();t||U.userError("unhandled exception: "+e);const n=t.handlerFrame;throw pxsim.runtime.currFrame=n,n.pc=t.handlerPC,n.tryFrame=t.parent,n.thrownValue=e,n.hasThrownValue=!0,new BreakLoopException}e.beginTry=function(e){pxsim.runtime.currFrame.tryFrame={parent:pxsim.runtime.currTryFrame(),handlerPC:e,handlerFrame:pxsim.runtime.currFrame}},e.endTry=function(){const e=pxsim.runtime.currFrame;e.tryFrame=e.tryFrame.parent},e.throwValue=t,e.getThrownValue=function(){const e=pxsim.runtime.currFrame;return U.assert(e.hasThrownValue),e.hasThrownValue=!1,e.thrownValue},e.endFinally=function(){const e=pxsim.runtime.currFrame;e.hasThrownValue&&(e.hasThrownValue=!1,t(e.thrownValue))}}(pxtcore=pxsim.pxtcore||(pxsim.pxtcore={})),pxsim.getResume=getResume;const SERIAL_BUFFER_LENGTH=16;class BaseBoard{constructor(){this.messageListeners=[],this.serialOutBuffer="",this.messages=[],this.lastSerialTime=0,this.debouncedPostAll=()=>{const e=Date.now();e-this.lastSerialTime>MIN_MESSAGE_WAIT_MS?(clearTimeout(this.serialTimeout),this.messages.length&&(Runtime.postMessage({type:"bulkserial",data:this.messages,id:pxsim.runtime.id,sim:!0}),this.messages=[],this.lastSerialTime=e)):this.serialTimeout=setTimeout(this.debouncedPostAll,50)},this.id=pxsim.Embed.frameid||"b"+Math.round(2147483647*Math.random()),this.bus=new pxsim.EventBus(pxsim.runtime,this)}updateView(){}receiveMessage(e){pxsim.runtime&&!pxsim.runtime.dead&&this.dispatchMessage(e)}dispatchMessage(e){for(const t of this.messageListeners)t(e)}addMessageListener(e){this.messageListeners.push(e)}get storedState(){return this.runOptions?(this.runOptions.storedState||(this.runOptions.storedState={}),this.runOptions.storedState):{}}initAsync(e){return this.runOptions=e,Promise.resolve()}setStoredState(e,t){null==t?delete this.storedState[e]:this.storedState[e]=t,Runtime.postMessage({type:"simulator",command:"setstate",stateKey:e,stateValue:t})}onDebuggerResume(){}screenshotAsync(e){return Promise.resolve(void 0)}kill(){}writeSerial(e){this.serialOutBuffer+=e,(/\n/.test(this.serialOutBuffer)||this.serialOutBuffer.length>SERIAL_BUFFER_LENGTH)&&(this.messages.push({time:Date.now(),data:this.serialOutBuffer}),this.debouncedPostAll(),this.serialOutBuffer="")}}pxsim.BaseBoard=BaseBoard;class CoreBoard extends BaseBoard{constructor(){super(),this.updateSubscribers=[],this.updateView=()=>{this.updateSubscribers.forEach((e=>e()))},this.builtinParts={},this.builtinVisuals={},this.builtinPartVisuals={}}kill(){super.kill(),pxsim.AudioContextManager.stopAll()}}pxsim.CoreBoard=CoreBoard;class BareBoard extends BaseBoard{}function initBareRuntime(){pxsim.runtime.board=new BareBoard;let e=pxsim;e.basic={pause:pxsim.thread.pause,showNumber:e=>{let t=getResume();console.log("SHOW NUMBER:",e),U.nextTick(t)}},e.serial={writeString:e=>pxsim.runtime.board.writeSerial(e)},e.pins={createBuffer:pxsim.BufferMethods.createBuffer},e.control={inBackground:pxsim.thread.runInBackground,createBuffer:pxsim.BufferMethods.createBuffer,dmesg:e=>console.log("DMESG: "+e),deviceDalVersion:()=>"sim",__log:(e,t)=>console.log("LOG: "+t.trim())}}let LogType;pxsim.initBareRuntime=initBareRuntime,function(e){e[e.UserSet=0]="UserSet",e[e.BackAdd=1]="BackAdd",e[e.BackRemove=2]="BackRemove"}(LogType||(LogType={}));class EventQueue{constructor(e,t){this.runtime=e,this.valueToArgs=t,this.max=5,this.events=[],this.awaiters=[],this._handlers=[],this._addRemoveLog=[]}push(e,t){if(this.awaiters.length>0)if(t){const e=this.awaiters.shift();e&&e()}else{const e=this.awaiters.slice();this.awaiters=[],e.forEach((e=>e()))}return 0==this.handlers.length||this.events.length>this.max?Promise.resolve():(this.events.push(e),this.lock?Promise.resolve():this.poke())}poke(){this.lock=!0;let e=this.events;return this.events=[],U.promiseMapAllSeries(e,(e=>U.promiseMapAllSeries(this.handlers,(t=>this.runtime.runFiberAsync(t,...this.valueToArgs?this.valueToArgs(e):[e]))))).then((()=>this.events.length>0?this.poke():(this.lock=!1,this._addRemoveLog.forEach((e=>{e.log===LogType.BackAdd?this.addHandler(e.act):e.log===LogType.BackRemove?this.removeHandler(e.act):this.setHandler(e.act)})),this._addRemoveLog=[],Promise.resolve())))}get handlers(){return this._handlers}setHandler(e){this.lock?this._addRemoveLog.push({act:e,log:LogType.UserSet}):this._handlers=[e]}addHandler(e){if(this.lock)this._addRemoveLog.push({act:e,log:LogType.BackAdd});else{-1==this._handlers.indexOf(e)&&this._handlers.push(e)}}removeHandler(e){if(this.lock)this._addRemoveLog.push({act:e,log:LogType.BackRemove});else{let t=this._handlers.indexOf(e);-1!=t&&this._handlers.splice(t,1)}}addAwaiter(e){this.awaiters.push(e)}}function bind(e){const t=e.arg0,n=e.fn;return e=>{let o=0;for(;e.hasOwnProperty("arg"+o);)o++;const r=e;for(let e=o;e>0;e--)r["arg"+e]=r["arg"+(e-1)];return e.arg0=t,n(e)}}function _leave(e,t){return e.parent.retval=t,e.parent}function syntheticRefAction(e){return pxtcore.mkAction(0,(t=>_leave(t,e(t))))}pxsim.EventQueue=EventQueue,pxsim.initCurrentRuntime=void 0,pxsim.handleCustomMessage=void 0,pxsim.syntheticRefAction=syntheticRefAction;class TimeoutScheduled{constructor(e,t,n,o){this.id=e,this.fn=t,this.totalRuntime=n,this.timestampCall=o}}pxsim.TimeoutScheduled=TimeoutScheduled;class PausedTimeout{constructor(e,t){this.fn=e,this.timeRemaining=t}}function mkVTable(e){return{name:e.name,numFields:e.numFields,classNo:e.classNo,methods:e.methods,iface:e.iface,lastSubtypeNo:e.lastSubtypeNo,toStringMethod:e.toStringMethod,maxBgInstances:e.maxBgInstances}}pxsim.PausedTimeout=PausedTimeout,pxsim.mkVTable=mkVTable;let mapVTable=null;function mkMapVTable(){return mapVTable||(mapVTable=mkVTable({name:"_Map",numFields:0,classNo:0,lastSubtypeNo:0,methods:null})),mapVTable}function functionName(e){const t=e.info;return t?`${t.functionName} (${t.fileName}:${t.line+1}:${t.column+1})`:"()"}pxsim.mkMapVTable=mkMapVTable,pxsim.functionName=functionName;class Runtime{constructor(msg){this.numGlobals=1e3,this.dead=!1,this.running=!1,this.idleTimer=void 0,this.recording=!1,this.recordingTimer=0,this.recordingLastImageData=void 0,this.recordingWidth=void 0,this.startTime=0,this.startTimeUs=0,this.pausedTime=0,this.lastPauseTimestamp=0,this.globals={},this.environmentGlobals={},this.otherFrames=[],this.loopLock=null,this.loopLockWaitList=[],this.heapSnapshots=[],this.timeoutsScheduled=[],this.timeoutsPausedOnBreakpoint=[],this.pausedOnBreakpoint=!1,this.traceDisabled=!1,this.perfOffset=0,this.perfElapsed=0,this.perfStack=0,this.refCountingDebug=!1,this.refObjId=1,this.numDisplayUpdates=0,U.assert(!!pxsim.initCurrentRuntime),this.id=msg.id,this.refCountingDebug=!!msg.refCountingDebug;let threadId=0,breakpoints=null,currResume,dbgHeap,dbgResume,breakFrame=null,lastYield=Date.now(),userGlobals,__this=this;this.traceDisabled=!!msg.traceDisabled;const evalIface={runtime:this,oops:oops,doNothing:doNothing,pxsim:pxsim,globals:this.globals,setupYield:setupYield,maybeYield:maybeYield,setupDebugger:setupDebugger,isBreakFrame:isBreakFrame,breakpoint:breakpoint,trace:trace,checkStack:checkStack,leave:_leave,checkResumeConsumed:checkResumeConsumed,setupResume:setupResume,setupLambda:setupLambda,checkSubtype:checkSubtype,failedCast:failedCast,buildResume:buildResume,mkVTable:mkVTable,bind:bind,leaveAccessor:leaveAccessor};function oops(e){throw new Error("sim error: "+e)}function doNothing(e){return e.pc=-1,_leave(e,e.parent.retval)}function flushLoopLock(){for(;__this.loopLockWaitList.length>0&&!__this.loopLock;){__this.loopLockWaitList.shift()()}}let yieldReset=()=>{};function setupYield(e){yieldReset=e}function loopForSchedule(e){const t=new Object,n=e.pc;return __this.loopLock=t,__this.otherFrames.push(e),()=>{__this.dead||(U.assert(e.pc==n),U.assert(__this.loopLock===t),__this.loopLock=null,loop(e),flushLoopLock())}}function maybeYield(e,t,n){if(__this.pausedOnBreakpoint)return!1;__this.cleanScheduledExpired(),yieldReset();let o=Date.now();return o-lastYield>=20&&(lastYield=o,e.pc=t,e.r0=n,setTimeout(loopForSchedule(e),5),!0)}function setupDebugger(e,t){return breakpoints=new Uint8Array(e),breakpoints[0]=msg.breakOnStart?1:0,userGlobals=t,breakpoints}function isBreakFrame(e){if(!breakFrame)return!0;for(let t=breakFrame;t;t=t.parent)if(t==e)return!0;return!1}function breakpoint(e,t,n,o){let r={};__this.loopLock=r,U.assert(!dbgResume),U.assert(!dbgHeap),e.pc=t,e.r0=o;const{msg:i,heap:s}=pxsim.getBreakpointMsg(e,n,userGlobals);return dbgHeap=s,pxsim.injectEnvironmentGlobals(i,s),Runtime.postMessage(i),breakpoints[0]=0,breakFrame=null,__this.pauseScheduled(),dbgResume=n=>{if(dbgResume=null,dbgHeap=null,__this.dead)return null;switch(__this.resumeAllPausedScheduled(),__this.board.onDebuggerResume(),pxsim.runtime=__this,U.assert(e.pc==t),breakpoints[0]=0,breakFrame=null,n.subtype){case"resume":break;case"stepover":breakpoints[0]=1,breakFrame=e;break;case"stepinto":breakpoints[0]=1;break;case"stepout":breakpoints[0]=1,breakFrame=e.parent||e}U.assert(__this.loopLock==r),__this.loopLock=null,__this.otherFrames.push(e),loop(e),flushLoopLock()},null}function trace(e,t,n,o){if(setupResume(t,n),"<main>"===o.functionName||"main.ts"===o.fileName){if(!pxsim.runtime.traceDisabled){const{msg:n}=pxsim.getBreakpointMsg(t,e,userGlobals);n.subtype="trace",Runtime.postMessage(n)}pxsim.thread.pause(tracePauseMs||1)}else pxsim.thread.pause(0);checkResumeConsumed()}function handleDebuggerMsg(e){switch(e.subtype){case"config":let t=e;if(t.setBreakpoints&&breakpoints){breakpoints.fill(0);for(let e of t.setBreakpoints)breakpoints[e]=1}break;case"traceConfig":tracePauseMs=e.interval;break;case"pause":breakpoints[0]=1,breakFrame=null;break;case"resume":case"stepover":case"stepinto":case"stepout":dbgResume&&dbgResume(e);break;case"variables":const n=e;let o;if(dbgHeap){const e=dbgHeap[n.variablesReference];void 0!==e&&(o=pxsim.dumpHeap(e,dbgHeap,n.fields))}Runtime.postMessage({type:"debugger",subtype:"variables",req_seq:e.seq,variables:o})}}function removeFrame(e){const t=__this.otherFrames;for(let n=t.length-1;n>=0;--n)if(t[n]===e)return void t.splice(n,1);U.userError("frame cannot be removed!")}function loop(e){if(__this.dead)console.log("Runtime terminated");else{U.assert(!__this.loopLock),__this.perfStartRuntime(),removeFrame(e);try{for(pxsim.runtime=__this;e;)__this.currFrame=e,__this.currFrame.overwrittenPC=!1,e=e.fn(e),__this.maybeUpdateDisplay(),__this.currFrame.overwrittenPC&&(e=__this.currFrame);__this.perfStopRuntime()}catch(t){if(t instanceof BreakLoopException)return void U.nextTick(loopForSchedule(__this.currFrame));if(__this.perfStopRuntime(),__this.errorHandler)__this.errorHandler(t);else{console.error("Simulator crashed, no error handler",t.stack);const{msg:n,heap:o}=pxsim.getBreakpointMsg(e,e.lastBrkId,userGlobals);pxsim.injectEnvironmentGlobals(n,o),n.exceptionMessage=t.message,n.exceptionStack=t.stack,Runtime.postMessage(n),__this.postError&&__this.postError(t)}}}}function checkStack(e){e>100&&U.userError("Stack overflow")}function actionCall(e){return e.depth=e.parent.depth+1,checkStack(e.depth),e.pc=0,e}function setupTop(e){let t=setupTopCore(e);return setupResume(t,0),t}function setupTopCore(e){let t={parent:null,pc:0,depth:0,threadId:++threadId,fn:()=>(e&&e(t.retval),null)};return t}function topCall(e,t){U.assert(!!__this.board),U.assert(!__this.running),__this.setRunning(!0);let n={parent:setupTopCore(t),fn:e,depth:0,pc:0};__this.otherFrames=[n],loop(actionCall(n))}function checkResumeConsumed(){currResume&&oops("getResume() not called")}function setupResume(e,t){currResume=buildResume(e,t)}function leaveAccessor(e,t){if(e.stage2Call){const n={pc:0,fn:null,depth:e.depth,parent:e.parent};let o=1;for(;e.hasOwnProperty("arg"+o);)n["arg"+(o-1)]=e["arg"+o],o++;return setupLambda(n,t),n}return e.parent.retval=t,e.parent}function setupLambda(e,t,n){if(n){const t=e;for(let e=1;e<n;++e)t["arg"+(e-1)]=t["arg"+e];delete t["arg"+(n-1)]}t instanceof pxsim.RefAction?(e.fn=t.func,e.caps=t.fields):"function"==typeof t?e.fn=t:oops("calling non-function")}function checkSubtype(e,t){if(!e)return!1;const n=e.vtable;return t===n||n&&t.classNo<=n.classNo&&n.classNo<=t.lastSubtypeNo}function failedCast(e){pxsim.control&&pxsim.control.dmesgValue&&pxsim.control.dmesgValue(e),oops("failed cast on "+e)}function buildResume(e,t){currResume&&oops("already has resume"),e.pc=t;let n=Date.now();__this.otherFrames.push(e);let o=r=>{if(__this.dead)return;if(__this.loopLock)return void __this.loopLockWaitList.push((()=>o(r)));pxsim.runtime=__this;let i=Date.now();if(i-n>3&&(lastYield=i),U.assert(e.pc==t),r instanceof pxsim.FnWrapper){let t=r,n={parent:e,fn:t.func,lambdaArgs:t.args,pc:0,caps:t.caps,depth:e.depth+1},o={};return __this.loopLock=o,removeFrame(e),__this.otherFrames.push(n),U.nextTick((()=>{U.assert(__this.loopLock===o),__this.loopLock=null,loop(actionCall(n)),flushLoopLock()}))}return e.retval=r,loop(e)};return o}const entryPoint=msg.code&&eval(msg.code)(evalIface);this.run=e=>topCall(entryPoint,e),this.getResume=()=>{currResume||oops("noresume");let e=currResume;return currResume=null,e},this.setupTop=setupTop,this.handleDebuggerMsg=handleDebuggerMsg,this.entry=entryPoint,this.overwriteResume=e=>{currResume=null,e>=0&&(this.currFrame.pc=e),this.currFrame.overwrittenPC=!0},pxsim.runtime=this,pxsim.initCurrentRuntime(msg)}registerLiveObject(e){return this.refObjId++}runningTime(){return U.now()-this.startTime-this.pausedTime}runningTimeUs(){return 4294967295&U.perfNowUs()-this.startTimeUs>>0}runFiberAsync(e,t,n,o){return new Promise(((r,i)=>U.nextTick((()=>{pxsim.runtime=this,this.setupTop(r),pxtcore.runAction(e,[t,n,o])}))))}currTryFrame(){for(let e=this.currFrame;e;e=e.parent)if(e.tryFrame)return e.tryFrame;return null}traceObjects(){const e={};for(;this.heapSnapshots.length>2;)this.heapSnapshots.shift();const t={count:0,size:0,name:"TOTAL"},n={TOTAL:t};function o(t,n,r=null){if(!(n instanceof pxsim.RefObject))return;const i=n;if(i.gcIsStatic())return;const s=e[i.id];if(s)return void(r&&s.pointers.push([r,t]));const a={obj:i,path:null,pointers:[[r,t]]};e[i.id]=a,i.scan(((t,n)=>{n instanceof pxsim.RefObject&&!e[n.id]&&o(t,n,a)}))}this.heapSnapshots.push({visited:e,statsByType:n});for(let e of Object.keys(this.globals))o(e.replace(/___\d+$/,""),this.globals[e]);const r=this.otherFrames.slice();this.currFrame&&r.indexOf(this.currFrame)<0&&r.unshift(this.currFrame);for(const e of this.getThreads()){const t="Thread-"+this.rootFrame(e).threadId;for(let n=e;n;n=n.parent){const e=t+"."+functionName(n.fn);for(let t of Object.keys(n))if(/^(r0|arg\d+|.*___\d+)/.test(t)){const r=n[t];r instanceof pxsim.RefObject&&(t=t.replace(/___.*/,""),o(e+"."+t,r))}if(n.caps)for(let t of n.caps)o(e+".cap",t)}}const i=Object.keys(e).map((t=>e[t]));i.sort(((e,t)=>t.obj.gcSize()-e.obj.gcSize()));const s=e=>{if(null!=e.path)return;let t="";e.path="(cycle)";for(let[n,o]of e.pointers){if(null==n)return void(e.path=o);s(n);const r=n.path+"."+o;(!t||t.length>r.length)&&(t=r)}e.path=t};i.forEach(s);const a=[t];for(const e of i){const o=e.obj.gcSize(),r=e.obj.gcKey();n.hasOwnProperty(r)||a.push(n[r]={count:0,size:0,name:r});const i=n[r];i.size+=o,i.count++,t.size+=o,t.count++}a.sort(((e,t)=>e.size-t.size));let l="";const c=e=>(" "+e.toString()).slice(-7);for(const e of a)l+=c(4*e.size)+c(e.count)+" "+e.name+"\n";const u=e=>c(4*e.obj.gcSize())+" "+e.obj.gcKey()+" "+e.path,d=i.slice(0,20).map(u).join("\n");let p="";if(this.heapSnapshots.length>=3){const e=this.heapSnapshots[this.heapSnapshots.length-3].visited,t=this.heapSnapshots[this.heapSnapshots.length-2].visited,o=e=>e instanceof pxsim.RefRecord&&!!(e.vtable&&e.vtable.maxBgInstances&&n[e.gcKey()].count<=e.vtable.maxBgInstances);p=i.filter((n=>!e[n.obj.id]&&t[n.obj.id])).filter((e=>!o(e.obj))).map(u).join("\n")}return"Threads:\n"+this.threadInfo()+"\n\nSummary:\n"+l+"\n\nLarge Objects:\n"+d+"\n\nNew Objects:\n"+p}getThreads(){const e=this.otherFrames.slice();return this.currFrame&&e.indexOf(this.currFrame)<0&&e.unshift(this.currFrame),e}rootFrame(e){let t=e;for(;t.parent;)t=t.parent;return t}threadInfo(){const e=this.getThreads();let t="";for(let n of e){t+=`Thread ${this.rootFrame(n).threadId}:\n`;for(let e of pxsim.getBreakpointMsg(n,n.lastBrkId).msg.stackframes){let n=e.funcInfo;t+=` at ${n.functionName} (${n.fileName}:${n.line+1}:${n.column+1})\n`}t+="\n"}return t}static postMessage(e){e&&("undefined"!=typeof window&&window.parent&&window.parent.postMessage&&window.parent.postMessage(e,"*"),Runtime.messagePosted&&Runtime.messagePosted(e))}static postScreenshotAsync(e){const t=pxsim.runtime&&pxsim.runtime.board;return(t?t.screenshotAsync().catch((e=>{console.debug("screenshot failed")})):Promise.resolve(void 0)).then((t=>Runtime.postMessage({type:"screenshot",data:t,delay:e&&e.delay})))}static requestToggleRecording(){const e=pxsim.runtime;e&&Runtime.postMessage({type:"recorder",action:e.recording?"stop":"start"})}restart(){this.kill(),setTimeout((()=>pxsim.Runtime.postMessage({type:"simulator",command:"restart"})),500)}kill(){this.dead=!0,this.stopRecording(),this.stopIdle(),this.setRunning(!1)}updateDisplay(){this.board.updateView(),this.postFrame()}startRecording(e){!this.recording&&this.running&&(this.recording=!0,this.recordingTimer=setInterval((()=>this.postFrame()),66),this.recordingLastImageData=void 0,this.recordingWidth=e)}stopRecording(){this.recording&&(this.recordingTimer&&clearInterval(this.recordingTimer),this.recording=!1,this.recordingTimer=0,this.recordingLastImageData=void 0,this.recordingWidth=void 0)}postFrame(){if(!this.recording||!this.running)return;let e=pxsim.U.now();this.board.screenshotAsync(this.recordingWidth).then((t=>{if(this.recordingLastImageData&&t&&this.recordingLastImageData.data.byteLength==t.data.byteLength){const e=this.recordingLastImageData.data,n=t.data,o=e.byteLength;let r=0;for(r=0;r<o&&e[r]==n[r];++r);if(r==o)return}this.recordingLastImageData=t,Runtime.postMessage({type:"screenshot",data:t,time:e})}))}queueDisplayUpdate(){this.numDisplayUpdates++}maybeUpdateDisplay(){this.numDisplayUpdates&&(this.numDisplayUpdates=0,this.updateDisplay())}setRunning(e){this.running!=e&&(this.running=e,this.running?(this.startTime=U.now(),this.startTimeUs=U.perfNowUs(),Runtime.postMessage({type:"status",frameid:pxsim.Embed.frameid,runtimeid:this.id,state:"running"})):(this.stopRecording(),this.stopIdle(),Runtime.postMessage({type:"status",frameid:pxsim.Embed.frameid,runtimeid:this.id,state:"killed"})),this.stateChanged&&this.stateChanged())}dumpLivePointers(){}setupPerfCounters(e){e&&e.length&&(this.perfCounters=e.map((e=>new PerfCounter(e))))}perfStartRuntime(){0!==this.perfOffset?this.perfStack++:this.perfOffset=U.perfNowUs()-this.perfElapsed}perfStopRuntime(){this.perfStack?this.perfStack--:(this.perfElapsed=this.perfNow(),this.perfOffset=0)}perfNow(){return 0===this.perfOffset&&U.userError("bad time now"),U.perfNowUs()-this.perfOffset|0}startPerfCounter(e){if(!this.perfCounters)return;const t=this.perfCounters[e];t.start&&U.userError("startPerf"),t.start=this.perfNow()}stopPerfCounter(e){if(!this.perfCounters)return;const t=this.perfCounters[e];t.start||U.userError("stopPerf");const n=this.perfNow()-t.start;t.start=0,t.value+=n,t.numstops++;let o=t.lastFewPtr++;o>=t.lastFew.length&&(o=0,t.lastFewPtr=1),t.lastFew[o]=n}startIdle(){void 0===this.idleTimer&&(this.idleTimer=setInterval((()=>{if(!this.running||this.pausedOnBreakpoint)return;const e=this.board.bus;e&&e.queueIdle()}),20))}stopIdle(){void 0!==this.idleTimer&&(clearInterval(this.idleTimer),this.idleTimer=void 0)}schedule(e,t){if(t<=0&&(t=0),this.pausedOnBreakpoint)return this.timeoutsPausedOnBreakpoint.push(new PausedTimeout(e,t)),-1;const n=U.now(),o=new TimeoutScheduled(-1,e,t,n);return o.id=setTimeout((()=>{const t=this.timeoutsScheduled.indexOf(o);t>=0&&this.timeoutsScheduled.splice(t,1),e()}),t),this.timeoutsScheduled.push(o),o.id}pauseScheduled(){this.pausedOnBreakpoint=!0,this.timeoutsScheduled.forEach((e=>{clearTimeout(e.id);let t=U.now()-e.timestampCall,n=e.totalRuntime-t;n<=0&&(n=1),this.timeoutsPausedOnBreakpoint.push(new PausedTimeout(e.fn,n))})),this.lastPauseTimestamp=U.now(),this.timeoutsScheduled=[]}resumeAllPausedScheduled(){this.pausedOnBreakpoint=!1,this.timeoutsPausedOnBreakpoint.forEach((e=>{this.schedule(e.fn,e.timeRemaining)})),this.lastPauseTimestamp&&(this.pausedTime+=U.now()-this.lastPauseTimestamp,this.lastPauseTimestamp=0),this.timeoutsPausedOnBreakpoint=[]}cleanScheduledExpired(){let e=U.now();this.timeoutsScheduled=this.timeoutsScheduled.filter((t=>{let n=e-t.timestampCall;return t.totalRuntime>n}))}}pxsim.Runtime=Runtime;class PerfCounter{constructor(e){this.name=e,this.start=0,this.numstops=0,this.value=0,this.lastFew=new Uint32Array(32),this.lastFewPtr=0}}pxsim.PerfCounter=PerfCounter}(pxsim||(pxsim={})),function(e){let t,n;!function(e){e[e.Unloaded=0]="Unloaded",e[e.Stopped=1]="Stopped",e[e.Pending=2]="Pending",e[e.Starting=3]="Starting",e[e.Running=4]="Running",e[e.Paused=5]="Paused",e[e.Suspended=6]="Suspended"}(t=e.SimulatorState||(e.SimulatorState={})),function(e){e[e.StepInto=0]="StepInto",e[e.StepOver=1]="StepOver",e[e.StepOut=2]="StepOut",e[e.Resume=3]="Resume",e[e.Pause=4]="Pause"}(n=e.SimulatorDebuggerCommand||(e.SimulatorDebuggerCommand={}));const o="pxtdriver";e.SimulatorDriver=class{constructor(n,o={}){this.container=n,this.options=o,this.themes=["blue","red","green","yellow"],this.runId="",this.nextFrameId=0,this.frameCounter=0,this.traceInterval=0,this.breakpointsSet=!1,this._runOptions={},this.state=t.Unloaded,this._allowedOrigins=[],this.frameCleanupTimeout=void 0,this.debuggerSeq=1,this.debuggerResolvers={},this._allowedOrigins.push(window.location.origin),o.parentOrigin&&this._allowedOrigins.push(o.parentOrigin),this._allowedOrigins.push(this.getSimUrl().origin);const r=null==o?void 0:o.messageSimulators;r&&Object.keys(r).map((e=>r[e])).forEach((e=>{this._allowedOrigins.push(new URL(e.url).origin),e.localHostUrl&&this._allowedOrigins.push(new URL(e.localHostUrl).origin)})),this._allowedOrigins=e.U.unique(this._allowedOrigins,(e=>e))}isDebug(){return this._runOptions&&!!this._runOptions.debug}isTracing(){return this._runOptions&&!!this._runOptions.trace}hasParts(){return this._runOptions&&this._runOptions.parts&&!!this._runOptions.parts.length}setDirty(){this.state==e.SimulatorState.Running&&this.suspend()}setPending(){this.setState(t.Pending)}focus(){const e=this.simFrames()[0];e&&e.focus()}registerDependentEditor(e){e&&(this._dependentEditors||(this._dependentEditors=[]),this._dependentEditors.push(e))}dependentEditors(){return this._dependentEditors&&(this._dependentEditors=this._dependentEditors.filter((e=>!!e.parent)),this._dependentEditors.length||(this._dependentEditors=void 0)),this._dependentEditors}setStarting(){this.setState(t.Starting)}setHwDebugger(e){e?(this.hwdbg=e,this.setState(t.Running),this.container.style.opacity="0.3"):(delete this.container.style.opacity,this.hwdbg=null,this.setState(t.Running),this.stop())}handleHwDebuggerMsg(e){this.hwdbg&&this.handleMessage(e)}setThemes(t){e.U.assert(t&&t.length>0),this.themes=t}startRecording(e){this.simFrames()[0]&&this.postMessage({type:"recorder",action:"start",source:o,width:e})}stopRecording(){this.postMessage({type:"recorder",source:o,action:"stop"})}setFrameState(n){const o=n.nextElementSibling,r=o.nextElementSibling;switch(this.state){case t.Pending:case t.Starting:o.style.display="",o.className="",r.style.display="";break;case t.Stopped:case t.Suspended:e.U.addClass(n,this.state==t.Stopped||this._runOptions&&this._runOptions.autoRun?this.stoppedClass:this.invalidatedClass),this._runOptions&&this._runOptions.autoRun?o.style.display="none":(o.style.display="",o.className="videoplay xicon icon"),r.style.display="none",this.scheduleFrameCleanup();break;default:e.U.removeClass(n,this.stoppedClass),e.U.removeClass(n,this.invalidatedClass),o.style.display="none",r.style.display="none"}}setState(e){this.state!=e&&(this.state=e,this.freeze(this.state==t.Paused),this.simFrames().forEach((e=>this.setFrameState(e))),this.options.onStateChanged&&this.options.onStateChanged(this.state))}freeze(t){const n="pause-overlay";t?e.util.toArray(this.container.querySelectorAll("div.simframe")).forEach((e=>{if(e.querySelector(`div.${n}`))return;const t=document.createElement("div");t.className=n,t.onclick=e=>(e.preventDefault(),!1),e.appendChild(t)})):e.util.toArray(this.container.querySelectorAll(`div.simframe div.${n}`)).forEach((e=>e.parentElement.removeChild(e)))}simFrames(t=!1){let n=e.util.toArray(this.container.getElementsByTagName("iframe"));const o=this.loanedIFrame();return o&&!t&&n.unshift(o),n}getSimUrl(){const e=this.options.simUrl||(window.pxtConfig||{}).simUrl||`${location.origin}/sim/simulator.html`;try{return new URL(e)}catch(t){return new URL(e,location.origin)}}postMessage(t,n,o){var r;if(this.hwdbg)return void this.hwdbg.postMessage(t);const i=this.dependentEditors();let s=this.simFrames();o&&(s=s.filter((e=>e.id===o)));const a=t;if(n&&(null==a?void 0:a.broadcast)){const o=!!(null===(r=this._currentRuntime)||void 0===r?void 0:r.single),a=window.parent&&window.parent!==window.window?window.parent:window.opener;if(this.options.nestedEditorSim&&a){if(n!==a){const e=this.options.parentOrigin||window.location.origin;a.postMessage(t,e)}}else if(i)i.forEach((e=>{n!==e&&e.postMessage(t,window.location.origin)}));else if(!o){const n="messagepacket"===t.type&&t.channel,o=n&&this.options.messageSimulators&&this.options.messageSimulators[n];if(o){let t=s.find((e=>e.dataset.messagechannel===n));if(t)t.dataset.runid!=this.runId&&this.startFrame(t);else{const r=(e.U.isLocalHost()&&/localhostmessagesims=1/i.test(window.location.href)&&o.localHostUrl||o.url).replace("$PARENT_ORIGIN$",encodeURIComponent(this.options.parentOrigin||""));let i=this.createFrame(r);this.container.appendChild(i),t=i.firstElementChild,t.dataset.messagechannel=n,e.U.addClass(i,"simmsg"),e.U.addClass(i,"simmsg"+n),o.permanent&&(t.dataset.permanent="true"),this.startFrame(t),s=this.simFrames()}}else{const e=s.filter((e=>!e.dataset.messagechannel));e.length<2?(this.container.appendChild(this.createFrame()),s=this.simFrames()):e[1].dataset.runid!=this.runId&&this.startFrame(e[1])}}}for(let e=0;e<s.length;++e){const o=s[e];if((!n||o.contentWindow!=n)&&(o.contentWindow&&(this.postMessageCore(o,t),"recorder"==t.type&&"start"==t.action)))break}}postMessageCore(t,n){var o,r,i,s;if(t.contentWindow.postMessage(n,t.dataset.origin),e.U.isLocalHostDev()&&(null===(r=null===(o=pxt)||void 0===o?void 0:o.appTarget)||void 0===r?void 0:r.id))try{t.contentWindow.postMessage(n,`https://trg-${null===(s=null===(i=pxt)||void 0===i?void 0:i.appTarget)||void 0===s?void 0:s.id}.userpxt.io/---simulator`)}catch(e){}}createFrame(n){const o=document.createElement("div");o.className="simframe ui embed";const r=document.createElement("iframe");r.id="sim-frame-"+this.nextId(),r.title=e.localization.lf("Simulator"),r.allowFullscreen=!0,r.setAttribute("allow","autoplay"),r.setAttribute("sandbox","allow-same-origin allow-scripts"),r.className="no-select";const i=(n||this.getSimUrl())+"#"+r.id;r.src=i,r.frameBorder="0",r.dataset.runid=this.runId,r.dataset.origin=new URL(i).origin||"*",o.appendChild(r);const s=document.createElement("i");s.className="videoplay xicon icon",s.style.display="none",s.onclick=e=>(e.preventDefault(),this.state!=t.Running&&this.state!=t.Starting&&(this.options.restart?this.options.restart():this.start()),r.focus(),!1),o.appendChild(s);const a=document.createElement("div");return a.className="ui active loader",s.style.display="none",o.appendChild(a),this._runOptions&&this.applyAspectRatioToFrame(r),o}preload(e){this.simFrames().length||(this.container.appendChild(this.createFrame()),this.applyAspectRatio(e),this.setStarting())}stop(e=!1,n=!1){this.clearDebugger(),this.postMessage({type:"stop",source:o}),this.setState(n?t.Starting:t.Stopped),e&&this.unload()}suspend(){this.postMessage({type:"stop",source:o}),this.setState(t.Suspended)}unload(){this.cancelFrameCleanup(),e.U.removeChildren(this.container),this.setState(t.Unloaded),this._runOptions=void 0,this._currentRuntime=void 0,this.runId=void 0}mute(e){this._currentRuntime&&(this._currentRuntime.mute=e),this.postMessage({type:"mute",source:o,mute:e})}stopSound(){this.postMessage({type:"stopsound",source:o})}isLoanedSimulator(e){return!!this.loanedSimulator&&this.loanedIFrame()==e}loanSimulator(){return this.loanedSimulator||(this.loanedSimulator=this.container.firstElementChild||this.createFrame(),this.loanedSimulator.parentNode&&this.container.removeChild(this.loanedSimulator)),this.loanedSimulator}unloanSimulator(){this.loanedSimulator&&(this.loanedSimulator.parentNode&&this.loanedSimulator.parentNode.removeChild(this.loanedSimulator),this.container.insertBefore(this.loanedSimulator,this.container.firstElementChild),delete this.loanedSimulator)}loanedIFrame(){return this.loanedSimulator&&this.loanedSimulator.parentNode&&this.loanedSimulator.querySelector("iframe")}cancelFrameCleanup(){this.frameCleanupTimeout&&(clearTimeout(this.frameCleanupTimeout),this.frameCleanupTimeout=void 0)}scheduleFrameCleanup(){this.cancelFrameCleanup(),this.frameCleanupTimeout=setTimeout((()=>{this.frameCleanupTimeout=void 0,this.cleanupFrames()}),5e3)}applyAspectRatio(e){if(!e&&!this._runOptions)return;this.simFrames().forEach((t=>this.applyAspectRatioToFrame(t,e)))}applyAspectRatioToFrame(e,t){var n,o,r,i;let s=t;if(void 0===s){const t=parseFloat(e.dataset.aspectratio);isNaN(t)||(s=t)}if(void 0===s){const t=e.dataset.messagechannel;if(t){const e=null===(r=null===(o=null===(n=this.options)||void 0===n?void 0:n.messageSimulators)||void 0===o?void 0:o[t])||void 0===r?void 0:r.aspectRatio;e&&(s=e)}}void 0===s&&(s=(null===(i=this._runOptions)||void 0===i?void 0:i.aspectRatio)||1.22),e.parentElement.style.paddingBottom=100/s+"%"}cleanupFrames(){const e=this.simFrames(!0);e.shift(),e.filter((e=>!e.dataset.permanent)).forEach((e=>{this.state!=t.Stopped&&e.dataset.runid==this.runId||(this.options.removeElement?this.options.removeElement(e.parentElement):e.parentElement.remove())}))}hide(e){if(this.suspend(),!this.options.removeElement)return;const t=this.simFrames();t.forEach((t=>{this.options.removeElement(t.parentElement,e)})),0==t.length&&e&&e()}unhide(){if(!this.options.unhideElement)return;this.simFrames().forEach((e=>{this.options.unhideElement(e.parentElement)}))}run(e,t={}){this._runOptions=t,this.runId=this.nextId(),this._currentRuntime={type:"run",source:o,boardDefinition:t.boardDefinition,parts:t.parts,builtinParts:t.builtinParts,fnArgs:t.fnArgs,code:e,partDefinitions:t.partDefinitions,mute:t.mute,highContrast:t.highContrast,light:t.light,cdnUrl:t.cdnUrl,localizedStrings:t.localizedStrings,refCountingDebug:t.refCountingDebug,version:t.version,clickTrigger:t.clickTrigger,breakOnStart:t.breakOnStart,storedState:t.storedState,ipc:t.ipc,single:t.single,dependencies:t.dependencies},this.start()}restart(){this.stop(),this.cleanupFrames(),this.start()}areBreakpointsSet(){return this.breakpointsSet}start(){if(this.clearDebugger(),this.addEventListeners(),this.applyAspectRatio(),this.scheduleFrameCleanup(),!this._currentRuntime)return;this.breakpointsSet=!1;let e=this.simFrames()[0];if(e)this.startFrame(e);else{let t=this.createFrame();this.container.appendChild(t),e=t.firstElementChild}this.debuggingFrame=e.id,this.setState(t.Running),this.setTraceInterval(this.traceInterval)}startFrame(e){if(!this._currentRuntime||!e.contentWindow)return!1;const t=JSON.parse(JSON.stringify(this._currentRuntime));return t.frameCounter=++this.frameCounter,t.options={theme:this.themes[this.nextFrameId++%this.themes.length]},t.id=`${t.options.theme}-${this.nextId()}`,e.dataset.runid=this.runId,e.dataset.runtimeid=t.id,e.id!==this.debuggingFrame&&(t.traceDisabled=!0,t.breakOnStart=!1),this.postMessageCore(e,t),this.traceInterval&&this.setTraceInterval(this.traceInterval),this.applyAspectRatioToFrame(e),this.setFrameState(e),!0}handleMessage(e,n){switch(e.type||""){case"ready":{const t=e.frameid,n=document.getElementById(t);n&&(this.startFrame(n),this.options.revealElement&&this.options.revealElement(n)),this.options.onSimulatorReady&&this.options.onSimulatorReady();break}case"status":{const n=e.frameid,o=document.getElementById(n);if(o){const n=e;if(n.runtimeid==o.dataset.runtimeid)switch(n.state){case"running":this.setState(t.Running);break;case"killed":this.setState(t.Stopped)}}break}case"simulator":this.handleSimulatorCommand(e);break;case"serial":case"pxteditor":case"screenshot":case"custom":case"recorder":case"addextensions":break;case"aspectratio":{const t=e,n=t.frameid,o=document.getElementById(n);o&&(o.dataset.aspectratio=t.value+"",this.applyAspectRatioToFrame(o));break}case"debugger":this.handleDebuggerMessage(e);break;case"toplevelcodefinished":this.options.onTopLevelCodeEnd&&this.options.onTopLevelCodeEnd();break;default:this.postMessage(e,n)}}addEventListeners(){this.listener||(this.listener=t=>{if(!this.hwdbg){if(e.U.isLocalHost());else if(this._allowedOrigins.indexOf(t.origin)<0)return;this.handleMessage(t.data,t.source)}},window.addEventListener("message",this.listener,!1))}removeEventListeners(){this.listener&&(window.removeEventListener("message",this.listener,!1),this.listener=void 0)}resume(e){let r;switch(e){case n.Resume:r="resume",this.setState(t.Running);break;case n.StepInto:r="stepinto",this.setState(t.Running);break;case n.StepOut:r="stepout",this.setState(t.Running);break;case n.StepOver:r="stepover",this.setState(t.Running);break;case n.Pause:r="pause";break;default:return void console.debug("unknown command")}this.postMessage({type:"debugger",subtype:r,source:o})}setBreakpoints(e){this.breakpointsSet=!0,this.postDebuggerMessage("config",{setBreakpoints:e},void 0,this.debuggingFrame)}setTraceInterval(e){this.traceInterval=e,this.postDebuggerMessage("traceConfig",{interval:e})}variablesAsync(e,t){return this.postDebuggerMessageAsync("variables",{variablesReference:e,fields:t},this.debuggingFrame).then((e=>e),(e=>{}))}handleSimulatorCommand(e){this.options.onSimulatorCommand&&this.options.onSimulatorCommand(e)}clearDebugger(){const e=new Error("Debugging cancelled");Object.keys(this.debuggerResolvers).forEach((t=>{const{reject:n}=this.debuggerResolvers[t];n(e)})),this.debuggerResolvers={},this.debuggerSeq++}handleDebuggerMessage(e){if("trace"!==e.subtype&&console.log("DBG-MSG",e.subtype,e),e.seq){const{resolve:t}=this.debuggerResolvers[e.seq];t&&t(e)}switch(e.subtype){case"warning":this.options.onDebuggerWarning&&this.options.onDebuggerWarning(e);break;case"breakpoint":{const o=e;if(this.state==t.Running){if(o.exceptionMessage)this.suspend();else{this.setState(t.Paused);this.simFrames(!0).length>1&&this.resume(n.Pause)}this.options.onDebuggerBreakpoint&&this.options.onDebuggerBreakpoint(o);let e=o.exceptionMessage+"\n";for(let t of o.stackframes){let n=t.funcInfo;e+=` at ${n.functionName} (${n.fileName}:${n.line+1}:${n.column+1})\n`}o.exceptionMessage&&console.error(e)}else console.error("debugger: trying to pause from "+this.state);break}case"trace":{const n=e;this.state==t.Running&&this.options.onTraceMessage&&this.options.onTraceMessage(n);break}default:const o=e.req_seq;if(o){const{resolve:t}=this.debuggerResolvers[o];t&&(delete this.debuggerResolvers[o],t(e))}}}postDebuggerMessageAsync(e,t={},n){return new Promise(((o,r)=>{const i=this.debuggerSeq++;this.debuggerResolvers[i.toString()]={resolve:o,reject:r},this.postDebuggerMessage(e,t,i,n)}))}postDebuggerMessage(e,t={},n,r){const i=JSON.parse(JSON.stringify(t));i.type="debugger",i.subtype=e,i.source=o,n&&(i.seq=n),this.postMessage(i,void 0,r)}nextId(){return this.nextFrameId+++(Math.random()+""+Math.random()).replace(/[^\d]/,"")}get stoppedClass(){return this.options&&this.options.stoppedClass||"grayscale"}get invalidatedClass(){return this.options&&this.options.invalidatedClass||"sepia"}}}(pxsim||(pxsim={})),function(e){e.mkRange=function(e,t){let n=[];for(;e<t;e++)n.push(e);return n};e.EventBus=class{constructor(e,t,n){this.runtime=e,this.board=t,this.valueToArgs=n,this.queues={},this.backgroundHandlerFlag=!1,this.nextNotifyEvent=1024,this.schedulerID=15,this.idleEventID=2,this.board.addMessageListener(this.handleMessage.bind(this))}handleMessage(e){if("eventbus"===e.type){const t=e;this.queue(t.id,t.eventid,t.value)}}setBackgroundHandlerFlag(){this.backgroundHandlerFlag=!0}setNotify(e,t){this.notifyID=e,this.notifyOneID=t}setIdle(e,t){this.schedulerID=e,this.idleEventID=t}start(t,n,o,r=!1){let i=(o?"back":"fore")+":"+t+":"+n;return!this.queues[i]&&r&&(this.queues[i]=new e.EventQueue(this.runtime,this.valueToArgs)),this.queues[i]}listen(e,t,n){e==this.schedulerID&&t==this.idleEventID&&this.runtime.startIdle();let o=this.start(e,t,this.backgroundHandlerFlag,!0);this.backgroundHandlerFlag?o.addHandler(n):o.setHandler(n),this.backgroundHandlerFlag=!1}removeBackgroundHandler(e){Object.keys(this.queues).forEach((t=>{t.startsWith("back:")&&this.queues[t].removeHandler(e)}))}getQueues(e,t,n){let o=[this.start(0,0,n)];return 0==e&&0==t||(t&&o.push(this.start(0,t,n)),e&&o.push(this.start(e,0,n)),e&&t&&o.push(this.start(e,t,n))),o}queue(t,n,o=null){if(e.runtime.pausedOnBreakpoint)return;const r=this.notifyID&&this.notifyOneID&&t==this.notifyOneID;r&&(t=this.notifyID);let i=this.getQueues(t,n,!0).concat(this.getQueues(t,n,!1));this.lastEventValue=n,this.lastEventTimestampUs=e.U.perfNowUs(),e.U.promiseMapAllSeries(i,(e=>e?e.push(o,r):Promise.resolve()))}queueIdle(){this.schedulerID&&this.idleEventID&&this.queue(this.schedulerID,this.idleEventID)}wait(e,t,n){this.start(e,t,!1,!0).addAwaiter(n)}getLastEventValue(){return this.lastEventValue}getLastEventTime(){return 4294967295&this.lastEventTimestampUs-e.runtime.startTimeUs}};let t;function n(){return"undefined"!=typeof window&&("ontouchstart"in window||navigator&&navigator.maxTouchPoints>0)}function o(){return"undefined"!=typeof window&&!!window.PointerEvent}e.AnimationQueue=class{constructor(e){this.runtime=e,this.queue=[],this.process=()=>{let t=this.queue[0];if(!t)return;if(this.runtime.dead)return;e=this.runtime;let n=t.frame();e.queueDisplayUpdate(),e.maybeUpdateDisplay(),!1===n?(this.queue.shift(),this.queue[0]&&(this.queue[0].setTimeoutHandle=setTimeout(this.process,this.queue[0].interval)),t.whenDone(!1)):t.setTimeoutHandle=setTimeout(this.process,t.interval)}}cancelAll(){let e=this.queue;this.queue=[];for(let t of e)t.whenDone(!0),t.setTimeoutHandle&&clearTimeout(t.setTimeoutHandle)}cancelCurrent(){let e=this.queue[0];e&&(this.queue.shift(),e.whenDone(!0),e.setTimeoutHandle&&clearTimeout(e.setTimeoutHandle))}enqueue(e){e.whenDone||(e.whenDone=()=>{}),this.queue.push(e),1==this.queue.length&&this.process()}executeAsync(t){return e.U.assert(!t.whenDone),new Promise(((e,n)=>{t.whenDone=e,this.enqueue(t)}))}},function(t){let n,o,r,i,s=0,a=!1;function l(){return n||(n=function(){if(window.AudioContext=window.AudioContext||window.webkitAudioContext,window.AudioContext)try{return new window.AudioContext}catch(e){}return}()),n}function c(){S(0),s=0,i&&i.pause()}function u(){c(),v()}function d(e,t){e.gain.value&&e.gain.setTargetAtTime(0,l().currentTime,.015),setTimeout((()=>{e.disconnect(),t&&t.disconnect()}),450)}t.mute=function(e){a=e,u();const t=l();!e&&t&&"suspended"===t.state&&t.resume()},t.stopAll=u,t.stop=function(){c(),function(){if(r){try{d(r,o)}catch(e){}r=void 0,o=void 0}}()},t.frequency=function(){return s};const p=[null,"triangle","sawtooth","sine"];let g,h,f=[],_=[];function m(e,t){let n,o=p[e];if(o){let e=l().createOscillator();return e.type=o,e.frequency.value=t,e}if(4==e)n=function(){if(!h){const e=131072;h=l().createBuffer(1,e,l().sampleRate);const t=h.getChannelData(0);let n=251771520;for(let o=0;o<e;o+=4)n^=n<<13,n^=n>>17,n^=n<<5,32768&n?(t[o]=1,t[o+1]=1,t[o+2]=-1,t[o+3]=-1):(t[o]=0,t[o+1]=0,t[o+2]=0,t[o+3]=0)}return h}();else if(5==e)n=function(){if(!g){const e=1e5;g=l().createBuffer(1,e,l().sampleRate);const t=g.getChannelData(0);let n=251771520;for(let o=0;o<e;o++)n^=n<<13,n^=n>>17,n^=n<<5,t[o]=(1023&n)/512-1}return g}();else if(11<=e&&e<=15)n=function(e){if(!_[e]){const t=1024,n=l().createBuffer(1,t,l().sampleRate),o=n.getChannelData(0);for(let n=0;n<t;n++)o[n]=n<e/100*t?1:-1;_[e]=n}return _[e]}(10*(e-10));else{if(!(16<=e&&e<=18))return null;n=function(e){if(!f[e]){const t=1024,n=l().createBuffer(1,t,l().sampleRate),o=n.getChannelData(0),r=[770763591,3356908179],i=[15,31,63];for(let n=0;n<t;n+=4){let t,s=n/4;s&=i[e-4],t=0!=(r[s>>5]&1<<(31&s)),t?(o[n]=1,o[n+1]=1,o[n+2]=-1,o[n+3]=-1):(o[n]=0,o[n+1]=0,o[n+2]=0,o[n+3]=0)}f[e]=n}return f[e]}(e-16+4)}let r=l().createBufferSource();r.buffer=n,r.loop=!0;return 4==e||16<=e&&e<=18?r.playbackRate.value=t/(l().sampleRate/4):5!=e&&(r.playbackRate.value=t/(l().sampleRate/1024)),r}const y=[];class k{mute(){this.gain?d(this.gain,this.generator):this.generator&&(this.generator.stop(),this.generator.disconnect()),this.gain=null,this.generator=null}remove(){const e=y.indexOf(this);e>=0&&y.splice(e,1),this.mute()}}let b=1;function v(){for(b++;y.length;)y[0].remove()}function T(t){const o=b;let r=l(),i=0,s=new k,c=-1,u=-1,d=0;y.length>5&&y[0].remove(),y.push(s);const p=(e,t)=>e/1024/4*(t?.5:1),g=()=>{s.mute(),d=0,c=-1,u=-1},h=()=>{if(i>=t.data.length||!t.data[i])return e.U.delay(d).then(g);const f=t.data[i],_=e.BufferMethods.getNumber(t,e.BufferMethods.NumberFormat.UInt16LE,i+2),y=e.BufferMethods.getNumber(t,e.BufferMethods.NumberFormat.UInt16LE,i+4),k=e.BufferMethods.getNumber(t,e.BufferMethods.NumberFormat.UInt16LE,i+6),v=e.BufferMethods.getNumber(t,e.BufferMethods.NumberFormat.UInt16LE,i+8),T=e.BufferMethods.getNumber(t,e.BufferMethods.NumberFormat.UInt16LE,i+10),E=11<=f&&f<=15,S=4==f||16<=f&&f<=18,C=p(k,E),x=p(v,E);if(!r||o!=b)return e.U.delay(y);if(c!=f||u!=_||_!=T){if(s.generator)return e.U.delay(d).then((()=>(g(),h())));if(s.generator=a?null:m(f,_),!s.generator)return e.U.delay(y);if(c=f,u=_,s.gain=r.createGain(),s.gain.gain.value=0,s.gain.gain.setTargetAtTime(C,n.currentTime,.015),T!=_)if(null!=s.generator.frequency){s.generator.frequency.linearRampToValueAtTime(T,r.currentTime+(d+y)/1e3)}else if(null!=s.generator.playbackRate){const e=S?4:1024;s.generator.playbackRate.linearRampToValueAtTime(T/(l().sampleRate/e),r.currentTime+(d+y)/1e3)}s.generator.connect(s.gain),s.gain.connect(r.destination),s.generator.start()}i+=12,s.gain.gain.setValueAtTime(C,r.currentTime+d/1e3),d+=y;const B=0!==x&&y>50?(d-50)/1e3:(d-10)/1e3;return s.gain.gain.linearRampToValueAtTime(x,r.currentTime+B),h()};return h().then((()=>s.remove()))}function E(e,t){if(e<0)return;s=e;let n=l();if(n){t=Math.max(0,Math.min(1,t));try{o||(o=n.createOscillator(),r=n.createGain(),r.gain.value=0,o.type="triangle",o.connect(r),r.connect(n.destination),o.start(0)),S(t)}catch(e){return o=void 0,void(r=void 0)}o.frequency.value=e,S(t)}}function S(e){(null==r?void 0:r.gain)&&r.gain.setTargetAtTime(a?0:e,n.currentTime,.015)}t.muteAllChannels=v,t.queuePlayInstructions=function(t,n){const o=b;e.U.delay(t).then((()=>o!=b?Promise.resolve():T(n)))},t.playInstructionsAsync=T,t.tone=E,t.setCurrentToneGain=S,t.playBufferAsync=function(e){return e?new Promise((t=>{function n(){t&&t(),t=void 0}const o="data:audio/wav;base64,"+window.btoa(function(e){let t=e.length,n="";for(let o=0;o<t;++o)n+=String.fromCharCode(e[o]);return n}(e.data));i=new Audio(o),a&&(i.volume=0),i.onended=()=>n(),i.onpause=()=>n(),i.onerror=()=>n(),i.play()})):Promise.resolve()};t.playPCMBufferStreamAsync=function(e,t,n=.3,o){return new Promise((r=>{let i=[],s=l().currentTime,c=!1;function u(){const t=o&&o();for(;!c&&i.length<3&&!t;){const t=e();if(!t||!t.length){c=!0;break}d(t)}c&&0===i.length&&(p.remove(),r&&r(),r=void 0)}function d(e){const n=l().createBuffer(1,e.length,t);if(n.copyToChannel)n.copyToChannel(e,0);else{const t=n.getChannelData(0);for(let n=0;n<e.length;n++)t[n]=e[n]}const o=l().createBufferSource();i.push(o),o.connect(p.gain),o.buffer=n,o.addEventListener("ended",(()=>{i.shift().disconnect(),u()})),o.start(s),s+=n.duration}const p=new k;p.gain=l().createGain(),p.gain.gain.value=0,a||p.gain.gain.setValueAtTime(n,l().currentTime),p.gain.connect(l().destination),y.length>5&&y[0].remove(),y.push(p),u()}))},t.sendMidiMessage=function(e){const t=e.data;if(!t.length)return;const n=t[0]>>4,o=15&t[0],r=t[1]||0,i=(s=r,440*Math.pow(2,(s-69)/12));var s;const a=t[2]||0;8==n||9==n&&0==a?c():9==n&&(E(i,1),9==o&&setTimeout((()=>c()),500))}}(t=e.AudioContextManager||(e.AudioContextManager={})),e.isTouchEnabled=n,e.hasPointerEvents=o,e.pointerEvents=o()?{up:"pointerup",down:["pointerdown"],move:"pointermove",enter:"pointerenter",leave:"pointerleave"}:n()?{up:"mouseup",down:["mousedown","touchstart"],move:"touchmove",enter:"touchenter",leave:"touchend"}:{up:"mouseup",down:["mousedown"],move:"mousemove",enter:"mouseenter",leave:"mouseleave"}}(pxsim||(pxsim={})),function(e){!function(t){function n(e,t){return n=>n*(t/e)}function o(e,t){let n=e[0]-t[0],o=e[1]-t[1];return n*n+o*o}t.translateEl=function(t,n){e.svg.hydrate(t,{transform:`translate(${n[0]} ${n[1]})`})},t.composeSVG=function(t){let[n,o]=[t.el1,t.el2];e.U.assert(0==n.x&&0==n.y&&0==o.x&&0==o.y,"el1 and el2 x,y offsets not supported");let r=(t,n,o)=>e.svg.hydrate(t,{x:n,y:o}),i=(t,n,o)=>e.svg.hydrate(t,{width:`${n}px`,height:`${o}px`}),s=t.scaleUnit2,a=t.scaleUnit2/t.scaleUnit1,l=n.w*a,c=n.h*a;i(n.el,l,c);let u=1*o.w,d=1*o.h;i(o.el,u,d);let[p,g,h,f]=t.margin,_=t.middleMargin,m=Math.max(l,u),y=g+(m-l)/2,k=p;r(n.el,y,k);let b=g+(m-u)/2,v=k+c+_;r(o.el,b,v);let T=[k,k+c,v,v+d],E=g+m+f,S=p+c+_+d+h,C=e.svg.elt("svg",{version:"1.0",viewBox:`0 0 ${E} ${S}`,class:"sim-bb"});((t,n,o)=>{n&&e.svg.hydrate(t,{width:n}),o&&e.svg.hydrate(t,{height:o})})(C,t.maxWidth,t.maxHeight),r(C,0,0);let x=e.svg.child(C,"g");return C.appendChild(n.el),C.appendChild(o.el),{under:x,over:e.svg.child(C,"g"),host:C,edges:T,scaleUnit:s,toHostCoord1:e=>{let[t,n]=e;return[t*a+y,n*a+k]},toHostCoord2:e=>{let[t,n]=e;return[1*t+b,1*n+v]}}},t.mkScaleFn=n,t.mkImageSVG=function(t){let o=n(t.imageUnitDist,t.targetUnitDist),r=o(t.width),i=o(t.height),s=e.svg.elt("image",{width:r,height:i});return s.setAttributeNS("http://www.w3.org/1999/xlink","href",`${t.image}`),{el:s,w:r,h:i,x:0,y:0}},t.findDistSqrd=o,t.findClosestCoordIdx=function(e,t){return t.map((t=>o(e,t))).reduce(((e,t,n,o)=>t<o[e]?n:e),0)},t.mkTxt=function(t,n,o,r,i,s,a){let l=e.svg.elt("text");a=a||.3;const c=(s=s||-.33333)*o*i.length,u=a*o;return e.svg.hydrate(l,{style:`font-size:${o}px;`,transform:`translate(${t} ${n}) rotate(${r}) translate(${c} ${u})`}),e.U.addClass(l,"noselect"),l.textContent=i,l},t.GPIO_WIRE_COLORS=["pink","orange","yellow","green","purple"],t.WIRE_COLOR_MAP={black:"#514f4d",white:"#fcfdfc",gray:"#acabab",purple:"#a772a1",blue:"#01a6e8",green:"#3cce73",yellow:"#ece600",orange:"#fdb262",red:"#f44f43",brown:"#c89764",pink:"#ff80fa"},t.mapWireColor=function(e){return t.WIRE_COLOR_MAP[e]||e},t.PIN_DIST=15,t.rgbToHsl=function(e){let t,n,o,[r,i,s]=e,[a,l,c]=[r/255,i/255,s/255],u=Math.min(a,l,c),d=Math.max(a,l,c),p=d-u,g=d+u;return o=g/2*100,0===p?n=t=0:(d===a?t=(l-c)/p%6*60:d===l?t=60*((c-a)/p+2):d===c&&(t=60*((a-l)/p+4)),n=o>50?p/(2-g)*100:p/g*100),[Math.floor(t),Math.floor(n),Math.floor(o)]}}(e.visuals||(e.visuals={}))}(pxsim||(pxsim={})),function(e){var t;!function(n){function o(e,n,o){let r={class:e,d:n};o&&(r.title=o);let i=t.elt("path");return t.hydrate(i,r),i}function r(e,n=!1){let o=t.elt("linearGradient");t.hydrate(o,{id:e,x1:"0%",y1:"0%",x2:n?"100%":"0%",y2:n?"0%":"100%"});t.child(o,"stop",{offset:"0%"}),t.child(o,"stop",{offset:"100%"}),t.child(o,"stop",{offset:"100%"}),t.child(o,"stop",{offset:"100%"});return o}function i(e){let n=t.elt("title");return n.textContent=e,n}n.parseString=function(e){return(new DOMParser).parseFromString(e,"image/svg+xml").getElementsByTagName("svg").item(0)},n.toDataUri=function(e){return"data:image/svg+xml,"+encodeURI(e)},n.cursorPoint=function(e,t,n){return e.x=null!=n.clientX?n.clientX:n.pageX,e.y=null!=n.clientY?n.clientY:n.pageY,e.matrixTransform(t.getScreenCTM().inverse())},n.rotateElement=function(e,t,n,o){e.setAttribute("transform",`translate(${t},${n}) rotate(${o+90}) translate(${-t},${-n})`)},n.hydrate=function(e,n){for(let o in n)"title"==o?t.title(e,n[o]):e.setAttributeNS(null,o,n[o])},n.elt=function(e,n){let o=document.createElementNS("http://www.w3.org/2000/svg",e);return n&&t.hydrate(o,n),o},n.child=function(e,n,o){let r=t.elt(n,o);return e.appendChild(r),r},n.mkPath=o,n.path=function(e,t,n,r){let i=o(t,n,r);return e.appendChild(i),i},n.fill=function(e,t){e.style.fill=t},n.filter=function(e,t){e.style.filter=t},n.fills=function(e,t){e.forEach((e=>e.style.fill=t))},n.isTouchEnabled=function(){return"undefined"!=typeof window&&("ontouchstart"in window||navigator.maxTouchPoints>0)},n.onClick=function(t,n){let o=!1;e.pointerEvents.down.forEach((e=>t.addEventListener(e,(e=>(o=!0,!0)),!1))),t.addEventListener(e.pointerEvents.up,(e=>!o||(o=!1,n(e),e.preventDefault(),!1)),!1)},n.buttonEvents=function(t,n,o,r,i){let s=!1;e.pointerEvents.down.forEach((e=>t.addEventListener(e,(e=>(s=!0,o&&o(e),!0)),!1))),t.addEventListener(e.pointerEvents.move,(e=>!s||(n&&n(e),e.preventDefault(),!1)),!1),t.addEventListener(e.pointerEvents.up,(e=>{s=!1,r&&r(e)}),!1),t.addEventListener(e.pointerEvents.leave,(e=>{s=!1,r&&r(e)}),!1),t.addEventListener("keydown",(e=>{s=!1,i&&i(e)}))},n.mkLinearGradient=r,n.linearGradient=function(e,t,n=!1){let o=r(t,n);return e.appendChild(o),o},n.setGradientColors=function(e,t,n){e&&(e.childNodes[0].style.stopColor=t,e.childNodes[1].style.stopColor=t,e.childNodes[2].style.stopColor=n,e.childNodes[3].style.stopColor=n)},n.setGradientValue=function(e,t){e.childNodes[1].getAttribute("offset")!=t&&(e.childNodes[1].setAttribute("offset",t),e.childNodes[2].setAttribute("offset",t))},n.animate=function(t,n){e.U.addClass(t,n);let o=t.parentElement;o&&(o.removeChild(t),o.appendChild(t))},n.mkTitle=i,n.title=function(e,t){let n=i(t);return e.appendChild(n),n},n.toHtmlColor=function(e){return`rgba(${e>>16&255}, ${e>>8&255}, ${255&e}, ${e>>24&1})`}}(t=e.svg||(e.svg={}))}(pxsim||(pxsim={})),function(e){class t{constructor(e){this.id=e}}e.Button=t;e.ButtonPairState=class{constructor(e){this.props=e,this.usesButtonAB=!1,this.aBtn=new t(this.props.ID_BUTTON_A),this.bBtn=new t(this.props.ID_BUTTON_B),this.abBtn=new t(this.props.ID_BUTTON_AB),this.abBtn.virtual=!0}}}(pxsim||(pxsim={})),function(e){e.CompassState=class{constructor(){this.usesHeading=!1,this.heading=90}}}(pxsim||(pxsim={})),function(e){e.FileSystemState=class{constructor(){this.files={}}append(e,t){this.files[e]=(this.files[e]||"")+t}remove(e){delete this.files[e]}}}(pxsim||(pxsim={})),function(e){e.LightSensorState=class{constructor(){this.usesLightLevel=!1,this.lightLevel=128}}}(pxsim||(pxsim={})),function(e){!function(t){t.mkBoardView=e=>{const n=e.visual;return new t.GenericBoardSvg({visualDef:n,boardDef:e.boardDef,wireframe:e.wireframe})};t.BoardHost=class{constructor(n,o){this.parts=[],this.boardView=n,this.opts=o,o.boardDef.pinStyles||(o.boardDef.pinStyles={}),this.state=o.state;let r=o.partsList,i=0<r.length||o.forceBreadboardLayout;if(i){this.breadboard=new t.Breadboard({wireframe:o.wireframe});const n=o.boardDef.marginWhenBreadboarding||[0,0,40,0],s=t.composeSVG({el1:this.boardView.getView(),scaleUnit1:this.boardView.getPinDist(),el2:this.breadboard.getSVGAndSize(),scaleUnit2:this.breadboard.getPinDist(),margin:[n[0],n[1],20,n[3]],middleMargin:n[2],maxWidth:o.maxWidth,maxHeight:o.maxHeight}),a=s.under,l=s.over;this.view=s.host;const c=s.edges;this.fromMBCoord=s.toHostCoord1,this.fromBBCoord=s.toHostCoord2,this.partGroup=l,this.partOverGroup=e.svg.child(this.view,"g"),this.style=e.svg.child(this.view,"style",{}),this.defs=e.svg.child(this.view,"defs",{}),this.wireFactory=new t.WireFactory(a,l,c,this.style,this.getLocCoord.bind(this),this.getPinStyle.bind(this));const u=e.allocateDefinitions({boardDef:o.boardDef,partDefs:o.partDefs,fnArgs:o.fnArgs,getBBCoord:this.breadboard.getCoord.bind(this.breadboard),partsList:r});u.partsAndWires.length||o.forceBreadboardLayout?(this.addAll(u),u.requiresBreadboard||o.forceBreadboardRender?u.hideBreadboard&&this.breadboard&&this.breadboard.hide():i=!1):i=!1}if(!i){delete this.breadboard,delete this.wireFactory,delete this.partOverGroup,delete this.partGroup,delete this.style,delete this.defs,delete this.fromBBCoord,delete this.fromMBCoord;const t=this.boardView.getView().el;this.view=t,this.partGroup=e.svg.child(this.view,"g"),this.partOverGroup=e.svg.child(this.view,"g"),o.maxWidth&&e.svg.hydrate(this.view,{width:o.maxWidth}),o.maxHeight&&e.svg.hydrate(this.view,{height:o.maxHeight})}this.state.updateSubscribers.push((()=>this.updateState()))}highlightBoardPin(e){this.boardView.highlightPin(e)}highlightBreadboardPin(e){this.breadboard.highlightLoc(e)}highlightWire(t){t.wires.forEach((t=>{e.U.addClass(t,"highlight"),t.style.visibility="visible"})),e.U.addClass(t.endG,"highlight")}getView(){return this.view}screenshotAsync(e){const t=this.view.cloneNode(!0);t.setAttribute("width",this.view.width.baseVal.value+""),t.setAttribute("height",this.view.height.baseVal.value+"");const n=(new XMLSerializer).serializeToString(t),o="data:image/svg+xml,"+encodeURIComponent(n.replace(/\s+/g," ").replace(/"/g,"'"));return new Promise(((t,n)=>{const r=document.createElement("img");r.onload=()=>{const n=document.createElement("canvas");n.width=r.width,n.height=r.height,e>0?(n.width=e,n.height=r.height*e/r.width|0):n.width<200?(n.width*=2,n.height*=2):n.width>480&&(n.width/=2,n.height/=2);const o=n.getContext("2d");o.drawImage(r,0,0,n.width,n.height),t(o.getImageData(0,0,n.width,n.height))},r.onerror=e=>{console.log(e),t(void 0)},r.src=o}))}updateState(){this.parts.forEach((e=>e.updateState()))}getBBCoord(e){let t=this.breadboard.getCoord(e);return this.fromBBCoord(t)}getPinCoord(e){let t=this.boardView.getCoord(e);if(t)return this.fromMBCoord(t);console.error(`Unable to find coord for pin: ${e}`)}getLocCoord(e){let t;if("breadboard"===e.type){let n=e;t=this.getBBCoord(n)}else{let n=e.pin;t=this.getPinCoord(n)}return t||console.debug("Unknown location: "+name),t}getPinStyle(e){return"breadboard"==e.type?"female":this.opts.boardDef.pinStyles[e.pin]||"female"}addPart(n){let o=null;if(n.simulationBehavior){let e=n.simulationBehavior,t=this.state.builtinVisuals[e],r=this.state.builtinParts[e];o=t(),o.init(this.state.bus,r,this.view,n.params)}else{let e=n.visual;o=new t.GenericPart(e)}this.parts.push(o),this.partGroup.appendChild(o.element),o.overElement&&this.partOverGroup.appendChild(o.overElement),o.defs&&o.defs.forEach((e=>this.defs.appendChild(e))),this.style.textContent+=o.style||"";let r=n.startColumnIdx,i=n.startRowIdx,s={type:"breadboard",row:t.getRowName(i),col:t.getColumnName(r),xOffset:n.bbFit.xOffset/n.visual.pinDistance,yOffset:n.bbFit.yOffset/n.visual.pinDistance},a=this.getBBCoord(s);o.moveToCoord(a);let l=`sim-${n.name}-cmp`;return e.U.addClass(o.element,l),e.U.addClass(o.element,"sim-cmp"),o.updateTheme(),o.updateState(),o}addWire(e){return this.wireFactory.addWire(e.start,e.end,e.color)}addAll(e){e.partsAndWires.forEach((t=>{const n=t.wires,o=n&&n.every((e=>this.wireFactory.checkWire(e.start,e.end)));o&&n.forEach((t=>e.wires.push(this.addWire(t))));let r=t.part;!r||n&&!o||e.parts.push(this.addPart(r))})),e.requiresBreadboard=!!e.wires.length||!!e.parts.length}}}(e.visuals||(e.visuals={}))}(pxsim||(pxsim={})),function(e){!function(t){const n=15,o="#DD4BA0",r=`\n /* bread board */\n .sim-bb-background {\n fill:#E0E0E0;\n }\n .sim-bb-pin {\n fill:#999;\n }\n .sim-bb-pin-hover {\n visibility: hidden;\n pointer-events: all;\n stroke-width: 7.5px;\n stroke: transparent;\n fill: #777;\n }\n .sim-bb-pin-hover:hover {\n visibility: visible;\n fill:#444;\n }\n .sim-bb-group-wire {\n stroke: #999;\n stroke-width: 3.75px;\n visibility: hidden;\n }\n .sim-bb-pin-group {\n pointer-events: all;\n }\n .sim-bb-label,\n .sim-bb-label-hover {\n font-family:"Lucida Console", Monaco, monospace;\n fill:#555;\n pointer-events: all;\n stroke-width: 0;\n cursor: default;\n }\n .sim-bb-label-hover {\n visibility: hidden;\n fill:#000;\n font-weight: bold;\n }\n .sim-bb-bar {\n stroke-width: 0;\n }\n .sim-bb-blue {\n fill:#1AA5D7;\n stroke:#1AA5D7\n }\n .sim-bb-red {\n fill:${o};\n stroke:${o};\n }\n .sim-bb-pin-group:hover .sim-bb-pin-hover,\n .sim-bb-pin-group:hover .sim-bb-group-wire,\n .sim-bb-pin-group:hover .sim-bb-label-hover {\n visibility: visible;\n }\n .sim-bb-pin-group:hover .sim-bb-label {\n visibility: hidden;\n }\n /* outline mode */\n .sim-bb-outline .sim-bb-background {\n stroke-width: ${n/7}px;\n fill: #FFF;\n stroke: #000;\n }\n .sim-bb-outline .sim-bb-mid-channel {\n fill: #FFF;\n stroke: #888;\n stroke-width: 2px;\n }\n /* grayed out */\n .grayed .sim-bb-background {\n stroke-width: 3px;\n }\n .grayed .sim-bb-red,\n .grayed .sim-bb-blue {\n fill: #BBB;\n }\n .grayed .sim-bb-bar {\n fill: #FFF;\n }\n .grayed .sim-bb-pin {\n fill: #000;\n stroke: #FFF;\n stroke-width: 3px;\n }\n .grayed .sim-bb-label {\n fill: none;\n }\n .grayed .sim-bb-background {\n stroke-width: 7.5px;\n stroke: #555;\n }\n .grayed .sim-bb-group-wire {\n stroke: #DDD;\n }\n .grayed .sim-bb-channel {\n visibility: hidden;\n }\n /* highlighted */\n .sim-bb-label.highlight {\n visibility: hidden;\n }\n .sim-bb-label-hover.highlight {\n visibility: visible;\n }\n .sim-bb-blue.highlight {\n fill:#1AA5D7;\n }\n .sim-bb-red.highlight {\n fill:${o};\n }\n .sim-bb-bar.highlight {\n stroke-width: 0px;\n }\n `;t.BREADBOARD_MID_ROWS=10,t.BREADBOARD_MID_COLS=30;const i=[4,4],s=t.BREADBOARD_MID_ROWS+i.length,a=25,l=[4,9,14,19],c=a+l.length,u=n*(t.BREADBOARD_MID_COLS+3),d=n*(s+4+5.5),p=2/3,g=d*p,h=.16666666666666669*d,f=(t.BREADBOARD_MID_COLS-1)*n,_=(u-f)/2,m=h+(g-(s-1)*n)/2,y=(c-1)*n,k=(u-y)/2,b=(h-15)/2,v=k,T=b+h+g,E=25.5,S=12,C=1.05,x=-90,B="abcdefghij".split("").reverse();function A(e){return`${e+1}`}function I(e){return B[e]}function D(t){let n=t.xOffset||0,o=t.yOffset||0,r=[],i=e.svg.elt("g"),s=t.colStartIdx||0,a=t.rowStartIdx||0,l=e=>e?e.slice(0,e.length):[],c=(e,t)=>{let n,o=0;for(;0<=(n=e.indexOf(t));)e.splice(n,1),o+=1;return o},u=0,d=l(t.rowIdxsWithGap);for(let p=0;p<t.rowCount;p++){let g=0,h=l(t.colIdxsWithGap),f=o+p*t.pinDist+u*t.pinDist,_=p+a;for(let o=0;o<t.colCount;o++){let a=n+o*t.pinDist+g*t.pinDist,l=o+s;const u=t=>(e.svg.hydrate(t.el,"circle"==t.el.tagName?{cx:a,cy:f}:{x:a-.5*t.w,y:f-.5*t.h}),i.appendChild(t.el),t.el);let d=u(t.mkPin()),p=u(t.mkHoverPin()),m=t.getRowName(_),y=t.getColName(l),k=t.getGroupName?t.getGroupName(_,l):null,b={el:d,hoverEl:p,cx:a,cy:f,row:m,col:y,group:k};r.push(b),g+=c(h,l)}u+=c(d,_)}return{g:i,allPins:r}}function N(){let t=e.svg.elt("rect");return e.svg.hydrate(t,{class:"sim-bb-pin",rx:2,ry:2,width:6,height:6}),{el:t,w:6,h:6,x:0,y:0}}function w(){let t=e.svg.elt("rect"),n=6*1.3;return e.svg.hydrate(t,{class:"sim-bb-pin-hover",rx:2,ry:2,width:n,height:n}),{el:t,w:n,h:n,x:0,y:0}}function R(n,o,r,i,s,a,l){let c=t.mkTxt(n,o,r,i,s);e.U.addClass(c,"sim-bb-label"),l&&l.forEach((t=>e.U.addClass(c,t)));let u=t.mkTxt(n,o,1.3*r,i,s);return e.U.addClass(u,"sim-bb-label-hover"),l&&l.forEach((t=>e.U.addClass(u,t))),{el:c,hoverEl:u,txt:s,group:a}}t.getColumnName=A,t.getRowName=I,t.mkGrid=D;t.Breadboard=class{constructor(t){this.allPins=[],this.allLabels=[],this.allPowerBars=[],this.rowColToPin={},this.rowColToLbls={},this.buildDom(),t.wireframe&&e.U.addClass(this.bb,"sim-bb-outline")}hide(){this.bb.style.display="none"}updateLocation(t,n){e.svg.hydrate(this.bb,{x:`${t}px`,y:`${n}px`})}getPin(e,t){let n=this.rowColToPin[e];if(!n)return null;let o=n[t];return o||null}getCoord(e){let{row:t,col:o,xOffset:r,yOffset:i}=e,s=this.getPin(t,o);if(!s)return null;let a=(r||0)*n,l=(i||0)*n;return[s.cx+a,s.cy+l]}getPinDist(){return n}buildDom(){this.bb=e.svg.elt("svg",{version:"1.0",viewBox:`0 0 ${u} ${d}`,class:"sim-bb",width:u+"px",height:d+"px"}),this.styleEl=e.svg.child(this.bb,"style",{}),this.styleEl.textContent+=r,this.defs=e.svg.child(this.bb,"defs",{}),e.svg.child(this.bb,"rect",{class:"sim-bb-background",width:u,height:d,rx:4.5,ry:4.5});let o="sim-bb-channel-grad",s=e.svg.elt("linearGradient");e.svg.hydrate(s,{id:o,x1:"0%",y1:"0%",x2:"0%",y2:"100%"}),this.defs.appendChild(s);e.svg.child(s,"stop",{offset:"0%",style:"stop-color: #AAA;"}),e.svg.child(s,"stop",{offset:"20%",style:"stop-color: #CCC;"}),e.svg.child(s,"stop",{offset:"80%",style:"stop-color: #CCC;"}),e.svg.child(s,"stop",{offset:"100%",style:"stop-color: #AAA;"});const c=(t,n,r)=>{let i=e.svg.child(this.bb,"rect",{class:`sim-bb-channel ${r||""}`,y:t-n/2,width:u,height:n});return i.setAttribute("fill",`url(#${o})`),i};c(h+g/2,15,"sim-bb-mid-channel"),c(h,.75,"sim-bb-sml-channel"),c(h+g,.75,"sim-bb-sml-channel");const p=(e,n)=>`${(e=>e<t.BREADBOARD_MID_ROWS/2?"b":"t")(e)}${A(n)}`,f=e=>0===e?"-":"+",B=(e,t)=>{let n=(e=>e<25?"b":"t")(t);return`${f(e)}${n}`};let O=D({xOffset:_,yOffset:m,rowCount:t.BREADBOARD_MID_ROWS,colCount:t.BREADBOARD_MID_COLS,pinDist:n,mkPin:N,mkHoverPin:w,getRowName:I,getColName:A,getGroupName:p,rowIdxsWithGap:i});O.g;this.allPins=this.allPins.concat(O.allPins);let P=D({xOffset:v,yOffset:T,rowCount:2,colCount:a,pinDist:n,mkPin:N,mkHoverPin:w,getRowName:f,getColName:A,getGroupName:B,colIdxsWithGap:l});P.g;this.allPins=this.allPins.concat(P.allPins);let L=D({xOffset:k,yOffset:b,rowCount:2,colCount:a,colStartIdx:a,pinDist:n,mkPin:N,mkHoverPin:w,getRowName:f,getColName:A,getGroupName:B,colIdxsWithGap:l.map((e=>e+a))});L.g;this.allPins=this.allPins.concat(L.allPins),this.allPins.forEach((t=>{let{el:n,row:o,col:r,hoverEl:i}=t,s=`(${o},${r})`;e.svg.hydrate(n,{title:s}),e.svg.hydrate(i,{title:s})})),this.allPins.forEach((e=>{let t=this.rowColToPin[e.row];t||(t=this.rowColToPin[e.row]={}),t[e.col]=e}));const M=(e,t,n,o,r,i)=>{let s=this.getCoord({type:"breadboard",row:e,col:t}),[a,l]=s;return R(a+n,l+o,10.5,-90,r,i)};for(let e=0;e<t.BREADBOARD_MID_COLS;e++){let n=A(e),o=0,r=M(I(o),n,0,-15,n,p(o,e));this.allLabels.push(r);let i=t.BREADBOARD_MID_ROWS-1,s=M(I(i),n,0,15,n,p(i,e));this.allLabels.push(s)}for(let e=0;e<t.BREADBOARD_MID_ROWS;e++){let n=I(e),o=M(n,A(0),-15,0,n);this.allLabels.push(o);let r=M(n,A(t.BREADBOARD_MID_COLS-1),15,0,n);this.allLabels.push(r)}let F=[R(13.05,h+g+S,30,x,"-",B(0,0),["sim-bb-blue"]),R(12,h+g+h-S,E,x,"+",B(1,0),["sim-bb-red"]),R(u-S+C,h+g+S,30,x,"-",B(0,24),["sim-bb-blue"]),R(u-S,h+g+h-S,E,x,"+",B(1,24),["sim-bb-red"])];this.allLabels=this.allLabels.concat(F);let U=[R(13.05,12,30,x,"-",B(0,a),["sim-bb-blue"]),R(12,h-S,E,x,"+",B(1,a),["sim-bb-red"]),R(u-S+C,12,30,x,"-",B(0,49),["sim-bb-blue"]),R(u-S,h-S,E,x,"+",B(1,49),["sim-bb-red"])];this.allLabels=this.allLabels.concat(U);let H={};this.allLabels.forEach((e=>{let{el:t,txt:n}=e;(H[n]=H[n]||[]).push(e)}));this.allPins.forEach((e=>{let{row:t,col:n,group:o}=e,r=this.rowColToLbls[t]||(this.rowColToLbls[t]={}),i=r[n]||(r[n]=[]);if((e=>"-"===e.row||"+"===e.row)(e)){Number(n)<=a?F.filter((t=>t.group==e.group)).forEach((e=>i.push(e))):U.filter((t=>t.group==e.group)).forEach((e=>i.push(e)))}else{H[t].forEach((e=>i.push(e))),H[n].forEach((e=>i.push(e)))}}));const V=y+22.5,G=(V-y)/2,W=(t,n,o,r)=>{let i=e.svg.elt("rect");return e.svg.hydrate(i,{class:`sim-bb-bar ${r}`,x:t,y:n-1.5,width:V,height:3}),{el:i,group:o}};let K=[W(v-G,T-9,B(0,49),"sim-bb-blue"),W(v-G,T+n+9,B(1,49),"sim-bb-red"),W(k-G,b-9,B(0,0),"sim-bb-blue"),W(k-G,b+n+9,B(1,0),"sim-bb-red")];this.allPowerBars=this.allPowerBars.concat(K),this.allPowerBars.forEach((e=>this.bb.appendChild(e.el)));let j=this.allPins.map((e=>e.group)).filter(((e,t,n)=>n.indexOf(e)==t)),z=j.map((t=>e.svg.elt("g")));z.forEach((t=>e.U.addClass(t,"sim-bb-pin-group"))),z.forEach(((t,n)=>e.U.addClass(t,`group-${j[n]}`)));let $={};j.forEach(((e,t)=>$[e]=z[t]));let X={};this.allPins.forEach(((e,t)=>{let n=e.group;(X[n]||(X[n]=[])).push(e)})),j.forEach((t=>{let n=X[t],[o,r]=[n.map((e=>e.cx)),n.map((e=>e.cy))],i=e=>e.reduce(((e,t)=>e<t?e:t)),s=e=>e.reduce(((e,t)=>e>t?e:t)),[a,l,c,u]=[i(o),s(o),i(r),s(r)],d=e.svg.elt("rect"),p=Math.max(l-a,1e-4),g=Math.max(u-c,1e-4);e.svg.hydrate(d,{x:a,y:c,width:p,height:g}),e.U.addClass(d,"sim-bb-group-wire"),$[t].appendChild(d)})),this.allPins.forEach((e=>{let t=$[e.group];t.appendChild(e.el),t.appendChild(e.hoverEl)}));let Y=e.svg.elt("g");e.svg.hydrate(Y,{class:"sim-bb-group-misc"}),z.push(Y),this.allLabels.forEach((e=>{if(e.group){let t=$[e.group];t.appendChild(e.el),t.appendChild(e.hoverEl)}else Y.appendChild(e.el),Y.appendChild(e.hoverEl)})),z.forEach((e=>this.bb.appendChild(e)))}getSVGAndSize(){return{el:this.bb,y:0,x:0,w:u,h:d}}highlightLoc(t){let{row:n,col:o}=t,r=this.rowColToPin[n][o],{cx:i,cy:s}=r;this.rowColToLbls[n][o].forEach((t=>{e.U.addClass(t.el,"highlight"),e.U.addClass(t.hoverEl,"highlight")}))}}}(e.visuals||(e.visuals={}))}(pxsim||(pxsim={})),function(e){!function(t){t.BOARD_SYTLE=`\n .noselect {\n -webkit-touch-callout: none; /* iOS Safari */\n -webkit-user-select: none; /* Chrome/Safari/Opera */\n -khtml-user-select: none; /* Konqueror */\n -moz-user-select: none; /* Firefox */\n -ms-user-select: none; /* Internet Explorer/Microsoft Edge */\n user-select: none; /* Non-prefixed version, currently\n not supported by any browser */\n }\n\n .sim-board-pin {\n fill:#999;\n stroke:#000;\n stroke-width:${t.PIN_DIST/3}px;\n }\n .sim-board-pin-lbl {\n fill: #333;\n }\n .gray-cover {\n fill:#FFF;\n opacity: 0.3;\n stroke-width:0;\n visibility: hidden;\n }\n .sim-board-pin-hover {\n visibility: hidden;\n pointer-events: all;\n stroke-width:${t.PIN_DIST/6}px;\n }\n .sim-board-pin-hover:hover {\n visibility: visible;\n }\n .sim-board-pin-lbl {\n visibility: hidden;\n }\n .sim-board-outline .sim-board-pin-lbl {\n visibility: visible;\n }\n .sim-board-pin-lbl {\n fill: #555;\n }\n .sim-board-pin-lbl-hover {\n fill: red;\n }\n .sim-board-outline .sim-board-pin-lbl-hover {\n fill: black;\n }\n .sim-board-pin-lbl,\n .sim-board-pin-lbl-hover {\n font-family:"Lucida Console", Monaco, monospace;\n pointer-events: all;\n stroke-width: 0;\n }\n .sim-board-pin-lbl-hover {\n visibility: hidden;\n }\n .sim-board-outline .sim-board-pin-hover:hover + .sim-board-pin-lbl,\n .sim-board-pin-lbl.highlight {\n visibility: hidden;\n }\n .sim-board-outline .sim-board-pin-hover:hover + * + .sim-board-pin-lbl-hover,\n .sim-board-pin-lbl-hover.highlight {\n visibility: visible;\n }\n /* Graying out */\n .grayed .sim-board-pin-lbl:not(.highlight) {\n fill: #AAA;\n }\n .grayed .sim-board-pin:not(.highlight) {\n fill:#BBB;\n stroke:#777;\n }\n .grayed .gray-cover {\n visibility: inherit;\n }\n .grayed .sim-cmp:not(.notgrayed) {\n opacity: 0.3;\n }\n /* Highlighting */\n .sim-board-pin-lbl.highlight {\n fill: #000;\n font-weight: bold;\n }\n .sim-board-pin.highlight {\n fill:#999;\n stroke:#000;\n }\n `;const n=.7*t.PIN_DIST,o=1.5*n,r=.66666*t.PIN_DIST,i=.66666*t.PIN_DIST+t.PIN_DIST/3;let s=0;t.GenericBoardSvg=class{constructor(a){this.props=a,this.allPins=[],this.allLabels=[],this.pinNmToLbl={},this.pinNmToPin={},this.id=s++;let l=a.visualDef,c=a.wireframe&&l.outlineImage?l.outlineImage:l.image,u=t.mkImageSVG({image:c,width:l.width,height:l.height,imageUnitDist:l.pinDist,targetUnitDist:t.PIN_DIST}),d=t.mkScaleFn(l.pinDist,t.PIN_DIST);this.width=u.w,this.height=u.h;let p=u.el;this.element=e.svg.elt("svg"),e.svg.hydrate(this.element,{version:"1.0",viewBox:`0 0 ${this.width} ${this.height}`,class:`sim sim-board-id-${this.id}`,x:"0px",y:"0px"}),a.wireframe&&e.U.addClass(this.element,"sim-board-outline"),this.style=e.svg.child(this.element,"style",{}),this.style.textContent+=t.BOARD_SYTLE,this.defs=e.svg.child(this.element,"defs",{}),this.g=e.svg.elt("g"),this.element.appendChild(this.g),this.g.appendChild(p),this.background=p,e.svg.hydrate(p,{class:"sim-board"});const g=()=>{let t=e.svg.elt("circle"),n=r;return e.svg.hydrate(t,{class:"sim-board-pin",r:n/2}),{el:t,w:n,h:n,x:0,y:0}},h=()=>{let t=e.svg.elt("circle"),n=i;return e.svg.hydrate(t,{class:"sim-board-pin-hover",r:n/2}),{el:t,w:n,h:n,x:0,y:0}},f=()=>{let t=e.svg.elt("rect"),n=r;return e.svg.hydrate(t,{class:"sim-board-pin",width:n,height:n}),{el:t,w:n,h:n,x:0,y:0}},_=()=>{let t=e.svg.elt("rect"),n=i;return e.svg.hydrate(t,{class:"sim-board-pin-hover",width:n,height:n}),{el:t,w:n,h:n,x:0,y:0}};let m=l.pinBlocks.map(((n,o)=>{let r=d(n.x)+t.PIN_DIST/2,i=d(n.y)+t.PIN_DIST/2,s=n.labels.length,a=t.mkGrid({xOffset:r,yOffset:i,rowCount:1,colCount:s,pinDist:t.PIN_DIST,mkPin:l.useCrocClips?g:f,mkHoverPin:l.useCrocClips?h:_,getRowName:()=>`${o+1}`,getColName:e=>n.labels[e],getGroupName:()=>n.labels.join(" ")});a.allPins,a.g;return e.U.addClass(a.g,"sim-board-pin-group"),a})),y=[];m.forEach(((e,t)=>e.allPins.forEach(((e,n)=>{this.allPins.push(e),y.push(l.pinBlocks[t])})))),this.allPins.forEach((t=>{let n=t.col;e.svg.hydrate(t.el,{title:n}),e.svg.hydrate(t.hoverEl,{title:n})})),this.allPins.forEach((e=>{this.pinNmToPin[e.col]=e}));const k=(e,n,o,r,i)=>{let s,a;if("below"===i){a=e,s=n+12+.25*o*r.length}else{a=e,s=n-11-.32*o*r.length}return t.mkTxt(a,s,o,-90,r)};this.allLabels=this.allPins.map(((t,r)=>{let i=y[r];return((t,r,i,s)=>{let a=k(t,r,n,i,s);e.U.addClass(a,"sim-board-pin-lbl");let l=k(t,r,o,i,s);return e.U.addClass(l,"sim-board-pin-lbl-hover"),{el:a,hoverEl:l,txt:i}})(t.cx,t.cy,t.col,i.labelPosition||"above")})),this.allPins.forEach(((e,t)=>{let n=this.allLabels[t];this.pinNmToLbl[e.col]=n})),this.allPins.forEach(((e,t)=>{let n=this.allLabels[t];this.g.appendChild(e.el),this.g.appendChild(e.hoverEl),this.g.appendChild(n.el),this.g.appendChild(n.hoverEl)}))}findPin(e){let t=this.pinNmToPin[e];return!t&&this.props.boardDef.gpioPinMap&&(e=this.props.boardDef.gpioPinMap[e])&&(t=this.pinNmToPin[e]),t}findPinLabel(e){let t=this.pinNmToLbl[e];return!t&&this.props.boardDef.gpioPinMap&&(e=this.props.boardDef.gpioPinMap[e])&&(t=this.pinNmToLbl[e]),t}getCoord(e){let t=this.findPin(e);return t?[t.cx,t.cy]:null}mkGrayCover(t,n,o,r){let i=e.svg.elt("rect");return e.svg.hydrate(i,{x:t,y:n,width:o,height:r,class:"gray-cover"}),i}getView(){return{el:this.element,w:this.width,h:this.height,x:0,y:0}}getPinDist(){return t.PIN_DIST}highlightPin(t){let n=this.findPinLabel(t),o=this.findPin(t);n&&o&&(e.U.addClass(n.el,"highlight"),e.U.addClass(n.hoverEl,"highlight"),e.U.addClass(o.el,"highlight"),e.U.addClass(o.hoverEl,"highlight"))}}}(e.visuals||(e.visuals={}))}(pxsim||(pxsim={})),function(e){!function(t){function n(e){return t.mkImageSVG({image:e.image,width:e.width,height:e.height,imageUnitDist:e.pinDistance,targetUnitDist:t.PIN_DIST})}t.mkGenericPartSVG=n;t.GenericPart=class{constructor(t){this.style="",this.defs=[];let o=n(t).el;this.element=e.svg.elt("g"),this.element.appendChild(o)}moveToCoord(e){t.translateEl(this.element,e)}init(e,t,n){}updateState(){}updateTheme(){}}}(e.visuals||(e.visuals={}))}(pxsim||(pxsim={})),function(e){!function(t){const n=t.PIN_DIST/2.5,o=.7;function r(e){return e.replace(/\#/g,"-").replace(/\(/g,"-").replace(/\)/g,"-").replace(/\,/g,"-").replace(/\./g,"-").replace(/\s/g,"")}let i;function s(t,n,o,r){const i=e=>`${e[0]}, ${e[1]}`;let[s,a]=t,[l,c]=n,u=c-a,d=[s,a+u*o],p=[l,c-u*o],g=e.svg.mkPath("sim-bb-wire",`M${i(t)} C${i(d)} ${i(p)} ${i(n)}`);return e.U.addClass(g,`wire-stroke-${r}`),g}function a(t,n,o){const r=e=>`${e[0]}, ${e[1]}`;let i=e.svg.mkPath("sim-bb-wire",`M${r(t)} L${r(n)}`);return e.U.addClass(i,`wire-stroke-${o}`),i}function l(o,r){const i=t.PIN_DIST/4;let s=e.svg.elt("circle"),a=o[0],l=o[1],c=n/2+i/2;return e.svg.hydrate(s,{cx:a,cy:l,r:c,class:"sim-bb-wire-end"}),e.U.addClass(s,`wire-fill-${r}`),s.style["stroke-width"]=`${i}px`,s}function c(n,o,r){let i=.24*t.PIN_DIST,s=10*i,a=2*i,l=6*i,c=i;const u=t.PIN_DIST/4;let[d,p]=n,g=o?-1:1,h=e.svg.elt("g"),f=e.svg.elt("rect"),_=s,m=a,y=d-m/2,k=p-_/2;e.svg.hydrate(f,{x:y,y:k,width:m,height:_,rx:.5,ry:.5,class:"sim-bb-wire-end"}),f.style["stroke-width"]=`${u}px`;let b=e.svg.elt("rect"),v=l,T=c,E=d-T/2,S=p+g*(_/2+v/2)-v/2;return e.svg.hydrate(b,{x:E,y:S,width:T,height:v,class:"sim-bb-wire-bare-end"}),b.style.fill="#bbb",h.appendChild(b),h.appendChild(f),{el:h,x:y-u,y:Math.min(k,S),w:m+2*u,h:_+v}}function u(n,o,r){let i=.24*t.PIN_DIST;const s=4*i,a=10*i,l=3.5*i,c=3.5*i,u=t.PIN_DIST/4;let[d,p]=n,g=o?-1:1,h=e.svg.elt("g"),f=e.svg.elt("polygon"),_=a,m=s,y=d-m/2,k=p-_/2;const b=o?.15:.3,v=o?.7:1-.7,T=o?.3:.15;e.svg.hydrate(f,{points:((...e)=>e.map((e=>(e=>`${e[0]},${e[1]}`)(e))).join(" "))([y+m*b,k],[y+m*(1-b),k],[y+m,k+_*v],[y+m*(1-T),k+_],[y+m*T,k+_],[y,k+_*v])}),e.svg.hydrate(f,{rx:.5,ry:.5,class:"sim-bb-wire-end"}),f.style["stroke-width"]=`${u}px`;let E=e.svg.elt("rect"),S=l,C=c,x=d-C/2,B=p+g*(_/2+S/2)-S/2;return e.svg.hydrate(E,{x:x,y:B,width:C,height:S,class:"sim-bb-wire-bare-end"}),h.appendChild(E),h.appendChild(f),{el:h,x:y-u,y:Math.min(k,B),w:m+2*u,h:_+S}}t.WIRES_CSS=`\n .sim-bb-wire {\n fill:none;\n stroke-linecap: round;\n stroke-width:${n}px;\n pointer-events: none;\n }\n .sim-bb-wire-end {\n stroke:#333;\n fill:#333;\n }\n .sim-bb-wire-bare-end {\n fill: #ccc;\n }\n .sim-bb-wire-hover {\n stroke-width: ${n}px;\n visibility: hidden;\n stroke-dasharray: ${t.PIN_DIST/10},${t.PIN_DIST/1.5};\n /*stroke-opacity: 0.4;*/\n }\n .grayed .sim-bb-wire-ends-g:not(.highlight) .sim-bb-wire-end {\n stroke: #777;\n fill: #777;\n }\n .grayed .sim-bb-wire:not(.highlight) {\n stroke: #CCC;\n }\n .sim-bb-wire-ends-g:hover .sim-bb-wire-end {\n stroke: red;\n fill: red;\n }\n .sim-bb-wire-ends-g:hover .sim-bb-wire-bare-end {\n stroke: #FFF;\n fill: #FFF;\n }\n `,function(e){e[e.BBJumper=0]="BBJumper",e[e.OpenJumper=1]="OpenJumper",e[e.Croc=2]="Croc"}(i=t.WireEndStyle||(t.WireEndStyle={})),t.mkWirePart=function(n,o,r=!1){let i,s=e.svg.elt("g"),[a,l]=n,d=[a-15,l-50],p=[a+15,l+50];o=t.mapWireColor(o),i=r?u(d,!0,o):c(d,!0,o);let g=function(t,n,o){const r=e=>`${e[0]}, ${e[1]}`;let[i,s]=t,[a,l]=n,c=l-s,u=[i,s+.8*c],d=[a,l-.8*c],p=e.svg.mkPath("sim-bb-wire",`M${r(t)} C${r(u)} ${r(d)} ${r(n)}`);return p.style.stroke=o,{el:p,x:Math.min(i,a),y:Math.min(s,l),w:Math.abs(i-a),h:Math.abs(s-l)}}(d,p,o),h=c(p,!1,o);s.appendChild(g.el),s.appendChild(i.el),s.appendChild(h.el);let f=Math.min(i.x,h.x),_=Math.max(i.x+i.w,h.x+h.w),m=Math.min(i.y,h.y);return{el:s,x:f,y:m,w:_-f,h:Math.max(i.y+i.h,h.y+h.h)-m}};t.WireFactory=class{constructor(e,n,o,r,i,s){this.nextWireId=0,this.styleEl=r,this.styleEl.textContent+=t.WIRES_CSS,this.underboard=e,this.overboard=n,this.boardEdges=o,this.getLocCoord=i,this.getPinStyle=s}indexOfMin(e){let t=0,n=e[0];for(let o=1;o<e.length;o++)e[o]<n&&(n=e[o],t=o);return t}closestEdgeIdx(e){let t=this.boardEdges.map((t=>Math.abs(e[1]-t)));return this.indexOfMin(t)}closestEdge(e){return this.boardEdges[this.closestEdgeIdx(e)]}drawWire(n,i,c){let u=[],d=e.svg.child(this.overboard,"g",{class:"sim-bb-wire-group"});const p=e=>{const n=t.PIN_DIST/2;let o,r=this.closestEdge(e);return o=r-e[1]<0?r-n:r+n,[e[0],o]};let g=this.nextWireId++,h=r(c),f=l(n,h),_=l(i,h),m=e.svg.child(d,"g",{class:"sim-bb-wire-ends-g"});m.appendChild(f),m.appendChild(_);let y=this.closestEdgeIdx(n),k=this.closestEdgeIdx(i);if(y==k){let e=a(n,i,h);d.appendChild(e),u.push(e)}else{let t,r,l=p(n),c=p(i),f=a(n,l,h),_=a(i,c,h);!(1!=y&&2!=y||1!=k&&2!=k)?(t=s(l,c,o,h),r=s(l,c,o,h)):(t=a(l,c,h),r=a(l,c,h)),e.U.addClass(r,"sim-bb-wire-hover"),d.appendChild(f),u.push(f),d.appendChild(_),u.push(_),this.underboard.appendChild(t),u.push(t),d.appendChild(r),u.push(r);let b=`sim-bb-wire-id-${g}`;const v=t=>e.U.addClass(t,b);v(m),v(r),this.styleEl.textContent+=`\n .${b}:hover ~ .${b}.sim-bb-wire-hover {\n visibility: visible;\n }`}let b=`\n .wire-stroke-${h} {\n stroke: ${t.mapWireColor(c)};\n }\n .wire-fill-${h} {\n fill: ${t.mapWireColor(c)};\n }\n `;return this.styleEl.textContent+=b,{endG:m,end1:f,end2:_,wires:u}}drawWireWithCrocs(n,i,c,d=!1){let p=[],g=e.svg.child(this.overboard,"g",{class:"sim-bb-wire-group"});const h=e=>{const n=t.PIN_DIST/2;let o,r=this.closestEdge(e);return o=r-e[1]<0?r-n:r+n,[e[0],o]};let f=this.nextWireId++,_=r(c),m=l(n,_),y=i,[k,b]=i;i=[k,b+40],[k,b]=i;let v,T=[k,b+-17];v=d?function(n,o,r){let i=.24*t.PIN_DIST,s=4*i,a=1.2*i,l=10*i,c=i;const u=t.PIN_DIST/4;let[d,p]=n,g=o?-1:1,h=e.svg.elt("g"),f=e.svg.elt("rect"),_=s,m=a,y=d-m/2,k=p+10-_/2;e.svg.hydrate(f,{x:y,y:k,width:m,height:_,rx:.5,ry:.5,class:"sim-bb-wire-end"}),f.style["stroke-width"]=`${u}px`;let b=e.svg.elt("rect"),v=l,T=c,E=d-T/2,S=p+10+g*(_/2+v/2)-v/2;return e.svg.hydrate(b,{x:E,y:S,width:T,height:v,class:"sim-bb-wire-bare-end"}),b.style.fill="#bbb",h.appendChild(b),h.appendChild(f),{el:h,x:y-u,y:Math.min(k,S),w:m+2*u,h:_+v}}(T,!0):u(T,!0);let E=v.el,S=e.svg.child(g,"g",{class:"sim-bb-wire-ends-g"});S.appendChild(m);let C=this.closestEdgeIdx(n),x=this.closestEdgeIdx(y);if(C==x){let e=a(n,i,_);g.appendChild(e),p.push(e)}else{let t,r,l=h(n),c=a(n,l,_);!(1!=C&&2!=C||1!=x&&2!=x)?(t=s(l,i,o,_),r=s(l,i,o,_)):(t=a(l,i,_),r=a(l,i,_)),e.U.addClass(r,"sim-bb-wire-hover"),g.appendChild(c),p.push(c),this.underboard.appendChild(t),p.push(t);let u=`sim-bb-wire-id-${f}`;const d=t=>e.U.addClass(t,u);d(S),d(r),this.styleEl.textContent+=`\n .${u}:hover ~ .${u}.sim-bb-wire-hover {\n visibility: visible;\n }`}S.appendChild(E);let B=`\n .wire-stroke-${_} {\n stroke: ${t.mapWireColor(c)};\n }\n .wire-fill-${_} {\n fill: ${t.mapWireColor(c)};\n }\n `;return this.styleEl.textContent+=B,{endG:S,end1:m,end2:E,wires:p}}checkWire(e,t){let n=this.getLocCoord(e),o=this.getLocCoord(t);return!!n&&!!o}addWire(e,t,n){let o=this.getLocCoord(e),r=this.getLocCoord(t);if(!o||!r)return void console.debug(`unable to allocate wire for ${e} or ${t}`);let i,s=this.getPinStyle(t);return i="dalboard"==t.type&&"croc"==s?this.drawWireWithCrocs(o,r,n):this.drawWire(o,r,n),i}}}(e.visuals||(e.visuals={}))}(pxsim||(pxsim={})),function(e){!function(t){t.startDebuggerAsync=function(e){new n(e).start()};class n{constructor(e){this.container=e,this.pkgLoaded=!1,this.intervalRunning=!1}start(){this.initializeWebsocket(),this.intervalRunning||(this.intervalRunning=!0,this.intervalId=setInterval((()=>{if(!this.ws)try{this.initializeWebsocket()}catch(e){console.warn(`Connection to server failed, retrying in ${n.RETRY_MS} ms`)}}),n.RETRY_MS)),this.session=new pxsim.SimDebugSession(this.container),this.session.start(this)}initializeWebsocket(){e.BrowserUtils.isLocalHost()&&e.Cloud.localToken&&(e.debug("initializing debug pipe"),this.ws=new WebSocket("ws://localhost:3234/"+e.Cloud.localToken+"/simdebug"),this.ws.onopen=t=>{e.debug("debug: socket opened")},this.ws.onclose=t=>{e.debug("debug: socket closed"),this.closeListener&&this.closeListener(),this.session.stopSimulator(),this.ws=void 0},this.ws.onerror=t=>{e.debug("debug: socket closed due to error"),this.errorListener&&this.errorListener(t.type),this.session.stopSimulator(),this.ws=void 0},this.ws.onmessage=t=>{let n;try{n=JSON.parse(t.data)}catch(t){e.debug("debug: could not parse message")}n&&("runner"===n.type?this.handleRunnerMessage(n):("request"===n.type&&"launch"===n.command&&this.sendRunnerMessage("configure",{projectDir:n.arguments.projectDir}),this.dataListener(n)))})}send(e){this.ws.send(e)}onData(e){this.dataListener=e}onError(e){this.errorListener=e}onClose(e){this.closeListener=e}close(){this.session&&this.session.stopSimulator(!0),this.intervalRunning&&(clearInterval(this.intervalId),this.intervalId=void 0),this.ws&&this.ws.close()}handleRunnerMessage(e){switch(e.subtype){case"ready":this.sendRunnerMessage("ready");break;case"runcode":this.runCode(e)}}runCode(t){const n=[];t.breakpoints.forEach((e=>{n.push([e.id,{verified:!0,line:e.line,column:e.column,endLine:e.endLine,endColumn:e.endColumn,source:{path:e.fileName}}])})),this.session.runCode(t.code,t.usedParts,t.usedArguments,new pxsim.BreakpointMap(n),e.appTarget.simulator.boardDefinition)}sendRunnerMessage(e,t={}){t.subtype=e,t.type="runner",this.send(JSON.stringify(t))}}n.RETRY_MS=2500,t.DebugRunner=n}(e.runner||(e.runner={}))}(pxt||(pxt={})),function(e){!function(t){function n(){return{blocksAspectRatio:window.innerHeight<window.innerWidth?1.62:1/1.62,snippetClass:"lang-blocks",signatureClass:"lang-sig",blocksClass:"lang-block",blocksXmlClass:"lang-blocksxml",diffBlocksXmlClass:"lang-diffblocksxml",diffClass:"lang-diff",diffStaticPythonClass:"lang-diffspy",diffBlocksClass:"lang-diffblocks",staticPythonClass:"lang-spy",simulatorClass:"lang-sim",linksClass:"lang-cards",namespacesClass:"lang-namespaces",apisClass:"lang-apis",codeCardClass:"lang-codecard",packageClass:"lang-package",jresClass:"lang-jres",assetJSONClass:"lang-assetsjson",projectClass:"lang-project",snippetReplaceParent:!0,simulator:!0,showEdit:!0,hex:!0,tutorial:!1,showJavaScript:!1,hexName:e.appTarget.id}}function o(e){"undefined"!=typeof hljs&&(e.hasClass("highlight")?hljs.highlightBlock(e[0]):e.find("code.highlight").each((function(e,t){hljs.highlightBlock(t)})),r(e))}function r(t){t.find("span.hljs-comment:contains(@highlight)").each(((t,n)=>{try{!function(e){const t=$(e),n=document.createElement("span");n.className="highlight-line";let o=e.nextSibling;if(!o||o.nodeType!=Node.TEXT_NODE)return;let r=o.textContent,i=r.indexOf("\n");if(i<0)return;o.textContent=r.substring(0,i+1),$(document.createTextNode(r.substring(i+1).replace(/^\s+/,""))).insertAfter($(o)),o=o.nextSibling;for(;o;){let e=o.nextSibling;if(o.nodeType==Node.TEXT_NODE){r=o.textContent;const t=r.indexOf("\n");if(!(t<0)){n.appendChild(document.createTextNode(r.substring(0,t))),o.textContent=r.substring(t+1);break}n.appendChild(o),o=e}else n.appendChild(o),o=e}$(n).insertAfter(t),t.remove()}(n)}catch(t){e.reportException(t)}}))}function i(e,t){e.append($('<div class="ui content blocks"/>').append(t))}function s(e,t,n){e.append($('<div class="ui content js"><div class="subheading"><i class="ui icon xicon js"></i>JavaScript</div></div>').append(t)),o(t)}function a(e,t,n){e.append($('<div class="ui content py"><div class="subheading"><i class="ui icon xicon python"></i>Python</div></div>').append(t)),o(t)}function l(e,t){const n=$('<a class="item" role="button" tabindex="0"><i role="presentation" aria-hidden="true"></i><span class="ui desktop only"></span></a>');return n.attr("aria-label",e),n.attr("title",e),n.find("i").attr("class",t),n.find("span").text(e),n.keypress((e=>{const t="number"==typeof e.which?e.which:e.keyCode;13!==t&&32!==t||(e.preventDefault(),e.currentTarget.click())})),n}function c(t,n,o,r,c,u,d={}){let p=$('<div class="ui bottom attached tabular icon small compact menu hideprint"> <div class="right icon menu"></div></div>'),g=$('<div class="ui top attached segment codewidget"></div>'),h=p.find(".right.menu");const f=e.appTarget.appTheme||{};if(d.showEdit&&!f.hideDocsEdit&&u){const n=l(lf("Edit"),"edit icon"),{package:o,compileBlocks:i,compilePython:s}=u,a=o.host();if(c&&i?(o.setPreferredEditor(e.BLOCKS_PROJECT_NAME),a.writeFile(o,e.MAIN_BLOCKS,i.outfiles[e.MAIN_BLOCKS])):r&&s?(o.setPreferredEditor(e.PYTHON_PROJECT_NAME),a.writeFile(o,e.MAIN_PY,i.outfiles[e.MAIN_PY])):o.setPreferredEditor(e.JAVASCRIPT_PROJECT_NAME),t.assetJSON)for(const e of Object.keys(t.assetJSON))o.config.files.indexOf(e)<0&&o.config.files.push(e),a.writeFile(o,e,t.assetJSON[e]);const d=o.compressToFileAsync();n.click((()=>{e.tickEvent("docs.btn",{button:"edit"}),d.then((n=>{window.open(`${function(t){return(t.pxtUrl||e.appTarget.appTheme.homeUrl||"").replace(/\/$/,"")}(t)}/#project:${ts.pxtc.encodeBase64(e.Util.uint8ArrayToString(n))}`,"pxt")}))})),h.append(n)}if(t.showJavaScript||!c&&!r?(g.append(o),m(),b()):c?(g.append(c),y(),b()):r&&(g.append(r),m(),y()),d.run&&!f.hideDocsSimulator){let n=l(lf("Run"),"play icon").click((()=>{if(e.tickEvent("docs.btn",{button:"sim"}),g.find(".sim")[0])g.find(".sim").remove(),v(g);else{let n="81.97%";e.appTarget.simulator&&(n=100/e.appTarget.simulator.aspectRatio+"%");const r=t.package?"&deps="+encodeURIComponent(t.package):"",i=k(t)+"#nofooter=1"+r,s=t.assetJSON?`data-assets="${encodeURIComponent(JSON.stringify(t.assetJSON))}"`:"",a=encodeURIComponent(o.text());let l=$(`<div class="ui card sim"><div class="ui content"><div style="position:relative;height:0;padding-bottom:${n};overflow:hidden;"><iframe style="position:absolute;top:0;left:0;width:100%;height:100%;" src="${i}" data-code="${a}" ${s} allowfullscreen="allowfullscreen" sandbox="allow-popups allow-forms allow-scripts allow-same-origin" frameborder="0"></iframe></div></div></div>`);g.append(l),v(l)}}));h.append(n)}if(d.hexname&&d.hex){let t=l(lf("Download"),"download icon").click((()=>{e.tickEvent("docs.btn",{button:"hex"}),e.BrowserUtils.browserDownloadBinText(d.hex,d.hexname,{contentType:e.appTarget.compile.hexMimeType})}));h.append(t)}let _=$("<div class=codesnippet></div>");function m(){if(!c)return;const t=l(lf("Blocks"),"icon xicon blocks").click((()=>{e.tickEvent("docs.btn",{button:"blocks"}),g.find(".blocks")[0]?(g.find(".blocks").remove(),v(g)):(i(o?o.parent():g,c),v(c))}));h.append(t)}function y(){if(o)if(d.showJs)s(g,o);else{const t=l("JavaScript","icon xicon js").click((()=>{e.tickEvent("docs.btn",{button:"js"}),g.find(".js")[0]?(g.find(".js").remove(),v(g)):(s(c?c.parent():g,o),v(o))}));h.append(t)}}function b(){if(r)if(d.showPy)a(g,r);else{const t=l("Python","icon xicon python").click((()=>{e.tickEvent("docs.btn",{button:"py"}),g.find(".py")[0]?(g.find(".py").remove(),v(g)):(a(c?c.parent():g,r),v(r))}));h.append(t)}}function v(e){var t;null===(t=e[0])||void 0===t||t.scrollIntoView({behavior:"smooth",block:"center"})}h.children().length&&_.append(p),_.append(g),n.replaceWith(_)}t.defaultClientRenderOptions=n;let u,d=[];function p(t,n,o){if(!t)return Promise.resolve();let r=$("."+t).first();return r[0]?(o.emPixels||(o.emPixels=18),o.layout||(o.layout=e.blocks.BlockLayout.Align),o.splitSvg=!0,d.push({el:r,source:r.text(),options:o,render:n}),r.addClass("lang-shadow"),r.removeClass(t),p(t,n,o)):Promise.resolve()}function g(e){if(!e||e.kind!=ts.SyntaxKind.ExpressionStatement)return null;let t=e;if(!t.expression||t.expression.kind!=ts.SyntaxKind.CallExpression)return null;let n=t.expression;return pxtc.pxtInfo(n).callInfo}function h(t){return u||(u=e.runner.decompileSnippetAsync("",t)),u}function f(t,n){if(!n)return;const o=/^\/(v\d+)/.exec(n.url),r=/^\/(v\d+)/.exec(window.location.pathname),i=/#doc/i.test(window.location.href);n.url&&!o&&r&&!i&&(n.url=`/${r[1]}/${n.url}`),t.append(e.docs.codeCard.render(n,{hideHeader:!0,shortName:!0}))}function _(t,n,o){const r=n.attributes,i=!r.blockHidden&&Blockly.Blocks[r.blockId];if(null==i?void 0:i.codeCard){const n=e.U.clone(i.codeCard);o&&(n.style=o),f(t,n)}else f(t,{name:n.qName,description:r.jsDoc,url:r.help||void 0,style:o})}function m(t,n,o,r){return p(n,((t,n)=>{const i=n.compileProgram;if(!i)return;const s=i.getSourceFile(e.MAIN_TS).statements.slice(0),a=$("<div />").addClass("ui cards");a.attr("role","listbox"),s.forEach((t=>{const o=t.kind,i=g(t);if(i&&n.apiInfo&&n.apiInfo.byQName[i.qName]){const e=n.apiInfo.byQName[i.qName],t=e.attributes,o=Blockly.Blocks[t.blockId];if(r){const r=e,i=n.compileBlocks.blocksInfo.apis.byQName[r.namespace];f(a,{name:i.attributes.blockNamespace||i.name,url:i.attributes.help||"reference/"+(i.attributes.blockNamespace||i.name).toLowerCase(),description:i.attributes.jsDoc,blocksXml:o&&o.codeCard?o.codeCard.blocksXml:t.blockId?`<xml xmlns="http://www.w3.org/1999/xhtml"><block type="${t.blockId}"></block></xml>`:void 0})}else _(a,e)}else switch(o){case ts.SyntaxKind.ExpressionStatement:{const n=t;switch(n.expression.kind){case ts.SyntaxKind.TrueKeyword:case ts.SyntaxKind.FalseKeyword:f(a,{name:"Boolean",url:"blocks/logic/boolean",description:lf("True or false values"),blocksXml:'<xml xmlns="http://www.w3.org/1999/xhtml"><block type="logic_boolean"><field name="BOOL">TRUE</field></block></xml>'});break;default:e.debug(`card expr kind: ${n.expression.kind}`)}break}case ts.SyntaxKind.IfStatement:f(a,{name:r?"Logic":"if",url:"blocks/logic"+(r?"":"/if"),description:lf(r?"Logic operators and constants":"Conditional statement"),blocksXml:'<xml xmlns="http://www.w3.org/1999/xhtml"><block type="controls_if"></block></xml>'});break;case ts.SyntaxKind.WhileStatement:f(a,{name:r?"Loops":"while",url:"blocks/loops"+(r?"":"/while"),description:lf(r?"Loops and repetition":"Repeat code while a condition is true."),blocksXml:'<xml xmlns="http://www.w3.org/1999/xhtml"><block type="device_while"></block></xml>'});break;case ts.SyntaxKind.ForOfStatement:f(a,{name:r?"Loops":"for of",url:"blocks/loops"+(r?"":"/for-of"),description:lf(r?"Loops and repetition":"Repeat code for each item in a list."),blocksXml:'<xml xmlns="http://www.w3.org/1999/xhtml"><block type="controls_for_of"></block></xml>'});break;case ts.SyntaxKind.BreakStatement:f(a,{name:r?"Loops":"break",url:"blocks/loops"+(r?"":"/break"),description:lf(r?"Loops and repetition":"Break out of the current loop."),blocksXml:'<xml xmlns="http://www.w3.org/1999/xhtml"><block type="break_keyword"></block></xml>'});break;case ts.SyntaxKind.ContinueStatement:f(a,{name:r?"Loops":"continue",url:"blocks/loops"+(r?"":"/continue"),description:lf(r?"Loops and repetition":"Skip iteration and continue the current loop."),blocksXml:'<xml xmlns="http://www.w3.org/1999/xhtml"><block type="continue_keyboard"></block></xml>'});break;case ts.SyntaxKind.ForStatement:{let e=t,n=!0;3==e.condition.getChildCount()&&(n=!("0"==e.condition.getChildAt(0).getText()||e.condition.getChildAt(1).kind==ts.SyntaxKind.LessThanToken)),f(a,n?{name:r?"Loops":"for",url:"blocks/loops"+(r?"":"/for"),description:lf(r?"Loops and repetition":"Repeat code for a given number of times using an index."),blocksXml:'<xml xmlns="http://www.w3.org/1999/xhtml"><block type="controls_simple_for"></block></xml>'}:{name:r?"Loops":"repeat",url:"blocks/loops"+(r?"":"/repeat"),description:lf(r?"Loops and repetition":"Repeat code for a given number of times."),blocksXml:'<xml xmlns="http://www.w3.org/1999/xhtml"><block type="controls_repeat_ext"></block></xml>'});break}case ts.SyntaxKind.VariableStatement:f(a,{name:r?"Variables":"variable declaration",url:"blocks/variables"+(r?"":"/assign"),description:lf(r?"Variables":"Assign a value to a named variable."),blocksXml:'<xml xmlns="http://www.w3.org/1999/xhtml"><block type="variables_set"></block></xml>'});break;default:e.debug(`card kind: ${o}`)}})),o&&(t=t.parent()),t.replaceWith(a)}),{package:t.package,aspectRatio:t.blocksAspectRatio,assets:t.assetJSON})}function y(t,n){if(!t)return Promise.resolve();let o=$("."+t).first();if(!o[0])return Promise.resolve();o.removeClass(t);const r=e.gallery.parseCodeCardsHtml(o[0]);return r||o.append($("<div/>").addClass("ui segment warning").text("invalid codecard format")),n.snippetReplaceParent&&(o=o.parent()),function(t,n,o){if(!n||0==n.length)return Promise.resolve();if(0==n.length){let r=e.docs.codeCard.render(n[0],o);t.replaceWith(r)}else{let r=document.createElement("div");r.className="ui cards",r.setAttribute("role","listbox"),n.forEach((t=>{const n=/^\/(v\d+)/.exec(t.url),i=/^\/(v\d+)/.exec(window.location.pathname),s=/#doc/i.test(window.location.href);t.url&&!n&&i&&!s&&(t.url=`/${i[1]}${t.url}`);const a=e.docs.codeCard.render(t,o);if(r.appendChild(a),"package"==t.cardType){const n=e.github.parseRepoId((t.url||"").replace(/^\/pkg\//,""));n&&e.packagesConfigAsync().then((i=>{switch(e.github.repoStatus(n,i)){case e.github.GitRepoStatus.Banned:a.remove();break;case e.github.GitRepoStatus.Approved:t.imageUrl=e.github.mkRepoIconUrl(n),r.insertBefore(e.docs.codeCard.render(t,o),a),a.remove()}})).catch((n=>{e.reportException(n),e.debug(`failed to load repo ${t.url}`)}))}})),t.replaceWith(r)}return Promise.resolve()}(o,r,{hideHeader:!0}).then((()=>e.U.delay(1,y(t,n))))}function k(t){return t.pxtUrl?t.pxtUrl+"/--run":e.webConfig&&e.webConfig.runUrl?e.webConfig.runUrl:"/--run"}function b(t){const n={showEdit:!!t.showEdit,run:!!t.simulator};$("code.lang-python").each(((o,i)=>{!function(o,i){"undefined"!=typeof hljs&&($(o).text($(o).text().replace(/^\s*\r?\n/,"")),hljs.highlightBlock(o),r($(o)));const s=e.U.clone(n);i&&(s.run=!1,s.showEdit=!1),c(t,$(o).parent(),$(o),void 0,void 0,void 0,s)}(i,!1),$(i).removeClass("lang-python")}))}t.renderAsync=function(t){return e.analytics.enable(),t||(t=n()),t.pxtUrl&&(t.pxtUrl=t.pxtUrl.replace(/\/$/,"")),t.showEdit&&(t.showEdit=!e.BrowserUtils.isIFrame()),function(e){e.packageClass&&($("."+e.packageClass).each(((t,n)=>{let o=$(n),r=o.text().split("\n").map((e=>e.replace(/\s*/g,""))).filter((e=>!!e)).join(",");e.package=e.package?`${e.package},${r}`:r,e.snippetReplaceParent&&(o=o.parent()),o.remove()})),$(".lang-config").each(((t,n)=>{let o=$(n);e.snippetReplaceParent&&(o=o.parent()),o.remove()})))}(t),function(t){let n,o;t.jresClass&&$(`.${t.jresClass}`).each(((e,t)=>{const n=$(t);o=n.text(),t.parentElement.remove()})),t.assetJSONClass&&$(`.${t.assetJSONClass}`).each(((e,t)=>{const o=$(t);n=o.text(),t.parentElement.remove()})),t.assetJSON=function(t,n){if(!t&&!n)return;const o=e.tutorial.parseAssetJson(t)||{};if(n){const t=JSON.parse(n);o[e.TILEMAP_JRES]=JSON.stringify(t),o[e.TILEMAP_CODE]=e.emitTilemapsFromJRes(t)}return o}(n,o)}(t),d=[],function(e){let t=$("code.lang-ghost");e.snippetReplaceParent&&(t=t.parent()),t.remove()}(t),function(t){t.simulatorClass&&$("."+t.simulatorClass).each(((n,o)=>{let r=$(o),i="81.97%";e.appTarget.simulator&&(i=100/e.appTarget.simulator.aspectRatio+"%");let s=$(`<div class="ui card"><div class="ui content">\n <div style="position:relative;height:0;padding-bottom:${i};overflow:hidden;">\n <iframe style="position:absolute;top:0;left:0;width:100%;height:100%;" allowfullscreen="allowfullscreen" frameborder="0" sandbox="allow-popups allow-forms allow-scripts allow-same-origin"></iframe>\n </div>\n </div></div>`);const a=t.package?"&deps="+encodeURIComponent(t.package):"",l=k(t)+"#nofooter=1"+a,c=encodeURIComponent(r.text().trim()),u=s.find("iframe");u.attr("src",l),u.attr("data-code",c),t.assetJSON&&u.attr("data-assets",JSON.stringify(t.assetJSON)),t.snippetReplaceParent&&(r=r.parent()),r.replaceWith(s)}))}(t),function(t){const n={showEdit:!!t.showEdit,run:!!t.simulator};function o(o,i){"undefined"!=typeof hljs&&($(o).text($(o).text().replace(/^\s*\r?\n/,"")),hljs.highlightBlock(o),r($(o)));const s=e.U.clone(n);i&&(s.run=!1,s.showEdit=!1),c(t,$(o).parent(),$(o),void 0,void 0,void 0,s)}$("code.lang-typescript").each(((e,t)=>{o(t,!1),$(t).removeClass("lang-typescript")})),$("code.lang-typescript-ignore").each(((e,t)=>{$(t).removeClass("lang-typescript-ignore"),$(t).addClass("lang-typescript"),o(t,!0),$(t).removeClass("lang-typescript")})),$("code.lang-typescript-invalid").each(((e,t)=>{$(t).removeClass("lang-typescript-invalid"),$(t).addClass("lang-typescript"),o(t,!0),$(t).removeClass("lang-typescript"),$(t).parent("div").addClass("invalid"),$(t).parent("div").prepend($("<i>",{class:"icon ban"})),$(t).addClass("invalid")})),$("code.lang-typescript-valid").each(((e,t)=>{$(t).removeClass("lang-typescript-valid"),$(t).addClass("lang-typescript"),o(t,!0),$(t).removeClass("lang-typescript"),$(t).parent("div").addClass("valid"),$(t).parent("div").prepend($("<i>",{class:"icon check"})),$(t).addClass("valid")}))}(t),b(t),Promise.resolve().then((()=>y(t.codeCardClass,t))).then((()=>function(t){return"core"==e.appTarget.id?Promise.resolve():h(t).then((t=>{let n={};const o=t.compileBlocks.blocksInfo;o.blocks.forEach((e=>{const t=(e.attributes.blockNamespace||e.namespace).split(".")[0];if(!n[t]){const e=o.apis.byQName[t];e&&e.attributes.color&&(n[t]=e.attributes.color)}}));let r="";return Object.keys(n).forEach((t=>{const o=n[t]||"#dddddd";r+=`\n span.docs.${t.toLowerCase()} {\n background-color: ${o} !important;\n border-color: ${e.toolbox.fadeColor(o,.1,!1)} !important;\n }\n `})),r})).then((t=>(Object.keys(e.toolbox.blockColors).forEach((n=>{const o=e.toolbox.getNamespaceColor(n);t+=`\n span.docs.${n.toLowerCase()} {\n background-color: ${o} !important;\n border-color: ${e.toolbox.fadeColor(o,.1,!1)} !important;\n }\n `})),t))).then((e=>{let t=document.createElement("style");t.id="namespaceColors",t.type="text/css",(document.head||document.getElementsByTagName("head")[0]).appendChild(t),t.appendChild(document.createTextNode(e))}))}(t))).then((()=>function(t){(t=e.Util.clone(t)).emPixels=18,t.snippetMode=!0;const n=$(":not(pre) > code");let o=0;return function r(){if(o>=n.length)return Promise.resolve();const i=$(n[o++]),s=i.text(),a=/^(\|+)([^\|]+)\|+$/.exec(s);if(a){const t=/^(([^\:\.]*?)[\:\.])?(.*)$/.exec(a[2]),n=t[2]?t[2].trim().toLowerCase():"",o=1==a[1].length?`docs inlinebutton ${n}`:`docs inlineblock ${n}`,s=t[3].trim();return i.replaceWith($(`<span class="${o}"/>`).text(e.U.rlf(s))),r()}const l=/^\[(.+)\]$/.exec(s);if(!l)return r();const c=l[1];return e.runner.decompileSnippetAsync(c,t).then((t=>{if(t.blocksSvg){let n=$('<span class="block"/>').append(t.blocksSvg);const o=g(t.compileProgram.getSourceFile(e.MAIN_TS).statements[0]);if(o&&t.apiInfo){const e=t.apiInfo.byQName[o.qName];e&&e.attributes.help&&(n=$('<a class="ui link"/>').attr("href",`/reference/${e.attributes.help}`).append(n))}i.replaceWith(n)}return e.U.delay(1,r())}))}()}(t))).then((()=>m(t,t.linksClass,t.snippetReplaceParent,!1))).then((()=>m(t,t.namespacesClass,t.snippetReplaceParent,!0))).then((()=>function(t,n){const o=t.apisClass;if(!o)return Promise.resolve();const r=$("."+o);return r.length?h(t).then((t=>{const o=t.compileBlocks.blocksInfo,i=e.Util.values(o.apis.byQName).filter((e=>!(e.attributes.hidden||e.attributes.deprecated||e.attributes.blockAliasFor||!e.attributes.jsDoc||!e.attributes.block||/^__/.test(e.name))));r.each(((t,o)=>{let r=$(o);const s=e.Util.toDictionary(r.text().split("\n"),(e=>e)),a=i.filter((e=>!!s[e.attributes.blockNamespace||e.namespace]));if(!a.length)return;a.sort(((e,t)=>{const n=!e.attributes.blockHidden&&Blockly.Blocks[e.attributes.blockId],o=!t.attributes.blockHidden&&Blockly.Blocks[t.attributes.blockId];return!!n!=!!o?(o?1:0)-(n?1:0):e.name.localeCompare(t.name)}));const l=$("<div />").addClass("ui divided items");l.attr("role","listbox"),a.forEach((e=>_(l,e,"item"))),n&&(r=r.parent()),r.replaceWith(l)}))})):Promise.resolve()}(t,t.snippetReplaceParent))).then((()=>function(t){return p(t.signatureClass,((n,o)=>{var r,i,s,a;let l=o.compileProgram;if(!l)return;let u=g(l.getSourceFile(e.MAIN_TS).statements[0]);if(!u||!o.apiInfo)return;const d=o.apiInfo.byQName[u.qName];if(!d)return;let p=Blockly.Blocks[d.attributes.blockId],h=(null===(r=null==p?void 0:p.codeCard)||void 0===r?void 0:r.blocksXml)||void 0;const f=h?e.blocks.render(h):(null===(i=o.compileBlocks)||void 0===i?void 0:i.success)?o.blocksSvg:void 0,_=f?$(f):void 0;let m=ts.pxtc.service.displayStringForSymbol(d,!1,o.apiInfo).split("\n")[1]+";";const y=$('<code class="lang-typescript highlight"/>').text(m),k=(null===(a=null===(s=e.appTarget)||void 0===s?void 0:s.appTheme)||void 0===a?void 0:a.python)&&ts.pxtc.service.displayStringForSymbol(d,!0,o.apiInfo).split("\n")[1],b=k&&$('<code class="lang-python highlight"/>').text(k);if(t.snippetReplaceParent&&(n=n.parent()),e.Util.isTranslationMode()){const e=$('<div class="ui segment" />');e.append($('<div class="ui header"><i class="ui xicon globe"></i></div>')),d.attributes.translationId&&e.append($('<div class="ui message">').text(d.attributes.translationId)),d.attributes.jsDoc&&e.append($('<div class="ui message">').text(d.attributes.jsDoc)),e.insertAfter(n)}c(t,n,y,b,_,o,{showJs:!0,showPy:!0,hideGutter:!0})}),{package:t.package,snippetMode:!0,aspectRatio:t.blocksAspectRatio,assets:t.assetJSON})}(t))).then((()=>function(t){if(t.tutorial)return p(t.snippetClass,((e,n)=>{const o=n.blocksSvg;t.snippetReplaceParent&&(e=e.parent());const r=$('<div class="ui segment codewidget"/>').append(o);e.replaceWith(r)}),{package:t.package,snippetMode:!1,aspectRatio:t.blocksAspectRatio,assets:t.assetJSON});let n=0;return p(t.snippetClass,((o,r)=>{const i=r.compileBlocks&&r.compileBlocks.success?$(r.blocksSvg):void 0,s=r.compilePython&&r.compilePython.success&&r.compilePython.outfiles[e.MAIN_PY],a=$('<code class="lang-typescript highlight"/>').text(o.text().trim()),l=s?$('<code class="lang-python highlight"/>').text(s.trim()):void 0;t.snippetReplaceParent&&(o=o.parent());const u=r.compileJS&&r.compileJS.success,d=t.hex&&u&&r.compileJS.outfiles[pxtc.BINARY_HEX]?r.compileJS.outfiles[pxtc.BINARY_HEX]:void 0,p=`${e.appTarget.nickname||e.appTarget.id}-${t.hexName||""}-${n++}.hex`;c(t,o,a,l,i,r,{showEdit:t.showEdit,run:t.simulator,hexname:p,hex:d})}),{package:t.package,aspectRatio:t.blocksAspectRatio,assets:t.assetJSON})}(t))).then((()=>function(e){return p(e.blocksClass,((t,n)=>{const o=n.blocksSvg;e.snippetReplaceParent&&(t=t.parent());const r=$('<div class="ui segment codewidget"/>').append(o);t.replaceWith(r)}),{package:e.package,snippetMode:!0,aspectRatio:e.blocksAspectRatio,assets:e.assetJSON})}(t))).then((()=>{return(n=t).blocksXmlClass?function t(n,o,r){let i=$("."+n).first();return i[0]?(r.emPixels||(r.emPixels=18),r.splitSvg=!0,e.runner.compileBlocksAsync(i.text(),r).then((s=>{try{o(i,s)}catch(t){e.reportException(t),i.append($("<div/>").addClass("ui segment warning").text(t.message))}return i.removeClass(n),e.U.delay(1,t(n,o,r))}))):Promise.resolve()}(n.blocksXmlClass,((e,t)=>{const o=t.blocksSvg;n.snippetReplaceParent&&(e=e.parent());const r=$('<div class="ui segment codewidget"/>').append(o);e.replaceWith(r)}),{package:n.package,snippetMode:!0,aspectRatio:n.blocksAspectRatio,assets:n.assetJSON}):Promise.resolve();var n})).then((()=>{return(n=t).diffBlocksXmlClass?function t(n,o,r){let i=$("."+n).first();if(!i[0])return Promise.resolve();r.emPixels||(r.emPixels=18),r.splitSvg=!0;const s=i.text().split(/-{10,}/),a=s[0],l=s[1];return e.runner.compileBlocksAsync("",r).then((s=>{i.removeClass(n);try{const t=e.blocks.diffXml(a,l);t?(s.blocksSvg=t.svg,o(i,s)):i.text("no changes")}catch(t){e.reportException(t),i.append($("<div/>").addClass("ui segment warning").text(t.message))}return e.U.delay(1,t(n,o,r))}))}(n.diffBlocksXmlClass,((e,t)=>{const o=t.blocksSvg;n.snippetReplaceParent&&(e=e.parent());const r=$('<div class="ui segment codewidget"/>').append(o);e.replaceWith(r)}),{package:n.package,snippetMode:!0,aspectRatio:n.blocksAspectRatio,assets:n.assetJSON}):Promise.resolve();var n})).then((()=>{return(n=t).diffBlocksClass?function t(o){let r=$("."+o).first();if(!r[0])return Promise.resolve();const{fileA:i,fileB:s}=e.diff.split(r.text(),{removeTrailingSemiColumns:!0});return e.U.promiseMapAllSeries([i,s],(t=>e.runner.decompileSnippetAsync(t,{generateSourceMap:!0}))).then((a=>{try{const t=e.blocks.decompiledDiffAsync(i,a[0].compileBlocks,s,a[1].compileBlocks,{hideDeletedTopBlocks:!0,hideDeletedBlocks:!0}),o=e.diff.render(i,s,{hideLineNumbers:!0,hideMarkerLine:!0,hideMarker:!0,hideRemoved:!0,update:!0,ignoreWhitespace:!0});let l;const[u,d]=a.map((t=>t.compilePython&&t.compilePython.outfiles&&t.compilePython.outfiles[e.MAIN_PY]));u&&d&&(l=e.diff.render(u,d,{hideLineNumbers:!0,hideMarkerLine:!0,hideMarker:!0,hideRemoved:!0,update:!0,ignoreWhitespace:!0})),c(n,r.parent(),$(o),l&&$(l),$(t.svg),void 0,{showEdit:!1,run:!1,hexname:void 0,hex:void 0})}catch(t){e.reportException(t),r.append($("<div/>").addClass("ui segment warning").text(t.message))}return e.U.delay(1,t(o))}))}(n.diffBlocksClass):Promise.resolve();var n})).then((()=>{return(n=t).diffClass?function t(o){let r=$("."+o).first();if(!r[0])return Promise.resolve();const{fileA:i,fileB:s}=e.diff.split(r.text());try{const t=e.diff.render(i,s,{hideLineNumbers:!0,hideMarkerLine:!0,hideMarker:!0,hideRemoved:!0,update:!0,ignoreWhitespace:!0});n.snippetReplaceParent&&(r=r.parent());const a=$('<div class="ui segment codewidget"/>').append(t);r.removeClass(o),r.replaceWith(a)}catch(t){e.reportException(t),r.append($("<div/>").addClass("ui segment warning").text(t.message))}return e.U.delay(1,t(o))}(n.diffClass):Promise.resolve();var n})).then((()=>function(t){const n={showEdit:!!t.showEdit,run:!!t.simulator};return p(t.staticPythonClass,((r,i)=>{const s=i.compilePython;if(s&&s.success){const a=r.clone().removeClass("lang-shadow").addClass("highlight"),l=a.clone().addClass("lang-python").text(s.outfiles[e.MAIN_PY]);a.addClass("lang-typescript"),o(l),c(t,r.parent(),a,l,void 0,i,n)}}),{package:t.package,snippetMode:!0,assets:t.assetJSON})}(t))).then((()=>function(t){return t.projectClass?function n(){let o=$("."+t.projectClass).first(),r=o[0];if(!r)return Promise.resolve();o.removeClass(t.projectClass);let i=e.Cloud.parseScriptId(r.innerText);if(i){if(t.snippetReplaceParent){r=r.parentElement;let e=document.createElement("div");r.parentElement.insertBefore(e,r),r.parentElement.removeChild(r),r=e}return e.runner.renderProjectAsync(r,i).then((()=>n()))}return n()}():Promise.resolve()}(t))).then((()=>function(){const t={};return function n(){const o=d.shift();if(!o)return Promise.resolve();const{el:r,options:i,render:s}=o;return e.runner.decompileSnippetAsync(r.text(),i).then((n=>{const o=n.compileJS&&n.compileJS.diagnostics&&n.compileJS.diagnostics.filter((e=>e.category==pxtc.DiagnosticCategory.Error));o&&o.length&&o.forEach((t=>e.reportError("docs.decompile",""+t.messageText,{code:t.code+""}))),n.blocksSvg.querySelectorAll("defs *").forEach((e=>{t[e.id]?e.remove():t[e.id]=!0})),s(r,n)}),(t=>{e.reportException(t),r.append($("<div/>").addClass("ui segment warning").text(t.message))})).finally((()=>(r.removeClass("lang-shadow"),n())))}().then((()=>{Blockly.Workspace.getAll().forEach((e=>e.dispose())),e.blocks.cleanRenderingWorkspace()}))}()))}}(e.runner||(e.runner={}))}(pxt||(pxt={})),function(e){!function(t){class n{constructor(e,t){this.ksPkg=e,this.topPkg=t,this.files={}}getKsPkg(){return this.ksPkg}getPkgId(){return this.ksPkg?this.ksPkg.id:this.id}isTopLevel(){return this.ksPkg&&0==this.ksPkg.level}setFiles(e){this.files=e}getAllFiles(){return e.Util.mapMap(this.files,((e,t)=>t))}}class o{constructor(){this.githubPackageCache={}}readFile(t,n){let o=l(t);return e.U.lookup(o.files,n)}writeFile(e,t,n){l(e).files[t]=n}getHexInfoAsync(t){return e.hexloader.getHexInfoAsync(this,t)}cacheStoreAsync(e,t){return Promise.resolve()}cacheGetAsync(e){return Promise.resolve(null)}patchDependencies(t,n,o){if(!o)return!1;const r=e.github.parseRepoId(o);if(!r)return!1;for(const n of Object.keys(t.dependencies)){const i=t.dependencies[n],s=e.github.parseRepoId(i);if(s&&r.fullName==s.fullName)return e.semver.strcmp(r.tag,s.tag)<0&&(t.dependencies[n]=o),!0}return!1}downloadPackageAsync(t,n){let o,r=t.verProtocol();"github"==r&&(o=this.githubPackageCache[t._verspec]);let i=l(t);return(o?Promise.resolve(o):t.commonDownloadAsync()).then((s=>{if(s)return"github"!=r||o||(this.githubPackageCache[t._verspec]=e.Util.clone(s)),i.setFiles(s),Promise.resolve();if("empty"==r){if(0==Object.keys(i.files).length&&i.setFiles(c()),n&&n.length){const o=l(t).files,r=JSON.parse(o[e.CONFIG_NAME]);n.forEach((e=>{a(r,e)})),o[e.CONFIG_NAME]=e.Package.stringifyConfig(r)}return Promise.resolve()}if("docs"==r){let n=c(),o=JSON.parse(n[e.CONFIG_NAME]);return t.verArgument().split(",").forEach((e=>{a(o,e)})),o.yotta||(o.yotta={}),o.yotta.ignoreConflicts=!0,n[e.CONFIG_NAME]=e.Package.stringifyConfig(o),i.setFiles(n),Promise.resolve()}return"invalid"==r?(e.log(`skipping invalid pkg ${t.id}`),Promise.resolve()):Promise.reject(`Cannot download ${t.version()}; unknown protocol`)}))}}let r,i,s;function a(e,t){let n=/^([a-zA-Z0-9_-]+)(=(.+))?$/.exec(t);if(n){if(n[3]&&this&&this.patchDependencies(e,n[1],n[3]))return!1;e.dependencies[n[1]]=n[3]||"*"}else console.warn(`unknown package syntax ${t}`);return!0}function l(e){let o=e._editorPkg;if(o)return o;let r=null;e!=t.mainPkg&&(r=l(t.mainPkg));let i=new n(e,r);return e==t.mainPkg&&(i.topPkg=i),e._editorPkg=i,i}function c(){let t=e.appTarget.tsprj,n=e.U.clone(t.files);return n[e.CONFIG_NAME]=e.Package.stringifyConfig(t.config),n[e.MAIN_BLOCKS]="",n}function u(){e.setAppTarget(window.pxtTargetBundle),e.Util.assert(!!e.appTarget);const n=window.location.href;let r,i=!1;if(/[&?]translate=1/.test(n)&&!e.BrowserUtils.isIE())r=ts.pxtc.Util.TRANSLATION_LOCALE,i=!0,e.Util.enableLiveLocalizationUpdates();else{const t=/PXT_LANG=(.*?)(?:;|$)/.exec(document.cookie),o=/(live)?(force)?lang=([a-z]{2,}(-[A-Z]+)?)/i.exec(n);r=o?o[3]:t&&t[1]||e.appTarget.appTheme.defaultLocale||navigator.userLanguage||navigator.language;const s=e.appTarget.appTheme.defaultLocale,a=null==r?void 0:r.toLocaleLowerCase(),l=e.BrowserUtils.isLocalHostDev()&&(!a||(s?s.toLocaleLowerCase()===a:"en"===a||"en-us"===a));(e.BrowserUtils.isPxtElectron()||l||e.appTarget.appTheme.disableLiveTranslations)&&!(null==o?void 0:o[1])||e.Util.enableLiveLocalizationUpdates(),i=!!o&&!!o[2]}const s=e.appTarget.versions;$&&$.fn&&$.fn.embed&&$.fn.embed.settings&&$.fn.embed.settings.sources&&$.fn.embed.settings.sources.youtube&&($.fn.embed.settings.sources.youtube.url="//www.youtube.com/embed/{id}?rel=0");const a=e.webConfig;return e.Util.updateLocalizationAsync({targetId:e.appTarget.id,baseUrl:a.commitCdnUrl,code:r,pxtBranch:s?s.pxtCrowdinBranch:"",targetBranch:s?s.targetCrowdinBranch:"",force:i}).then((()=>{t.mainPkg=new e.MainPackage(new o)}))}function d(e){console.error(e)}function p(n,o,r){const s=n?/\w+:\w+/.test(n)?n:"pub:"+n:"empty:tsprj";let a,c,u;return i&&i._verspec==s?(t.mainPkg=i,a=t.mainPkg.host(),c=Promise.resolve(),u=Promise.resolve()):(a=t.mainPkg.host(),t.mainPkg=new e.MainPackage(a),t.mainPkg._verspec=n?/\w+:\w+/.test(n)?n:"pub:"+n:"empty:tsprj",c=a.downloadPackageAsync(t.mainPkg,r),u=t.mainPkg.installAllAsync(),i=t.mainPkg),c.then((()=>a.readFile(t.mainPkg,e.CONFIG_NAME))).then((n=>n?u.then((()=>{if(o){let n=l(t.mainPkg);n.files[e.MAIN_TS]=o;let r=JSON.parse(n.files[e.CONFIG_NAME]);r.name=window.location.href.split("/").pop().split(/[?#]/)[0],n.files[e.CONFIG_NAME]=e.Package.stringifyConfig(r),t.mainPkg.config.name=r.name,-1==t.mainPkg.config.files.indexOf(e.MAIN_BLOCKS)&&t.mainPkg.config.files.push(e.MAIN_BLOCKS)}})).catch((e=>{d(lf("Cannot load extension: {0}",e.message))})):Promise.resolve()))}function g(e){let n=t.mainPkg.getTargetOptions();return n.isNative=!!e,n.hasHex=!!e,t.mainPkg.getCompileOptionsAsync(n)}function h(e,t){return g(e).then((e=>{t&&t(e);let n=pxtc.compile(e);return n.diagnostics&&n.diagnostics.length>0&&n.diagnostics.forEach((e=>{console.error(e.messageText)})),n}))}async function f(n){var o;await p(n.id,n.code,n.dependencies);let r=!1;const i=e.appTarget.versions.target;let s=await h(!1,(o=>{var s;if(n.assets){const t=JSON.parse(n.assets);for(const n of Object.keys(t)){const r=t[n];if(o.fileSystem[n]=r,o.sourceFiles.indexOf(n)<0&&o.sourceFiles.push(n),/\.jres$/.test(n)){const t=JSON.parse(r);o.jres=e.inflateJRes(t,o.jres)}}}if(n.code&&(o.fileSystem[e.MAIN_TS]=n.code),o.target.preferredEditor===e.PYTHON_PROJECT_NAME){o.target.preferredEditor=e.JAVASCRIPT_PROJECT_NAME,o.ast=!0;const t=S(pxtc.compile(o).ast,o);o.apisInfo=t,o.target.preferredEditor=e.PYTHON_PROJECT_NAME}const a=null===(s=t.mainPkg.config.targetVersions)||void 0===s?void 0:s.target;if(a&&i&&e.semver.cmp(e.semver.parse(a),e.semver.parse(i))<0)for(const t of Object.keys(o.fileSystem))!e.Util.startsWith(t,"pxt_modules")&&e.Util.endsWith(t,".ts")&&(r=!0,o.fileSystem[t]=e.patching.patchJavaScript(a,o.fileSystem[t]))}));return(null===(o=s.diagnostics)||void 0===o?void 0:o.length)>0&&r&&(e.log("Compile with upgrade rules failed, trying again with original code"),s=await h(!1,(t=>{n.code&&(t.fileSystem[e.MAIN_TS]=n.code)}))),s.diagnostics&&s.diagnostics.length>0&&console.error("Diagnostics",s.diagnostics),pxtc.buildSimJsInfo(s)}function _(e){let t={};try{let n=window.localStorage.getItem(e);n&&(t=JSON.parse(n))}catch(e){}return t}function m(n,o){if(t.editorLanguageMode=n,o!=e.Util.localeInfo()){const t=/^live-/;return t.test(o)&&e.Util.enableLiveLocalizationUpdates(),e.Util.updateLocalizationAsync({targetId:e.appTarget.id,baseUrl:e.webConfig.commitCdnUrl,code:o.replace(t,""),pxtBranch:e.appTarget.versions.pxtCrowdinBranch,targetBranch:e.appTarget.versions.targetCrowdinBranch})}return Promise.resolve()}function y(t){let n=t.data;if(n)switch(n.type){case"fileloaded":let t=n,o=t.name;m(/\.ts$/i.test(o)?s.TypeScript:s.Blocks,t.locale);break;case"popout":let r=/((\/v[0-9+])\/)?[^\/]*#(doc|md):([^&?:]+)/i.exec(window.location.href);if(r){const t=e.webConfig.docsUrl||"/--docs";let n=r[2]||"",o="doc"==r[3]?e.webConfig.isStatic?`/docs${r[4]}.html`:`${r[4]}`:`${t}?md=${r[4]}`;window.parent&&window.parent.postMessage({type:"opendoc",url:e.BrowserUtils.urlJoin(n,o)},"*")}break;case"localtoken":let i=n;i&&i.localToken&&(e.Cloud.localToken=i.localToken,C.forEach((e=>e())),C=[])}}function k(t,n){return e.Cloud.privateGetTextAsync(n+"/text").then((e=>JSON.parse(e))).then((e=>b(t,e,n)))}function b(n,o,r=null,i=!1){const a=JSON.parse(o[e.CONFIG_NAME])||{};let l=`# ${a.name} ${a.version?a.version:""}\n\n`;const c="README.md";o[c]&&(l+=o[c].replace(/^#+/,"$0#")+"\n"),a.files.filter((t=>t!=e.CONFIG_NAME&&t!=c)).filter((e=>t.editorLanguageMode==s.Blocks==/\.blocks?$/.test(e))).forEach((e=>{/^main\.(ts|blocks)$/.test(e)||(l+=`\n## ${e}\n`),/\.ts$/.test(e)?l+=`\`\`\`typescript\n${o[e]}\n\`\`\`\n`:/\.blocks?$/.test(e)?l+=`\`\`\`blocksxml\n${o[e]}\n\`\`\`\n`:l+=`\`\`\`${e.substr(e.indexOf("."))}\n${o[e]}\n\`\`\`\n`}));const u=a&&a.dependencies&&Object.keys(a.dependencies).filter((t=>t!=e.appTarget.corepkg));if(u&&u.length&&(l+=`\n## ${lf("Extensions")} #extensions\n\n${u.map((e=>`* ${e}, ${a.dependencies[e]}`)).join("\n")}\n\n\`\`\`package\n${u.map((e=>`${e}=${a.dependencies[e]}`)).join("\n")}\n\`\`\`\n`),r){let t=(e.appTarget.appTheme.shareUrl||"https://makecode.com/")+r;i&&(t="`"+t+"`"),l+=`\n${t}\n\n`}console.debug(`print md: ${l}`);return v(n,l,{print:!0})}e.react.getTilemapProject||(e.react.getTilemapProject=()=>(r||(r=new e.TilemapProject,r.loadPackage(t.mainPkg)),r)),t.initFooter=function(t,n){if(!t)return;let o=e.appTarget.appTheme,r=$("body"),i=$(t),s=$("<a/>").attr("href",o.homeUrl).attr("target","_blank");i.append(s),o.organizationLogo?s.append($("<img/>").attr("src",e.Util.toDataUri(o.organizationLogo))):s.append(lf("powered by {0}",o.title)),r.mouseenter((e=>i.fadeOut())),r.mouseleave((e=>i.fadeIn()))},t.showError=d,t.generateHexFileAsync=function(t){return p(t.id).then((()=>h(!0,(n=>{t.code&&(n.fileSystem[e.MAIN_TS]=t.code)})))).then((e=>(e.diagnostics&&e.diagnostics.length>0&&console.error("Diagnostics",e.diagnostics),e.outfiles[pxtc.BINARY_HEX])))},t.generateVMFileAsync=function(t){return e.setHwVariant("vm"),p(t.id).then((()=>h(!0,(n=>{t.code&&(n.fileSystem[e.MAIN_TS]=t.code)})))).then((e=>(console.log(e),e)))},t.simulateAsync=async function(t,n){var o,r;const i=n.builtJsInfo||await f(n),{js:s,fnArgs:a,parts:l,usedBuiltinParts:c}=i;if(!s)return void console.error("Program failed to compile");let u={};u.onSimulatorCommand=e=>{"restart"===e.command&&(h.storedState=_(n.id),d.run(s,h)),"setstate"==e.command&&e.stateKey&&e.stateValue&&function(e,t,n){let o=_(e);if(!e)return;n?o[t]=n:delete o[t];try{window.localStorage.setItem(e,JSON.stringify(o))}catch(e){}}(n.id,e.stateKey,e.stateValue)},u.messageSimulators=null===(r=null===(o=e.appTarget)||void 0===o?void 0:o.simulator)||void 0===r?void 0:r.messageSimulators;let d=new pxsim.SimulatorDriver(t,u),p=e.appTarget.simulator.boardDefinition,g=_(n.id),h={boardDefinition:p,parts:l,builtinParts:c,fnArgs:a,cdnUrl:e.webConfig.commitCdnUrl,localizedStrings:e.Util.getLocalizedStrings(),highContrast:n.highContrast,storedState:g,light:n.light,single:n.single};return e.appTarget.simulator&&!n.fullScreen&&(h.aspectRatio=l.length&&e.appTarget.simulator.partsAspectRatio?e.appTarget.simulator.partsAspectRatio:e.appTarget.simulator.aspectRatio),d.run(s,h),i},t.buildSimJsInfo=f,function(e){e[e.Blocks=0]="Blocks",e[e.TypeScript=1]="TypeScript"}(s=t.LanguageMode||(t.LanguageMode={})),t.editorLanguageMode=s.Blocks,t.setEditorContextAsync=m,t.startRenderServer=function(){e.tickEvent("renderer.ready");const n=[];let o;function r(){if(o)return;const i=n.shift();if(!i)return;const s=i.options||{};s.splitSvg=!1,e.tickEvent("renderer.job");const a=/^\s*<xml/.test(i.code);o=(async()=>{await e.BrowserUtils.loadBlocklyAsync();const n=(a?await e.runner.compileBlocksAsync(i.code,s):await t.decompileSnippetAsync(i.code,i.options)).blocksSvg,o=n.viewBox.baseVal.width,r=n.viewBox.baseVal.height,l=n?await e.blocks.layout.blocklyToSvgAsync(n,0,0,o,r):void 0;let c;try{c=l?await e.BrowserUtils.encodeToPngAsync(l.xml,{width:o,height:r}):void 0}catch(e){console.warn(e)}window.parent.postMessage({source:"makecode",type:"renderblocks",id:i.id,width:null==l?void 0:l.width,height:null==l?void 0:l.height,svg:null==l?void 0:l.svg,uri:c||(null==l?void 0:l.xml),css:null==l?void 0:l.css},"*")})().catch((e=>{window.parent.postMessage({source:"makecode",type:"renderblocks",id:i.id,error:e.message},"*")})).finally((()=>{o=void 0,r()}))}e.editor.initEditorExtensionsAsync().then((()=>{window.addEventListener("message",(function(e){const t=e.data;"renderblocks"==t.type&&(n.push(t),r())}),!1),window.parent.postMessage({source:"makecode",type:"renderready",versions:e.appTarget.versions},"*")}))},t.startDocsServer=function(t,n,o){e.tickEvent("docrenderer.ready");const r=[];function i(r,s){e.debug(`rendering ${r}`),o&&$(o).hide(),$(n).hide(),$(t).show(),e.U.delay(100).then((()=>{switch(r){case"print":const t=window.localStorage.printjob;return delete window.localStorage.printjob,b(n,JSON.parse(t),void 0,!0).then((()=>pxsim.print(1e3)));case"project":return b(n,JSON.parse(s)).then((()=>pxsim.print(1e3)));case"projectid":return k(n,JSON.parse(s)).then((()=>pxsim.print(1e3)));case"doc":return function(t,n){return n=n.replace(/^\//,""),e.Cloud.markdownAsync(n).then((e=>v(t,e,{path:n})))}(n,s);case"book":return function(t,n){n=n.replace(/^\//,""),e.tickEvent("book",{id:n}),e.log(`rendering book from ${n}`);let o;return $("#loading").find(".loader").addClass("text").text(lf("Compiling your book (this may take a minute)")),e.U.delay(100).then((()=>e.Cloud.markdownAsync(n))).then((t=>{o=e.docs.buildTOC(t),e.log(`TOC: ${JSON.stringify(o,null,2)}`);const n=[];return e.docs.visitTOC(o,(e=>{/^\//.test(e.path)&&!/^\/pkg\//.test(e.path)&&n.push(e)})),e.U.promisePoolAsync(4,n,(async t=>{try{const n=await e.Cloud.markdownAsync(t.path);t.markdown=n}catch(e){t.markdown=`_${t.path} failed to load._`}}))})).then((n=>{let r=o[0].name;return e.docs.visitTOC(o,(e=>{e.markdown&&(r+="\n\n"+e.markdown)})),v(t,r)}))}(n,s);default:return v(n,s)}})).catch((t=>{$(n).html(`\n <img style="height:4em;" src="${e.appTarget.appTheme.docsLogo}" />\n <h1>${lf("Oops")}</h1>\n <h3>${lf("We could not load the documentation, please check your internet connection.")}</h3>\n <button class="ui button primary" id="tryagain">${lf("Try Again")}</button>`),$(n).find("#tryagain").click((()=>{i(r,s)})),window.parent&&window.parent.postMessage({type:"docfailed",docType:r,src:s},"*")})).finally((()=>{$(t).hide(),o&&$(o).show(),$(n).show()})).then((()=>{}))}function a(e,t){t?(pxsim.U.addClass(e,"disabled"),e.setAttribute("aria-disabled","true")):(pxsim.U.removeClass(e,"disabled"),e.setAttribute("aria-disabled","false"))}function l(){let e=/^#(doc|md|tutorial|book|project|projectid|print):([^&?:]+)(:([^&?:]+):([^&?:]+))?/i.exec(window.location.hash);if(e){o&&(r.push(window.location.hash),r.length>10&&r.shift(),r.length>1&&a(o,!1));(e[4]?m(/^blocks$/.test(e[4])?s.Blocks:s.TypeScript,e[5]):Promise.resolve()).then((()=>i(e[1],decodeURIComponent(e[2]))))}}o&&(o.addEventListener("click",(()=>{!function(){if(!o)return;r.length>1&&(r.pop(),window.location.hash=r.pop());r.length<=1&&a(o,!0)}()})),a(o,!0)),e.editor.initEditorExtensionsAsync().then((()=>{window.addEventListener("message",y,!1),window.addEventListener("hashchange",(()=>{l()}),!1),parent.postMessage({type:"sidedocready"},"*"),setTimeout((()=>l()),1)}))},t.renderProjectAsync=k,t.renderProjectFilesAsync=b;function v(n,o,r={}){const i=e.docs.renderMarkdown({template:'\n<aside id=button class=box>\n <a class="ui primary button" href="@ARGS@">@BODY@</a>\n</aside>\n\n<aside id=vimeo>\n<div class="ui two column stackable grid container">\n<div class="column">\n <div class="ui embed mdvid" data-source="vimeo" data-id="@ARGS@" data-placeholder="/thumbnail/1024/vimeo/@ARGS@" data-icon="video play">\n </div>\n</div></div>\n</aside>\n\n<aside id=youtube>\n<div class="ui two column stackable grid container">\n<div class="column">\n <div class="ui embed mdvid" data-source="youtube" data-id="@ARGS@" data-placeholder="https://img.youtube.com/vi/@ARGS@/0.jpg">\n </div>\n</div></div>\n</aside>\n\n<aside id=section>\n \x3c!-- section @ARGS@ --\x3e\n</aside>\n\n<aside id=hide class=box>\n <div style=\'display:none\'>\n @BODY@\n </div>\n</aside>\n\n<aside id=avatar class=box>\n <div class=\'avatar @ARGS@\'>\n <div class=\'avatar-image\'></div>\n <div class=\'ui compact message\'>\n @BODY@\n </div>\n </div>\n</aside>\n\n<aside id=hint class=box>\n <div class="ui info message">\n <div class="content">\n @BODY@\n </div>\n </div>\n</aside>\n\n<aside id=codecard class=box>\n <pre><code class="lang-codecard">@BODY@</code></pre>\n</aside>\n\n<aside id=tutorialhint class=box>\n <div class="ui hint message">\n <div class="content">\n @BODY@\n </div>\n </div>\n</aside>\n\n<aside id=reminder class=box>\n <div class="ui warning message">\n <div class="content">\n @BODY@\n </div>\n </div>\n</aside>\n\n<aside id=alert class=box>\n <div class="ui negative message">\n <div class="content">\n @BODY@\n </div>\n </div>\n</aside>\n\n<aside id=tip class=box>\n <div class="ui positive message">\n <div class="content">\n @BODY@\n </div>\n </div>\n</aside>\n\n\x3c!-- wrapped around ordinary content --\x3e\n<aside id=main-container class=box>\n <div class="ui text">\n @BODY@\n </div>\n</aside>\n\n\x3c!-- used for \'column\' box - they are collected and wrapped in \'column-container\' --\x3e\n<aside id=column class=aside>\n <div class=\'column\'>\n @BODY@\n </div>\n</aside>\n<aside id=column-container class=box>\n <div class="ui three column stackable grid text">\n @BODY@\n </div>\n</aside>\n@breadcrumb@\n@body@',markdown:o,theme:e.appTarget.appTheme});let a=r.blocksAspectRatio||window.innerHeight<window.innerWidth?1.62:1/1.62;$(n).html(i),$(n).find("a").attr("target","_blank");const l=e.runner.defaultClientRenderOptions();return l.tutorial=!!r.tutorial,l.blocksAspectRatio=a||l.blocksAspectRatio,l.showJavaScript=t.editorLanguageMode==s.TypeScript,r.print&&(l.showEdit=!1,l.simulator=!1),e.runner.renderAsync(l).then((()=>{$(n).find('a[href^="/"]').removeAttr("target").each(((e,t)=>{$(t).attr("href","#doc:"+$(t).attr("href").replace(/^\//,""))})),$(n).find(".ui.embed").embed()}))}let T,E;function S(e,t){E||(E={});const n=Object.keys(t.fileSystem).sort().join(";");return E[n]||(E[n]=pxtc.getApiInfo(e,t.jres)),E[n]}t.renderMarkdownAsync=v,t.decompileSnippetAsync=function(n,o){const{assets:i,forceCompilation:s,snippetMode:a,generateSourceMap:l}=o||{};return p(o&&o.packageId?"pub:"+o.packageId:o&&o.package?"docs:"+o.package:null,n).then((()=>g(!!e.appTarget.compile&&e.appTarget.compile.hasHex))).then((c=>{if(n&&(c.fileSystem[e.MAIN_TS]=n),c.ast=!0,i)for(const e of Object.keys(i))c.sourceFiles.indexOf(e)<0&&c.sourceFiles.push(e),c.fileSystem[e]=i[e];let u,d,p;s?(u=pxtc.compile(c),d=u&&u.ast):d=pxtc.getTSProgram(c,T),T=d,e.appTarget.appTheme.python&&(p=ts.pxtc.transpile.tsToPy(d,e.MAIN_TS));let g=S(d,c);return ts.pxtc.localizeApisAsync(g,t.mainPkg).then((()=>{let n=pxtc.getBlocksInfo(g);e.blocks.initializeAndInject(n);const s=null==i?void 0:i[e.TILEMAP_JRES],c=null==i?void 0:i[e.IMAGES_JRES];(s||c)&&(r=new e.TilemapProject,r.loadPackage(t.mainPkg),s&&r.loadTilemapJRes(JSON.parse(s),!0),c&&r.loadAssetsJRes(JSON.parse(c)));let h=pxtc.decompiler.decompileToBlocks(n,d.getSourceFile(e.MAIN_TS),{snippetMode:a,generateSourceMap:l});if(h.diagnostics&&h.diagnostics.length>0&&h.diagnostics.forEach((e=>console.error(e.messageText))),!h.success)return{package:t.mainPkg,compileProgram:d,compileJS:u,compileBlocks:h,apiInfo:g};e.debug(h.outfiles[e.MAIN_BLOCKS]);const f=e.blocks.render(h.outfiles[e.MAIN_BLOCKS],o);return(s||c)&&(r=null),{package:t.mainPkg,compileProgram:d,compileJS:u,compileBlocks:h,compilePython:p,apiInfo:g,blocksSvg:f}}))}))},t.compileBlocksAsync=function(n,o){const{assets:i}=o||{};return p(o&&o.packageId?"pub:"+o.packageId:o&&o.package?"docs:"+o.package:null,"").then((()=>g(!!e.appTarget.compile&&e.appTarget.compile.hasHex))).then((s=>{if(s.ast=!0,i)for(const e of Object.keys(i))s.sourceFiles.indexOf(e)<0&&s.sourceFiles.push(e),s.fileSystem[e]=i[e];const a=S(pxtc.compile(s).ast,s);return ts.pxtc.localizeApisAsync(a,t.mainPkg).then((()=>{const s=pxtc.getBlocksInfo(a);e.blocks.initializeAndInject(s);const l=null==i?void 0:i[e.TILEMAP_JRES],c=null==i?void 0:i[e.IMAGES_JRES];(l||c)&&(r=new e.TilemapProject,r.loadPackage(t.mainPkg),l&&r.loadTilemapJRes(JSON.parse(l),!0),c&&r.loadAssetsJRes(JSON.parse(c)));const u=e.blocks.render(n,o);return(l||c)&&(r=null),{package:t.mainPkg,blocksSvg:u,apiInfo:a}}))}))};let C=[];t.initCallbacks=[],t.init=function(){u().then((()=>{for(let e=0;e<t.initCallbacks.length;++e)t.initCallbacks[e]()}))},function(){let e=window.ksRunnerWhenLoaded;e&&e()}()}(e.runner||(e.runner={}))}(pxt||(pxt={}));
|
|
67
|
+
*/}])})),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(e){!function(t){function n(t,n){return e.worker.getWorker(e.webConfig.workerjs).opAsync(t,n)}t.workerOpAsync=n;let o={};function r(e,t){e.push.apply(e,t)}function i(e){if(!e)throw new Error("Assertion failure")}class s{constructor(e,t,n,o,r){this.link=e,this.type=t,this.parentType=n,this.childType=o,this.isArrayType=r}}let a;function l(e){return e.link?l(e.link):e}function c(e,t){let n=l(e),o=l(t);if(i(null==n.link&&null==o.link),n==o)return;if(n.childType&&o.childType){const e=n.childType;n.childType=null,c(e,o.childType)}else n.childType&&!o.childType&&(o.childType=n.childType);if(n.parentType&&o.parentType){const e=n.parentType;n.parentType=null,c(e,o.parentType)}else!n.parentType||o.parentType||o.type||(o.parentType=n.parentType);let r=function(e,t){if(null==e||"Array"===e&&y(t))return t;if(null==t||"Array"===t&&y(e))return e;if(e==t)return e;throw new Error("cannot mix "+e+" with "+t)}(n.type,o.type);e.link=o,n.link=o,n.isArrayType=o.isArrayType,e.type=null,t.type=r}function u(e,t=!1){return new s(null,e,null,null,t)}t.Point=s,function(e){e[e.None=0]="None",e[e.Argument=1]="Argument",e[e.Assigned=2]="Assigned",e[e.Implicit=3]="Implicit"}(a=t.BlockDeclarationType||(t.BlockDeclarationType={}));const d=u("number"),p=u("boolean"),g=u("string"),h=u("void");function f(e){if(!e)return u(e);switch(e.toLowerCase()){case"number":return d;case"boolean":return p;case"string":return g;case"void":return h;default:return u(e)}}function _(e,t){if(i(null!=t),function(e){return"placeholder"==e.type||e.type===pxtc.TS_OUTPUT_TYPE}(t))return t.p||(t.p=u(null)),l(t.p);if("variables_get"==t.type)return l(L(e,t,t.getField("VAR").getText()).type);if("function_call_output"==t.type)return function(e,t){const n=t.getField("function_name").getText();return m(e,n)}(e,t);if(!t.outputConnection)return f(h.type);const n=t.outputConnection.check_&&t.outputConnection.check_.length?t.outputConnection.check_[0]:"T";if("Array"===n){if(t.outputConnection.check_.length>1)return f(t.outputConnection.check_[1]);let n;if("lists_create_with"==t.type){if(t.inputList&&t.inputList.length)for(const o of t.inputList)if(o.connection&&o.connection.targetBlock()){let t=l(_(e,o.connection.targetBlock()));if(t){if(t.parentType)return t.parentType;n=t.type?f(t.type+"[]"):u(null),C(n,t);break}}}else"argument_reporter_array"==t.type&&(n||(n=f("any[]")));return n&&(n.isArrayType=!0),n||u(null,!0)}if("T"===n){const n=e.stdCallTable[t.type],o="lists_index_get"===t.type;if(o||n&&n.comp.thisParameter){let r;if(r=o?t.inputList.find((e=>"LIST"===e.name)):t.inputList.find((e=>e.name===n.comp.thisParameter.definitionName)),r.connection&&r.connection.targetBlock()){const t=_(e,r.connection.targetBlock());if(t.childType)return t.childType;const n=y(t.type)&&"Array"!==t.type?u(t.type.substr(0,t.type.length-2)):u(null);return C(t,n),n}}return u(null)}return f(n)}function m(t,n){if(!t.userFunctionReturnValues[n]){const o=Blockly.Functions.getDefinition(n,t.workspace);let r=u("void");if(me(o,!0))r=u("any");else{const i=[];for(const e of o.getDescendants(!1))"function_return"===e.type&&(k(t,e,"RETURN_VALUE"),i.push(_(t,v(e,"RETURN_VALUE"))));if(i.length)try{const e=u(null);for(const t of i)c(e,t);r=e}catch(i){t.diagnostics.push({blockId:o.id,message:e.Util.lf("Function '{0}' has an invalid return type",n)}),r=u("any")}}t.userFunctionReturnValues[n]=r}return t.userFunctionReturnValues[n]}function y(e){return e&&(-1!==e.indexOf("[]")||"Array"==e)}function k(e,t,n,r){const i=t.getInputTargetBlock(n);i?i.type!==pxtc.TS_OUTPUT_TYPE||i.p||(i.p=u(null)):(o[t.id]||(o[t.id]={}),o[t.id][n]||(o[t.id][n]=function(e,t,n){return{type:"placeholder",p:u(n||null),workspace:e.workspace,parentBlock_:t}}(e,t,r)))}function b(e){return"pxt_controls_for"==e.type||"pxt_controls_for_of"==e.type?v(e,"VAR"):e}function v(e,t){const n=e.getInputTargetBlock(t);return n||o[e.id]&&o[e.id][t]}function T(){o={}}function E(e,t,n,o){k(e,t,n);try{c(_(e,v(t,n)),o)}catch(e){}}function S(e,t,n){function o(e){return e.name?e.connection&&e.connection.check_&&e.connection.check_.length?e.connection.check_[0]:"T":void 0}function r(e,n){let r=e.inputList.filter((e=>"T"===o(e)));if(r.length){const o=v(e,r[0].name);if(o){const r=_(t,o),i=r.type?f(_(t,o).type+"[]"):f(null);return C(i,r),E(t,e,n,i),!0}}return!1}e&&e.filter((e=>e.isEnabled())).forEach((e=>{try{switch(e.type){case"math_op2":E(t,e,"x",f(d.type)),E(t,e,"y",f(d.type));break;case"math_op3":E(t,e,"x",f(d.type));break;case"math_arithmetic":case"logic_compare":switch(e.getFieldValue("OP")){case"ADD":case"MINUS":case"MULTIPLY":case"DIVIDE":case"LT":case"LTE":case"GT":case"GTE":case"POWER":E(t,e,"A",f(d.type)),E(t,e,"B",f(d.type));break;case"AND":case"OR":k(t,e,"A",p.type),k(t,e,"B",p.type);break;case"EQ":case"NEQ":k(t,e,"A"),k(t,e,"B");let n=_(t,v(e,"A")),o=_(t,v(e,"B"));try{c(n,o)}catch(e){}}break;case"logic_operation":k(t,e,"A",p.type),k(t,e,"B",p.type);break;case"logic_negate":k(t,e,"BOOL",p.type);break;case"controls_if":for(let n=0;n<=e.elseifCount_;++n)k(t,e,"IF"+n,p.type);break;case"pxt_controls_for":case"controls_simple_for":E(t,e,"TO",f(d.type));break;case"pxt_controls_for_of":case"controls_for_of":const n=_(t,v(e,"LIST"));C(n,L(t,e,b(e).getField("VAR").getText()).type);break;case"variables_set":case"variables_change":let i=L(t,e,e.getField("VAR").getText()).type;k(t,e,"VALUE");let s=v(e,"VALUE");if(s){let e=function(e,t){var n,o;return(null===(o=null===(n=t.outputConnection)||void 0===n?void 0:n.check_)||void 0===o?void 0:o.length)&&"Array"!==t.outputConnection.check_[0]&&"T"!==t.outputConnection.check_[0]?t.outputConnection.check_.map((e=>f(e))):[_(e,t)]}(t,s);const n=l(i);if(n.type&&e.slice(1).some((e=>e.type===n.type)))i.link=l(e[0]);else try{c(i,e[0])}catch(e){}}break;case"controls_repeat_ext":E(t,e,"TIMES",f(d.type));break;case"device_while":k(t,e,"COND",p.type);break;case"lists_index_get":E(t,e,"LIST",f("Array")),E(t,e,"INDEX",f(d.type));const a=_(t,v(e,"LIST"));C(a,_(t,e));break;case"lists_index_set":E(t,e,"LIST",f("Array")),k(t,e,"VALUE"),r(e,"LIST"),E(t,e,"INDEX",f(d.type));break;case"function_definition":m(t,e.getField("function_name").getText());break;case"function_call":case"function_call_output":e.getArguments().forEach((n=>{E(t,e,n.id,f(n.type))}));break;case pxtc.TS_RETURN_STATEMENT_TYPE:k(t,e,"RETURN_VALUE");break;case pxtc.PAUSE_UNTIL_TYPE:E(t,e,"PREDICATE",p);break;default:if(e.type in t.stdCallTable){const n=t.stdCallTable[e.type];if("ENUM_GET"===n.attrs.shim||"KIND_GET"===n.attrs.shim)return;ie(n,re(e)).forEach(((i,s)=>{const a=n.isExtensionMethod&&0===s;if(i.definitionName&&!e.getFieldValue(i.definitionName)){let n=e.inputList.find((e=>e.name==i.definitionName));if(n&&n.connection&&n.connection.check_){if(a&&"Array"===o(n)){if(r(e,i.definitionName))return}for(let o=0;o<n.connection.check_.length;o++)try{let r=n.connection.check_[o];E(t,e,i.definitionName,f(r));break}catch(e){}}}}))}}}catch(n){const o=n.block||e;o.setWarningText(n+""),t.errors.push(o)}})),t.allVariables.forEach((e=>{null==x(e.type).type&&c(e.type,f(e.type.isArrayType?"number[]":d.type))}))}function C(e,t){const n=l(e),o=l(t);n.childType?c(n.childType,o):n.type||(n.childType=o),o.parentType?c(o.parentType,n):o.type||(o.parentType=n),y(n.type)&&(n.isArrayType=!0)}function x(e,t=[]){const n=l(e);if(-1===t.indexOf(n)&&(t.push(n),!n.type||"Array"===n.type)){if(n.parentType){const e=x(n.parentType,t);if(e.type&&"Array"!==e.type)return y(e.type)?n.type=e.type.substr(0,e.type.length-2):n.type=e.type,n}if(n.childType){const e=x(n.childType,t);if(e.type)return n.type=e.type+"[]",n}}return n}function B(e){let t=e.getFieldValue("math_number_minmax"===e.type?"SLIDER":"NUM");const n=parseFloat(t);return function(e,t){isFinite(e)&&!isNaN(e)||function(e,t){let n=new Error(e);throw n.block=t,n}(lf("Number entered is either too large or too small"),t)}(n,e),n}function A(e,n,o){return t.H.mkNumberLiteral(B(n))}let I={ADD:"+",MINUS:"-",MULTIPLY:"*",DIVIDE:"/",LT:"<",LTE:"<=",GT:">",GTE:">=",AND:"&&",OR:"||",EQ:"==",NEQ:"!=",POWER:"**"};function D(e,n,o){const r=M(n.getFieldValue("NAME"),e,!0);return t.mkStmt(t.mkText(r+"()"))}function N(e,n,o,r){const i=M(n.getField("function_name").getText(),e,!0),s=!n.getInputsInline(),a=n.getArguments().map((e=>({actualName:e.name,definitionName:e.id}))).map((t=>V(e,n,t,o))),l=t.H.stdCall(i,a,s);return r?t.mkStmt(l):l}function w(e,n,o){const r=v(n,"RETURN_VALUE");return r&&"placeholder"!=r.type?t.mkStmt(t.mkText("return "),P(e,r,o)):t.mkStmt(t.mkText("return"))}function R(e){const n=e.getContent();return t.Helpers.mkMultiComment(n.trim())}function O(e){if(null==e.type&&(c(e,f(d.type)),e=l(e)),y(e.type)||e.isArrayType)return t.mkText("[]");switch(e.type){case"boolean":return t.H.mkBooleanLiteral(!1);case"number":return t.H.mkNumberLiteral(0);case"string":return t.H.mkStringLiteral("");default:return t.mkText("null")}}function P(n,o,r){let s;if(i(null!=o),n.stats[o.type]=(n.stats[o.type]||0)+1,ne(o,r),"placeholder"!=o.type&&o.isEnabled&&o.isEnabled())switch(o.type){case"math_number":case"math_integer":case"math_whole_number":case"math_number_minmax":s=A(0,o);break;case"math_op2":s=function(e,n,o){let r=n.getFieldValue("op"),i=P(e,v(n,"x"),o),s=P(e,v(n,"y"),o);return t.H.mathCall(r,[i,s])}(n,o,r);break;case"math_op3":s=function(e,n,o){let r=P(e,v(n,"x"),o);return t.H.mathCall("abs",[r])}(n,o,r);break;case"math_arithmetic":case"logic_compare":case"logic_operation":s=function(e,n,o){let r=n.getFieldValue("OP"),s=v(n,"A"),a=v(n,"B"),l=[P(e,s,o),P(e,a,o)],c=_(e,s).type;if(c==g.type){if("EQ"==r)return t.H.mkSimpleCall("==",l);if("NEQ"==r)return t.H.mkSimpleCall("!=",l)}else if(c==p.type)return t.H.mkSimpleCall(I[r],l);return i(r in I),t.H.mkSimpleCall(I[r],l)}(n,o,r);break;case"math_modulo":s=function(e,n,o){let r=v(n,"DIVIDEND"),i=v(n,"DIVISOR"),s=[P(e,r,o),P(e,i,o)];return t.H.mkSimpleCall("%",s)}(n,o,r);break;case"logic_boolean":s=function(e,n,o){return t.H.mkBooleanLiteral("TRUE"==n.getFieldValue("BOOL"))}(0,o);break;case"logic_negate":s=function(e,n,o){let r=P(e,v(n,"BOOL"),o);return t.mkPrefix("!",[t.H.mkParenthesizedExpression(r)])}(n,o,r);break;case"variables_get":s=function(e,n){const o=n.getField("VAR").getText();let r=L(e,n,o);if(!r)return t.mkText(o);r.firstReference||(r.firstReference=n);return i(null!=r&&null!=r.type),t.mkText(r.escapedName)}(n,o);break;case"text":s=function(e,n,o){return t.H.mkStringLiteral(n.getFieldValue("TEXT"))}(0,o);break;case"text_join":s=function(e,n,o){let r,i=0;for(;;){const s=v(n,"ADD"+i);if(i++,!s){if(i<n.inputList.length)continue;break}const a=P(e,s,o);r=r?t.H.mkSimpleCall("+",[r,a]):0===s.type.indexOf("text")?a:t.H.mkSimpleCall("+",[t.H.mkStringLiteral(""),a])}return r||t.H.mkStringLiteral("")}(n,o,r);break;case"lists_create_with":s=function(e,n,o){let r=n.inputList.map((t=>t.connection&&t.connection.targetBlock()?P(e,t.connection.targetBlock(),o):void 0)).filter((e=>!!e));return t.H.mkArrayLiteral(r,!n.getInputsInline())}(n,o,r);break;case"lists_index_get":s=function(e,n,o){const r=P(e,v(n,"LIST"),o),i=P(e,v(n,"INDEX"),o);return t.mkGroup([r,t.mkText("["),i,t.mkText("]")])}(n,o,r);break;case"lists_index_set":s=function(e,n,o){const r=v(n,"LIST"),i=P(e,r,o),s=P(e,v(n,"INDEX"),o),a=P(e,v(n,"VALUE"),o),l=t.mkGroup([i,t.mkText("["),s,t.mkText("] = "),a]);return"lists_create_with"===r.type?X(l):l}(n,o,r);break;case"math_js_op":case"math_js_round":s=function(e,n,o){const r=n.getFieldValue("OP"),i=[P(e,v(n,"ARG0"),o)];return n.getInput("ARG1")&&i.push(P(e,v(n,"ARG1"),o)),t.H.mathCall(r,i)}(n,o,r);break;case pxtc.TS_OUTPUT_TYPE:s=function(e,n,o){return t.mkText(n.getFieldValue("EXPRESSION").trim())}(0,o);break;case"argument_reporter_boolean":case"argument_reporter_number":case"argument_reporter_string":case"argument_reporter_array":case"argument_reporter_custom":s=function(e,n,o){const r=M(n.getFieldValue("VALUE"),e);return t.mkText(r)}(n,o);break;case"function_call_output":s=N(n,o,r,!1);break;default:let a=n.stdCallTable[o.type];a?s=a.imageLiteral?j(n,o,a.imageLiteral,a.imageLiteralColumns,a.imageLiteralRows,a.namespace,a.f,ie(a,re(o)).map((e=>V(n,o,e,r)))):G(n,o,a,r):(e.reportError("blocks","unable to compile expression",{details:o.type}),s=O(_(n,o)))}else{if("Array"===l(_(n,o)).type){let e="lists_index_get"===o.parentBlock_.type;if(!e){const t=n.stdCallTable[o.parentBlock_.type];e=t&&t.isExpression}const r=t.mkText("[0]");s=e?r:X(r)}else s=O(_(n,o))}return s.id=o.id,s}function L(e,t,n){return de(n,e.idToScope[t.id])}function M(e,t,n=!1){if(!e)return"_";if(n){if(t.renames.oldToNewFunctions[e])return t.renames.oldToNewFunctions[e]}else if(t.renames.oldToNew[e])return t.renames.oldToNew[e];let o=ts.pxtc.escapeIdentifier(e);if(t.renames.takenNames[o]){let e=2;for(;t.renames.takenNames[o+e];)e++;o+=e}return n?(t.renames.oldToNewFunctions[e]=o,t.renames.takenNames[o]=!0):t.renames.oldToNew[e]=o,o}function F(e,n,o){let r=v(n,"VALUE"),i=L(e,n,n.getField("VAR").getText());let s=e.idToScope[n.id].declaredVars[i.name]===i&&!i.firstReference&&!i.alreadyDeclared;s&&pe(n,(t=>{if("variables_get"===t.type){L(e,t,t.getField("VAR").getText())===i&&(s=!1)}}),!0);let l=P(e,r,o),c=i.escapedName+" = ";if(i.isAssigned=!0,s){i.alreadyDeclared=a.Assigned;const t=x(i.type);if(c=`let ${i.escapedName} = `,t){const n=x(_(e,r));t.type!==n.type&&(c=`let ${i.escapedName}: ${t.type} = `)}}else i.firstReference||(i.firstReference=n);return t.mkStmt(t.mkText(c),l)}function U(e,n,o){let r=v(n,"VALUE"),i=L(e,n,n.getField("VAR").getText()),s=P(e,r,o),a=t.mkText(i.escapedName);return t.mkStmt(t.mkInfix(a,"+=",s))}function H(n,o,r){const i=n.stdCallTable[o.type];return i.imageLiteral?t.mkStmt(j(n,o,i.imageLiteral,i.imageLiteralColumns,i.imageLiteralRows,i.namespace,i.f,ie(i,re(o)).map((e=>V(n,o,e,r))))):i.hasHandler?function(n,o,r,i,s,a){const l=i.map((e=>V(n,o,e,a))),c=v(o,"HANDLER"),u=$(n,c);e.appTarget.compile&&e.appTarget.compile.emptyEventHandlerComments&&0===u.children.length&&u.children.unshift(t.mkStmt(t.mkText(`// ${pxtc.HANDLER_COMMENT}`)));let d;if(K(o)&&o.mutation.getMutationType()===t.MutatorTypes.ObjectDestructuringMutator)d=o.mutation.compileMutation(n,a);else if(r.comp.handlerArgs.length){let e=function(e,t,n){return se(e,t).map((t=>L(n,e,t[0]).escapedName))}(o,r,n);d=t.mkText(`function (${e.join(", ")})`)}return W(n,s,r.f,l,u,d,r.isExtensionMethod)}(n,o,i,function(e,t){return ie(e,re(t)).filter((e=>!!e.definitionName))}(i,o),i.namespace,r):t.mkStmt(G(n,o,i,r))}function V(n,o,r,i,s=!1){let a=o.getFieldValue(r.definitionName);if(null!=a){const i=o.getField(r.definitionName);if(i instanceof pxtblockly.FieldTextInput)return t.H.mkStringLiteral(a);if(i instanceof pxtblockly.FieldTilemap&&!i.isGreyBlock){const o=e.react.getTilemapProject(),r=i.getValue();if(r.startsWith("tilemap`"))return t.mkText(r);if(n.options.emitTilemapLiterals)try{const n=e.sprite.decodeTilemap(r,"typescript",o);if(n){const[e]=o.createNewTilemapFromData(n);return t.mkText(`tilemap\`${e}\``)}}catch(n){}}const s=n.blocksInfo.apis.byQName[r.type];if(s&&s.attributes.emitAsConstant)for(const e of Object.keys(n.blocksInfo.apis.byQName)){const o=n.blocksInfo.apis.byQName[e];if(o&&o.attributes&&o.attributes.enumIdentity===a)return t.mkText(e)}let l=t.mkText(a);return l.canIndentInside="string"==typeof a&&a.indexOf("\n")>=0,l}{k(n,o,r.definitionName);const e=v(o,r.definitionName);return s&&"lists_create_with"===e.type?X(P(n,e,i)):r.shadowOptions&&r.shadowOptions.toString&&_(n,e)!==g?t.H.mkSimpleCall("+",[t.H.mkStringLiteral(""),t.H.mkParenthesizedExpression(P(n,e,i))]):P(n,e,i)}}function G(e,n,o,r){let i;if(K(n)&&n.mutation.getMutationType()===t.MutatorTypes.RestParameterMutator)i=n.mutation.compileMutation(e,r).children;else{if("ENUM_GET"===o.attrs.shim){const e=o.attrs.enumName,r=n.getFieldValue("MEMBER").replace(/^\d+/,"");return t.H.mkPropertyAccess(r,t.mkText(e))}if("KIND_GET"===o.attrs.shim){const r=e.kinds.filter((e=>e.blockId===o.attrs.blockId))[0];return t.H.mkPropertyAccess(n.getFieldValue("MEMBER"),t.mkText(r.name))}i=ie(o,re(n)).map(((t,i)=>V(e,n,t,r,o.isExtensionMethod&&0===i&&!o.isExpression)))}let s=o.namespace,a=o.f;if(o.attrs.blockAliasFor){const t=e.blocksInfo.apis.byQName[o.attrs.blockAliasFor];t&&(a=t.name,s=t.namespace)}const l=!n.getInputsInline();if(o.isIdentity)return i[0];if(o.property)return t.H.mkPropertyAccess(a,i[0]);if("@get@"==a)return t.H.mkPropertyAccess(i[1].op.replace(/.*\./,""),i[0]);if("@set@"==a)return t.H.mkAssign(t.H.mkPropertyAccess(i[1].op.replace(/.*\./,"").replace(/@set/,""),i[0]),i[2]);if("@change@"==a)return t.H.mkSimpleCall("+=",[t.H.mkPropertyAccess(i[1].op.replace(/.*\./,"").replace(/@set/,""),i[0]),i[2]]);if(o.isExtensionMethod){if(o.attrs.defaultInstance){let s;K(n)&&n.mutation.getMutationType()===t.MutatorTypes.DefaultInstanceMutator&&(s=n.mutation.compileMutation(e,r)),s?i.unshift(s):i.unshift(t.mkText(o.attrs.defaultInstance))}return t.H.extensionCall(a,i,l)}return s?t.H.namespaceCall(s,a,i,l):t.H.stdCall(a,i,l)}function W(e,n,o,r,i,s,a=!1){let l;return i.noFinalNewline=!0,l=s?t.mkGroup([s,i]):t.mkGroup([t.mkText("function ()"),i]),a?t.mkStmt(t.H.extensionCall(o,r.concat([l]),!1)):n?t.mkStmt(t.H.namespaceCall(n,o,r.concat([l]),!1)):t.mkStmt(t.H.mkCall(o,r.concat([l]),!1))}function K(e){return!!e.mutation}function j(e,n,o,r,i,s,a,l){l=void 0===l?[]:l;let c="\n";i=i||5,r=(r||5)*o;let u=n.getFieldValue("LEDS");u=u.replace(/[ `\n]+/g,"");for(let e=0;e<i;++e){for(let t=0;t<r;++t)t>0&&(c+=" "),c+="#"===u[e*r+t]?"#":".";c+="\n"}let d=t.H.mkStringLiteral(c);return d.canIndentInside=!0,t.H.namespaceCall(s,a,[d].concat(l),!1)}function z(n,o){let i;const s=[];switch(n.stats[o.type]=(n.stats[o.type]||0)+1,ne(o,s),o.type){case"controls_if":i=function(e,n,o){let i=[];for(let s=0;s<=n.elseifCount_;++s){let a=P(e,v(n,"IF"+s),o),l=$(e,v(n,"DO"+s)),c=t.mkText("if (");s>0&&(c=t.mkText("else if ("),c.glueToBlock=t.GlueMode.WithSpace),r(i,[c,a,t.mkText(")"),l])}if(n.elseCount_){let o=t.mkText("else");o.glueToBlock=t.GlueMode.WithSpace,r(i,[o,$(e,v(n,"ELSE"))])}return i}(n,o,s);break;case"pxt_controls_for":case"controls_for":case"controls_simple_for":i=function(e,n,o){let r=v(n,"TO"),i=v(n,"DO"),s=v(n,"BY"),a=v(n,"FROM"),l=!s||s.type.match(/^math_number/)&&1==B(s),c=L(e,n,b(n).getField("VAR").getText());return[t.mkText("for (let "+c.escapedName+" = "),a?P(e,a,o):t.mkText("0"),t.mkText("; "),t.mkInfix(t.mkText(c.escapedName),"<=",P(e,r,o)),t.mkText("; "),l?t.mkText(c.escapedName+"++"):t.mkInfix(t.mkText(c.escapedName),"+=",P(e,s,o)),t.mkText(")"),$(e,i)]}(n,o,s);break;case"pxt_controls_for_of":case"controls_for_of":i=function(e,n,o){let r=v(n,"LIST"),i=v(n,"DO"),s=L(e,n,b(n).getField("VAR").getText());return[t.mkText("for (let "+s.escapedName+" of "),P(e,r,o),t.mkText(")"),$(e,i)]}(n,o,s);break;case"variables_set":i=[F(n,o,s)];break;case"variables_change":i=[U(n,o,s)];break;case"controls_repeat_ext":i=function(e,n,o){let r=P(e,v(n,"TIMES"),o),i=$(e,v(n,"DO")),s="index";for(let t=2;L(e,n,s);t++)s="index"+t;return[t.mkText("for (let "+s+" = 0; "),t.mkInfix(t.mkText(s),"<",r),t.mkText("; "+s+"++)"),i]}(n,o,s);break;case"device_while":i=function(e,n,o){let r=P(e,v(n,"COND"),o),i=$(e,v(n,"DO"));return[t.mkText("while ("),r,t.mkText(")"),i]}(n,o,s);break;case"procedures_defnoreturn":i=function(e,n,o){const r=M(n.getFieldValue("NAME"),e,!0),i=v(n,"STACK");return[t.mkText("function "+r+"() "),$(e,i)]}(n,o);break;case"function_definition":i=function(e,n,o){const r=M(n.getField("function_name").getText(),e,!0),i=v(n,"STACK"),s=n.getArguments().map((t=>"Array"==t.type?`${M(t.name,e)}: any[]`:`${M(t.name,e)}: ${t.type}`)),a=me(n,!1);return[t.mkText(`function ${r} (${s.join(", ")})${a?": any":""}`),$(e,i)]}(n,o);break;case"procedures_callnoreturn":i=[D(n,o)];break;case"function_call":i=[N(n,o,s,!0)];break;case pxtc.TS_RETURN_STATEMENT_TYPE:i=[w(n,o,s)];break;case ts.pxtc.ON_START_TYPE:i=function(n,o){const r=$(n,v(o,"HANDLER"));return e.appTarget.compile&&e.appTarget.compile.onStartText&&r&&r.children&&r.children.unshift(t.mkStmt(t.mkText(`// ${pxtc.ON_START_COMMENT}\n`))),r}(n,o).children;break;case pxtc.TS_STATEMENT_TYPE:i=function(e,n){return n.getLines().map((e=>t.mkText(e+"\n")))}(0,o);break;case pxtc.PAUSE_UNTIL_TYPE:i=function(n,o,r){const i=e.appTarget.runtime&&e.appTarget.runtime.pauseUntilBlock;e.Util.assert(!!i,"target has block enabled");const s=i.namespace,a=i.callName||"pauseUntil",l=V(n,o,{definitionName:"PREDICATE",actualName:"PREDICATE"},r),c=[t.mkGroup([t.mkText("() => "),l])];return s?[t.mkStmt(t.H.namespaceCall(s,a,c,!1))]:[t.mkStmt(t.H.mkCall(a,c,!1,!1))]}(n,o,s);break;case pxtc.TS_DEBUGGER_TYPE:i=function(e,n){if("1"==n.getFieldValue("ON_OFF"))return[t.mkText("debugger;\n")];return[]}(0,o);break;case pxtc.TS_BREAK_TYPE:i=[t.mkText("break;\n")];break;case pxtc.TS_CONTINUE_TYPE:i=[t.mkText("continue;\n")];break;default:i=n.stdCallTable[o.type]?[H(n,o,s)]:[t.mkStmt(P(n,o,s))]}let a=i[i.length-1];return a&&!a.id&&(a.id=o.id),s.length&&function(e,n){const o=[];for(const n of e)for(const e of n.split("\n"))o.push(t.mkText(`// ${e}`)),o.push(t.mkNewLine());for(const e of o.reverse())n.unshift(e)}(s,i),i.forEach((n=>{!(n.type===t.NT.Block||n.type===t.NT.Prefix&&e.Util.startsWith(n.op,"//"))||o.type==pxtc.ON_START_TYPE&&n.id||(n.id=o.id)})),i}function $(e,n){let o=[],i=n;for(;n;)n.isEnabled()&&r(o,z(e,n)),n=n.getNextBlock();return i&&e.blockDeclarations[i.id]&&e.blockDeclarations[i.id].filter((e=>!e.alreadyDeclared)).forEach((t=>{o.unshift(oe(t,e.blocksInfo)),t.alreadyDeclared=a.Implicit})),t.mkBlock(o)}function X(e){const n=t.mkStmt(t.mkText(";"));return n.glueToBlock=t.GlueMode.NoSpace,t.mkGroup([n,e])}function Y(t,n,o={}){let r=function(e,t){return{workspace:e,options:t,stdCallTable:{},userFunctionReturnValues:{},diagnostics:[],errors:[],renames:{oldToNew:{},takenNames:{},oldToNewFunctions:{}},stats:{},enums:[],kinds:[],idToScope:{},blockDeclarations:{},allVariables:[],blocksInfo:null}}(t,o);return r.blocksInfo=n,n&&(Object.keys(n.apis.byQName).forEach((e=>{const t=n.apis.byQName[e];!t.pkg||6!==t.kind&&3!==t.kind&&5!==t.kind&&4!==t.kind||(r.renames.takenNames[t.qName]=!0)})),n.enumsByName&&Object.keys(n.enumsByName).forEach((e=>r.enums.push(n.enumsByName[e]))),n.kindsByName&&Object.keys(n.kindsByName).forEach((e=>r.kinds.push(n.kindsByName[e]))),n.blocks.forEach((t=>{if(r.stdCallTable[t.attributes.blockId])return void e.reportError("blocks","function already defined",{details:t.attributes.blockId,qualifiedName:t.qName,packageName:t.pkg});r.renames.takenNames[t.namespace]=!0;const n=e.blocks.compileInfo(t),o=!!n.thisParameter;r.stdCallTable[t.attributes.blockId]={namespace:t.namespace,f:t.name,comp:n,attrs:t.attributes,isExtensionMethod:o,isExpression:t.retType&&"void"!==t.retType,imageLiteral:t.attributes.imageLiteral,imageLiteralColumns:t.attributes.imageLiteralColumns,imageLiteralRows:t.attributes.imageLiteralRows,hasHandler:e.blocks.hasHandler(t),property:!t.parameters,isIdentity:"TD_ID"==t.attributes.shim}})),t.getTopBlocks(!1).filter(fe).forEach((e=>{M("procedures_defnoreturn"===e.type?e.getFieldValue("NAME"):e.getField("function_name").getText(),r,!0)}))),r}function J(e,t){if(e.type===ts.pxtc.ON_START_TYPE)return 0;const n=t.stdCallTable[e.type],o=Z(t,e),r=1+ts.pxtc.Util.codalHash16(o);return n&&n.attrs.afterOnStart?r:-r}function q(n,o,i){try{let s=o.getAllBlocks(!1);e.react.getTilemapProject&&e.react.getTilemapProject().removeInactiveBlockAssets(s.map((e=>e.id)));let l=o.getTopBlocks(!0);l=l.sort(((e,t)=>J(e,n)-J(t,n))),function(e,t,n){t.forEach((e=>e.setEnabled(!0)));const o={};function r(e,t){o[e]?ee(t,!1):(ee(t,!0),o[e]=t)}n.forEach((t=>{const n=e.stdCallTable[t.type];if(t.type==ts.pxtc.ON_START_TYPE)r(ts.pxtc.ON_START_TYPE,t);else{if(fe(t)||n&&n.attrs.blockAllowMultiple&&!n.attrs.handlerStatement)return;if(n&&n.hasHandler&&!n.attrs.handlerStatement){r(n.attrs.blockHandlerKey||Z(e,t),t)}else{let e=t;for(;e;)ee(t,!1),e=e.getNextBlock()}}}))}(n,s,l),s=s.filter((e=>e.isEnabled())),l=l.filter((e=>e.isEnabled())),function(e,t){let n,o=1;e.forEach((e=>{if(e.type===ts.pxtc.ON_START_TYPE){const o=e.getInputTargetBlock("HANDLER");o&&(n={firstStatement:o,declaredVars:{},referencedVars:[],children:[],assignedVars:[]},r(o,n,t))}})),n||(n={firstStatement:null,declaredVars:{},referencedVars:[],children:[],assignedVars:[]});return e.forEach((e=>{e.type!==ts.pxtc.ON_START_TYPE&&r(e,n,t)})),Object.keys(n.declaredVars).forEach((e=>{const t=n.declaredVars[e];delete n.declaredVars[e];(ue(n,t.id)||n).declaredVars[e]=t})),ge(n,t),ce(n,t),n;function r(e,t,n){if(n.idToScope[e.id]=t,"variables_get"===e.type){const n=i(e.getField("VAR").getText(),t);t.referencedVars.push(n.id)}else if("variables_set"===e.type||"variables_change"===e.type){const n=i(e.getField("VAR").getText(),t);t.assignedVars.push(n.id),t.referencedVars.push(n.id)}else if(e.type===pxtc.TS_STATEMENT_TYPE){const n=e.declaredVariables;if(n){n.split(",").forEach((e=>{i(e,t).alreadyDeclared=a.Argument}))}}if(function(e){return e.inputList.some((e=>e.type===Blockly.NEXT_STATEMENT))}(e)){const i=function(e,t){switch(e.type){case"pxt_controls_for":case"controls_simple_for":return[[b(e).getField("VAR").getText(),d]];case"pxt_controls_for_of":case"controls_for_of":return[[b(e).getField("VAR").getText(),u(null)]]}if(K(e)){const t=e.mutation.getDeclaredVariables();if(t)return Object.keys(t).map((e=>[e,u(t[e])]))}let n=t.stdCallTable[e.type];if(n&&n.comp.handlerArgs.length)return se(e,n);return[]}(e,n).map((e=>({name:e[0],type:e[1],id:o++})));let s=t;i.length&&(s={parent:t,firstStatement:e,declaredVars:{},referencedVars:[],assignedVars:[],children:[]},i.forEach((e=>{e.alreadyDeclared=a.Assigned,s.declaredVars[e.name]=e})),n.idToScope[e.id]=s),t!==s&&t.children.push(s),pe(e,(e=>{r(e,s,n)})),function(e,t){e.inputList.filter((e=>e.type===Blockly.NEXT_STATEMENT)).forEach((e=>{e.connection&&e.connection.targetBlock()&&t(e.connection.targetBlock())}))}(e,(e=>{const t={parent:s,firstStatement:e,declaredVars:{},referencedVars:[],assignedVars:[],children:[]};s.children.push(t),r(e,t,n)}))}else pe(e,(e=>{r(e,t,n)}));e.nextConnection&&e.nextConnection.targetBlock()&&r(e.nextConnection.targetBlock(),t,n)}function i(e,t){return t.declaredVars[e]?t.declaredVars[e]:t.parent?i(e,t.parent):(t.declaredVars[e]={name:e,type:u(null),id:o++},t.declaredVars[e])}}(l,n),S(s,n);const c=[],p=function(e,t){if(!e.length||e.some((e=>!e.rendered)))return{orphans:t,idToComments:{}};const n=e.map((e=>{const t=e.getBoundingRectangle(),n=e.getHeightWidth();return{id:e.id,x:t.left,y:t.top,width:n.width,height:n.height}})),o={orphans:[],idToComments:{}},r=20;for(const e of t){const t=e.getBoundingRectangle(),i=e.getHeightWidth(),s=t.left,a=t.top;let l;for(const e of n)(he(s,a,i.width,i.height,e)||!l&&he(s-r,a-r,i.width+2*r,i.height+2*r,e))&&(l=e);l?(o.idToComments[l.id]||(o.idToComments[l.id]=[]),o.idToComments[l.id].push(e)):o.orphans.push(e)}return o}(l,o.getTopComments(!0));p.orphans.forEach((e=>r(c,R(e).children))),l.forEach((e=>{if(p.idToComments[e.id]&&p.idToComments[e.id].forEach((e=>{r(c,R(e).children)})),e.type==ts.pxtc.ON_START_TYPE)r(c,z(n,e));else{const o=t.mkBlock(z(n,e));o.type==t.NT.Block?r(c,o.children):c.push(o)}}));const g=[];n.enums.forEach((e=>{const n=o.getVariablesOfType(e.name);if(n&&n.length){const o=n.map((e=>{const t=/^(\d+)([^0-9].*)$/.exec(e.name);return t?[t[2],parseInt(t[1])]:[e.name,-1]}));o.sort(((e,t)=>e[1]-t[1]));const r=[];let i=-1;o.forEach((([n,o],s)=>{let a;if(e.isBitMask){const e=Math.log2(o);e>=0&&Math.floor(e)===e&&(a=t.H.mkAssign(t.mkText(n),t.H.mkSimpleCall("<<",[t.H.mkNumberLiteral(1),t.H.mkNumberLiteral(e)])))}else if(e.isHash){const e=ts.pxtc.Util.codalHash16(n.toLowerCase());a=t.H.mkAssign(t.mkText(n),t.H.mkNumberLiteral(e))}a||(a=o===i+1?t.mkText(n):t.H.mkAssign(t.mkText(n),t.H.mkNumberLiteral(o))),r.push(a),i=o}));const s=t.mkCommaSep(r,!0);s.glueToBlock=t.GlueMode.NoSpace,g.push(t.mkGroup([t.mkText(`enum ${e.name}`),t.mkBlock([s])]))}})),n.kinds.forEach((e=>{const n=o.getVariablesOfType("KIND_"+e.name);if(n&&n.length){const o=n.map((e=>e.name)).filter((t=>-1===e.initialMembers.indexOf(t)));o.length&&g.push(t.mkGroup([t.mkText(`namespace ${e.name}`),t.mkBlock(o.map((n=>t.mkStmt(t.mkText(`export const ${n} = ${e.name}.${e.createFunctionName}()`)))))]))}}));const h=n.allVariables.filter((e=>!e.alreadyDeclared)).map((e=>oe(e,i)));return n.allVariables.filter((e=>e.alreadyDeclared===a.Implicit&&!e.isAssigned)).forEach((e=>{const t=x(e.type);"string"===t.type||"number"===t.type||"boolean"===t.type||y(t.type)||n.diagnostics.push({blockId:e.firstReference&&e.firstReference.id,message:lf("Variable '{0}' is never assigned",e.name)})})),[g.concat(h.concat(c)),n.diagnostics]}catch(e){let t=e.block;if(!t)throw e;t.setWarningText(e+""),n.errors.push(t)}finally{T()}return[null,null]}function Z(e,t){if(t.type==ts.pxtc.ON_START_TYPE)return JSON.stringify({name:ts.pxtc.ON_START_TYPE});if(t.type==ts.pxtc.FUNCTION_DEFINITION_TYPE)return JSON.stringify({type:"function",name:t.getFieldValue("function_name")});return JSON.stringify(Q(t)).replace(/"id"\s*:\s*"[^"]+"/g,"")}function Q(e){const t=[],n=[];for(const o of e.inputList){for(const e of o.fieldRow)e.name&&t.push(e.getText());o.type===Blockly.INPUT_VALUE&&(o.connection.targetBlock()?n.push(Q(o.connection.targetBlock())):n.push(null))}return{type:e.type,fields:t,inputs:n}}function ee(e,t){e.setEnabled(t);const n=e.getDescendants(!1);for(const e of n)e.setEnabled(t)}function te(e,o,r){let i=t.flattenNode(o);return n("format",{format:{input:i.output,pos:1}}).then((()=>({source:i.output,sourceMap:i.sourceMap,stats:e.stats,diagnostics:r||[]})))}function ne(e,t){var n;const o=null===(n=e.getCommentText)||void 0===n?void 0:n.call(e);o&&t.push(o)}function oe(e,n){const o=x(e.type);let r;r="Array"===o.type?t.mkText("[]"):O(o);let i="";if("null"==r.op||"[]"==r.op){let e=o.type;"Array"!==e&&"null[]"!==e||(e="number[]");let s=n.apis.byQName[e];s&&s.attributes.autoCreate?r=t.mkText(s.attributes.autoCreate+"()"):i=": "+e}return t.mkStmt(t.mkText("let "+e.escapedName+i+" = "),r)}function re(e){if(e.mutationToDom){const t=e.mutationToDom();if(t.hasAttribute("_expanded")){const e=parseInt(t.getAttribute("_expanded"));return isNaN(e)?0:Math.max(e,0)}}return 0}function ie({comp:e},t){const n=[];return e.thisParameter&&n.push(e.thisParameter),e.parameters.forEach((e=>{e.isOptional&&t>0?(n.push(e),--t):e.isOptional||n.push(e)})),n}function se(e,t){let n=[];if(t.attrs.draggableParameters)for(let o=0;o<t.comp.handlerArgs.length;o++){const r=t.comp.handlerArgs[o];let i;const s=v(e,"HANDLER_DRAG_PARAM_"+r.name);if(i="reporter"===t.attrs.draggableParameters?s&&s.getFieldValue("VALUE"):s&&s.getField("VAR").getText(),null===i)break;n.push([i,u(r.type)])}else for(let o=0;o<t.comp.handlerArgs.length;o++){const r=t.comp.handlerArgs[o],i=e.getField("HANDLER_"+r.name),s=i&&i.getText();if(null===s)break;n.push([s,u(r.type)])}return n}function ae(e,t){if(-1!==e.referencedVars.indexOf(t))return!0;for(const n of e.children)if(ae(n,t))return!0;return!1}function le(e,t){if(-1!==e.assignedVars.indexOf(t))return!0;for(const n of e.children)if(le(n,t))return!0;return!1}function ce(e,t){for(const t of Object.keys(e.declaredVars)){const o=e.declaredVars[t];o.escapedName||(o.escapedName=n(t))}function n(n){if(!n)return"_";let r=ts.pxtc.escapeIdentifier(n);if(t.renames.takenNames[r]||o(r,e,n)){let i=2;for(;t.renames.takenNames[r+i]||o(r+i,e,n);)i++;r+=i}return r}function o(e,t,n){if(t){for(const o of Object.keys(t.declaredVars)){const r=t.declaredVars[o];if((n!==r.name||r.name!==r.escapedName)&&r.escapedName===e)return!0}return o(e,t.parent,n)}return!1}e.children.forEach((e=>ce(e,t)))}function ue(e,t){let n;if(-1!==e.referencedVars.indexOf(t))return e;for(const o of e.children)if(ae(o,t)){if(le(o,t))return e;if(n)return e;n=o}return n?ue(n,t):void 0}function de(e,t){return t&&t.declaredVars[e]?t.declaredVars[e]:t&&t.parent?de(e,t.parent):null}function pe(e,t,n=!1){e.inputList.filter((e=>e.type===Blockly.INPUT_VALUE)).forEach((e=>{e.connection&&e.connection.targetBlock()&&(t(e.connection.targetBlock()),n&&pe(e.connection.targetBlock(),t,n))}))}function ge(e,t){const n=Object.keys(e.declaredVars);if(n.length){const o=n.map((t=>e.declaredVars[t]));e.firstStatement&&(t.blockDeclarations[e.firstStatement.id]=o.concat(t.blockDeclarations[e.firstStatement.id]||[])),o.forEach((e=>t.allVariables.push(e)))}e.children.forEach((e=>ge(e,t)))}function he(e,t,n,o,r){const i=a(e,r.x,r.x+r.width)||a(r.x,e,e+n),s=a(t,r.y,r.y+r.height)||a(r.y,t,t+o);return i&&s;function a(e,t,n){return e>=t&&e<=n}}function fe(e){return"procedures_defnoreturn"===e.type||"function_definition"===e.type}function _e(e){return e.getField("function_name").getText()}function me(e,t){const n=_e(e),o={};return function e(r){let i;i=t?r.getDescendants(!1).filter((e=>"function_return"==e.type)).map((e=>v(e,"RETURN_VALUE"))).filter((e=>e&&"function_call_output"===e.type)):r.getDescendants(!1).filter((e=>"function_call_output"==e.type));for(const t of i){const r=_e(t);if(r===n)return!0;if(!o[r]&&(o[r]=!0,e(Blockly.Functions.getDefinition(r,t.workspace))))return!0}return!1}(e)}t.compileExpression=P,t.escapeVarName=M,t.mkEnv=Y,t.compileBlockAsync=function(e,t){const n=e.workspace,o=Y(n,t);S(n&&n.getAllBlocks(!1),o);const r=z(o,e);return T(),te(o,r)},t.callKey=Z,t.findBlockIdByPosition=function(e,t){if(!t)return;let n,o;for(let r=0;r<e.length;++r){let i=e[r];i.startPos<=t.start&&i.endPos>=t.start+t.length&&(!n||o>i.endPos-i.startPos)&&(n=i,o=i.endPos-i.startPos)}return n?n.id:void 0},t.findBlockIdByLine=function(e,t){if(!t)return;let n,o;for(let r=0;r<e.length;++r){let i=e[r];i.startLine<=t.start&&i.endLine>t.start+t.length&&(!n||o>i.endLine-i.startLine)&&(n=i,o=i.endLine-i.startLine)}return n?n.id:void 0},t.compileAsync=function(e,t,n={}){const o=Y(e,t,n),[r,i]=q(o,e,t);return te(o,r,i)}}(e.blocks||(e.blocks={}))}(pxt||(pxt={})),function(e){!function(t){let n={};function o(e,t,o){null==n[e]&&(n[e]={field:t,validator:o})}t.initFieldEditors=function(){o("text",pxtblockly.FieldTextInput),o("note",pxtblockly.FieldNote),o("gridpicker",pxtblockly.FieldGridPicker),o("textdropdown",pxtblockly.FieldTextDropdown),o("numberdropdown",pxtblockly.FieldNumberDropdown),o("imagedropdown",pxtblockly.FieldImageDropdown),o("colorwheel",pxtblockly.FieldColorWheel),o("toggle",pxtblockly.FieldToggle),o("toggleonoff",pxtblockly.FieldToggleOnOff),o("toggleyesno",pxtblockly.FieldToggleYesNo),o("toggleupdown",pxtblockly.FieldToggleUpDown),o("toggledownup",pxtblockly.FieldToggleDownUp),o("togglehighlow",pxtblockly.FieldToggleHighLow),o("togglewinlose",pxtblockly.FieldToggleWinLose),o("colornumber",pxtblockly.FieldColorNumber),o("images",pxtblockly.FieldImages),o("sprite",pxtblockly.FieldSpriteEditor),o("animation",pxtblockly.FieldAnimationEditor),o("tilemap",pxtblockly.FieldTilemap),o("tileset",pxtblockly.FieldTileset),o("speed",pxtblockly.FieldSpeed),o("turnratio",pxtblockly.FieldTurnRatio),o("protractor",pxtblockly.FieldProtractor),o("position",pxtblockly.FieldPosition),o("melody",pxtblockly.FieldCustomMelody)},t.registerFieldEditor=o,t.createFieldEditor=function(t,o,r){if(null==n[t])return console.error(`Field editor ${t} not registered`),null;r||(r={}),e.Util.assert(null==r.lightMode,"lightMode is a reserved parameter for custom fields"),r.lightMode=e.options.light;let i=n[t];return new i.field(o,r,i.validator)}}(e.blocks||(e.blocks={}))}(pxt||(pxt={})),function(e){!function(t){t.needsDecompiledDiff=function(e,t){if(!e||!t)return!1;const n={};if(e.replace(/id="([^"]+)"/g,((e,t)=>(n[t]=!0,""))),!Object.keys(n).length)return!1;let o=0,r=0;return t.replace(/id="([^"]+)"/g,((e,t)=>(o++,n[t]&&r++,""))),o>0&&0==r},t.diffXml=function(t,n,r){return o(e.blocks.loadWorkspaceXml(t,!0),e.blocks.loadWorkspaceXml(n,!0),r)};const n="#d0d0d0";function o(o,s,a){try{return Blockly.Events.disable(),function(o,s,a){e.tickEvent("blocks.diff",{started:1}),a=a||{};const l=r();if(!o)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=e.Util.toDictionary(o.getTopBlocks(!1),(e=>i(e,!0)));s.getTopBlocks(!1).forEach((e=>{const t=i(e,!0),n=o.getBlockById(e.id)||c[t];if(n){t==i(n,!0)&&(l("fast unmodified top ",e.id),e.dispose(!1),n.dispose(!1))}}));const u=o.getAllBlocks(!1).filter((e=>e.isEnabled())),d=o.getTopBlocks(!1).filter((e=>e.isEnabled())),p=s.getAllBlocks(!1).filter((e=>e.isEnabled()));if(l("blocks",p.map((e=>e.toDevString()))),l(p),0==u.length&&0==p.length)return e.tickEvent("blocks.diff",{moves:1}),{ws:void 0,message:lf("Some blocks were moved or changed."),added:0,deleted:0,modified:1};const g=d.filter((e=>!s.getBlockById(e.id))),h=u.filter((e=>!s.getBlockById(e.id))),f=p.filter((e=>!o.getBlockById(e.id))),_=e.blocks.initRenderingWorkspace(),m=e.blocks.saveWorkspaceXml(s,!0);e.blocks.domToWorkspaceNoEvents(Blockly.Xml.textToDom(m),_),_.getAllBlocks(!1).filter((e=>!e.isEnabled())).forEach((e=>{l("disabled ",e.toDevString()),e.dispose(!1)}));const y=e.Util.toDictionary(_.getAllBlocks(!1),(e=>e.id));l("todo blocks",y),D("start"),a.hideDeletedTopBlocks||(g.forEach((e=>{l(`deleted top ${e.toDevString()}`),A(e);const t=x(e);A(t),t.setEnabled(!1)})),D("deleted top"));f.map((e=>_.getBlockById(e.id))).filter((e=>!!e)).forEach((e=>{l(`added ${e.toDevString()}`),A(e)})),D("added");const k={};if(!a.hideDeletedBlocks){const e=h.filter((e=>!(y[e.id]||C(e)||e.outputConnection&&e.outputConnection.isConnected())));e.forEach((e=>{const t=x(e);k[e.id]=t.id,l(`deleted block ${e.toDevString()}->${t.toDevString()}`)})),e.forEach((e=>E(e)))}let b=0;if(e.Util.values(y).filter((e=>N(e))).forEach((e=>{l(`moved ${e.toDevString()}`),delete y[e.id],S(e),b++})),D("moved"),e.Util.values(y).filter((e=>w(e))).forEach((e=>{l(`changed ${e.toDevString()}`),delete y[e.id],S(e),b++})),D("changed"),_.getTopBlocks(!1).forEach((e=>{I(e)||(l(`unmodified top ${e.toDevString()}`),delete y[e.id],e.dispose(!1))})),D("cleaned"),e.Util.values(y).filter((e=>!!_.getBlockById(e.id))).forEach((e=>{R(e)})),D("unmodified"),!_.getAllBlocks(!1).length)return e.tickEvent("blocks.diff",{missed:1}),{ws:_,message:lf("Some blocks were changed."),deleted:h.length,added:f.length,modified:b};_.resize(),Blockly.svgResize(_);const v=e.blocks.renderWorkspace(a.renderOptions||{emPixels:20,layout:t.BlockLayout.Flow,aspectRatio:.5,useViewWidth:!0}),T={ws:_,svg:v,deleted:h.length,added:f.length,modified:b};return e.tickEvent("blocks.diff",{deleted:T.deleted,added:T.added,modified:T.modified}),T;function E(e){l(`stitching ${e.toDevString()}->${k[e.id]}`);const t=_.getBlockById(k[e.id]);t.setEnabled(!1),S(t),A(t);const n=e.getPreviousBlock();if(n){const o=_.getBlockById(k[n.id])||_.getBlockById(n.id);if(l(`previous ${e.id}->${t.toDevString()}: ${o.toDevString()}`),o)if(o.nextConnection)t.previousConnection.connect(o.nextConnection);else{const e=o.inputList.slice().reverse().find((e=>e.connection&&e.connection.type==Blockly.NEXT_STATEMENT));e&&t.previousConnection.connect(e.connection)}}const o=e.getNextBlock();if(o){const n=_.getBlockById(k[o.id])||_.getBlockById(o.id);n&&(l(`next ${e.id}->${t.toDevString()}: ${n.toDevString()}`),t.nextConnection.connect(n.previousConnection))}}function S(e){e.__pxt_used=!0}function C(e){return!!e.__pxt_used}function x(e){const t=Blockly.Xml.blockToDom(e,!1),n=Blockly.Xml.domToBlock(t,_);return n.nextConnection&&n.nextConnection.targetConnection&&n.nextConnection.disconnect(),n.previousConnection&&n.previousConnection.targetConnection&&n.previousConnection.disconnect(),n}function B(e){e.rendered=!1,e.inputList.forEach((t=>t.fieldRow.forEach((t=>{t.init(),t.borderRect_&&(t.borderRect_.setAttribute("fill",e.getColour()),t.borderRect_.setAttribute("stroke",e.getColourTertiary()))}))))}function A(e){e.getDescendants(!1).forEach((e=>{delete y[e.id],S(e)}))}function I(e){return!!e.getDescendants(!1).find((e=>C(e)))}function D(t){l(`${t}:`,e.Util.values(y).map((e=>e.toDevString())))}function N(e){const t=o.getBlockById(e.id);if(!t)return!1;const n=e.getPreviousBlock();if(n&&!y[n.id])return!1;const r=e.getNextBlock();if(r&&!y[r.id])return!1;const i=t.getPreviousBlock();if(!i&&!n)return!1;if(!!i!=!!n||i.id!=n.id)return!0;const s=t.getNextBlock();return!(!s&&!r)&&(!!s!=!!r||s.id!=r.id)}function w(e){let t=o.getBlockById(e.id);if(!t)return!1;const n=i(t),r=i(e);return n!=r&&(l(`old ${t.toDevString()}`,n),l(`new ${e.toDevString()}`,r),!0)}function R(e){e.setColour(n),B(e),a.statementsOnly&&(e.inputList||[]).map((e=>e.type==Blockly.INPUT_VALUE&&e.connection&&e.connection.targetBlock())).filter((e=>!!e)).forEach((e=>R(e)))}}(o,s,a)}catch(t){return e.reportException(t),{ws:void 0,message:lf("Oops, we could not diff those blocks."),error:t,deleted:0,added:0,modified:0}}finally{Blockly.Events.enable()}}function r(){return e.options.debug||window&&/diffdbg=1/.test(window.location.href)?console.log:(e,...t)=>{}}function i(e,t){const n=Blockly.Xml.blockToDom(e,!0);return s(n),a(n,(e=>{s(e),t||("next"==e.localName||"statement"==e.localName||"shadow"==e.localName)&&e.remove()})),Blockly.Xml.domToText(n)}function s(e){e.removeAttribute("id"),e.removeAttribute("x"),e.removeAttribute("y"),e.removeAttribute("deletable"),e.removeAttribute("editable"),e.removeAttribute("movable")}function a(t,n){if(t){n(t);for(const o of e.Util.toArray(t.children))a(o,n)}}t.mergeXml=function(e,t,n){return e==t?n:n==t?e:void 0},t.decompiledDiffAsync=function(t,n,i,s,a={}){const l=r(),c=n.outfiles[e.MAIN_BLOCKS];let u=s.outfiles[e.MAIN_BLOCKS];l(c),l(u);const d=e.diff.compute(t,i,{ignoreWhitespace:!0,full:!0});l(d);const p={};let g=0,h=0;d.forEach(((t,o)=>{const r=t[0],i=t.substr(2);let a=i.length;switch(r){case"-":g+=a+1;break;case"+":h+=a+1;break;default:const o=/^\s+/.exec(i);if(o){const e=o[0].length;g+=e,h+=e,a-=e}const r=e.blocks.findBlockIdByPosition(s.blockSourceMap,{start:h,length:a});if(r&&!p[r]){const o=e.blocks.findBlockIdByPosition(n.blockSourceMap,{start:g,length:a});o&&(l(t),l(`id ${g}:${i.length}>${o} ==> ${h}:${i.length}>${r}`),p[r]=o,u=u.replace(r,o))}g+=a+1,h+=a+1}}));const f=e.blocks.loadWorkspaceXml(c,!0),_=e.blocks.loadWorkspaceXml(u,!0);return a.statementsOnly=!0,o(f,_,a)}}(e.blocks||(e.blocks={}))}(pxt||(pxt={})),function(e){!function(t){function n(e,t){const n=[];for(let o=0;o<e.childNodes.length;o++){const r=e.childNodes.item(o);r.tagName===t&&n.push(r)}return n}function o(e,t){return r(e,"block","type",t).concat(r(e,"shadow","type",t))}function r(t,n,o,r){return e.Util.toArray(t.getElementsByTagName(n)).filter((e=>e.getAttribute(o)===r))}function i(e,t,n,o){const i=r(e,t,n,o);return i.length?i[0]:void 0}function s(e,n,o){var r;let s=o.getAttribute("type"),a=Blockly.Blocks[s],l=t.blockSymbol(s);if(!l||!a)return;let c=t.compileInfo(l);null===(r=l.parameters)||void 0===r||r.forEach(((t,r)=>{let s=e.apis.byQName[t.type];if(s&&6==s.kind){let e=i(o,"field","name",c.actualNameToParam[t.name].definitionName);if(e){let t=n[s.name+"."+e.textContent];t&&(e.textContent=t)}}}))}t.domToWorkspaceNoEvents=function(t,n){e.tickEvent("blocks.domtow");let o=[];try{Blockly.Events.disable(),o=Blockly.Xml.domToWorkspace(t,n),function(e){e.getAllBlocks(!1).filter((e=>!!e.getCommentText())).forEach((t=>{var n,o;const r=t.getCommentText();if(/@highlight/.test(r)){const i=r.replace(/@highlight/g,"").trim();t.setCommentText(i||null),null===(o=(n=e).highlightBlock)||void 0===o||o.call(n,t.id)}}))}(n)}catch(t){e.reportException(t)}finally{Blockly.Events.enable()}return o},t.clearWithoutEvents=function(t){if(e.tickEvent("blocks.clear"),t)try{Blockly.Events.disable(),t.clear(),t.clearUndo()}finally{Blockly.Events.enable()}},t.saveWorkspaceXml=function(e,t){const n=Blockly.Xml.workspaceToDom(e,!t);return Blockly.Xml.domToText(n)},t.saveBlocksXml=function(e,t){return e.getTopBlocks(!1).map((e=>Blockly.Xml.domToText(Blockly.Xml.blockToDom(e,!t))))},t.getDirectChildren=n,t.getBlocksWithType=o,t.getChildrenWithAttr=r,t.getFirstChildWithAttr=i,t.loadBlocksXml=function(e,t){let n=Blockly.Xml.textToDom(t),o=Blockly.Xml.domToBlock(n,e);if(e.getMetrics){let t=e.getMetrics(),n=o.getHeightWidth();o.moveBy(t.viewLeft+t.viewWidth/2-n.width/2,t.viewTop+t.viewHeight/2-n.height/2)}},t.loadWorkspaceXml=function(t,n=!1){const o=new Blockly.Workspace;try{const n=Blockly.Xml.textToDom(t);return e.blocks.domToWorkspaceNoEvents(n,o),o}catch(t){return n||e.reportException(t),null}},t.importXml=function(i,a,l,c=!1){try{e.blocks.initializeAndInject(l);const c=(new DOMParser).parseFromString(a,"application/xml"),d=e.patching.computePatches(i);d&&(d.filter((e=>"blockId"==e.type)).forEach((t=>Object.keys(t.map).forEach((n=>{o(c,n).forEach((o=>{o.setAttribute("type",t.map[n]),e.debug(`patched block ${n} -> ${t.map[n]}`)}))})))),d.filter((e=>"blockValue"==e.type)).forEach((t=>Object.keys(t.map).forEach((r=>{const i=r.split("."),s=i[0];i[1];o(c,s).reduce(((e,t)=>e.concat(n(t,"value"))),[]).forEach((n=>{n.setAttribute("name",t.map[r]),e.debug(`patched block value ${r} -> ${t.map[r]}`)}))})))),d.filter((e=>"userenum"==e.type)).forEach((t=>Object.keys(t.map).forEach((n=>{r(c,"variable","type",n).forEach((o=>{o.setAttribute("type",t.map[n]),e.debug(`patched enum variable type ${n} -> ${t.map[n]}`)}))})))));const p=n(c.children.item(0),"shadow");for(const e of p){const t=c.createElement("block");e.getAttributeNames().forEach((n=>t.setAttribute(n,e.getAttribute(n))));for(let n=0;n<e.childNodes.length;n++)t.appendChild(e.childNodes.item(n));e.replaceWith(t)}const g={};Object.keys(l.apis.byQName).forEach((e=>{let t=l.apis.byQName[e];7==t.kind&&(g[t.namespace+"."+(t.attributes.blockImportId||t.attributes.block||t.attributes.blockId||t.name)]=t.namespace+"."+t.name)}));const h=c.getElementsByTagName("block");for(let e=0;e<h.length;++e)s(l,g,h[e]);return function(n,r){const i=o(n,ts.pxtc.ON_START_TYPE);let s=i.length?i[0]:void 0;if(s)return void s.removeAttribute("deletable");let a=[];const l=r.blocksById;let c,u=n.firstElementChild;for(;u;){const o=u.nextElementSibling,r=u.getAttribute("type");if(!u.getAttribute("disabled")&&!u.getElementsByTagName("statement").length&&(e.blocks.buildinBlockStatements[r]||l[r]&&"void"==l[r].retType&&!t.hasArrowFunction(l[r])))if(c){const e=n.ownerDocument.createElement("next");e.appendChild(u),c.appendChild(e),u.removeAttribute("x"),u.removeAttribute("y"),c=u}else c=n.ownerDocument.createElement("statement"),c.setAttribute("name","HANDLER"),s||(s=n.ownerDocument.createElement("block"),s.setAttribute("type",ts.pxtc.ON_START_TYPE),a.push(s)),s.appendChild(c),c.appendChild(u),u.removeAttribute("x"),u.removeAttribute("y"),c=u;u=o}a.forEach((e=>n.appendChild(e)))}(c.documentElement,l),u=c.documentElement,e.U.toArray(u.querySelectorAll("block[type=procedures_defnoreturn]")).forEach((e=>{e.setAttribute("type","function_definition"),e.querySelector("field[name=NAME]").setAttribute("name","function_name")})),e.U.toArray(u.querySelectorAll("block[type=procedures_callnoreturn]")).forEach((e=>{e.setAttribute("type","function_call"),e.querySelector("field[name=NAME]").setAttribute("name","function_name")})),e.blocks.extensionBlocklyPatch&&e.blocks.extensionBlocklyPatch(i,c.documentElement),(new XMLSerializer).serializeToString(c)}catch(t){return c||e.reportException(t),a}var u}}(e.blocks||(e.blocks={}))}(pxt||(pxt={})),function(e){var t;(function(n){n.patchBlocksFromOldWorkspace=function(t,n,o){const r=e.blocks.loadWorkspaceXml(o,!0);return function(t,n,o){let r,i;n.getTopBlocks(!1).filter((e=>e.isEnabled())).forEach((s=>{const a=s.xy_;if(a&&0!=a.x&&0!=a.y){r||(r=e.blocks.mkEnv(n,t),i={},o.getTopBlocks(!1).forEach((t=>{const n=e.blocks.callKey(r,t),o=i[n]||[];o.push(t),i[n]=o})));const l=e.blocks.callKey(r,s),c=(i[l]||[]).shift();c&&(c.xy_=a.clone())}}))}(t,n,r),function(t,n){const o=Blockly.Xml.workspaceToDom(t,!0),r=Blockly.Xml.workspaceToDom(n,!0);return e.Util.toArray(o.childNodes).filter((e=>e.nodeType==Node.ELEMENT_NODE&&"block"==e.localName&&"true"==e.getAttribute("disabled"))).forEach((e=>r.appendChild(r.ownerDocument.importNode(e,!0)))),Blockly.Xml.domToText(r)}(n,r)},n.splitSvg=function(t,n,o=18){const r=n.getTopComments(!0),i=n.getTopBlocks(!0);if(r.length+i.length<2)return t;const s=document.createElement("div");function a(n,r,i,a,l,c){const u=t.cloneNode(!0),d=u.querySelector(`g.blocklyWorkspace > g.${n}`),p=u.querySelector(`g.blocklyWorkspace > g.${r}`),g=e.Util.toArray(d.querySelectorAll(`g.blocklyWorkspace > g.${n} > ${c?"."+c:"g[transform]"}`)),h=g.splice(i,1)[0];if(!h)return void e.log("missing block, did block failed to load?");g.filter((e=>e!=h)).forEach((e=>{e.parentNode.removeChild(e)})),d.removeAttribute("transform"),p.parentNode.removeChild(p),h.setAttribute("transform",`translate(${l.x}, ${l.y})`);const f=a.width/o+"em",_=a.height/o+"em";u.setAttribute("viewBox",`0 0 ${a.width} ${a.height}`),u.style.width=f,u.style.height=_,u.setAttribute("width",f),u.setAttribute("height",_),s.appendChild(u)}return s.className=`blocks-svg-list ${n.getInjectionDiv().className}`,r.forEach(((e,t)=>a("blocklyBubbleCanvas","blocklyBlockCanvas",t,e.getHeightWidth(),{x:0,y:0},"blocklyComment"))),i.forEach(((e,t)=>{const n=e.getHeightWidth(),r={x:0,y:0};e.getStartHat()&&(n.height+=o,r.y+=o),a("blocklyBlockCanvas","blocklyBubbleCanvas",t,n,r)})),s},n.verticalAlign=function(e,t){let n=0;e.getTopComments(!0).forEach((e=>{e.moveBy(0,n),n+=e.getHeightWidth().height,n+=t})),e.getTopBlocks(!0).forEach(((e,o)=>{e.getStartHat()&&(n+=t),e.moveBy(0,n),n+=e.getHeightWidth().height,n+=t}))},n.setCollapsedAll=function(e,t){e.getTopBlocks(!1).filter((e=>e.isEnabled())).forEach((e=>e.setCollapsed(t)))};const o=20;function r(t,n,o){let r;o&&(r={target:e.appTarget.id,versions:e.appTarget.versions,xml:e.blocks.saveBlocksXml(t).map((t=>e.Util.htmlEscape(t)))});const i=0|n||4;return a(t,i).then((t=>t?e.BrowserUtils.encodeToPngAsync(t.xml,{width:t.width,height:t.height,pixelDensity:i,text:o?JSON.stringify(r,null,2):null}):Promise.resolve(void 0))).catch((t=>{e.reportException(t)}))}n.flow=function(e,t){if(t){if(t.useViewWidth){const t=e.getMetrics();if(t.viewHeight>t.viewWidth)return f(e.getTopComments(!0),e.getTopBlocks(!0),void 0,t.viewWidth),void e.scroll(o,20)}f(e.getTopComments(!0),e.getTopBlocks(!0),t.ratio)}else f(e.getTopComments(!0),e.getTopBlocks(!0));e.scroll(o,20)},n.screenshotEnabled=function(){return!e.BrowserUtils.isIE()&&!e.BrowserUtils.isUwpEdge()},n.screenshotAsync=function(e,t,n){return r(e,t,n)},n.toPngAsync=r;const i="http://www.w3.org/1999/xlink",s=12e7;function a(e,t){if(!e)return Promise.resolve(void 0);const n=e.getBlocksBoundingBox(),o=e.getParentSvg().cloneNode(!0);u(o);let r=n.right-n.left,i=n.bottom-n.top,a=1;const l=r*i*Math.pow(t,2);return l>s&&(a=Math.sqrt(s/l)),d(o,n.left,n.top,r,i,a)}function l(e){return c((new XMLSerializer).serializeToString(e))}function c(e){return e.replace(new RegExp(" ","g")," ")}function u(t){e.BrowserUtils.removeClass(t,"blocklySvg"),e.BrowserUtils.addClass(t,"blocklyPreview pxt-renderer classic-theme"),e.U.toArray(t.querySelectorAll(".blocklyMainBackground,.blocklyScrollbarBackground")).forEach((e=>{e&&e.parentNode.removeChild(e)})),e.U.toArray(t.querySelectorAll(".blocklyConnectionIndicator,.blocklyInputConnectionIndicator")).forEach((e=>{e&&e.parentNode.removeChild(e)})),t.removeAttribute("width"),t.removeAttribute("height"),e.U.toArray(t.querySelectorAll(".blocklyBlockCanvas,.blocklyBubbleCanvas")).forEach((e=>e.removeAttribute("transform")));const n=new DOMParser;return e.U.toArray(t.querySelectorAll(".blocklyCommentTextarea")).forEach((t=>{const o=n.parseFromString("<!doctype html><body>"+e.docs.html2Quote(t.value),"text/html");t.textContent=o.body.textContent})),t}function d(t,n,o,r,s,a){if(!t.childNodes[0])return Promise.resolve(void 0);t.removeAttribute("width"),t.removeAttribute("height"),t.removeAttribute("transform");let c=Math.round(r*(a||1)),u=Math.round(s*(a||1));const d=l(t).replace(/^\s*<svg[^>]+>/i,"").replace(/<\/svg>\s*$/i,""),f=`<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="${i}" width="${c}" height="${u}" viewBox="${n} ${o} ${r} ${s}" class="pxt-renderer">${d}</svg>`,_=(new DOMParser).parseFromString(f,"image/svg+xml"),m=_.createElementNS("http://www.w3.org/1999/xhtml","style"),y=e.Util.isUserLanguageRtl(),k=document.getElementById(`style-${y?"rtl":""}blockly.css`).href,b=e.Util.toArray(document.head.getElementsByTagName("link")).filter((t=>e.Util.endsWith(t.getAttribute("href"),"semantic.css")))[0].href;return Promise.all([e.BrowserUtils.loadAjaxAsync(k),e.BrowserUtils.loadAjaxAsync(b)]).then((t=>{var n,o;const r=e.Util.toArray(document.head.querySelectorAll("style")).filter((e=>/\.blocklySvg/.test(e.innerText)))[0];t.unshift((null===(n=document.getElementById("blockly-common-style"))||void 0===n?void 0:n.innerText)||""),t.unshift((null===(o=document.getElementById("blockly-renderer-style-pxt"))||void 0===o?void 0:o.innerText)||"");const s=(r?r.innerText:"")+"\n\n"+t.map((e=>e+"\n\n"));return m.appendChild(_.createCDATASection(s)),_.documentElement.insertBefore(m,_.documentElement.firstElementChild),function(t){g||(g={});const n=t.getElementsByTagName("image"),o=e.Util.toArray(n).filter((e=>{const t=e.getAttributeNS(i,"href");return t&&!/^data:/.test(t)})).map((e=>e)).map((t=>{const n=t.getAttributeNS(i,"href");let o=g[n];return(o?Promise.resolve(g[n]):e.BrowserUtils.loadImageAsync(t.getAttributeNS(i,"href")).then((e=>{const t=document.createElement("canvas"),r=t.getContext("2d");let i=e.width,s=e.height;return t.width=i,t.height=s,r.drawImage(e,0,0,i,s,0,0,t.width,t.height),g[n]=o=t.toDataURL("image/png"),o})).catch((t=>(e.debug(`svg render: failed to load ${n}`),"")))).then((e=>{t.setAttributeNS(i,"href",e)}))}));return Promise.all(o).then((()=>{}))}(_).then((()=>function(t){if(h||(h={}),!e.BrowserUtils.isEdge())return Promise.resolve();const n=t.getElementsByTagName("image"),o=e.Util.toArray(n).filter((e=>/^data:image\/svg\+xml/.test(e.getAttributeNS(i,"href")))).map((e=>e)).map((t=>{const n=t.getAttributeNS(i,"href"),o=parseInt(t.getAttribute("width").replace(/[^0-9]/g,"")),r=parseInt(t.getAttribute("height").replace(/[^0-9]/g,""));let s=h[n];return(s?Promise.resolve(s):e.BrowserUtils.encodeToPngAsync(n,{width:o,height:r,pixelDensity:2})).then((e=>{h[n]=e,t.setAttributeNS(i,"href",e)}))}));return Promise.all(o).then((()=>{}))}(_))).then((()=>({width:c,height:u,svg:l(_).replace('<style xmlns="http://www.w3.org/1999/xhtml">',"<style>"),xml:p(_),css:s})))}))}function p(e){const t=(new XMLSerializer).serializeToString(e);return"data:image/svg+xml;base64,"+ts.pxtc.encodeBase64(unescape(encodeURIComponent(t)))}let g,h;function f(e,n,r=1.62,i){const s=[],a={};let l;e.forEach((e=>{const t=e.data;null!=t&&(a[t]=e)})),n.sort(((e,t)=>e.isEnabled()===t.isEnabled()?e.type===t.type?0:"function_definition"===e.type?1:"function_definition"===t.type?-1:e.type.localeCompare(t.type):e.isEnabled()?-1:1)),n.forEach((e=>{const n=t.getBlockData(e).commentRefs;if(n.length){const t=[];for(let e=0;e<n.length;e++){const o=a[n[e]];o&&(t.push(_(o)),delete a[n[e]])}if(t.length)return void s.push({value:e,width:-1,height:-1,children:t})}const o=_(e);!l&&e.isEnabled()&&e.type===pxtc.ON_START_TYPE?l=o:s.push(o)})),l&&s.unshift(l),Object.keys(a).sort(((e,t)=>e.length===t.length?e>t?-1:1:e.length>t.length?-1:1)).forEach((e=>{a[e]&&s.push(_(a[e]))})),e.forEach((e=>{null==e.data&&s.push(_(e))}));let c,u=0;for(let e=0;e<s.length;e++){const t=s[e];if(t.children){const e=t.value.getHeightWidth();t.x=0,t.y=0;let n=e.width+13,o=0;for(let e=0;e<t.children.length;e++){const r=t.children[e];r.x=n,r.y=o,o+=r.height+13,t.width=Math.max(t.width,n+r.width)}t.height=Math.max(o-13,e.height)}u+=(t.height+13)*(t.width+13)}c=i>o?i-o:Math.sqrt(u)*r;let d=o,p=20,g=0;for(let e=0;e<s.length;e++){const t=s[e];if(t.children){h(t,d+t.x,p+t.y);for(let e=0;e<t.children.length;e++){const n=t.children[e];h(n,d+n.x,p+n.y)}}else h(t,d,p);d+=t.width+45,g=Math.max(g,p+t.height+45),d>c&&(d=o,p=g)}function h(e,t,n){const o=e.value.getBoundingRectangle();e.value.moveBy(t-o.left,n-o.top)}}function _(e){const t=e.getHeightWidth();return{value:e,height:t.height,width:t.width}}n.toSvgAsync=a,n.serializeNode=l,n.serializeSvgString=c,n.cleanUpBlocklySvg=u,n.blocklyToSvgAsync=d,n.documentToSvg=p})((t=e.blocks||(e.blocks={})).layout||(t.layout={}))}(pxt||(pxt={})),function(e){!function(t){const n={string:{field:"TEXT",block:"text",defaultValue:""},number:{field:"NUM",block:"math_number",defaultValue:"0"},boolean:{field:"BOOL",block:"logic_boolean",defaultValue:"false"},Array:{field:"VAR",block:"variables_get",defaultValue:"list"}};function o(e){let t=/^(?:Array<(.+)>)|(?:(.+)\[\])|(?:\[.+\])$/.exec(e);return t?t[1]?t[1]:t[2]:void 0}t.optionalDummyInputPrefix="0_optional_dummy",t.optionalInputWithFieldPrefix="0_optional_field",t.isArrayType=o,t.isTupleType=function(e){let t=/^\[(.+)\]$/.exec(e);return t?t[1].split(/,\s*/):void 0};const r=/^(string|number|boolean)$/;let i,s;function a(){return i||(i={},Object.keys(Blockly.Blocks).forEach((e=>i[e]={block:Blockly.Blocks[e]}))),i}t.builtinBlocks=a,t.buildinBlockStatements={controls_if:!0,controls_for:!0,pxt_controls_for:!0,controls_simple_for:!0,controls_repeat_ext:!0,pxt_controls_for_of:!0,controls_for_of:!0,variables_set:!0,variables_change:!0,device_while:!0};let l={};function c(e,t,r,i){let s;if(i=i||t.defaultValue,!(r=r||t.shadowBlockId)&&t.range&&(r="math_number_minmax"),s=i&&'"'==i.slice(0,1)?JSON.parse(i):i,"number"==t.type&&"value"==r){const e=document.createElement("field");return e.setAttribute("name",t.definitionName),e.appendChild(document.createTextNode("0")),e}const a="variables_get"==r,l="text"==r,c=document.createElement("value");c.setAttribute("name",t.definitionName);const d=o(t.type),p=document.createElement(a||d?"block":"shadow");c.appendChild(p);const g=n[d||t.type];if(p.setAttribute("type",r||(d?"lists_create_with":g&&g.block||t.type)),p.setAttribute("colour",Blockly.Colours.textField),d){if(g&&!r){let e;switch(d){case"number":e=["0","1"];break;case"string":e=["a","b","c"];break;case"boolean":e=["FALSE","FALSE","FALSE"]}return u(p,g.block,g.field,e),c}if(r&&s)return u(p,s),c}if(!g||r&&g.block!==r&&"math_number_minmax"!==r){if(s){const n=document.createElement("field");if(n.textContent=s,a)n.setAttribute("name","VAR"),p.appendChild(n);else if(l)n.setAttribute("name","TEXT"),p.appendChild(n);else if(r){const t=e.blocksById[r];if(t&&t.attributes._def&&t.attributes._def.parameters.length){const e=t.attributes._def.parameters[0];n.setAttribute("name",e.name),p.appendChild(n)}}else n.setAttribute("name",t.definitionName),p.appendChild(n)}}else{const e=document.createElement("field");let n,o;switch(p.appendChild(e),r){case"variables_get":n="VAR";break;case"math_number_minmax":n="SLIDER";break;default:n=g.field}e.setAttribute("name",n),o="boolean"==t.type?document.createTextNode((s||g.defaultValue).toUpperCase()):document.createTextNode(s||g.defaultValue),e.appendChild(o)}let h;return t.range&&(h=document.createElement("mutation"),h.setAttribute("min",t.range.min.toString()),h.setAttribute("max",t.range.max.toString()),h.setAttribute("label",t.actualName.charAt(0).toUpperCase()+t.actualName.slice(1)),t.fieldOptions&&(t.fieldOptions.step&&h.setAttribute("step",t.fieldOptions.step),t.fieldOptions.color&&h.setAttribute("color",t.fieldOptions.color),t.fieldOptions.precision&&h.setAttribute("precision",t.fieldOptions.precision))),t.fieldOptions&&(h||(h=document.createElement("mutation")),h.setAttribute("customfield",JSON.stringify(t.fieldOptions))),h&&p.appendChild(h),c}function u(e,t,n,o){const r=o?o.length:2,i=document.createElement("mutation");i.setAttribute("items",""+r),i.setAttribute("horizontalafter",""+r),e.appendChild(i);for(let i=0;i<r;i++){const r=document.createElement("value");r.setAttribute("name","ADD"+i);const s=document.createElement("shadow");if(s.setAttribute("type",t),n){const e=document.createElement("field");e.setAttribute("name",n),o&&e.appendChild(document.createTextNode(o[i])),s.appendChild(e)}r.appendChild(s),e.appendChild(r)}}function d(t,n,o,r){const i=p(t,e.toolbox.convertColor(n),o,r);return i.setAttribute("web-class","blocklyFlyoutHeading"),i}function p(t,n,o,r){let i=Blockly.utils.xml.createElement("label");return i.setAttribute("text",t),n&&i.setAttribute("web-icon-color",e.toolbox.convertColor(n)),o&&(1===o.length?(i.setAttribute("web-icon",o),r&&i.setAttribute("web-icon-class",r)):i.setAttribute("web-icon-class",`blocklyFlyoutIcon${t}`)),i}function g(t,n,i){let s=document.createElement("block");if(s.setAttribute("type",n.attributes.blockId),n.attributes.blockGap?s.setAttribute("gap",n.attributes.blockGap):e.appTarget.appTheme&&e.appTarget.appTheme.defaultBlockGap&&s.setAttribute("gap",e.appTarget.appTheme.defaultBlockGap.toString()),i.thisParameter){const e=i.thisParameter;s.appendChild(c(t,e,e.shadowBlockId||"variables_get",e.defaultValue||e.definitionName))}return n.parameters&&(i.parameters.filter((e=>!e.isOptional&&(r.test(e.type)||r.test(o(e.type))||e.shadowBlockId||e.defaultValue))).forEach((e=>{s.appendChild(c(t,e))})),n.attributes.draggableParameters?i.handlerArgs.forEach((t=>{const o="reporter"===n.attributes.draggableParameters,r=document.createElement("value");r.setAttribute("name","HANDLER_DRAG_PARAM_"+t.name);const i=o?e.blocks.reporterTypeForArgType(t.type):"variables_get_reporter",a=document.createElement("shadow");if(a.setAttribute("type",i),o&&"argument_reporter_custom"===i){const e=document.createElement("mutation");e.setAttribute("typename",t.type),a.appendChild(e)}const l=document.createElement("field");l.setAttribute("name",o?"VALUE":"VAR"),l.textContent=e.Util.htmlEscape(t.name),a.appendChild(l),r.appendChild(a),s.appendChild(r)})):i.handlerArgs.forEach((e=>{const t=document.createElement("field");t.setAttribute("name","HANDLER_"+e.name),t.textContent=e.name,s.appendChild(t)}))),s}function h(n){return s=n,Blockly.pxtBlocklyUtils.whitelistDraggableBlockTypes(n.blocks.filter((e=>e.attributes.duplicateShadowOnDrag)).map((e=>e.attributes.blockId))),n.blocks.map((o=>{const r=t.compileInfo(o),i=g(n,o,r);if(o.attributes.blockBuiltin){e.Util.assert(!!a()[o.attributes.blockId]);const t=a()[o.attributes.blockId];t.symbol=o,t.block.codeCard=_(o,i)}else!function(n,o,r,i){let s=o.attributes.blockId;if(a()[s])return e.reportError("blocks","trying to override builtin block",{details:s}),!1;let c=JSON.stringify(o);if(l[s]&&l[s].hash==c)return!0;if(Blockly.Blocks[o.attributes.blockId])return console.error("duplicate block definition: "+s),!1;let u={hash:c,fn:o,block:{codeCard:_(o,i),init:function(){!function(n,o,r,i){var s;const a=(r.attributes.blockNamespace||r.namespace).split(".")[0],l=1==r.kind||2==r.kind,c=o.apis.byQName[a],u=r.attributes.blockNamespace&&c&&c.attributes.color||r.attributes.color||c&&c.attributes.color||e.toolbox.getNamespaceColor(a)||255;if(r.attributes.help){const e=r.attributes.help.replace(/^\//,"");/^github:/.test(e)?n.setHelpUrl(e):"none"!==e&&n.setHelpUrl("/reference/"+e)}else if(r.pkg&&!e.appTarget.bundledpkgs[r.pkg]){let e=r.qName.toLowerCase().split(".");e[0]==r.pkg&&e.shift(),n.setHelpUrl(`/pkg/${r.pkg}#${encodeURIComponent(e.join("-"))}`)}n.setColour(u);let d=Blockly.OUTPUT_SHAPE_ROUND;"boolean"==r.retType&&(d=Blockly.OUTPUT_SHAPE_HEXAGONAL);n.setOutputShape(d),r.attributes.undeletable&&n.setDeletable(!1);h(r.attributes._def);let p=!1;if(r.attributes.mutate)t.addMutation(n,r,r.attributes.mutate);else if(r.attributes.defaultInstance)t.addMutation(n,r,t.MutatorTypes.DefaultInstanceMutator);else if(r.attributes._expandedDef&&"disabled"!==r.attributes.expandableArgumentMode){const e="toggle"===r.attributes.expandableArgumentMode;t.initExpandableBlock(o,n,r.attributes._expandedDef,i,e,(()=>h(r.attributes._expandedDef,!0)))}else if(i.handlerArgs.length)if(p=!0,r.attributes.optionalVariableArgs)t.initVariableArgsBlock(n,i.handlerArgs);else if(r.attributes.draggableParameters)i.handlerArgs.filter((e=>!e.inBlockDef)).forEach((e=>{const t=n.appendValueInput("HANDLER_DRAG_PARAM_"+e.name);"reporter"==r.attributes.draggableParameters?t.setCheck(b(e.type,o)):t.setCheck("Variable")}));else{let e=n.appendDummyInput();i.handlerArgs.filter((e=>!e.inBlockDef)).forEach((t=>{e.appendField(new Blockly.FieldVariable(t.name),"HANDLER_"+t.name)}))}if(t.appendMutation(n,{mutationToDom:e=>(n.inputList.forEach((t=>{t.fieldRow.forEach((t=>{if(t.isFieldCustom_&&t.saveOptions){const n=t.saveOptions();n&&e.setAttribute("customfield",JSON.stringify(n))}}))})),e),domToMutation:e=>{n.inputList.forEach((t=>{t.fieldRow.forEach((t=>{if(t.isFieldCustom_&&t.restoreOptions){const n=JSON.parse(e.getAttribute("customfield"));n&&t.restoreOptions(n)}}))}))}}),r.attributes.imageLiteral){const e=(r.attributes.imageLiteralColumns||5)*r.attributes.imageLiteral,t=r.attributes.imageLiteralRows||5,o=r.attributes.imageLiteralScale;n.appendDummyInput().appendField(new pxtblockly.FieldMatrix("",{columns:e,rows:t,scale:o}),"LEDS")}"external"===r.attributes.inlineInputMode?n.setInputsInline(!1):"inline"===r.attributes.inlineInputMode?n.setInputsInline(!0):n.setInputsInline(!r.parameters||r.parameters.length<4&&!r.attributes.imageLiteral);((null===(s=r.parameters)||void 0===s?void 0:s.find((e=>pxtc.parameterTypeIsArrowFunction(e))))||p)&&(n.appendStatementInput("HANDLER").setCheck(null),n.setInputsInline(!0));v(n,r.retType,o);const g=m(r);function h(s,a=!1){let c=0,d=!a&&!!i.thisParameter;const p=function(e){const t=[];let n=[];return e.parts.forEach((e=>{switch(e.kind){case"break":o();break;case"param":n.push(e),o();break;case"image":case"label":n.push(e)}})),o(),t;function o(){n.length&&(t.push(n),n=[])}}(s),g=new e.ImageConverter;"ENUM_GET"!==r.attributes.shim&&"KIND_GET"!==r.attributes.shim||!(i.parameters.length>1||i.thisParameter)?(p.forEach((s=>{const p=[];let h,f,_,m=!1;if(s.forEach((n=>{if("param"!==n.kind){const t=function(t){if("image"===t.kind)return function(t){let n=I[t];if(!n)return void e.log(`missing jres icon ${t}`);return new Blockly.FieldImage(n,40,40,"",null,e.Util.isUserLanguageRtl())}(t.uri);const n=function(e){if(" "===e)return"";if(e.length>1){const t=" "==e.charAt(0),n=" "==e.charAt(e.length-1);if(t||n)return e.substring(t?1:0,n?e.length-1:e.length)}return e}(t.text);if(!n)return;return t.cssClass?new Blockly.FieldLabel(n,t.cssClass):t.style.length?new pxtblockly.FieldStyledLabel(n,{bold:-1!==t.style.indexOf("bold"),italics:-1!==t.style.indexOf("italics"),blocksInfo:void 0}):new Blockly.FieldLabel(n,void 0)}(n);t&&p.push({field:t})}else{if("ENUM_GET"===r.attributes.shim)return e.U.assert(!!r.attributes.enumName,"Trying to create an ENUM_GET block without a valid enum name"),void p.push({name:"MEMBER",field:new pxtblockly.FieldUserEnum(o.enumsByName[r.attributes.enumName])});if("KIND_GET"===r.attributes.shim)return void p.push({name:"MEMBER",field:new pxtblockly.FieldKind(o.kindsByName[r.attributes.kindNamespace||r.attributes.blockNamespace||r.namespace])});{let c=function(e,t,n=!1){if(e.ref){const n="this"===e.name?t.thisParameter:t.actualNameToParam[e.name];if(!n){let n;if(t.handlerArgs.forEach((t=>{t.name===e.name&&(n=t)})),n)return n}return n}return n?t.thisParameter:t.definitionNameToParam[e.name]}(n,i,d);if(d=!1,!c)return void console.error("block "+r.attributes.blockId+": unknown parameter "+n.name+(n.ref?` (${n.ref})`:""));if(!c.definitionName)return h="HANDLER_DRAG_PARAM_"+c.name,void(f="reporter"===r.attributes.draggableParameters?b(c.type,o):"Variable");let _=e.U.lookup(o.apis.byQName,c.type);m=!0;const y=c.definitionName,k=c.actualName;let v=_&&6==_.kind,T=_&&!!_.attributes.fixedInstances&&!c.shadowBlockId,E=!!r.attributes.constantShim,S="@combined@"==c.type,C=c.fieldEditor,x=y.charAt(0).toUpperCase()+y.slice(1),B=c.type;if(v||T||E||S){let n;v?(s=o.apis,a=c.type,n=e.Util.values(s.byQName).filter((e=>e.namespace===a&&!e.attributes.blockHidden))):n=T?N(o.apis,_.qName):S?r.combinedProperties.map((t=>e.U.lookup(o.apis.byQName,t))):function(t,n){return e.Util.values(t.byQName).filter((e=>e.attributes.blockIdentity===n))}(o.apis,r.qName),0==n.length&&console.error(`no instances of ${_.qName} found`);const i=n.map((t=>{let n=t.attributes.block||t.attributes.blockId||t.name,o=t.attributes.blockCombine;return t.attributes.jresURL&&!t.attributes.iconURL&&e.U.startsWith(t.attributes.jresURL,"data:image/x-mkcd-f")&&(t.attributes.iconURL=g.convert(t.attributes.jresURL)),o&&(n=n.replace(/@set/,"")),[t.attributes.iconURL||t.attributes.blockImage?{src:t.attributes.iconURL||e.Util.pathJoin(e.webConfig.commitCdnUrl,`blocks/${t.namespace.toLowerCase()}/${t.name.toLowerCase()}.png`),alt:n,width:36,height:36,value:t.name}:n,t.namespace+"."+t.name]}));if(c.defaultValue){let e=-1;if(i.some(((t,n)=>t[1]===c.defaultValue&&(e=n,!0))),e>-1){const t=i.splice(e,1)[0];i.unshift(t)}}if(C){let n=r.attributes.paramDefl[k]||"";const s={data:i,colour:u,label:x,type:B,blocksInfo:o};e.Util.jsonMergeFrom(s,r.attributes.paramFieldEditorOptions&&r.attributes.paramFieldEditorOptions[k]||{}),p.push(D(t.createFieldEditor(C,n,s),y))}else p.push(D(new Blockly.FieldDropdown(i),y))}else if(C){const n=r.attributes.paramDefl[c.actualName]||"",i={colour:u,label:x,type:B,blocksInfo:o};e.Util.jsonMergeFrom(i,r.attributes.paramFieldEditorOptions&&r.attributes.paramFieldEditorOptions[c.actualName]||{}),p.push(D(t.createFieldEditor(C,n,i),c.definitionName))}else h=y,l&&"this"===n.name?f=c.type:"number"==c.type&&c.shadowBlockId&&"value"==c.shadowBlockId?(h=void 0,p.push(D(new Blockly.FieldNumber("0"),y))):f="string"==c.type&&c.shadowOptions&&c.shadowOptions.toString?null:b(c.type,o)}}var s,a})),h)_=n.appendValueInput(h),_.setAlign(Blockly.ALIGN_LEFT);else if(a){const e=m?t.optionalInputWithFieldPrefix:t.optionalDummyInputPrefix;_=n.appendDummyInput(e+c++)}else _=n.appendDummyInput();f&&_.setCheck(f),p.forEach((e=>_.appendField(e.field,e.name)))})),g.logTime()):console.warn(`Enum blocks may only have 1 parameter but ${r.attributes.blockId} has ${i.parameters.length}`)}n.setPreviousStatement(!(g&&!r.attributes.handlerStatement)&&"void"==r.retType),n.setNextStatement(!(g&&!r.attributes.handlerStatement)&&"void"==r.retType),n.setTooltip(/^__/.test(r.namespace)?"":r.attributes.jsDoc)}(this,n,o,r)}}};e.Util.isTranslationMode()&&e.blocks.promptTranslateBlock&&(u.block.customContextMenu=t=>{o.attributes.translationId&&t.push({enabled:!0,text:lf("Translate this block"),callback:function(){e.blocks.promptTranslateBlock(s,[o.attributes.translationId])}})});l[s]=u,Blockly.Blocks[s]=u.block}(n,o,r,i);return o}))}function f(e){return e.outerHTML.replace(/^<\?[^>]*>/,"")}function _(e,t){return{name:e.namespace+"."+e.name,shortName:e.name,description:e.attributes.jsDoc,url:e.attributes.help?"reference/"+e.attributes.help.replace(/^\//,""):void 0,blocksXml:`<xml xmlns="http://www.w3.org/1999/xhtml">${f(t)}</xml>`}}function m(e){var t;return!!(null===(t=e.parameters)||void 0===t?void 0:t.some((e=>pxtc.parameterTypeIsArrowFunction(e))))}t.blockSymbol=function(e){let t=l[e];return t?t.fn:void 0},t.createShadowValue=c,t.createFlyoutHeadingLabel=d,t.createFlyoutGroupLabel=function(e,t,n,o){const r=p(e,void 0,t);return r.setAttribute("web-class","blocklyFlyoutGroup"),r.setAttribute("web-line","1.5"),n&&r.setAttribute("web-line-width",n),o&&(r.setAttribute("web-help-button","true"),r.setAttribute("callbackKey",o)),r},t.createFlyoutButton=function(e,t){let n=Blockly.utils.xml.createElement("button");return n.setAttribute("text",t),n.setAttribute("callbackKey",e),n},t.createToolboxBlock=g,t.injectBlocks=h,t.hasArrowFunction=m,t.cleanBlocks=function(){e.debug("removing all custom blocks");for(const e in l)x(l[e].fn)},t.initializeAndInject=function(e){k(),h(e)},t.initialize=function(e){k(),function(e){I={};const t=e.apis.jres;if(!t)return;Object.keys(t).forEach((e=>{const n=t[e];n&&n.icon&&(I[e]=n.icon)}))}(e)};let y=!1;function k(){y||(y=!0,goog.provide("Blockly.Blocks.device"),goog.require("Blockly.Blocks"),Blockly.FieldCheckbox.CHECK_CHAR="■",Blockly.Constants.ADD_START_HATS=!!e.appTarget.appTheme.blockHats,t.initFieldEditors(),function(){const n=Blockly.Msg;n.DUPLICATE_BLOCK=lf("{id:block}Duplicate"),n.DUPLICATE_COMMENT=lf("Duplicate Comment"),n.REMOVE_COMMENT=lf("Remove Comment"),n.ADD_COMMENT=lf("Add Comment"),n.EXTERNAL_INPUTS=lf("External Inputs"),n.INLINE_INPUTS=lf("Inline Inputs"),n.EXPAND_BLOCK=lf("Expand Block"),n.COLLAPSE_BLOCK=lf("Collapse Block"),n.ENABLE_BLOCK=lf("Enable Block"),n.DISABLE_BLOCK=lf("Disable Block"),n.DELETE_BLOCK=lf("Delete Block"),n.DELETE_X_BLOCKS=lf("Delete Blocks"),n.DELETE_ALL_BLOCKS=lf("Delete All Blocks"),n.HELP=lf("Help"),Blockly.BlockSvg.prototype.showHelp=function(){const t=goog.isFunction(this.helpUrl)?this.helpUrl():this.helpUrl;t&&(e.blocks.openHelpUrl||window.open)(t)},Blockly.WorkspaceSvg.prototype.configureContextMenu=function(o,r){if(this.options.readOnly||this.isFlyout)return;o.length=0;let i=this.getTopBlocks(!0),s=Blockly.utils.genUid(),a=this.getTopComments(),l=this;const c=!(this.options.debugMode||this.options.readOnly);if(this.options.comments&&!e.BrowserUtils.isIE()){const e=Blockly.ContextMenu.workspaceCommentOption(l,r);e.enabled=e.enabled&&c,o.push(e)}let u=Blockly.WorkspaceSvg.buildDeleteList_(i),d=0;for(let e=0;e<u.length;e++)u[e].isShadow()||d++;const p=10;function g(){Blockly.Events.setGroup(s);let e=u.shift();e&&(e.workspace?(e.dispose(!1,!0),setTimeout(g,p)):g()),Blockly.Events.setGroup(!1)}const h={text:1==d?n.DELETE_BLOCK:n.DELETE_ALL_BLOCKS,enabled:d>0&&c,callback:()=>{e.tickEvent("blocks.context.delete",void 0,{interactiveConsent:!0}),d<2?g():Blockly.confirm(lf("Delete all {0} blocks?",d),(e=>{e&&g()}))}};o.push(h);const f={text:lf("Format Code"),enabled:c,callback:()=>{e.tickEvent("blocks.context.format",void 0,{interactiveConsent:!0}),e.blocks.layout.flow(this,{useViewWidth:!0})}};if(o.push(f),e.appTarget.appTheme.blocksCollapsing){const t={text:lf("Collapse Blocks"),enabled:i.length&&i.find((e=>e.isEnabled()&&!e.isCollapsed()))&&c,callback:()=>{e.tickEvent("blocks.context.collapse",void 0,{interactiveConsent:!0}),e.blocks.layout.setCollapsedAll(this,!0)}};o.push(t);const n={text:lf("Expand Blocks"),enabled:i.length&&i.find((e=>e.isEnabled()&&e.isCollapsed()))&&c,callback:()=>{e.tickEvent("blocks.context.expand",void 0,{interactiveConsent:!0}),e.blocks.layout.setCollapsedAll(this,!1)}};o.push(n)}if(e.blocks.layout.screenshotEnabled()){const t={text:lf("Snapshot"),enabled:i.length>0||a.length>0,callback:()=>{var t;e.tickEvent("blocks.context.screenshot",void 0,{interactiveConsent:!0}),e.blocks.layout.screenshotAsync(this,null,null===(t=e.appTarget.appTheme)||void 0===t?void 0:t.embedBlocksInSnapshot).then((t=>{e.BrowserUtils.isSafari()&&(t=t.replace(/^data:image\/[^;]/,"data:application/octet-stream")),e.BrowserUtils.browserDownloadDataUri(t,`${e.appTarget.nickname||e.appTarget.id}-${lf("screenshot")}.png`)}))}};o.push(t)}e.appTarget.appTheme.workspaceSearch&&o.push({text:lf("Find..."),enabled:i.length>0,callback:()=>{var t,n;e.tickEvent("blocks.context.workspacesearch",void 0,{interactiveConsent:!0}),null===(n=null===(t=this.getComponentManager())||void 0===t?void 0:t.getComponent("workspaceSearch"))||void 0===n||n.open()}}),t.onShowContextMenu&&t.onShowContextMenu(this,o)},Blockly.Constants.Logic.LOGIC_COMPARE_ONCHANGE_MIXIN.onchange=function(){}}(),function(){const t=e.blocks.getBlockDefinition(ts.pxtc.ON_START_TYPE);if(Blockly.Blocks[ts.pxtc.ON_START_TYPE]={init:function(){this.jsonInit({message0:t.block.message0,args0:[{type:"input_dummy"},{type:"input_statement",name:"HANDLER"}],colour:(e.appTarget.runtime?e.appTarget.runtime.onStartColor:"")||e.toolbox.getNamespaceColor("loops")}),S(this,ts.pxtc.ON_START_TYPE,t.name,t.tooltip,t.url,String((e.appTarget.runtime?e.appTarget.runtime.onStartColor:"")||e.toolbox.getNamespaceColor("loops")),void 0,void 0,!!e.appTarget.runtime&&e.appTarget.runtime.onStartUnDeletable)}},Blockly.Blocks[pxtc.TS_STATEMENT_TYPE]={init:function(){let t,n,o=this;o.setColour("#717171"),o.setPreviousStatement(!0),o.setNextStatement(!0),o.setInputsInline(!1),o.domToMutation=e=>{const t=parseInt(e.getAttribute("numlines"));o.declaredVariables=e.getAttribute("declaredvars"),n=[];for(let o=0;o<t;o++){const t=e.getAttribute("line"+o);n.push(t)}o.setPythonEnabled(!1)},o.mutationToDom=()=>{let e=document.createElement("mutation");return n&&(n.forEach(((t,n)=>e.setAttribute("line"+n,t))),e.setAttribute("numlines",n.length.toString())),o.declaredVariables&&e.setAttribute("declaredvars",this.declaredVariables),e},o.setPythonEnabled=r=>{if(t!==r){for(;o.inputList.length;)o.removeInput(o.inputList[0].name);t=r,r?(o.appendDummyInput().appendField(e.Util.lf("<python code>"),"LINE0"),o.setTooltip(lf("A Python statement that could not be converted to blocks"))):(n.forEach(((e,t)=>{o.appendDummyInput().appendField(e,"LINE"+t)})),o.setTooltip(lf("A JavaScript statement that could not be converted to blocks")))}},o.getLines=()=>n,o.setEditable(!1),S(this,pxtc.TS_STATEMENT_TYPE,lf("JavaScript statement"),lf("A JavaScript statement that could not be converted to blocks"),"/blocks/javascript-blocks","#717171")}},Blockly.Blocks[pxtc.TS_OUTPUT_TYPE]={init:function(){let e=this;e.setColour("#717171"),e.setPreviousStatement(!1),e.setNextStatement(!1),e.setOutput(!0),e.setEditable(!1),e.appendDummyInput().appendField(new pxtblockly.FieldTsExpression(""),"EXPRESSION"),e.setPythonEnabled=t=>{e.getField("EXPRESSION").setPythonEnabled(t),t?e.setTooltip(lf("A Python expression that could not be converted to blocks")):e.setTooltip(lf("A JavaScript expression that could not be converted to blocks"))},S(e,pxtc.TS_OUTPUT_TYPE,lf("JavaScript expression"),lf("A JavaScript expression that could not be converted to blocks"),"/blocks/javascript-blocks","#717171")}},e.appTarget.runtime&&e.appTarget.runtime.pauseUntilBlock){const t=e.appTarget.runtime.pauseUntilBlock,n=e.blocks.getBlockDefinition(ts.pxtc.PAUSE_UNTIL_TYPE);Blockly.Blocks[pxtc.PAUSE_UNTIL_TYPE]={init:function(){const o=t.color||e.toolbox.getNamespaceColor("loops");this.jsonInit({message0:n.block.message0,args0:[{type:"input_value",name:"PREDICATE",check:"Boolean"}],inputsInline:!0,previousStatement:null,nextStatement:null,colour:o}),S(this,ts.pxtc.PAUSE_UNTIL_TYPE,n.name,n.tooltip,n.url,o,void 0,void 0,!1)}}}const n="pxt_controls_for_of",o=e.blocks.getBlockDefinition(n);Blockly.Blocks[n]={init:function(){this.jsonInit({message0:o.block.message0,args0:[{type:"input_value",name:"VAR",variable:o.block.variable,check:"Variable"},{type:"input_value",name:"LIST",check:["Array","String"]}],previousStatement:null,nextStatement:null,colour:e.toolbox.blockColors.loops,inputsInline:!0}),this.appendStatementInput("DO").appendField(o.block.appendField);let t=this;S(this,n,o.name,(function(){return e.U.rlf(o.tooltip,t.getInputTargetBlock("VAR")?t.getInputTargetBlock("VAR").getField("VAR").getText():"")}),o.url,String(e.toolbox.getNamespaceColor("loops")))}};const r="controls_for_of",i=e.blocks.getBlockDefinition(r);Blockly.Blocks[r]={init:function(){this.jsonInit({message0:i.block.message0,args0:[{type:"field_variable",name:"VAR",variable:i.block.variable},{type:"input_value",name:"LIST",check:"Array"}],previousStatement:null,nextStatement:null,colour:e.toolbox.blockColors.loops,inputsInline:!0}),this.appendStatementInput("DO").appendField(i.block.appendField);let t=this;S(this,r,i.name,(function(){return e.U.rlf(i.tooltip,t.getField("VAR").getText())}),i.url,String(e.toolbox.getNamespaceColor("loops")))}};const s="lists_index_get",a=e.blocks.getBlockDefinition(s);Blockly.Blocks.lists_index_get={init:function(){this.jsonInit({message0:a.block.message0,args0:[{type:"input_value",name:"LIST",check:"Array"},{type:"input_value",name:"INDEX",check:"Number"}],colour:e.toolbox.blockColors.arrays,outputShape:Blockly.OUTPUT_SHAPE_ROUND,inputsInline:!0}),this.setPreviousStatement(!1),this.setNextStatement(!1),this.setOutput(!0),T(this,s)}};const l="lists_index_set",c=e.blocks.getBlockDefinition(l);Blockly.Blocks[l]={init:function(){this.jsonInit({message0:c.block.message0,args0:[{type:"input_value",name:"LIST",check:"Array"},{type:"input_value",name:"INDEX",check:"Number"},{type:"input_value",name:"VALUE",check:null}],previousStatement:null,nextStatement:null,colour:e.toolbox.blockColors.arrays,inputsInline:!0}),T(this,l)}}}(),function(){const n="math_op2",o=e.blocks.getBlockDefinition(n),r=o.tooltip;Blockly.Blocks[n]={init:function(){this.jsonInit({message0:lf("%1 of %2 and %3"),args0:[{type:"field_dropdown",name:"op",options:[[lf("{id:op}min"),"min"],[lf("{id:op}max"),"max"]]},{type:"input_value",name:"x",check:"Number"},{type:"input_value",name:"y",check:"Number"}],inputsInline:!0,output:"Number",outputShape:Blockly.OUTPUT_SHAPE_ROUND,colour:e.toolbox.getNamespaceColor("math")});S(this,n,o.name,(function(e){return r[e.getFieldValue("op")]}),o.url,e.toolbox.getNamespaceColor(o.category))}};const i="math_op3",s=e.blocks.getBlockDefinition(i);Blockly.Blocks[i]={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:e.toolbox.getNamespaceColor("math")}),T(this,i)}};["math_number","math_integer","math_whole_number","math_number_minmax"].forEach((t=>{const n=e.blocks.getBlockDefinition(t);C(t,n.name,n.tooltip,n.url,Blockly.Colours.textField,Blockly.Colours.textField,Blockly.Colours.textField)}));const a=Blockly.Msg,l="math_arithmetic",c=e.blocks.getBlockDefinition(l),u=c.tooltip;a.MATH_ADDITION_SYMBOL=c.block.MATH_ADDITION_SYMBOL,a.MATH_SUBTRACTION_SYMBOL=c.block.MATH_SUBTRACTION_SYMBOL,a.MATH_MULTIPLICATION_SYMBOL=c.block.MATH_MULTIPLICATION_SYMBOL,a.MATH_DIVISION_SYMBOL=c.block.MATH_DIVISION_SYMBOL,a.MATH_POWER_SYMBOL=c.block.MATH_POWER_SYMBOL,C(l,c.name,(function(e){return u[e.getFieldValue("OP")]}),c.url,e.toolbox.getNamespaceColor(c.category));const d="math_modulo",p=e.blocks.getBlockDefinition(d);a.MATH_MODULO_TITLE=p.block.MATH_MODULO_TITLE,E(d),t.initMathOpBlock(),t.initMathRoundBlock()}(),function(){Blockly.FieldVariable.prototype.getVariableTypes_=()=>[""];let t=lf("{id:var}item");Blockly.Variables.flyoutCategory=function(t){let n=[];if(!e.appTarget.appTheme.hideFlyoutHeadings){let t=d(lf("Variables"),e.toolbox.getNamespaceColor("variables"),e.toolbox.getNamespaceIcon("variables"));n.push(t)}let o=document.createElement("button");o.setAttribute("text",lf("Make a Variable...")),o.setAttribute("callbackKey","CREATE_VARIABLE"),t.registerButtonCallback("CREATE_VARIABLE",(function(e){Blockly.Variables.createVariable(e.getTargetWorkspace())})),n.push(o);let r=Blockly.Variables.flyoutCategoryBlocks(t);return n=n.concat(r),n},Blockly.Variables.flyoutCategoryBlocks=function(e){let t=e.getVariablesOfType(""),n=[];if(t.length>0){let e=t[t.length-1];t.sort(Blockly.VariableModel.compareByName);for(let e=0;e<t.length;e++){const o=t[e];if(Blockly.Blocks.variables_get){let e='<xml><block type="variables_get" gap="8">'+Blockly.Variables.generateVariableFieldXmlString(o)+"</block></xml>",t=Blockly.Xml.textToDom(e).firstChild;n.push(t)}}if(n[n.length-1].setAttribute("gap","24"),Blockly.Blocks.variables_set){let t='<xml><block type="variables_set" gap="'+(Blockly.Blocks.variables_change?8:24)+'">'+Blockly.Variables.generateVariableFieldXmlString(e)+"</block></xml>",o=Blockly.Xml.textToDom(t).firstChild;{let e=goog.dom.createDom("value");e.setAttribute("name","VALUE");let t=goog.dom.createDom("shadow");t.setAttribute("type","math_number"),e.appendChild(t);let n=goog.dom.createDom("field");n.setAttribute("name","NUM"),n.appendChild(document.createTextNode("0")),t.appendChild(n),o.appendChild(e)}n.push(o)}if(Blockly.Blocks.variables_change){let t='<xml><block type="variables_change" gap="'+(Blockly.Blocks.variables_get?20:8)+'">'+Blockly.Variables.generateVariableFieldXmlString(e)+"</block></xml>",o=Blockly.Xml.textToDom(t).firstChild;{let e=goog.dom.createDom("value");e.setAttribute("name","VALUE");let t=goog.dom.createDom("shadow");t.setAttribute("type","math_number"),e.appendChild(t);let n=goog.dom.createDom("field");n.setAttribute("name","NUM"),n.appendChild(document.createTextNode("1")),t.appendChild(n),o.appendChild(e)}n.push(o)}}return n};const n=Blockly.Msg,o="variables_get",r=e.blocks.getBlockDefinition(o);n.VARIABLES_GET_CREATE_SET=r.block.VARIABLES_GET_CREATE_SET,E(o);E("variables_get_reporter"),n.RENAME_VARIABLE=lf("Rename variable..."),n.DELETE_VARIABLE=lf('Delete the "%1" variable'),n.DELETE_VARIABLE_CONFIRMATION=lf('Delete %1 uses of the "%2" variable?'),n.NEW_VARIABLE_DROPDOWN=lf("New variable...");const i="variables_set",s=e.blocks.getBlockDefinition(i);n.VARIABLES_SET=s.block.VARIABLES_SET,n.VARIABLES_DEFAULT_NAME=t,n.VARIABLES_SET_CREATE_GET=lf("Create 'get %1'"),E(i);const a="variables_change",l=e.blocks.getBlockDefinition(a);Blockly.Blocks[a]={init:function(){this.jsonInit({message0:l.block.message0,args0:[{type:"field_variable",name:"VAR",variable:t},{type:"input_value",name:"VALUE",check:"Number"}],inputsInline:!0,previousStatement:null,nextStatement:null,colour:e.toolbox.getNamespaceColor("variables")}),T(this,a)},customContextMenu:function(e){if(!this.inDebugWorkspace()){let t={enabled:this.workspace.remainingCapacity()>0},n=this.getField("VAR").getText();t.text=lf("Create 'get {0}'",n);let o=goog.dom.createDom("field",null,n);o.setAttribute("name","VAR");let r=goog.dom.createDom("block",null,o);r.setAttribute("type","variables_get"),t.callback=Blockly.ContextMenu.callbackFactory(this,r),e.push(t)}}},n.NEW_VARIABLE_TITLE=lf("New variable name:"),n.RENAME_VARIABLE_TITLE=lf("Rename all '%1' variables to:")}(),function(){const n=Blockly.Msg;n.FUNCTION_CREATE_NEW=lf("Make a Function..."),n.FUNCTION_WARNING_DUPLICATE_ARG=lf("Functions cannot use the same argument name more than once."),n.FUNCTION_WARNING_ARG_NAME_IS_FUNCTION_NAME=lf("Argument names must not be the same as the function name."),n.FUNCTION_WARNING_EMPTY_NAME=lf("Function and argument names cannot be empty."),n.FUNCTIONS_DEFAULT_FUNCTION_NAME=lf("doSomething"),n.FUNCTIONS_DEFAULT_BOOLEAN_ARG_NAME=lf("bool"),n.FUNCTIONS_DEFAULT_STRING_ARG_NAME=lf("text"),n.FUNCTIONS_DEFAULT_NUMBER_ARG_NAME=lf("num"),n.FUNCTIONS_DEFAULT_CUSTOM_ARG_NAME=lf("arg"),n.PROCEDURES_HUE=e.toolbox.getNamespaceColor("functions"),n.REPORTERS_HUE=e.toolbox.getNamespaceColor("variables");const o="procedures_defnoreturn",r=e.blocks.getBlockDefinition(o);n.PROCEDURES_DEFNORETURN_TITLE=r.block.PROCEDURES_DEFNORETURN_TITLE,n.PROCEDURE_ALREADY_EXISTS=r.block.PROCEDURE_ALREADY_EXISTS,Blockly.Blocks.procedures_defnoreturn.init=function(){let t=new Blockly.FieldTextInput("",Blockly.Procedures.rename);this.appendDummyInput().appendField(Blockly.Msg.PROCEDURES_DEFNORETURN_TITLE).appendField(t,"NAME").appendField("","PARAMS"),this.setColour(e.toolbox.getNamespaceColor("functions")),this.arguments_=[],this.argumentVarModels_=[],this.setStartHat(!0),this.setStatements_(!0),this.statementConnection_=null},E(o);const i="procedures_callnoreturn",a=e.blocks.getBlockDefinition(i);n.PROCEDURES_CALLRETURN_TOOLTIP=r.tooltip.toString(),Blockly.Blocks.procedures_callnoreturn={init:function(){let t=new pxtblockly.FieldProcedure("");this.appendDummyInput("TOPROW").appendField(a.block.PROCEDURES_CALLNORETURN_TITLE).appendField(t,"NAME"),this.setPreviousStatement(!0),this.setNextStatement(!0),this.setColour(e.toolbox.getNamespaceColor("functions")),this.arguments_=[],this.quarkConnections_={},this.quarkIds_=null},getProcedureCall:function(){return this.getFieldValue("NAME")},renameProcedure:function(e,t){Blockly.Names.equals(e,this.getProcedureCall())&&this.setFieldValue(t,"NAME")},onchange:function(t){if(this.workspace&&!this.workspace.isFlyout&&!this.isInsertionMarker())if(t.type==Blockly.Events.CREATE&&-1!=t.ids.indexOf(this.id)){let n=this.getProcedureCall(),o=Blockly.Procedures.getDefinition(n,this.workspace);if(!o||o.type==this.defType_&&JSON.stringify(o.arguments_)==JSON.stringify(this.arguments_)||(o=null),!o){Blockly.Events.setGroup(t.group);let n=Blockly.utils.xml.createElement("xml"),o=Blockly.utils.xml.createElement("block");o.setAttribute("type",this.defType_);let r=this.getRelativeToSurfaceXY(),i=r.x+Blockly.SNAP_RADIUS*(this.RTL?-1:1),s=r.y+2*Blockly.SNAP_RADIUS;o.setAttribute("x",i),o.setAttribute("y",s);let a=Blockly.utils.xml.createElement("field");a.setAttribute("name","NAME"),a.appendChild(document.createTextNode(this.getProcedureCall())),o.appendChild(a),n.appendChild(o),e.blocks.domToWorkspaceNoEvents(n,this.workspace),Blockly.Events.setGroup(!1)}}else if(t.type==Blockly.Events.DELETE){let e=this.getProcedureCall();Blockly.Procedures.getDefinition(e,this.workspace)||(Blockly.Events.setGroup(t.group),this.dispose(!0,!1),Blockly.Events.setGroup(!1))}},mutationToDom:function(){const e=document.createElement("mutation");return e.setAttribute("name",this.getProcedureCall()),e},domToMutation:function(e){const t=e.getAttribute("name");this.renameProcedure(this.getProcedureCall(),t)},customContextMenu:function(e){let t={enabled:!0};t.text=Blockly.Msg.PROCEDURES_HIGHLIGHT_DEF;let n=this.getProcedureCall(),o=this.workspace;t.callback=function(){let e=Blockly.Procedures.getDefinition(n,o);e&&e.select()},e.push(t)},defType_:"procedures_defnoreturn"},E(i);const l="function_definition",c=e.blocks.getBlockDefinition(l);n.FUNCTIONS_EDIT_OPTION=c.block.FUNCTIONS_EDIT_OPTION,E(l);const u="function_call",p=e.blocks.getBlockDefinition(u);n.FUNCTIONS_CALL_TITLE=p.block.FUNCTIONS_CALL_TITLE,n.FUNCTIONS_GO_TO_DEFINITION_OPTION=p.block.FUNCTIONS_GO_TO_DEFINITION_OPTION,E(u),E("function_call_output");const g="function_return";Blockly.Blocks[g]={init:function(){t.initReturnStatement(this)},onchange:function(e){const t=this;if(!t.workspace||t.workspace.isFlyout)return;const n=e.type===Blockly.Events.BLOCK_CREATE&&-1!=e.ids.indexOf(t.id),o=e.type===Blockly.Events.END_DRAG&&-1!=e.allNestedIds.indexOf(t.id);if(n||o){const n=t.getRootBlock();if(n.type===g||null!=n.previousConnection)return;n.type!==l&&(Blockly.Events.setGroup(e.group),t.previousConnection.disconnect(),Blockly.Events.setGroup(!1))}}},E(g),Blockly.Procedures.flyoutCategory=function(t){let n=[];if(!e.appTarget.appTheme.hideFlyoutHeadings){let t=d(lf("Functions"),e.toolbox.getNamespaceColor("functions"),e.toolbox.getNamespaceIcon("functions"),"blocklyFlyoutIconfunctions");n.push(t)}const o=lf("Make a Function..."),r=lf("New function name:");let i=Blockly.utils.xml.createElement("button");i.setAttribute("text",o),i.setAttribute("callbackKey","CREATE_FUNCTION");let s=n=>{let o=t.getTopBlocks(!0)[0],r=10,i=10;if(o){let e=o.getRelativeToSurfaceXY();r=e.x+Blockly.SNAP_RADIUS*(o.RTL?-1:1),i=e.y+2*Blockly.SNAP_RADIUS}let s=Blockly.utils.xml.createElement("xml"),a=Blockly.utils.xml.createElement("block");a.setAttribute("type","procedures_defnoreturn"),a.setAttribute("x",String(r)),a.setAttribute("y",String(i));let l=Blockly.utils.xml.createElement("field");l.setAttribute("name","NAME"),l.appendChild(document.createTextNode(n)),a.appendChild(l),s.appendChild(a);let c=e.blocks.domToWorkspaceNoEvents(s,t);Blockly.hideChaff();let u=t.getBlockById(c[0]);u.select(),t.centerOnBlock(u.id)};function a(t,o){for(let r=0;r<t.length;r++){let i=t[r][0],s=(t[r][1],Blockly.utils.xml.createElement("block"));s.setAttribute("type",o),s.setAttribute("gap","16"),s.setAttribute("colour",e.toolbox.getNamespaceColor("functions"));let a=goog.dom.createDom("field",null,i);a.setAttribute("name","NAME"),s.appendChild(a),n.push(s)}}return t.registerButtonCallback("CREATE_FUNCTION",(function(n){let i=n=>{Blockly.prompt(r,n,(function(n){e.tickEvent("blocks.makeafunction"),n&&(n=n.replace(/[\s\xa0]+/g," ").replace(/^ | $/g,""))==o&&(n=null),n&&(t.getVariable(n)?Blockly.alert(Blockly.Msg.VARIABLE_ALREADY_EXISTS.replace("%1",n.toLowerCase()),(function(){i(n)})):Blockly.Procedures.isLegalName_(n,t)?s(n):Blockly.alert(Blockly.Msg.PROCEDURE_ALREADY_EXISTS.replace("%1",n.toLowerCase()),(function(){i(n)})))}))};i("doSomething")})),n.push(i),a(Blockly.Procedures.allProcedures(t)[0],"procedures_callnoreturn"),n};const h=Blockly.Functions.flyoutCategory;Blockly.Functions.flyoutCategory=t=>{const n=h(t);if(n.length>1){let e=A();n.splice(1,0,e)}const o=Blockly.Functions.getAllFunctionDefinitionBlocks(t).filter((e=>e.getDescendants(!1).some((e=>"function_return"===e.type&&e.getInputTargetBlock("RETURN_VALUE"))))).map((e=>e.getField("function_name").getText())),r=d(lf("Functions"),e.toolbox.getNamespaceColor("functions"),e.toolbox.getNamespaceIcon("functions"),"blocklyFlyoutIconfunctions");n.unshift(r);const i=[];for(const e of n)if(i.push(e),"function_call"===e.getAttribute("type")){const t=e.children.item(0);if(t){const n=t.getAttribute("name");if(o.some((e=>e===n))){const t=e.cloneNode(!0);t.setAttribute("type","function_call_output"),i.push(t)}}}return i};const f={number:e.blocks.defaultIconForArgType("number"),boolean:e.blocks.defaultIconForArgType("boolean"),string:e.blocks.defaultIconForArgType("string"),Array:e.blocks.defaultIconForArgType("Array")},_={},m=e.appTarget.runtime&&e.appTarget.runtime.functionsOptions;m&&m.extraFunctionEditorTypes&&m.extraFunctionEditorTypes.forEach((t=>{f[t.typeName]=t.icon||e.blocks.defaultIconForArgType(),t.defaultName&&(_[t.typeName]=t.defaultName)}));Blockly.PXTBlockly.FunctionUtils.argumentIcons=f,Blockly.PXTBlockly.FunctionUtils.argumentDefaultNames=_,Blockly.Blocks.argument_reporter_custom&&(Blockly.Blocks.argument_reporter_custom.domToMutation=function(e){const t=e.getAttribute("typename");this.typeName_=t,v(this,t,s)});const y=Blockly.Functions.makeCreateCallOption;Blockly.Msg.FUNCTIONS_CREATE_CALL_OPTION="",Blockly.Functions.makeCreateCallOption=function(t){let n=y(t),o=t.getField("function_name").getText();return n.text=e.Util.lf("Create 'call {0}'",o),n}}(),function(){const t=Blockly.Msg,n="lists_create_with",o=e.blocks.getBlockDefinition(n);t.LISTS_CREATE_EMPTY_TITLE=o.block.LISTS_CREATE_EMPTY_TITLE,t.LISTS_CREATE_WITH_INPUT_WITH=o.block.LISTS_CREATE_WITH_INPUT_WITH,t.LISTS_CREATE_WITH_CONTAINER_TITLE_ADD=o.block.LISTS_CREATE_WITH_CONTAINER_TITLE_ADD,t.LISTS_CREATE_WITH_ITEM_TITLE=o.block.LISTS_CREATE_WITH_ITEM_TITLE,E(n);const r="lists_length",i=e.blocks.getBlockDefinition(r);t.LISTS_LENGTH_TITLE=i.block.LISTS_LENGTH_TITLE,Blockly.Blocks[r].init=function(){this.jsonInit({message0:t.LISTS_LENGTH_TITLE,args0:[{type:"input_value",name:"VALUE",check:["Array"]}],output:"Number",outputShape:Blockly.OUTPUT_SHAPE_ROUND})},E(r)}(),function(){const t=Blockly.Msg,n="controls_repeat_ext",o=e.blocks.getBlockDefinition(n);t.CONTROLS_REPEAT_TITLE=o.block.CONTROLS_REPEAT_TITLE,t.CONTROLS_REPEAT_INPUT_DO=o.block.CONTROLS_REPEAT_INPUT_DO,E(n);const r="device_while",i=e.blocks.getBlockDefinition(r);Blockly.Blocks[r]={init:function(){this.jsonInit({message0:i.block.message0,args0:[{type:"input_value",name:"COND",check:"Boolean"}],previousStatement:null,nextStatement:null,colour:e.toolbox.getNamespaceColor("loops")}),this.appendStatementInput("DO").appendField(i.block.appendField),T(this,r)}};const s="pxt_controls_for",a=e.blocks.getBlockDefinition(s);Blockly.Blocks[s]={init:function(){this.jsonInit({message0:a.block.message0,args0:[{type:"input_value",name:"VAR",variable:a.block.variable,check:"Variable"},{type:"input_value",name:"TO",check:"Number"}],previousStatement:null,nextStatement:null,colour:e.toolbox.getNamespaceColor("loops"),inputsInline:!0}),this.appendStatementInput("DO").appendField(a.block.appendField);let t=this;S(this,s,a.name,(function(){return e.U.rlf(a.tooltip,t.getInputTargetBlock("VAR")?t.getInputTargetBlock("VAR").getField("VAR").getText():"")}),a.url,String(e.toolbox.getNamespaceColor("loops")))},getVars:function(){return[this.getField("VAR").getText()]},renameVar:function(e,t){const n=this.getField("VAR");Blockly.Names.equals(e,n.getText())&&n.setValue(t)}};const l="controls_simple_for",c=e.blocks.getBlockDefinition(l);Blockly.Blocks[l]={init:function(){this.jsonInit({message0:c.block.message0,args0:[{type:"field_variable",name:"VAR",variable:c.block.variable},{type:"input_value",name:"TO",check:"Number"}],previousStatement:null,nextStatement:null,colour:e.toolbox.getNamespaceColor("loops"),inputsInline:!0}),this.appendStatementInput("DO").appendField(c.block.appendField);let t=this;S(this,l,c.name,(function(){return e.U.rlf(c.tooltip,t.getField("VAR").getText())}),c.url,String(e.toolbox.getNamespaceColor("loops")))},getVars:function(){return[this.getField("VAR").getText()]},renameVar:function(e,t){const n=this.getField("VAR");Blockly.Names.equals(e,n.getText())&&n.setValue(t)},customContextMenu:function(e){if(!this.isCollapsed()&&!this.inDebugWorkspace()){let t={enabled:!0},n=this.getField("VAR").getText();t.text=lf("Create 'get {0}'",n);let o=goog.dom.createDom("field",null,n);o.setAttribute("name","VAR");let r=goog.dom.createDom("block",null,o);r.setAttribute("type","variables_get"),t.callback=Blockly.ContextMenu.callbackFactory(this,r),e.push(t)}}};const u=e.blocks.getBlockDefinition(ts.pxtc.TS_BREAK_TYPE);Blockly.Blocks[pxtc.TS_BREAK_TYPE]={init:function(){const t=e.toolbox.getNamespaceColor("loops");this.jsonInit({message0:u.block.message0,inputsInline:!0,previousStatement:null,nextStatement:null,colour:t}),S(this,ts.pxtc.TS_BREAK_TYPE,u.name,u.tooltip,u.url,t,void 0,void 0,!1)}};const d=e.blocks.getBlockDefinition(ts.pxtc.TS_CONTINUE_TYPE);Blockly.Blocks[pxtc.TS_CONTINUE_TYPE]={init:function(){const t=e.toolbox.getNamespaceColor("loops");this.jsonInit({message0:d.block.message0,inputsInline:!0,previousStatement:null,nextStatement:null,colour:t}),S(this,ts.pxtc.TS_CONTINUE_TYPE,d.name,d.tooltip,d.url,t,void 0,void 0,!1)}};const p="#cccccc";Blockly.Blocks[pxtc.COLLAPSED_BLOCK]={init:function(){this.jsonInit({message0:"...",inputsInline:!0,previousStatement:null,nextStatement:null,colour:p}),S(this,ts.pxtc.COLLAPSED_BLOCK,"...",lf("a few blocks"),void 0,p,void 0,void 0,!1)}}}(),function(){const t=Blockly.Msg,n="controls_if",o=e.blocks.getBlockDefinition(n),r=o.tooltip;t.CONTROLS_IF_MSG_IF=o.block.CONTROLS_IF_MSG_IF,t.CONTROLS_IF_MSG_THEN=o.block.CONTROLS_IF_MSG_THEN,t.CONTROLS_IF_MSG_ELSE=o.block.CONTROLS_IF_MSG_ELSE,t.CONTROLS_IF_MSG_ELSEIF=o.block.CONTROLS_IF_MSG_ELSEIF,t.CONTROLS_IF_TOOLTIP_1=r.CONTROLS_IF_TOOLTIP_1,t.CONTROLS_IF_TOOLTIP_2=r.CONTROLS_IF_TOOLTIP_2,t.CONTROLS_IF_TOOLTIP_3=r.CONTROLS_IF_TOOLTIP_3,t.CONTROLS_IF_TOOLTIP_4=r.CONTROLS_IF_TOOLTIP_4,E(n);const i="logic_compare",s=e.blocks.getBlockDefinition(i).tooltip;t.LOGIC_COMPARE_TOOLTIP_EQ=s.LOGIC_COMPARE_TOOLTIP_EQ,t.LOGIC_COMPARE_TOOLTIP_NEQ=s.LOGIC_COMPARE_TOOLTIP_NEQ,t.LOGIC_COMPARE_TOOLTIP_LT=s.LOGIC_COMPARE_TOOLTIP_LT,t.LOGIC_COMPARE_TOOLTIP_LTE=s.LOGIC_COMPARE_TOOLTIP_LTE,t.LOGIC_COMPARE_TOOLTIP_GT=s.LOGIC_COMPARE_TOOLTIP_GT,t.LOGIC_COMPARE_TOOLTIP_GTE=s.LOGIC_COMPARE_TOOLTIP_GTE,E(i);const a="logic_operation",l=e.blocks.getBlockDefinition(a),c=l.tooltip;t.LOGIC_OPERATION_AND=l.block.LOGIC_OPERATION_AND,t.LOGIC_OPERATION_OR=l.block.LOGIC_OPERATION_OR,t.LOGIC_OPERATION_TOOLTIP_AND=c.LOGIC_OPERATION_TOOLTIP_AND,t.LOGIC_OPERATION_TOOLTIP_OR=c.LOGIC_OPERATION_TOOLTIP_OR,E(a);const u="logic_negate",d=e.blocks.getBlockDefinition(u);t.LOGIC_NEGATE_TITLE=d.block.LOGIC_NEGATE_TITLE,E(u);const p="logic_boolean",g=e.blocks.getBlockDefinition(p);t.LOGIC_BOOLEAN_TRUE=g.block.LOGIC_BOOLEAN_TRUE,t.LOGIC_BOOLEAN_FALSE=g.block.LOGIC_BOOLEAN_FALSE,E(p)}(),function(){const t=e.blocks.getBlockDefinition("text");C("text",t.name,t.tooltip,t.url,Blockly.Colours.textField,Blockly.Colours.textField,Blockly.Colours.textField);const n=Blockly.Msg,o="text_length",r=e.blocks.getBlockDefinition(o);n.TEXT_LENGTH_TITLE=r.block.TEXT_LENGTH_TITLE,Blockly.Blocks[o].init=function(){this.jsonInit({message0:n.TEXT_LENGTH_TITLE,args0:[{type:"input_value",name:"VALUE",check:["String"]}],output:"Number",outputShape:Blockly.OUTPUT_SHAPE_ROUND})},E(o);const i="text_join",s=e.blocks.getBlockDefinition(i);n.TEXT_JOIN_TITLE_CREATEWITH=s.block.TEXT_JOIN_TITLE_CREATEWITH,E(i)}(),function(){const t=(e,t)=>Math.abs(t-(e.left+e.width/2)),n=Blockly.BlockDragger.prototype.drag;Blockly.BlockDragger.prototype.drag=function(o,r){const i=document.getElementsByClassName("blocklyToolboxDiv")[0],s=document.getElementsByClassName("blocklyTreeRoot")[0]||document.getElementsByClassName("blocklyFlyout")[0],a=document.getElementById("blocklyTrashIcon");if(s&&a){const n=t(s.getBoundingClientRect(),o.clientX);if(n<200){const t=n/200;a.style.opacity=""+(1-t),a.style.display="block",i&&(s.style.opacity=`${t}`,n<50&&e.BrowserUtils.addClass(i,"blocklyToolboxDeleting"))}else a.style.display="none",s.style.opacity="1",i&&e.BrowserUtils.removeClass(i,"blocklyToolboxDeleting")}return n.call(this,o,r)};const o=Blockly.BlockDragger.prototype.endDrag;Blockly.BlockDragger.prototype.endDrag=function(t,n){o.call(this,t,n);const r=document.getElementsByClassName("blocklyToolboxDiv")[0],i=document.getElementsByClassName("blocklyTreeRoot")[0]||document.getElementsByClassName("blocklyFlyout")[0],s=document.getElementById("blocklyTrashIcon");s&&i&&(s.style.display="none",i.style.opacity="1",r&&e.BrowserUtils.removeClass(r,"blocklyToolboxDeleting"))}}(),Blockly.Blocks[pxtc.TS_DEBUGGER_TYPE]={init:function(){let t=this;t.setColour(e.toolbox.getNamespaceColor("debug")),t.setPreviousStatement(!0),t.setNextStatement(!0),t.setInputsInline(!1),t.appendDummyInput("ON_OFF").appendField(new Blockly.FieldLabel(lf("breakpoint"),void 0),"DEBUGGER").appendField(new pxtblockly.FieldBreakpoint("1",{type:"number"}),"ON_OFF"),S(this,pxtc.TS_DEBUGGER_TYPE,lf("Debugger statement"),lf("A debugger statement invokes any available debugging functionality"),"/javascript/debugger",e.toolbox.getNamespaceColor("debug"))}},Blockly.Msg.WORKSPACE_COMMENT_DEFAULT_TEXT="",function(){const t=e=>{if(e.disabled)return lf("This block is disabled and will not run. Attach this block to an event to enable it.");let t=e.tooltip;for(;goog.isFunction(t);)t=t(e);return t};Blockly.Tooltip.show_=function(){const n=Blockly.Tooltip;if(n.poisonedElement_=n.element_,!Blockly.Tooltip.DIV)return;goog.dom.removeChildren(Blockly.Tooltip.DIV);function o(){let e=n.element_.RTL,t=goog.dom.getViewportSize(),o=Blockly.Tooltip.DIV;o.style.direction=e?"rtl":"ltr",o.style.display="block",Blockly.Tooltip.visible=!0;let r=n.lastX_;e?r-=Blockly.Tooltip.OFFSET_X+o.offsetWidth:r+=Blockly.Tooltip.OFFSET_X;let i=n.lastY_+Blockly.Tooltip.OFFSET_Y;i+o.offsetHeight>t.height+window.scrollY&&(i-=o.offsetHeight+2*Blockly.Tooltip.OFFSET_Y),e?r=Math.max(Blockly.Tooltip.MARGINS-window.scrollX,r):r+o.offsetWidth>t.width+window.scrollX-2*Blockly.Tooltip.MARGINS&&(r=t.width-o.offsetWidth-2*Blockly.Tooltip.MARGINS),o.style.top=i+"px",o.style.left=r+"px"}if(n.element_.codeCard){const r=e.docs.codeCard.render({header:t(n.element_)});Blockly.Tooltip.DIV.appendChild(r),o()}else{let e=t(n.element_);e=Blockly.utils._string.wrap(e,Blockly.Tooltip.LIMIT);let r=e.split("\n");for(let e=0;e<r.length;e++){let t=document.createElement("div");t.appendChild(document.createTextNode(r[e])),Blockly.Tooltip.DIV.appendChild(t)}o()}}}(),Blockly.Block.prototype.setEnabled=function(e){if(this.disabled==e){let t=Blockly.Events.recordUndo;Blockly.Events.recordUndo=!1,Blockly.Events.fire(new Blockly.Events.BlockChange(this,"disabled",null,this.disabled,!e)),Blockly.Events.recordUndo=t,this.disabled=!e}})}function b(e,t){const n=e.split(/\s*\|\s*/),r=[];for(const e of n)switch(e){case"number":r.push("Number");break;case"string":r.push("String");break;case"boolean":r.push("Boolean");break;case"T":case"any":return null;case"void":return;default:if(o(e)){if(n.length>1)return null;r.push("Array")}const i=t.apis.byQName[e];i&&i.extendsTypes&&0<i.extendsTypes.length?r.push(...i.extendsTypes):r.push(e)}return r}function v(e,t,n){const o=b(t,n);(o||null===o)&&e.setOutput(!0,o)}function T(t,n){const o=e.blocks.getBlockDefinition(n);S(t,n,o.name,o.tooltip,o.url,e.toolbox.getNamespaceColor(o.category))}function E(t){const n=e.blocks.getBlockDefinition(t);C(t,n.name,n.tooltip,n.url,e.toolbox.getNamespaceColor(n.category))}function S(n,o,r,i,s,a,l,c,u){!i||"string"!=typeof i&&"function"!=typeof i||n.setTooltip(i),s&&n.setHelpUrl(s),a&&n.setColour(a,l,c),u&&n.setDeletable(!1);let d=document.getElementById("blocklyToolboxDefinition"),p=d?t.getFirstChildWithAttr(d,"block","type",o):void 0;n.codeCard={header:r,name:r,software:1,description:goog.isFunction(i)?i(n):i,blocksXml:p?'<xml xmlns="http://www.w3.org/1999/xhtml">'+(f(p)||`<block type="${o}"></block>`)+"</xml>":void 0,url:s},e.Util.isTranslationMode()&&e.blocks.promptTranslateBlock&&(n.customContextMenu=t=>{const r=e.blocks.getBlockDefinition(n.type);r&&r.translationIds&&t.push({enabled:!0,text:lf("Translate this block"),callback:function(){e.blocks.promptTranslateBlock(o,r.translationIds)}})})}function C(e,t,n,o,r,i,s){let a=Blockly.Blocks[e],l=a.init;l&&(a.init=function(){l.call(this);S(this,e,t,n,o,r,i,s)})}function x(e){delete Blockly.Blocks[e.attributes.blockId],delete l[e.attributes.blockId]}function B(t,n,o,r){const i=document.createElement(r?"shadow":"block");i.setAttribute("type",e.Util.htmlEscape(t));const s=document.createElement("field");return s.setAttribute("name",e.Util.htmlEscape(n)),s.textContent=e.Util.htmlEscape(o),i.appendChild(s),i}function A(){const e=document.createElement("block");e.setAttribute("type","function_return");const t=document.createElement("value");t.setAttribute("name","RETURN_VALUE"),e.appendChild(t);const n=B("math_number","NUM","0",!0);return t.appendChild(n),e}t.installHelpResources=C,t.onShowContextMenu=void 0,t.mkPredicateBlock=function(e){const t=document.createElement("block");t.setAttribute("type",e);const n=document.createElement("value");n.setAttribute("name","PREDICATE"),t.appendChild(n);const o=B("logic_boolean","BOOL","TRUE",!0);return n.appendChild(o),t},t.mkFieldBlock=B,t.mkReturnStatementBlock=A;let I={};function D(e,t){return{field:e,name:t}}function N(t,n){return e.Util.values(t.byQName).filter((e=>4===e.kind&&e.attributes.fixedInstance&&function(e,t,n){if(t==n)return!0;let o=e.byQName[t];return!(!o||!o.extendsTypes)&&o.extendsTypes.indexOf(n)>=0}(t,e.retType,n)))}function w(e){return e.data?/^(?:\d+;?)+$/.test(e.data)?{commentRefs:e.data.split(";"),fieldData:{}}:JSON.parse(e.data):{commentRefs:[],fieldData:{}}}function R(e,t){e.data=JSON.stringify(t)}t.getFixedInstanceDropdownValues=N,t.generateIcons=function(t){const n=new e.ImageConverter;t.forEach((t=>{t.attributes.jresURL&&!t.attributes.iconURL&&e.U.startsWith(t.attributes.jresURL,"data:image/x-mkcd-f")&&(t.attributes.iconURL=n.convert(t.attributes.jresURL))}))},t.setVarFieldValue=function(e,t,n){const o=e.getField(t),r=e.workspace.getAllVariables();let i=!1;if(r&&r.length)for(let e=0;e<r.length;e++){const t=r[e];t.name===n&&(o.setValue(t.getId()),i=!0)}if(!i){o.initModel();const e=o.getVariable();e.name=n,o.setValue(e.getId())}},t.getBlockData=w,t.setBlockData=R,t.setBlockDataForField=function(e,t,n){const o=w(e);o.fieldData[t]=n,R(e,o)},t.getBlockDataForField=function(e,t){return w(e).fieldData[t]};class O extends WorkspaceSearch{createDom_(){super.createDom_(),this.addEvent_(this.workspace_.getInjectionDiv(),"click",this,(e=>{"flex"!=this.htmlDiv_.style.display||this.htmlDiv_.contains(e.target)||this.close()}))}highlightSearchGroup_(e){e.forEach((e=>{const t=e.pathObject.svgPath;Blockly.utils.dom.addClass(t,"blockly-ws-search-highlight-pxt")}))}unhighlightSearchGroup_(e){e.forEach((e=>{const t=e.pathObject.svgPath;Blockly.utils.dom.removeClass(t,"blockly-ws-search-highlight-pxt")}))}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")}}t.PxtWorkspaceSearch=O}(e.blocks||(e.blocks={}))}(pxt||(pxt={})),function(e){!function(t){let n;!function(e){e.ObjectDestructuringMutator="objectdestructuring",e.RestParameterMutator="restparameter",e.DefaultInstanceMutator="defaultinstance"}(n=t.MutatorTypes||(t.MutatorTypes={})),t.addMutation=function(e,t,o){let a;switch(o){case n.ObjectDestructuringMutator:if(!t.parameters||t.parameters.length<1)console.error("Destructuring mutations require at least one parameter");else{let e=!1;for(const n of t.parameters)if(-1!==n.type.indexOf("=>")){if(!n.properties||0===n.properties.length)return void console.error("Destructuring mutations only supported for functions with an event parameter that has multiple properties");e=!0}if(!e)return void console.error("Destructuring mutations must have an event parameter")}a=new r(e,t);break;case n.RestParameterMutator:a=new i(e,t);break;case n.DefaultInstanceMutator:a=new s(e,t);break;default:return void console.warn("Ignoring unknown mutation type: "+o)}e.mutationToDom=a.mutationToDom.bind(a),e.domToMutation=a.domToMutation.bind(a),e.compose=a.compose.bind(a),e.decompose=a.decompose.bind(a),e.mutation=a},t.mutateToolboxBlock=function(e,t,o){const a=document.createElement("mutation");switch(t){case n.ObjectDestructuringMutator:a.setAttribute(r.propertiesAttributeName,o);break;case n.RestParameterMutator:a.setAttribute(i.countAttributeName,o);break;case n.DefaultInstanceMutator:a.setAttribute(s.attributeName,o);default:return void console.warn("Ignoring unknown mutation type: "+t)}e.appendChild(a)};class o{constructor(e,t){this.info=t,this.block=e,this.topBlockType=this.block.type+"_mutator";const n=this.getSubBlockNames();this.initializeMutatorTopBlock(),this.initializeMutatorSubBlocks(n);const o=n.map((e=>e.type));this.block.setMutator(new Blockly.Mutator(o))}compose(e){const t=e.getDescendants(!1).map((e=>({type:e.type,name:e.inputList[0].name})));t.shift(),this.updateBlock(t)}decompose(e){const t=e.newBlock(this.topBlockType);t.initSvg();for(const n of t.inputList)if(n.name===o.mutatorStatmentInput){let t=n.connection;this.getVisibleBlockTypes().forEach((n=>{const o=e.newBlock(n);o.initSvg(),t.connect(o.previousConnection),t=o.nextConnection}));break}return t}compileMutation(e,t){}getDeclaredVariables(){}isDeclaredByMutation(e){return!1}initializeMutatorSubBlock(e,t,n){e.appendDummyInput(t).appendField(t),e.setColour(n),e.setNextStatement(!0),e.setPreviousStatement(!0)}initializeMutatorTopBlock(){const e=this.info.attributes.mutateText,t=this.block.getColour();Blockly.Blocks[this.topBlockType]=Blockly.Blocks[this.topBlockType]||{init:function(){const n=this;n.appendDummyInput().appendField(e),n.setColour(t),n.appendStatementInput(o.mutatorStatmentInput)}}}initializeMutatorSubBlocks(e){const t=this.block.getColour(),n=this.initializeMutatorSubBlock.bind(this);e.forEach((e=>{Blockly.Blocks[e.type]=Blockly.Blocks[e.type]||{init:function(){n(this,e.name,t)}}}))}}o.mutatorStatmentInput="PROPERTIES",o.mutatedVariableInputName="properties";class r extends o{constructor(e,t){super(e,t),this.currentlyVisible=[],this.parameterRenames={},this.prefix=this.info.attributes.mutatePrefix,this.block.appendDummyInput(o.mutatedVariableInputName),this.block.appendStatementInput("HANDLER").setCheck("null")}getMutationType(){return n.ObjectDestructuringMutator}compileMutation(e,n){if(!this.info.attributes.mutatePropertyEnum&&!this.parameters.length)return;const o=`function ({ ${this.parameters.map((n=>{const o=this.block.getField(n),r=o&&o.getText(),i=t.escapeVarName(n,e);return r!==n?(this.parameterRenames[n]=r,`${n}: ${t.escapeVarName(r,e)}`):i})).join(", ")} })`;return this.info.attributes.mutatePropertyEnum?t.mkText(` [${this.parameters.map((e=>`${this.info.attributes.mutatePropertyEnum}.${e}`)).join(", ")}],${o}`):t.mkText(o)}getDeclaredVariables(){const e={};return this.parameters.forEach((t=>{e[this.getVarFieldValue(t)]=this.parameterTypes[t]})),e}isDeclaredByMutation(e){return this.parameters.some((t=>this.getVarFieldValue(t)===e))}mutationToDom(){const t=document.createElement("mutation"),n=this.parameters.map((t=>{const n=this.getVarFieldValue(t);return n!==t&&(this.parameterRenames[t]=e.Util.htmlEscape(n)),e.Util.htmlEscape(t)})).join(",");t.setAttribute(r.propertiesAttributeName,n);for(const e in this.parameterRenames)e===this.parameterRenames[e]&&delete this.parameterRenames[e];return t.setAttribute(r.renameAttributeName,JSON.stringify(this.parameterRenames)),t}domToMutation(e){const t=e.getAttribute(r.propertiesAttributeName);if(t){const n=t.split(","),o=[];if(void 0===this.paramIndex&&(this.paramIndex=this.getParameterIndex()),n.forEach((e=>{const t=e.split(":");this.info.parameters[this.paramIndex].properties.some((e=>e.name===t[0]))&&o.push({property:t[0],newName:t[1]})})),this.parameterRenames=void 0,e.hasAttribute(r.renameAttributeName))try{this.parameterRenames=JSON.parse(e.getAttribute(r.renameAttributeName))}catch(e){console.warn("Ignoring invalid rename map in saved block mutation")}this.parameterRenames=this.parameterRenames||{},this.parameters=[],o.forEach((e=>{this.parameters.push(e.property),e.newName&&e.newName!==e.property&&(this.parameterRenames[e.property]=e.newName)})),this.updateVisibleProperties(),o.filter((e=>!!e.newName)).forEach((e=>this.setVarFieldValue(e.property,e.newName)))}}getVarFieldValue(e){const t=this.block.getField(e);return t&&t.getText()}setVarFieldValue(e,n){this.block.getField(e);this.block.getField(e)&&t.setVarFieldValue(this.block,e,n)}updateBlock(e){this.parameters=[],e.forEach((e=>{-1===this.parameters.indexOf(e.name)&&this.parameters.push(e.name)})),this.updateVisibleProperties()}getSubBlockNames(){return this.parameters=[],this.parameterTypes={},void 0===this.paramIndex&&(this.paramIndex=this.getParameterIndex()),this.info.parameters[this.paramIndex].properties.map((e=>(this.parameterTypes[e.name]=e.type,{type:this.propertyId(e.name),name:e.name})))}getVisibleBlockTypes(){return this.currentlyVisible.map((e=>this.propertyId(e)))}updateVisibleProperties(){if(e.Util.listsEqual(this.currentlyVisible,this.parameters))return;const t=this.block.inputList.find((e=>e.name===o.mutatedVariableInputName));this.prefix&&0===this.currentlyVisible.length&&t.appendField(this.prefix,r.prefixLabel),this.currentlyVisible.forEach((e=>{if(-1===this.parameters.indexOf(e)){const n=this.getVarFieldValue(e);n!==e&&(this.parameterRenames[e]=n),t.removeField(e)}})),this.parameters.forEach((e=>{if(-1===this.currentlyVisible.indexOf(e)){const n=this.parameterRenames[e]||e;t.appendField(new Blockly.FieldVariable(n),e)}})),this.prefix&&0===this.parameters.length&&t.removeField(r.prefixLabel),this.currentlyVisible=this.parameters}propertyId(e){return this.block.type+"_"+e}getParameterIndex(){for(let e=0;e<this.info.parameters.length;e++)if(-1!==this.info.parameters[e].type.indexOf("=>"))return e}}r.propertiesAttributeName="callbackproperties",r.renameAttributeName="renamemap",r.prefixLabel="0prefix_label_";class i extends o{constructor(){super(...arguments),this.count=0}getMutationType(){return n.RestParameterMutator}compileMutation(e,n){const o=[];return this.forEachInput((r=>o.push(t.compileExpression(e,r,n)))),t.mkGroup(o)}mutationToDom(){const e=document.createElement("mutation");return e.setAttribute(i.countAttributeName,this.count.toString()),e}domToMutation(e){const t=e.getAttribute(i.countAttributeName);if(t){try{this.count=parseInt(t)}catch(e){return}for(let e=0;e<this.count;e++)this.addNumberField(!1,e)}}updateBlock(e){if(e){const t=Math.abs(this.count-e.length);if(this.count<e.length)for(let e=0;e<t;e++)this.addNumberField(!0,this.count);else if(this.count>e.length)for(let e=0;e<t;e++)this.removeNumberField()}}getSubBlockNames(){return[{name:"Value",type:i.entryTypeName}]}getVisibleBlockTypes(){const e=[];return this.forEachInput((()=>e.push(i.entryTypeName))),e}addNumberField(e,t){const n=this.block.appendValueInput(i.valueInputPrefix+t).setCheck("Number");if(e){const e=this.block.workspace.newBlock("math_number");e.initSvg(),e.setShadow(!0),n.connection.connect(e.outputConnection),this.block.workspace.render(),this.count++}}removeNumberField(){this.count>0&&this.block.removeInput(i.valueInputPrefix+(this.count-1)),this.count--}forEachInput(e){for(let t=0;t<this.count;t++)e(this.block.getInputTargetBlock(i.valueInputPrefix+t),t)}}i.countAttributeName="count",i.entryTypeName="entry",i.valueInputPrefix="value_input_";class s extends o{constructor(){super(...arguments),this.showing=!1}getMutationType(){return n.DefaultInstanceMutator}compileMutation(e,n){if(this.showing){const o=this.block.getInputTargetBlock(s.instanceInputName);if(o)return t.compileExpression(e,o,n)}}mutationToDom(){const e=document.createElement("mutation");return e.setAttribute(s.attributeName,this.showing?"true":"false"),e}domToMutation(e){const t=e.getAttribute(s.attributeName);t?this.updateShape("true"===t):this.updateShape(!1)}updateBlock(e){this.updateShape(!(!e||!e.length))}getSubBlockNames(){return[{name:"Instance",type:s.instanceSubBlockType}]}getVisibleBlockTypes(){const e=[];return this.showing&&e.push(s.instanceSubBlockType),e}updateShape(e){this.showing!==e&&(e&&!this.block.getInputTargetBlock(s.instanceInputName)?this.block.appendValueInput(s.instanceInputName):this.block.removeInput(s.instanceInputName),this.showing=e)}}s.attributeName="showing",s.instanceInputName="__instance__",s.instanceSubBlockType="instance"}(e.blocks||(e.blocks={}))}(pxt||(pxt={})),function(e){!function(t){let n,o,r;function i(){return n||(o=document.createElement("div"),o.style.position="absolute",o.style.top="0",o.style.left="0",o.style.width="1px",o.style.height="1px",document.body.appendChild(o),n=Blockly.inject(o,{move:{scrollbars:!1},readOnly:!0,sounds:!1,media:e.webConfig.commitCdnUrl+"blockly/media/",rtl:e.Util.isUserLanguageRtl(),renderer:"pxt"})),e.blocks.clearWithoutEvents(n),n}function s(){n&&n.dispose(),n=void 0}function a(t={emPixels:18,layout:r.Align}){switch(t.splitSvg?r.Align:t.layout||r.Flow){case r.Align:e.blocks.layout.verticalAlign(n,t.emPixels||18);break;case r.Flow:e.blocks.layout.flow(n,{ratio:t.aspectRatio,useViewWidth:t.useViewWidth});break;case r.Clean:n.cleanUp_&&n.cleanUp_()}let i=n.getMetrics();const s=o.querySelectorAll("svg")[0].cloneNode(!0);return e.blocks.layout.cleanUpBlocklySvg(s),e.U.toArray(s.querySelectorAll(".blocklyBlockCanvas,.blocklyBubbleCanvas")).forEach((e=>e.setAttribute("transform",`translate(${-i.contentLeft}, ${-i.contentTop}) scale(1)`))),s.setAttribute("viewBox",`0 0 ${i.contentWidth} ${i.contentHeight}`),t.emPixels&&(s.style.width=i.contentWidth/t.emPixels+"em",s.style.height=i.contentHeight/t.emPixels+"em"),t.splitSvg?e.blocks.layout.splitSvg(s,n,t.emPixels):s}!function(e){e[e.None=0]="None",e[e.Align=1]="Align",e[e.Clean=3]="Clean",e[e.Flow=4]="Flow"}(r=t.BlockLayout||(t.BlockLayout={})),t.initRenderingWorkspace=i,t.cleanRenderingWorkspace=s,t.renderWorkspace=a,t.render=function(t,o={emPixels:18,layout:r.Align}){i();try{let r=t||'<xml xmlns="http://www.w3.org/1999/xhtml"></xml>',i=Blockly.Xml.textToDom(r);return e.blocks.domToWorkspaceNoEvents(i,n),a(o)}catch(t){return void e.reportException(t)}finally{s()}},t.blocksMetrics=function(e){const t=e.getTopBlocks(!1);if(!t.length)return{width:0,height:0};let n;return t.forEach((e=>{const t=e.getBoundingRectangle();n?(n.l=Math.min(n.l,t.left),n.r=Math.max(n.r,t.right),n.t=Math.min(n.t,t.top),n.b=Math.min(n.b,t.bottom)):n={l:t.left,r:t.right,t:t.top,b:t.bottom}})),{width:n.r-n.l,height:n.b-n.t}}}(e.blocks||(e.blocks={}))}(pxt||(pxt={})),function(e){!function(e){function t(e,t){let o=[];for(const r in e.children){const i=e.children[r];if("block"===i.tagName)if(t){const e=i.getAttribute("type");e&&e===t&&o.push(i)}else o.push(i);else{const e=n(i);e&&(o=o.concat(e))}}return o}function n(e,n){let o=t(e,n);return o.length?o[0]:null}e.findRootBlocks=t,e.findRootBlock=n}(e.blocks||(e.blocks={}))}(pxt||(pxt={})),function(e){!function(t){!function(t){t.render=function(t,n={}){const o=t.url?/^[^:]+:\/\//.test(t.url)?t.url:"/"+t.url.replace(/^\.?\/?/,""):t.youTubeId?`https://youtu.be/${t.youTubeId}`:void 0,r=!!o,i=(e,t,n="div",o="")=>{let r=document.createElement(n);return t&&(r.className=t),e&&e.appendChild(r),o&&r.appendChild(document.createTextNode(o+"")),r};let s=i(null,"ui "+(t.style||"card")+" "+(t.color||"")+(r?" link":""),r?"a":"div");if(s.setAttribute("role","option"),s.setAttribute("aria-selected","true"),r){const e=s;e.href=o,/^https?:\/\//.test(o)&&(e.target="_blank")}if(!n.hideHeader&&t.header){let e=i(s,"ui content "+(t.responsive?" tall desktop only":""));t.header&&i(e,"description","span",t.header)}const a=(n.shortName?t.shortName:"")||t.name;let l=i(s,"ui image"+(t.responsive?" tall landscape only":""));if(t.label){let e=document.createElement("label");e.className=`ui ${t.labelClass?t.labelClass:"orange right ribbon"} label`,e.textContent=t.label,l.appendChild(e)}if(t.blocksXml){const n=e.blocks.render(t.blocksXml);if(n){let e=i(l,"");e.setAttribute("style","width:100%; min-height:10em"),e.appendChild(n)}else console.error("failed to render blocks"),e.debug(t.blocksXml)}if(t.typeScript){let e=document.createElement("pre");e.appendChild(document.createTextNode(t.typeScript)),l.appendChild(e)}if(t.imageUrl||(t.youTubeId?`https://img.youtube.com/vi/${t.youTubeId}/0.jpg`:void 0)){let e=document.createElement("div");e.className="ui imagewrapper";let n=document.createElement("div");n.className="ui cardimage",n.style.backgroundImage=`url("${t.imageUrl}")`,n.title=a,n.setAttribute("role","presentation"),e.appendChild(n),l.appendChild(e)}if("file"==t.cardType){let e=i(s,"ui fileimage");l.appendChild(e)}if(a||t.description){let e=i(s,"ui content");if(a&&(s.setAttribute("aria-label",a),i(e,"header","div",a)),t.description){const n=i(e,"ui description"),o=t.description.split(".")[0]+".";n.appendChild(document.createTextNode(o))}}if(t.time){let n=i(s,"meta");if(t.time){i(n,"date","span").appendChild(document.createTextNode(e.Util.timeSince(t.time)))}}if(t.extracontent){i(s,"extra content","div").appendChild(document.createTextNode(t.extracontent))}return s}}(t.codeCard||(t.codeCard={}))}(e.docs||(e.docs={}))}(pxt||(pxt={})),function(e){!function(t){function n(e,t){const n=e,o=n.mutationToDom,r=n.domToMutation;n.mutationToDom=()=>{const e=o?o():document.createElement("mutation");return t.mutationToDom(e)},n.domToMutation=e=>{r&&r(e),t.domToMutation(e)}}t.appendMutation=n,t.initVariableArgsBlock=function(e,o){let r=0,i=0,s=e.appendDummyInput(),a=()=>{if(r!==i){if(r>i){const t=r-i;for(let n=0;n<t;n++){const t=o[i+n];s.insertFieldAt(s.fieldRow.length-1,new pxtblockly.FieldArgumentVariable(t.name),"HANDLER_"+t.name);const r=e;(null==r?void 0:r.initSvg)&&r.initSvg()}}else{let e=i-r;for(let t=0;t<e;t++){const e=o[i-t-1];s.removeField("HANDLER_"+e.name)}}r>=o.length?s.removeField("_HANDLER_ADD"):i>=o.length&&l(),i=r}};function l(){s.appendField(new Blockly.FieldImage(e.ADD_IMAGE_DATAURI,24,24,lf("Add argument"),(()=>{r=Math.min(r+1,o.length),a()}),!1),"_HANDLER_ADD")}Blockly.Extensions.apply("inline-svgs",e,!1),l(),n(e,{mutationToDom:t=>{t.setAttribute("numArgs",r.toString());for(let n=0;n<r;n++){const r=e.getField("HANDLER_"+o[n].name);let i=r&&r.getText();t.setAttribute("arg"+n,i)}return t},domToMutation:n=>{let i=parseInt(n.getAttribute("numargs"));r=Math.min(isNaN(i)?0:i,o.length),a();for(let i=0;i<r;i++){const r=n.getAttribute("arg"+i),s="HANDLER_"+o[i].name;e.getField(s)&&t.setVarFieldValue(e,s,r)}}})},t.initExpandableBlock=function(r,i,s,a,l,c){const u="0_add_button",d="0_rem_button",p="_expanded",g="_input_init",h=s.parameters.map((e=>e.name)),f=s.parameters.length,_=l?f:1,m=new o(i);function y(n,o=!1,l=!1){const c=E(n);if(!l&&!o&&c===m.getNumber(p))return;m.setValue(p,c);const u=c;if(!m.getBoolean(g)&&u>0&&(T(),!i.rendered))return;let d=0;for(let n=0;n<i.inputList.length;n++){const o=i.inputList[n];if(e.Util.startsWith(o.name,t.optionalDummyInputPrefix))S(o,d<u||u===f);else if(e.Util.startsWith(o.name,t.optionalInputWithFieldPrefix)||-1!==h.indexOf(o.name)){const e=d<u;if(S(o,e),e&&o.connection&&!o.connection.isConnected()&&!i.isInsertionMarker()){const e=a.definitionNameToParam[s.parameters[d].name];let n=t.createShadowValue(r,e);"value"===n.tagName.toLowerCase()&&(n=n.firstElementChild),Blockly.Events.disable();try{const e=Blockly.Xml.domToBlock(n,i.workspace);e&&o.connection.connect(e.outputConnection)}catch(e){}Blockly.Events.enable()}++d}}b(),o||i.render()}function k(e,t,n,o){i.appendDummyInput(e).appendField(new Blockly.FieldImage(t,24,24,n,(()=>y(o)),!1))}function b(){const e=m.getNumber(p),t=e!==f,n=0!==e,o=!!i.getInput(d),r=!!i.getInput(u);t||i.removeInput(u,!0),n||i.removeInput(d,!0),n&&!o&&k(d,i.REMOVE_IMAGE_DATAURI,lf("Hide optional arguments"),-1*_),t&&(r&&i.inputList.findIndex((e=>e.name===u))!==i.inputList.length-1?(i.removeInput(u,!0),v()):r||v())}function v(){k(u,i.ADD_IMAGE_DATAURI,lf("Reveal optional arguments"),_)}function T(){m.setValue(g,!0),c(),b()}function E(e){return Math.min(Math.max(m.getNumber(p)+e,0),f)}function S(e,t){if(i.rendered){e.setVisible(t).forEach((e=>{e.render()}))}}m.setEventsEnabled(!1),m.setValue(p,0),m.setValue(g,!1),m.setEventsEnabled(!0),Blockly.Extensions.apply("inline-svgs",i,!1),v(),n(i,{mutationToDom:e=>(e.setAttribute(p,m.getString(p)),e.setAttribute(g,m.getString(g)),e),domToMutation:e=>{if(m.setEventsEnabled(!1),e.hasAttribute(g)&&"true"==e.getAttribute(g)&&!m.getBoolean(g)&&(m.setValue(g,!0),T()),e.hasAttribute(p)){const t=parseInt(e.getAttribute(p));if(!isNaN(t)){const e=t-(m.getNumber(p)||0);m.getBoolean(g)?i.rendered||i.isInsertionMarker()?y(e,!0,i.isInsertionMarker()):m.setValue(p,E(e)):y(e,!0)}}m.setEventsEnabled(!0)}}),setTimeout((()=>{i.rendered&&!i.workspace.isDragging()&&y(0,void 0,!0)}),1)},t.initReturnStatement=function(t){const n=e.blocks.getBlockDefinition("function_return"),o="0_add_button",r="0_rem_button";Blockly.Extensions.apply("inline-svgs",t,!1);let i,s=!0;function a(){const a=t.getInput("RETURN_VALUE");if(s){if(!a){for(;t.getInput("");)t.removeInput("");t.jsonInit({message0:n.block.message_with_value,args0:[{type:"input_value",name:"RETURN_VALUE",check:null}],previousStatement:null,colour:e.toolbox.getNamespaceColor("functions")})}if(t.getInput(o)&&t.removeInput(o),t.getInput(r)||u(r,t.REMOVE_IMAGE_DATAURI,lf("Remove return value")),i){const e=t.workspace.getBlockById(i);e&&e.outputConnection&&!e.outputConnection.targetBlock()&&t.getInput("RETURN_VALUE").connection.connect(e.outputConnection),i=void 0}}else{if(a){const o=a.connection.targetBlock();o&&(o.isShadow()&&o.setShadow(!1),a.connection.disconnect(),i=o.id),t.removeInput("RETURN_VALUE"),t.jsonInit({message0:n.block.message_no_value,args0:[],previousStatement:null,colour:e.toolbox.getNamespaceColor("functions")})}t.getInput(r)&&t.removeInput(r),t.getInput(o)||u(o,t.ADD_IMAGE_DATAURI,lf("Add return value"))}t.setInputsInline(!0)}function l(){return Blockly.Xml.domToText(t.mutationToDom())}function c(e,n){e!==n&&Blockly.Events.fire(new Blockly.Events.BlockChange(t,"mutation",null,e,n))}function u(e,n,o){t.appendDummyInput(e).appendField(new Blockly.FieldImage(n,24,24,o,(()=>{const e=l();s=!s;const t=l();c(e,t),a();c(t,l())}),!1))}a(),t.domToMutation=e=>{e.hasAttribute("last_connected_id")&&(i=e.getAttribute("last_connected_id")),s="true"!==e.getAttribute("no_return_value"),a()},t.mutationToDom=()=>{const e=document.createElement("mutation");return function(e,t){e.setAttribute("no_return_value",t?"false":"true")}(e,!!t.getInput("RETURN_VALUE")),i&&e.setAttribute("last_connected_id",i),e}};class o{constructor(e,t){this.block=e,this.fireEvents=!0,this.state=t||{}}setValue(e,t){if(this.fireEvents&&this.block.mutationToDom){const n=this.block.mutationToDom();this.state[e]=t.toString();const o=this.block.mutationToDom();Object.keys(this.state).forEach((e=>{n.getAttribute(e)!==this.state[e]&&o.setAttribute(e,this.state[e])}));const r=Blockly.Xml.domToText(n),i=Blockly.Xml.domToText(o);r!=i&&Blockly.Events.fire(new Blockly.Events.BlockChange(this.block,"mutation",null,r,i))}else this.state[e]=t.toString()}getNumber(e){return parseInt(this.state[e])}getBoolean(e){return"false"!=this.state[e]}getString(e){return this.state[e]}setEventsEnabled(e){this.fireEvents=e}}}(e.blocks||(e.blocks={}))}(pxt||(pxt={})),function(e){!function(t){const n=e.blocks.MATH_FUNCTIONS.unary.concat(e.blocks.MATH_FUNCTIONS.binary).concat(e.blocks.MATH_FUNCTIONS.infix);let o;t.initMathOpBlock=function(){const r="math_js_op",i=e.blocks.getBlockDefinition(r);function s(e,t){const n=e.appendValueInput("ARG"+(t?1:0));n.setCheck("Number"),t&&(n.connection.setShadowDom(function(){if(!o){o=document.createElement("shadow"),o.setAttribute("type","math_number");const e=document.createElement("field");e.setAttribute("name","NUM"),e.textContent="0",o.appendChild(e)}return o}()),n.connection.respawnShadow_())}function a(e,t){let n=!!e.getInput("ARG1");t?(n&&e.moveInputBefore("op_dropdown","ARG1"),e.moveInputBefore("ARG0","op_dropdown")):(n&&e.moveInputBefore("ARG0","ARG1"),e.moveInputBefore("op_dropdown","ARG0"))}Blockly.Blocks[r]={init:function(){const o=this;o.setPreviousStatement(!1),o.setNextStatement(!1),o.setOutput(!0,"Number"),o.setOutputShape(Blockly.OUTPUT_SHAPE_ROUND),o.setInputsInline(!0);o.appendDummyInput("op_dropdown").appendField(new Blockly.FieldDropdown(n.map((e=>[i.block[e],e])),(t=>function(t,n){!function(t){return-1!==e.blocks.MATH_FUNCTIONS.unary.indexOf(t)}(n)?t.getInput("ARG1")||s(t,!0):t.removeInput("ARG1",!0);a(t,function(t){return-1!==e.blocks.MATH_FUNCTIONS.infix.indexOf(t)}(n))}(o,t))),"OP"),s(o,!1),t.appendMutation(o,{mutationToDom:e=>{let t;for(let e=0;e<o.inputList.length;e++){const n=o.inputList[e];if("op_dropdown"===n.name){t=!1;break}if("ARG0"===n.name){t=!0;break}}return e.setAttribute("op-type",(o.getInput("ARG1")?t?"infix":"binary":"unary").toString()),e},domToMutation:e=>{if(e.hasAttribute("op-type")){const t=e.getAttribute("op-type");"unary"!=t&&s(o,!0),a(o,"infix"===t)}}})}},t.installHelpResources(r,i.name,(function(e){return i.tooltip[e.getFieldValue("OP")]}),i.url,e.toolbox.getNamespaceColor(i.category))}}(e.blocks||(e.blocks={}))}(pxt||(pxt={})),function(e){!function(t){const n=e.blocks.ROUNDING_FUNCTIONS;t.initMathRoundBlock=function(){const o="math_js_round",r=e.blocks.getBlockDefinition(o);Blockly.Blocks[o]={init:function(){const e=this;e.setPreviousStatement(!1),e.setNextStatement(!1),e.setOutput(!0,"Number"),e.setOutputShape(Blockly.OUTPUT_SHAPE_ROUND),e.setInputsInline(!0);e.appendDummyInput("round_dropdown").appendField(new Blockly.FieldDropdown(n.map((e=>[r.block[e],e])),(e=>{})),"OP"),function(e){e.appendValueInput("ARG0").setCheck("Number")}(e)}},t.installHelpResources(o,r.name,(function(e){return r.tooltip[e.getFieldValue("OP")]}),r.url,e.toolbox.getNamespaceColor(r.category))}}(e.blocks||(e.blocks={}))}(pxt||(pxt={})),function(e){class t extends Blockly.Field{constructor(e,t,n){super(e,n),this.SERIALIZABLE=!0,this.options=t,e&&!this.valueText&&(this.valueText=e)}init(){super.init(),this.onInit()}dispose(){this.onDispose()}getValue(){return this.valueText}doValueUpdate_(e){null!==e&&(this.valueText=this.loaded?this.onValueChanged(e):e)}getDisplayText_(){return this.valueText}onLoadedIntoWorkspace(){this.loaded||(this.loaded=!0,this.valueText=this.onValueChanged(this.valueText))}isInitialized(){return!!this.fieldGroup_}getBlockData(){return pxt.blocks.getBlockDataForField(this.sourceBlock_,this.name)}setBlockData(e){pxt.blocks.setBlockDataForField(this.sourceBlock_,this.name,e)}}e.FieldBase=t}(pxtblockly||(pxtblockly={})),function(e){var t=pxt.svgUtil;const n=32;class o extends e.FieldBase{constructor(e,t,n){super(e,t,n),this.pendingEdit=!1,this.isEmpty=!1,this.assetChangeListener=()=>{if(this.pendingEdit)return;const e=this.getBlockData();e&&(this.asset=pxt.react.getTilemapProject().lookupAsset(this.getAssetType(),e)),this.redrawPreview()},this.lightMode=t.lightMode,this.params=this.parseFieldOptions(t),this.blocksInfo=t.blocksInfo}onInit(){this.redrawPreview()}onValueChanged(e){return this.parseValueText(e),this.redrawPreview(),this.getValueText()}showEditor_(){if(this.isGreyBlock)return;const t=Object.assign({},this.params);let n;switch(t.blocksInfo=this.blocksInfo,this.asset.type){case"tile":case"image":n="image-editor",t.temporaryAssets=e.getTemporaryAssets(this.sourceBlock_.workspace,"image");break;case"animation":n="animation-editor",t.temporaryAssets=e.getTemporaryAssets(this.sourceBlock_.workspace,"image").concat(e.getTemporaryAssets(this.sourceBlock_.workspace,"animation"));break;case"tilemap":n="tilemap-editor";const o=pxt.react.getTilemapProject();pxt.sprite.addMissingTilemapTilesAndReferences(o,this.asset)}const o=pxt.react.getFieldEditorView(n,this.asset,t);this.undoRedoState&&o.restorePersistentData(this.undoRedoState),pxt.react.getTilemapProject().pushUndo(),o.onHide((()=>{var e;const t=o.getResult(),n=pxt.react.getTilemapProject();if(t){const s=this.getValue();if(pxt.assetEquals(this.asset,t))return;const a=r(this.asset)?null:this.asset.id;let l=r(t)?null:t.id;a||l!==this.sourceBlock_.id||(t.id=n.generateNewID(t.type),l=t.id),this.pendingEdit=!0,(null===(e=t.meta)||void 0===e?void 0:e.displayName)&&this.disposeOfTemporaryAsset(),this.asset=t;const c=n.revision();if(this.onEditorClose(this.asset),this.updateAssetListener(),this.updateAssetMeta(),this.redrawPreview(),this.undoRedoState=o.getPersistentData(),this.sourceBlock_&&Blockly.Events.isEnabled()){const e=new i(this.sourceBlock_,"field",this.name,s,this.getValue(),c,n.revision());a!==l&&(e.oldAssetId=a,e.newAssetId=l),Blockly.Events.fire(e)}this.pendingEdit=!1}})),o.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 e=pxt.Util.htmlUnescape(this.valueText);return e.substr(0,e.indexOf("("))+"(...)"}return""}updateEditable(){if(this.isGreyBlock&&this.fieldGroup_){const e=this.fieldGroup_;Blockly.utils.dom.removeClass(e,"blocklyNonEditableText"),Blockly.utils.dom.removeClass(e,"blocklyEditableText"),e.style.cursor=""}else super.updateEditable()}getValue(){return this.isGreyBlock?pxt.Util.htmlUnescape(this.valueText):this.getValueText()}onDispose(){var e;(null===(e=this.sourceBlock_)||void 0===e?void 0:e.workspace)&&!this.sourceBlock_.workspace.rendered&&this.disposeOfTemporaryAsset(),pxt.react.getTilemapProject().removeChangeListener(this.getAssetType(),this.assetChangeListener)}disposeOfTemporaryAsset(){this.isTemporaryAsset()&&(pxt.react.getTilemapProject().removeAsset(this.asset),this.setBlockData(null),this.asset=void 0)}clearTemporaryAssetData(){this.isTemporaryAsset()&&this.setBlockData(null)}isTemporaryAsset(){return r(this.asset)}getAsset(){return this.asset}updateAsset(e){this.asset=e,this.setValue(this.getValue())}onEditorClose(e){}redrawPreview(){if(!this.fieldGroup_)return;if(pxsim.U.clear(this.fieldGroup_),this.isGreyBlock)return this.createTextElement_(),this.render_(),void this.updateEditable();const o=(new t.Rect).at(5,1).size(40,40).setClass("blocklySpriteField").stroke("#898989",1).corner(4);if(this.fieldGroup_.appendChild(o.el),this.asset){let o;switch(this.asset.type){case"image":case"tile":o=e.bitmapToImageURI(pxt.sprite.Bitmap.fromData(this.asset.bitmap),n,this.lightMode);break;case"animation":o=e.bitmapToImageURI(pxt.sprite.Bitmap.fromData(this.asset.frames[0]),n,this.lightMode);break;case"tilemap":o=e.tilemapToImageURI(this.asset.data,n,this.lightMode)}const r=(new t.Image).src(o).at(9,5).size(n,n);this.fieldGroup_.appendChild(r.el)}}parseValueText(e){if(e=pxt.Util.htmlUnescape(e),this.sourceBlock_&&!this.sourceBlock_.isInFlyout){const t=pxt.react.getTilemapProject(),n=this.getBlockData(),o=t.lookupAsset(this.getAssetType(),n);!o||e&&this.isEmpty?(this.setBlockData(null),this.asset&&this.sourceBlock_&&this.asset.meta.blockIDs&&(this.asset.meta.blockIDs=this.asset.meta.blockIDs.filter((e=>e!==this.sourceBlock_.id)),this.isTemporaryAsset()||t.updateAsset(this.asset)),this.isEmpty=!e,this.asset=this.createNewAsset(e)):this.asset=o,this.updateAssetMeta(),this.updateAssetListener()}}parseFieldOptions(e){const t={initWidth:16,initHeight:16,disableResize:!1,lightMode:!1};return e?(e.disableResize&&(t.disableResize="true"===e.disableResize.toLowerCase()||"1"===e.disableResize),t.initWidth=n(e.initWidth,t.initWidth),t.initHeight=n(e.initHeight,t.initHeight),t.lightMode=e.lightMode,t):t;function n(e,t){const n=parseInt(e);return isNaN(n)?t:n}}updateAssetMeta(){if(this.asset){if(this.asset.meta||(this.asset.meta={}),this.asset.meta.blockIDs||(this.asset.meta.blockIDs=[]),this.sourceBlock_){if(-1===this.asset.meta.blockIDs.indexOf(this.sourceBlock_.id)){const e=this.asset.meta.blockIDs;e.length&&this.isTemporaryAsset()&&e.some((e=>this.sourceBlock_.workspace.getBlockById(e)))&&(this.asset=pxt.cloneAsset(this.asset),this.asset.meta.blockIDs=[]),this.asset.meta.blockIDs.push(this.sourceBlock_.id)}this.setBlockData(this.asset.id)}this.isTemporaryAsset()?this.asset.meta.temporaryInfo={blockId:this.sourceBlock_.id,fieldName:this.name}:pxt.react.getTilemapProject().updateAsset(this.asset)}}updateAssetListener(){pxt.react.getTilemapProject().removeChangeListener(this.getAssetType(),this.assetChangeListener),this.asset&&!this.isTemporaryAsset()&&pxt.react.getTilemapProject().addChangeListener(this.asset,this.assetChangeListener)}}function r(e){return e&&!e.meta.displayName}e.FieldAssetEditor=o;class i extends Blockly.Events.BlockChange{constructor(e,t,n,o,r,i,s){super(e,t,n,o,r),this.oldRevision=i,this.newRevision=s,this.fieldName=n}isNull(){return this.oldRevision===this.newRevision&&super.isNull()}run(e){if(this.newAssetId||this.oldAssetId){const t=this.getEventWorkspace_().getBlockById(this.blockId);e?pxt.blocks.setBlockDataForField(t,this.fieldName,this.newAssetId):pxt.blocks.setBlockDataForField(t,this.fieldName,this.oldAssetId)}e?(pxt.react.getTilemapProject().redo(),super.run(e)):(pxt.react.getTilemapProject().undo(),super.run(e));const t=this.getEventWorkspace_(),n=new i(t.getBlockById(this.blockId),"tilemap-revision","revision",null,pxt.react.getTilemapProject().revision(),0,0);n.recordUndo=!1,Blockly.Events.fire(n)}}e.BlocklyTilemapChange=i}(pxtblockly||(pxtblockly={})),function(e){var t=pxt.svgUtil;const n=32;class o extends e.FieldAssetEditor{constructor(){super(...arguments),this.onMouseEnter=()=>{if(this.animateRef||!this.asset)return;const e=this.getParentInterval()||this.asset.interval,t=e>50?e:50;let n=0;this.animateRef=setInterval((()=>{this.preview&&this.frames[n]&&this.preview.src(this.frames[n]),n=(n+1)%this.frames.length}),t)},this.onMouseLeave=()=>{this.animateRef&&clearInterval(this.animateRef),this.animateRef=void 0,this.preview&&this.frames[0]&&this.preview.src(this.frames[0])}}initView(){this.sourceBlock_.getSvgRoot().addEventListener("mouseenter",this.onMouseEnter),this.sourceBlock_.getSvgRoot().addEventListener("mouseleave",this.onMouseLeave)}showEditor_(){this.asset&&(this.asset.interval=this.getParentInterval()||this.asset.interval),super.showEditor_()}render_(){super.render_(),this.size_.height=42,this.size_.width=80}getAssetType(){return"animation"}createNewAsset(e){const t=pxt.react.getTilemapProject();if(e){const o=pxt.lookupProjectAssetByTSReference(e,t);if(o)return o;const r=-1===(n=e).indexOf("[")?null:(n=n.replace(/[\[\]]/gm,"")).split(",").map((e=>pxt.sprite.imageLiteralToBitmap(e).data())).filter((e=>e.height&&e.width));if(r&&r.length){return{internalID:-1,id:this.sourceBlock_.id,type:"animation",frames:r,interval:this.getParentInterval(),meta:{}}}const i=t.lookupAssetByName("animation",e.trim());if(i)return i}var n;return{internalID:-1,id:this.sourceBlock_.id,type:"animation",frames:[new pxt.sprite.Bitmap(this.params.initWidth,this.params.initHeight).data()],interval:500,meta:{}}}onEditorClose(e){this.setParentInterval(e.interval)}getValueText(){return this.asset?this.isTemporaryAsset()?"["+this.asset.frames.map((e=>pxt.sprite.bitmapToImageLiteral(pxt.sprite.Bitmap.fromData(e),"typescript"))).join(",")+"]":pxt.getTSReferenceForAsset(this.asset):"[]"}redrawPreview(){if(!this.fieldGroup_)return;pxsim.U.clear(this.fieldGroup_);const o=(new t.Rect).at(35,1).size(40,40).corner(4).setClass("blocklyAnimationField");this.fieldGroup_.appendChild(o.el);const r=new t.Text("").at(5,26).fill(this.sourceBlock_.getColourSecondary()).setClass("semanticIcon");this.fieldGroup_.appendChild(r.el),this.asset&&(this.frames=this.asset.frames.map((t=>e.bitmapToImageURI(pxt.sprite.Bitmap.fromData(t),n,this.lightMode))),this.preview=(new t.Image).src(this.frames[0]).at(39,5).size(n,n),this.fieldGroup_.appendChild(this.preview.el))}getParentIntervalBlock(){const e=this.sourceBlock_;if(e.parentBlock_){const t=e.parentBlock_;for(const e of t.inputList)if("frameInterval"===e.name)return e.connection.targetBlock()}}setParentInterval(e){const t=this.getParentIntervalBlock();if(t){const n=r(t);n&&t.setFieldValue(String(e),n)}}getParentInterval(){const e=this.getParentIntervalBlock();if(e){const t=r(e);if(t)return Number(e.getFieldValue(t))}return 100}parseFieldOptions(e){return function(e){const t={initWidth:16,initHeight:16,disableResize:!1,lightMode:!1};if(!e)return t;t.lightMode=e.lightMode,e.filter&&(t.filter=e.filter);return t.initWidth=n(e.initWidth,t.initWidth),t.initHeight=n(e.initHeight,t.initHeight),t;function n(e,t){const n=parseInt(e);return isNaN(n)?t:n}}(e)}}function r(e){return"math_number_minmax"===e.type?"SLIDER":"math_number"===(t=e.type)||"math_integer"===t||"math_whole_number"===t?"NUM":"timePicker"===e.type?"ms":null;var t}e.FieldAnimationEditor=o}(pxtblockly||(pxtblockly={})),function(e){class t extends Blockly.FieldVariable{constructor(e){super(e),this.menuGenerator_=this.dropdownCreate}dropdownCreate(){return Blockly.FieldVariable.dropdownCreate.call(this).filter((e=>e[1]!=Blockly.DELETE_VARIABLE_ID))}}e.FieldArgumentVariable=t}(pxtblockly||(pxtblockly={})),function(e){class t extends Blockly.FieldNumber{constructor(e,t,n){super(e,void 0,void 0,void 0,n),this.isFieldCustom_=!0,this.CURSOR="pointer",this.params=t,this.setValue(e),this.addArgType("toggle"),this.type_=t.type}initView(){if(!this.fieldGroup_)return;null!==this.getArgTypes()&&(this.sourceBlock_.isShadow()?this.sourceBlock_.svgGroup_.setAttribute("data-argument-type",this.getArgTypes()):this.fieldGroup_.setAttribute("data-argument-type",this.getArgTypes()));const e=this.getSize();this.checkElement_=Blockly.utils.dom.createSvgElement("g",{class:"blocklyToggle "+(this.state_?"blocklyToggleOnBreakpoint":"blocklyToggleOffBreakpoint"),transform:`translate(8, ${e.height/2})`},this.fieldGroup_),this.toggleThumb_=Blockly.utils.dom.createSvgElement("polygon",{class:"blocklyToggleRect",points:"50,5 100,5 125,30 125,80 100,105 50,105 25,80 25,30"},this.checkElement_);let t=this.sourceBlock_.RTL?-e.width/2:e.width/2;this.textElement_=Blockly.utils.dom.createSvgElement("text",{class:"blocklyText",x:t,dy:"0.6ex",y:e.height/2},this.fieldGroup_),this.switchToggle(this.state_),this.setValue(this.getValue()),this.markDirty()}updateSize_(){this.size_.width=30}getValue(){return this.toVal(this.state_)}setValue(e){let t=this.fromVal(e);this.state_!==t&&(this.sourceBlock_&&Blockly.Events.isEnabled()&&Blockly.Events.fire(new Blockly.Events.BlockChange(this.sourceBlock_,"field",this.name,this.state_,t)),this.state_=t,this.switchToggle(this.state_))}switchToggle(e){this.checkElement_&&(this.updateSize_(),e?(pxt.BrowserUtils.addClass(this.checkElement_,"blocklyToggleOnBreakpoint"),pxt.BrowserUtils.removeClass(this.checkElement_,"blocklyToggleOffBreakpoint")):(pxt.BrowserUtils.removeClass(this.checkElement_,"blocklyToggleOnBreakpoint"),pxt.BrowserUtils.addClass(this.checkElement_,"blocklyToggleOffBreakpoint")),this.checkElement_.setAttribute("transform","translate(-7, -1) scale(0.3)"))}updateDisplay_(e){super.updateDisplay_(e),this.textElement_&&pxt.BrowserUtils.addClass(this.textElement_,"blocklyToggleText")}render_(){this.visible_&&this.textElement_&&(goog.dom.removeChildren(this.textElement_),this.updateSize_())}showEditor_(){let e=!this.state_;null!==e&&this.setValue(this.toVal(e))}toVal(e){return"number"==this.type_?String(e?"1":"0"):String(e?"true":"false")}fromVal(e){return"string"==typeof e?"1"==e||"TRUE"==e.toUpperCase():!!e}}e.FieldBreakpoint=t}(pxtblockly||(pxtblockly={})),function(e){class t extends Blockly.FieldSlider{constructor(e,t,n){super(String(e),"0","255","1","10","Color",n),this.isFieldCustom_=!0,this.params=t,this.params.min&&(this.min_=parseFloat(this.params.min)),this.params.max&&(this.max_=parseFloat(this.params.max)),this.params.label&&(this.labelText_=this.params.label),this.params.channel&&(this.channel_=this.params.channel)}setBackground_(e){let t=this.createColourStops_().join(",");goog.style.setStyle(e,"background","-moz-linear-gradient(left, "+t+")"),goog.style.setStyle(e,"background","-webkit-linear-gradient(left, "+t+")"),goog.style.setStyle(e,"background","-o-linear-gradient(left, "+t+")"),goog.style.setStyle(e,"background","-ms-linear-gradient(left, "+t+")"),goog.style.setStyle(e,"background","linear-gradient(left, "+t+")"),this.params.sliderWidth&&goog.style.setStyle(e,"width",`${this.params.sliderWidth}px`)}setReadout_(e,t){const n=this.colorWheel(parseInt(t),this.channel_),o=document.createElement("span");o.className="blocklyColorReadout",o.style.backgroundColor=`${n}`,pxsim.U.clear(e),e.appendChild(o)}createColourStops_(){let e=[];for(let t=0;t<=255;t+=20)e.push(this.colorWheel(t,this.channel_));return e}colorWheel(e,t){return"hsvfast"==t?this.hsvFast(e,255,255):(e=255-e)<85?this.hex(3*e,255,255-3*e):e<170?(e-=85,this.hex(255,255-3*e,3*e)):(e-=170,this.hex(255-3*e,3*e,255))}hsvFast(e,t,n){let o=e%255>>0;o<0&&(o+=255),o=192*o/255>>0;let r,i,s,a=n*(255-t)/255>>0,l=n-a,c=o/64>>0,u=o%64>>0,d=(u*l/63.75>>0)+a,p=((63-u)*l/63.75>>0)+a;return c?1==c?(r=a,i=p,s=d):(r=d,i=a,s=p):(r=p,i=d,s=a),this.hex(r,i,s)}hex(e,t,n){return`#${this.componentToHex(255&e)}${this.componentToHex(255&t)}${this.componentToHex(255&n)}`}componentToHex(e){let t=e.toString(16);return 1==t.length?"0"+t:t}}e.FieldColorWheel=t}(pxtblockly||(pxtblockly={})),function(e){class t extends Blockly.FieldColour{constructor(e,t,n){if(super(e,n),this.isFieldCustom_=!0,this.valueMode_="rgb",t.colours)this.setColours(JSON.parse(t.colours));else if(pxt.appTarget.runtime&&pxt.appTarget.runtime.palette){let e,t=pxt.Util.clone(pxt.appTarget.runtime.palette);t[0]="#dedede",pxt.appTarget.runtime.paletteNames&&(e=pxt.Util.clone(pxt.appTarget.runtime.paletteNames),e[0]=lf("transparent")),this.setColours(t,e)}this.setValue(this.getColours_()[0]),t.columns&&this.setColumns(parseInt(t.columns)),t.className&&(this.className_=t.className),t.valueMode&&(this.valueMode_=t.valueMode)}applyColour(){var e,t,n,o,r,i;this.borderRect_?this.borderRect_.style.fill=this.value_:this.sourceBlock_&&(null===(n=null===(t=null===(e=this.sourceBlock_)||void 0===e?void 0:e.pathObject)||void 0===t?void 0:t.svgPath)||void 0===n||n.setAttribute("fill",this.value_),null===(i=null===(r=null===(o=this.sourceBlock_)||void 0===o?void 0:o.pathObject)||void 0===r?void 0:r.svgPath)||void 0===i||i.setAttribute("stroke","#fff"))}doClassValidation_(e){return"string"!=typeof e?null:n(e,this.getColours_())}getValue(e){if(e)return this.value_;switch(this.valueMode_){case"hex":return`"${this.value_}"`;case"rgb":return this.value_.indexOf("#")>-1?`0x${this.value_.replace(/^#/,"")}`:this.value_;case"index":if(!this.value_)return"-1";const e=this.getColours_();for(let t=0;t<e.length;t++)if(this.value_.toUpperCase()===e[t].toUpperCase())return t+""}return this.value_}doValueUpdate_(e){this.value_=n(e,this.getColours_()),this.applyColour()}showEditor_(){super.showEditor_(),this.className_&&this.picker_&&pxt.BrowserUtils.addClass(this.picker_,this.className_)}getColours_(){return this.colours_}}function n(e,t){if(e){const n=/Colors\.([a-zA-Z]+)/.exec(e),o=/(0x|#)([0-9a-fA-F]+)/.exec(e);if(n)switch(n[1].toLocaleLowerCase()){case"red":return"#FF0000";case"orange":return"#FF7F00";case"yellow":return"#FFFF00";case"green":return"#00FF00";case"blue":return"#0000FF";case"indigo":return"#4B0082";case"violet":return"#8A2BE2";case"purple":return"#A033E5";case"pink":return"#FF007F";case"white":return"#FFFFFF";case"black":return"#000000";default:return e}else if(o){const e=o[2];if(3===e.length){let t="#";for(let n=0;n<e.length;n++){const o=e.charAt(n);t+=o+o}return t}if(6===e.length)return"#"+e}if(t){const n=parseInt(e);return isNaN(n)||null==t[n]?t[0]:t[n]}}return e}e.FieldColorNumber=t}(pxtblockly||(pxtblockly={})),function(e){class t extends Blockly.FieldDropdown{constructor(t,n,o){super(n.data),this.isFieldCustom_=!0,this.buttonClick_=function(e){let t=e.target.getAttribute("data-value");null!==t&&(this.setValue(t),this.closeModal_&&(this.close(),this.closeModal_=!1))},this.buttonClickAndClose_=function(e){this.closeModal_=!0,this.buttonClick_(e)},this.columns_=parseInt(n.columns)||4,this.maxRows_=parseInt(n.maxRows)||0,this.width_=parseInt(n.width)||200,this.backgroundColour_=e.parseColour(n.colour),this.borderColour_=pxt.toolbox.fadeColor(this.backgroundColour_,.4,!1);let r={xOffset:parseInt(n.tooltipsXOffset)||15,yOffset:parseInt(n.tooltipsYOffset)||-10};this.tooltipConfig_=r,this.hasSearchBar_=!!n.hasSearchBar||!1,this.hideRect_=!!n.hideRect||!1}dispose(){super.dispose(),this.disposeTooltip(),this.disposeIntersectionObserver()}createTooltip_(){this.gridTooltip_||(this.gridTooltip_=document.createElement("div"),this.gridTooltip_.className="goog-tooltip blocklyGridPickerTooltip",this.gridTooltip_.style.position="absolute",this.gridTooltip_.style.display="none",this.gridTooltip_.style.visibility="hidden",document.body.appendChild(this.gridTooltip_))}populateTableContainer(e,t,n){pxsim.U.removeChildren(t),0==e.length&&(this.firstItem_=void 0);for(let n=0;n<e.length/this.columns_;n++){let o=this.populateRow(n,e,t);t.appendChild(o)}}populateRow(e,n,o){const r=this.columns_,i=document.createElement("div");i.className="blocklyGridPickerRow";for(let s=r*e;s<Math.min(r*e+r,n.length);s++){let e=n[s][0];const r=n[s][1],a=document.createElement("div");a.className="goog-menuitem goog-option",a.setAttribute("id",":"+s),a.setAttribute("role","menuitem"),a.style.userSelect="none",a.title=e.alt||e,a.setAttribute("data-value",r);const l=document.createElement("div");l.setAttribute("class","goog-menuitem-content"),l.title=e.alt||e,l.setAttribute("data-value",r);const c="object"==typeof e;let u=this.backgroundColour_;if(r==this.getValue()&&(a.setAttribute("aria-selected","true"),pxt.BrowserUtils.addClass(a,"goog-option-selected"),u=this.sourceBlock_.getColourTertiary(),this.selectedItemDom=a,c&&!this.shouldShowTooltips()&&this.updateSelectedBar_(e,r)),a.style.backgroundColor=u,a.style.borderColor=this.borderColour_,c){const n=new Image(e.width,e.height);n.setAttribute("draggable","false"),"IntersectionObserver"in window?(n.src=t.DEFAULT_IMG,n.setAttribute("data-src",e.src),this.observer.observe(n)):n.src=e.src,n.alt=e.alt||"",n.setAttribute("data-value",r),l.appendChild(n)}else l.textContent=e;if(this.shouldShowTooltips()){Blockly.bindEvent_(a,"click",this,this.buttonClickAndClose_);const e=this.sourceBlock_.RTL?-this.tooltipConfig_.xOffset:this.tooltipConfig_.xOffset,t=this.tooltipConfig_.yOffset;Blockly.bindEvent_(a,"mousemove",this,(n=>{if(c){this.gridTooltip_.style.top=`${n.clientY+t}px`,this.gridTooltip_.style.left=`${n.clientX+e}px`;const o=document.elementFromPoint(n.clientX,n.clientY),r=o.title||o.alt;this.gridTooltip_.textContent=r,this.gridTooltip_.style.visibility=r?"visible":"hidden",this.gridTooltip_.style.display=r?"":"none"}pxt.BrowserUtils.addClass(a,"goog-menuitem-highlight"),o.setAttribute("aria-activedescendant",a.id)})),Blockly.bindEvent_(a,"mouseout",this,(e=>{c&&(this.gridTooltip_.style.visibility="hidden",this.gridTooltip_.style.display="none"),pxt.BrowserUtils.removeClass(a,"goog-menuitem-highlight"),o.removeAttribute("aria-activedescendant")}))}else c?(this.selectedBar_.style.display="",Blockly.bindEvent_(a,"click",this,(t=>{if(this.closeModal_)this.buttonClick_(t);else{const t=o.getElementsByClassName("goog-menuitem-highlight");for(let e=0;e<t.length;e++)pxt.BrowserUtils.removeClass(t[e],"goog-menuitem-highlight");pxt.BrowserUtils.addClass(a,"goog-menuitem-highlight"),this.updateSelectedBar_(e,r)}}))):(Blockly.bindEvent_(a,"click",this,this.buttonClickAndClose_),Blockly.bindEvent_(a,"mouseup",this,this.buttonClickAndClose_));a.appendChild(l),i.appendChild(a),0==s&&(this.firstItem_=a)}return i}shouldShowRect_(){return!this.hideRect_&&!this.sourceBlock_.isShadow()}doClassValidation_(e){return e}close(){this.disposeTooltip(),Blockly.WidgetDiv.hideIfOwner(this),Blockly.Events.setGroup(!1)}getFirstItem(){return this.firstItem_}highlightFirstItem(e){let t=e.childNodes;if(t.length&&t[0].childNodes){for(let e=0;e<t.length;++e){let n=t[e].childNodes.length;for(let o=0;o<n;++o){const n=t[e].childNodes[o];pxt.BrowserUtils.removeClass(n,"goog-menuitem-highlight"),pxt.BrowserUtils.removeClass(n,"goog-option-selected")}}t[0].childNodes[0].className+=" goog-menuitem-highlight"}}highlightAndScrollSelected(e,t){this.selectedItemDom&&goog.style.scrollIntoContainerView(this.selectedItemDom,t,!0)}showEditor_(){Blockly.WidgetDiv.show(this,this.sourceBlock_.RTL,(()=>{this.onClose_()})),this.setupIntersectionObserver_(),this.createTooltip_();const e=document.createElement("div");this.positionMenu_(e)}positionMenu_(e){const t=Blockly.utils.getViewportBBox(),n=this.getAnchorDimensions_(),{paddingContainer:o,scrollContainer:r}=this.createWidget_(e),i={width:o.offsetWidth,height:o.offsetHeight},s=goog.dom.getViewportSize();this.width_>s.width&&(this.width_=s.width),e.style.width=this.width_+"px";let a=0;if(this.hasSearchBar_&&(a+=50),this.selectedBar_&&(a+=50),this.maxRows_){let t=e.children[0].offsetHeight*(this.maxRows_+.3);s.height<t+a&&(t=s.height-a),i.height>t&&(r.style.overflowY="auto",goog.style.setHeight(r,t),i.height=t)}i.height+=a,this.sourceBlock_.RTL&&Blockly.utils.uiMenu.adjustBBoxesForRTL(t,n,i),Blockly.WidgetDiv.positionWithAnchor(t,n,i,this.sourceBlock_.RTL),this.highlightAndScrollSelected(e,r)}shouldShowTooltips(){return!pxt.BrowserUtils.isMobile()}getAnchorDimensions_(){const e=this.getScaledBBox();return this.sourceBlock_.RTL?e.right+=Blockly.FieldDropdown.CHECKMARK_OVERHANG:e.left-=Blockly.FieldDropdown.CHECKMARK_OVERHANG,e}createWidget_(e){const t=Blockly.WidgetDiv.DIV,n=this.getOptions();e.setAttribute("role","menu"),e.setAttribute("aria-haspopup","true");const o=document.createElement("div"),r=document.createElement("div");if(r.style.border=`solid 1px ${this.borderColour_}`,e.style.backgroundColor=this.backgroundColour_,o.style.backgroundColor=this.backgroundColour_,r.style.backgroundColor=this.backgroundColour_,e.className="blocklyGridPickerMenu",o.className="blocklyGridPickerScroller",r.className="blocklyGridPickerPadder",r.appendChild(o),o.appendChild(e),t.appendChild(r),this.hasSearchBar_){const t=this.createSearchBar_(e,o,n);r.insertBefore(t,r.childNodes[0])}return this.shouldShowTooltips()||(this.selectedBar_=this.createSelectedBar_(),r.appendChild(this.selectedBar_)),this.populateTableContainer(n,e,o),{paddingContainer:r,scrollContainer:o}}createSearchBar_(e,t,n){const o=document.createElement("div");o.setAttribute("class","ui fluid icon input");const r=document.createElement("i");r.setAttribute("class","search icon");const i=document.createElement("input");return i.setAttribute("type","search"),i.setAttribute("id","search-bar"),i.setAttribute("class","blocklyGridPickerSearchBar"),i.setAttribute("placeholder",pxt.Util.lf("Search")),i.addEventListener("click",(()=>{i.focus(),i.setSelectionRange(0,i.value.length)})),i.addEventListener("keyup",pxt.Util.debounce((()=>{let o=i.value,r=new RegExp(o,"i"),s=n.filter((e=>{const t=e[0].alt,n=e[1];return t?r.test(t):r.test(n)}));this.populateTableContainer.bind(this)(s,e,t),o?this.highlightFirstItem(e):this.highlightAndScrollSelected(e,t),this.gridTooltip_.style.visibility="hidden",this.gridTooltip_.style.display="none"}),300,!1)),i.addEventListener("keyup",(t=>{if(13==t.which){const t=e.childNodes[0];if(t){const e=t.childNodes[0];e&&(this.closeModal_=!0,e.click())}}})),o.appendChild(i),o.appendChild(r),o}createSelectedBar_(){const e=document.createElement("div");e.setAttribute("class","blocklyGridPickerSelectedBar"),e.style.display="none";const n=document.createElement("div"),o=document.createElement("div");o.className="blocklyGridPickerSelectedImage",n.appendChild(o),this.selectedImg_=document.createElement("img"),this.selectedImg_.setAttribute("width","30px"),this.selectedImg_.setAttribute("height","30px"),this.selectedImg_.setAttribute("draggable","false"),this.selectedImg_.style.display="none",this.selectedImg_.src=t.DEFAULT_IMG,o.appendChild(this.selectedImg_),this.selectedBarText_=document.createElement("span"),this.selectedBarText_.className="blocklyGridPickerTooltip",n.appendChild(this.selectedBarText_);const r=document.createElement("div"),i=document.createElement("div");i.className="ui buttons mini",r.appendChild(i);const s=document.createElement("button");s.className="ui button icon green";const a=document.createElement("i");a.className="icon check",s.appendChild(a),Blockly.bindEvent_(s,"click",this,(()=>{this.setValue(this.selectedBarValue_),this.close()}));const l=document.createElement("button");l.className="ui button icon red";const c=document.createElement("i");return c.className="icon cancel",l.appendChild(c),Blockly.bindEvent_(l,"click",this,(()=>{this.close()})),i.appendChild(s),i.appendChild(l),e.appendChild(n),e.appendChild(r),e}updateSelectedBar_(e,t){e.src&&(this.selectedImg_.src=e.src,this.selectedImg_.style.display=""),this.selectedImg_.alt=e.alt||e,this.selectedBarText_.textContent=e.alt||e,this.selectedBarValue_=t}setupIntersectionObserver_(){if(!("IntersectionObserver"in window))return;this.disposeIntersectionObserver();this.observer=new IntersectionObserver((e=>{e.forEach((e=>{e.intersectionRatio>0&&(this.observer.unobserve(e.target),(e=>{const t=e.getAttribute("data-src");t&&(e.src=t,e.removeAttribute("data-src"))})(e.target))}))}),{rootMargin:"20px 0px",threshold:.01})}disposeIntersectionObserver(){this.observer&&(this.observer=null)}disposeTooltip(){this.gridTooltip_&&(pxsim.U.remove(this.gridTooltip_),this.gridTooltip_=null)}onClose_(){this.disposeTooltip()}}t.DEFAULT_IMG="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==",e.FieldGridPicker=t}(pxtblockly||(pxtblockly={})),function(e){class t extends Blockly.FieldDropdown{constructor(t,n,o){super(n.data),this.isFieldCustom_=!0,this.buttonClick_=function(e){let t=e.target.getAttribute("data-value");t&&(this.setValue(t),Blockly.DropDownDiv.hide())},this.columns_=parseInt(n.columns),this.maxRows_=parseInt(n.maxRows)||0,this.width_=parseInt(n.width)||300,this.backgroundColour_=e.parseColour(n.colour),this.borderColour_=pxt.toolbox.fadeColor(this.backgroundColour_,.4,!1)}showEditor_(){if(Blockly.DropDownDiv.hideIfOwner(this))return;Blockly.DropDownDiv.hideWithoutAnimation(),Blockly.DropDownDiv.clearContent();let e=Blockly.DropDownDiv.getContentDiv(),t=document.createElement("div");t.setAttribute("role","menu"),t.setAttribute("aria-haspopup","true");const n=this.getOptions();let o=0;for(let e=0;e<n.length;e++){let r=n[e][0];const i=n[e][1];if("placeholder"==r.type){let e=document.createElement("span");e.setAttribute("class","blocklyDropDownPlaceholder"),e.style.width=r.width+"px",e.style.height=r.height+"px",t.appendChild(e);continue}let s=document.createElement("button");s.setAttribute("id",":"+e),s.setAttribute("role","menuitem"),s.setAttribute("class","blocklyDropDownButton"),s.title=r.alt;let a=r.height;this.columns_?(a=this.width_/this.columns_-8,s.style.width=a+"px",s.style.height=a+"px"):(s.style.width=r.width+"px",s.style.height=r.height+"px"),a>o&&(o=a);let l=this.backgroundColour_;i==this.getValue()&&(l=this.sourceBlock_.getColourTertiary(),s.setAttribute("aria-selected","true")),s.style.backgroundColor=l,s.style.borderColor=this.borderColour_,Blockly.bindEvent_(s,"click",this,this.buttonClick_),Blockly.bindEvent_(s,"mouseover",s,(function(){this.setAttribute("class","blocklyDropDownButton blocklyDropDownButtonHover"),t.setAttribute("aria-activedescendant",this.id)})),Blockly.bindEvent_(s,"mouseout",s,(function(){this.setAttribute("class","blocklyDropDownButton"),t.removeAttribute("aria-activedescendant")}));let c=document.createElement("img");c.src=r.src,s.setAttribute("data-value",i),c.setAttribute("data-value",i),s.appendChild(c),t.appendChild(s)}t.style.width=this.width_+"px",e.appendChild(t),this.maxRows_&&(e.style.maxHeight=(this.maxRows_+.4)*(o+8)+"px"),pxt.BrowserUtils.isFirefox()&&(e.style.paddingRight="20px"),Blockly.DropDownDiv.setColour(this.backgroundColour_,this.borderColour_),Blockly.DropDownDiv.showPositionedByField(this,this.onHide_.bind(this));let r=this.sourceBlock_;this.savedPrimary_=null==r?void 0:r.getColour(),(null==r?void 0:r.isShadow())?r.setColour(r.getColourTertiary()):this.borderRect_&&this.borderRect_.setAttribute("fill",r.getColourTertiary())}onHide_(){let e=Blockly.DropDownDiv.getContentDiv();e.removeAttribute("role"),e.removeAttribute("aria-haspopup"),e.removeAttribute("aria-activedescendant"),e.style.width="",e.style.paddingRight="",e.style.maxHeight="";let t=this.sourceBlock_;(null==t?void 0:t.isShadow())?this.sourceBlock_.setColour(this.savedPrimary_):this.borderRect_&&this.borderRect_.setAttribute("fill",this.savedPrimary_)}}e.FieldImageDropdown=t}(pxtblockly||(pxtblockly={})),function(e){class t extends e.FieldImageDropdown{constructor(e,t,n){super(e,t,n),this.isFieldCustom_=!0,this.shouldSort_=t.sort,this.addLabel_=!!t.addLabel}showEditor_(){if(Blockly.DropDownDiv.hideIfOwner(this))return;let e=this.sourceBlock_;Blockly.DropDownDiv.hideWithoutAnimation(),Blockly.DropDownDiv.clearContent();let t=Blockly.DropDownDiv.getContentDiv(),n=document.createElement("div");n.setAttribute("role","menu"),n.setAttribute("aria-haspopup","true");const o=this.getOptions();this.shouldSort_&&o.sort();for(let t=0;t<o.length;t++){const r=o[t][0],i=o[t][1];if("placeholder"==r.type){let e=document.createElement("span");e.setAttribute("class","blocklyDropDownPlaceholder"),e.style.width=r.width+"px",e.style.height=r.height+"px",n.appendChild(e);continue}let s=document.createElement("button");s.setAttribute("id",":"+t),s.setAttribute("role","menuitem"),s.setAttribute("class","blocklyDropDownButton"),s.title=r.alt,this.columns_?s.style.width=this.width_/this.columns_-8+"px":(s.style.width=r.width+"px",s.style.height=r.height+"px");let a=e.getColour();i==this.getValue()&&(a=e.getColourTertiary(),s.setAttribute("aria-selected","true")),s.style.backgroundColor=a,s.style.borderColor=e.getColourTertiary(),Blockly.bindEvent_(s,"click",this,this.buttonClick_),Blockly.bindEvent_(s,"mouseover",s,(function(){this.setAttribute("class","blocklyDropDownButton blocklyDropDownButtonHover"),n.setAttribute("aria-activedescendant",this.id)})),Blockly.bindEvent_(s,"mouseout",s,(function(){this.setAttribute("class","blocklyDropDownButton"),n.removeAttribute("aria-activedescendant")}));let l=document.createElement("img");if(l.src=r.src,s.setAttribute("data-value",i),l.setAttribute("data-value",i),s.appendChild(l),this.addLabel_){const e=this.createTextNode_(r.alt);e.setAttribute("data-value",i),s.appendChild(e)}n.appendChild(s)}n.style.width=this.width_+"px",t.appendChild(n),Blockly.DropDownDiv.setColour(e.getColour(),e.getColourTertiary()),Blockly.DropDownDiv.showPositionedByField(this,this.onHideCallback.bind(this)),this.savedPrimary_=null==e?void 0:e.getColour(),(null==e?void 0:e.isShadow())?e.setColour(e.style.colourTertiary):this.borderRect_&&this.borderRect_.setAttribute("fill",e.style.colourTertiary)}onHideCallback(){let e=this.sourceBlock_;(null==e?void 0:e.isShadow())?e.setColour(this.savedPrimary_):this.borderRect_&&this.borderRect_.setAttribute("fill",this.savedPrimary_)}createTextNode_(e){const t=document.createElement("span");return t.setAttribute("class","blocklyDropdownTextLabel"),t.textContent=e,t}}e.FieldImages=t}(pxtblockly||(pxtblockly={})),function(e){class t extends Blockly.FieldDropdown{constructor(e){super(function(e){return function(){const t=[],n=this;if(n.sourceBlock_&&n.sourceBlock_.workspace){n.sourceBlock_.workspace.getVariablesOfType(i(e.name)).forEach((e=>{t.push([e.name,e.name])}))}else e.initialMembers.forEach((e=>t.push([e,e])));return t.push([lf("Add a new {0}...",e.memberName),"CREATE"]),t}}(e)),this.opts=e}initView(){super.initView()}onItemSelected_(e,t){"CREATE"===t.getValue()?n(this.sourceBlock_.workspace,this.opts,lf("New {0}:",this.opts.memberName),(e=>e&&this.setValue(e))):super.onItemSelected_(e,t)}doClassValidation_(e){var t;return(null===(t=this.opts)||void 0===t?void 0:t.initialMembers)&&!this.opts.initialMembers.find((t=>t==e))&&this.getOptions(),super.doClassValidation_(e)}getOptions(e){return this.initVariables(),super.getOptions(e)}initVariables(){if(this.sourceBlock_&&this.sourceBlock_.workspace){const e=this.sourceBlock_.workspace,t=o(e,this.opts.name);this.opts.initialMembers.forEach((n=>{-1===t.indexOf(n)&&r(e,this.opts,n)})),"CREATE"===this.getValue()&&this.opts.initialMembers.length&&this.setValue(this.opts.initialMembers[0])}}}function n(e,t,i,s){Blockly.prompt(i,null,(a=>{if(a){let l=!1;if(pxtc.isIdentifierStart(a.charCodeAt(0),2)){l=!0;for(let e=1;e<a.length;e++)pxtc.isIdentifierPart(a.charCodeAt(e),2)||(l=!1)}if(!l)return void Blockly.alert(lf("Names must start with a letter and can only contain letters, numbers, '$', and '_'."),(()=>n(e,t,i,s)));if(pxt.blocks.isReservedWord(a))return void Blockly.alert(lf("'{0}' is a reserved word and cannot be used.",a),(()=>n(e,t,i,s)));const c=o(e,t.name);for(let o=0;o<c.length;o++){if(c[o]===a)return void Blockly.alert(lf("A {0} named '{1}' already exists.",t.memberName,a),(()=>n(e,t,i,s)))}a===t.createFunctionName&&Blockly.alert(lf("'{0}' is a reserved name.",t.createFunctionName),(()=>n(e,t,i,s))),s(r(e,t,a))}}),{placeholder:t.promptHint})}function o(e,t){const n=e.getVariablesOfType(i(t));return n&&n.length?n.map((e=>e.name)):[]}function r(e,t,n){return Blockly.Variables.getOrCreateVariablePackage(e,null,n,i(t.name)),n}function i(e){return"KIND_"+e}e.FieldKind=t}(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,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxt,pxt,pxt;!function(e){e[e.None=0]="None",e[e.Number=1]="Number",e[e.Letter=2]="Letter"}(LabelMode||(LabelMode={})),function(e){class t extends Blockly.Field{constructor(e,t,n){if(super(e,n),this.isFieldCustom_=!0,this.SERIALIZABLE=!0,this.onColor="#FFFFFF",this.scale=1,this.matrixWidth=5,this.matrixHeight=5,this.yAxisLabel=LabelMode.None,this.xAxisLabel=LabelMode.None,this.cellState=[],this.cells=[],this.dontHandleMouseEvent_=e=>{e.stopPropagation(),e.preventDefault()},this.clearLedDragHandler=e=>{const t=this.sourceBlock_.getSvgRoot();pxsim.pointerEvents.down.forEach((e=>t.removeEventListener(e,this.dontHandleMouseEvent_))),t.removeEventListener(pxsim.pointerEvents.move,this.dontHandleMouseEvent_),document.removeEventListener(pxsim.pointerEvents.up,this.clearLedDragHandler),document.removeEventListener(pxsim.pointerEvents.leave,this.clearLedDragHandler),Blockly.Touch.clearTouchIdentifier(),this.elt.removeEventListener(pxsim.pointerEvents.move,this.handleRootMouseMoveListener),e.stopPropagation(),e.preventDefault()},this.toggleRect=(e,t)=>{this.cellState[e][t]=this.currentDragState_,this.updateValue()},this.handleRootMouseMoveListener=e=>{let t,n;e.changedTouches&&1==e.changedTouches.length?(t=e.changedTouches[0].clientX,n=e.changedTouches[0].clientY):(t=e.clientX,n=e.clientY);const o=document.elementFromPoint(t,n);if(!o)return;const r=o.getAttribute("data-x"),i=o.getAttribute("data-y");null!=r&&null!=i&&this.toggleRect(parseInt(r),parseInt(i))},this.params=t,void 0!==this.params.rows){let e=parseInt(this.params.rows);isNaN(e)||(this.matrixHeight=e)}if(void 0!==this.params.columns){let e=parseInt(this.params.columns);isNaN(e)||(this.matrixWidth=e)}void 0!==this.params.onColor&&(this.onColor=this.params.onColor),void 0!==this.params.offColor&&(this.offColor=this.params.offColor),void 0!==this.params.scale?this.scale=Math.max(.6,Math.min(2,Number(this.params.scale))):Math.max(this.matrixWidth,this.matrixHeight)>15?this.scale=.85:Math.max(this.matrixWidth,this.matrixHeight)>10&&(this.scale=.9)}showEditor_(){}initMatrix(){if(!this.sourceBlock_.isInsertionMarker()){this.elt=pxsim.svg.parseString('<svg xmlns="http://www.w3.org/2000/svg" id="field-matrix" />');for(let e=0;e<this.matrixWidth;e++){this.cellState.push([]),this.cells.push([]);for(let t=0;t<this.matrixHeight;t++)this.cellState[e].push(!1)}this.restoreStateFromString();for(let e=0;e<this.matrixWidth;e++)for(let t=0;t<this.matrixHeight;t++)this.createCell(e,t);if(this.updateValue(),this.xAxisLabel!==LabelMode.None){const e=this.scale*this.matrixHeight*(t.CELL_WIDTH+t.CELL_VERTICAL_MARGIN)+2*t.CELL_VERTICAL_MARGIN+t.BOTTOM_MARGIN,n=pxsim.svg.child(this.elt,"g",{transform:`translate(0 ${e})`});for(let e=0;e<this.matrixWidth;e++){const o=this.getYAxisWidth()+this.scale*e*(t.CELL_WIDTH+t.CELL_HORIZONTAL_MARGIN)+t.CELL_WIDTH/2+t.CELL_HORIZONTAL_MARGIN/2;pxsim.svg.child(n,"text",{x:o,class:"blocklyText"}).textContent=this.getLabel(e,this.xAxisLabel)}}if(this.yAxisLabel!==LabelMode.None){const e=pxsim.svg.child(this.elt,"g",{});for(let n=0;n<this.matrixHeight;n++){const o=this.scale*n*(t.CELL_WIDTH+t.CELL_VERTICAL_MARGIN)+t.CELL_WIDTH/2+2*t.CELL_VERTICAL_MARGIN;pxsim.svg.child(e,"text",{x:0,y:o,class:"blocklyText"}).textContent=this.getLabel(n,this.yAxisLabel)}}this.fieldGroup_.replaceChild(this.elt,this.fieldGroup_.firstChild)}}getLabel(e,t){switch(t){case LabelMode.Letter:return String.fromCharCode(e+65);default:return(e+1).toString()}}createCell(e,n){const o=this.scale*e*(t.CELL_WIDTH+t.CELL_HORIZONTAL_MARGIN)+t.CELL_HORIZONTAL_MARGIN+this.getYAxisWidth(),r=this.scale*n*(t.CELL_WIDTH+t.CELL_VERTICAL_MARGIN)+t.CELL_VERTICAL_MARGIN,i=pxsim.svg.child(this.elt,"g",{transform:`translate(${o} ${r})`}),s=pxsim.svg.child(i,"rect",{class:"blocklyLed"+(this.cellState[e][n]?"On":"Off"),cursor:"pointer",width:this.scale*t.CELL_WIDTH,height:this.scale*t.CELL_WIDTH,fill:this.getColor(e,n),"data-x":e,"data-y":n,rx:Math.max(2,this.scale*t.CELL_CORNER_RADIUS)});this.cells[e][n]=s,this.sourceBlock_.workspace.isFlyout||pxsim.pointerEvents.down.forEach((t=>s.addEventListener(t,(t=>{const o=this.sourceBlock_.getSvgRoot();this.currentDragState_=!this.cellState[e][n],Blockly.hideChaff(),this.sourceBlock_.select(),this.toggleRect(e,n),pxsim.pointerEvents.down.forEach((e=>o.addEventListener(e,this.dontHandleMouseEvent_))),o.addEventListener(pxsim.pointerEvents.move,this.dontHandleMouseEvent_),document.addEventListener(pxsim.pointerEvents.up,this.clearLedDragHandler),document.addEventListener(pxsim.pointerEvents.leave,this.clearLedDragHandler),this.elt.addEventListener(pxsim.pointerEvents.move,this.handleRootMouseMoveListener),t.stopPropagation(),t.preventDefault()}),!1)))}getColor(e,n){return this.cellState[e][n]?this.onColor:this.offColor||t.DEFAULT_OFF_COLOR}getOpacity(e,t){return this.cellState[e][t]?"1.0":"0.2"}updateCell(e,t){const n=this.cells[e][t];n.setAttribute("fill",this.getColor(e,t)),n.setAttribute("fill-opacity",this.getOpacity(e,t)),n.setAttribute("class","blocklyLed"+(this.cellState[e][t]?"On":"Off"))}setValue(e,t=!0){if(super.setValue(String(e)),this.elt){t&&this.restoreStateFromString();for(let e=0;e<this.matrixWidth;e++)for(let t=0;t<this.matrixHeight;t++)this.updateCell(e,t)}}render_(){this.visible_?(this.elt||this.initMatrix(),this.size_.height=this.scale*Number(this.matrixHeight)*(t.CELL_WIDTH+t.CELL_VERTICAL_MARGIN)+2*t.CELL_VERTICAL_MARGIN+t.BOTTOM_MARGIN+this.getXAxisHeight(),this.size_.width=this.scale*Number(this.matrixWidth)*(t.CELL_WIDTH+t.CELL_HORIZONTAL_MARGIN)+this.getYAxisWidth()):this.markDirty()}getValue(){let e=function(e){const t=(e=(e||"").trim()).charAt(0);if(t===e.charAt(e.length-1)&&-1!==o.indexOf(t))return e.substr(1,e.length-2).trim();return e}(this.value_);return`\`\n${t.TAB}${e}\n${t.TAB}\``}restoreStateFromString(){let e=this.value_;if(e){const o=e.split("\n").filter((e=>rowRegex.test(e)));for(let e=0;e<o.length&&e<this.matrixHeight;e++){let r=0;const i=o[e];for(let o=0;o<i.length&&r<this.matrixWidth;o++)"."===(t=i[o])||"_"===t||"0"===t?(this.cellState[r][e]=!1,r++):n(i[o])&&(this.cellState[r][e]=!0,r++)}}var t}updateValue(){let e="";for(let n=0;n<this.matrixHeight;n++){for(let t=0;t<this.matrixWidth;t++)e+=(this.cellState[t][n]?"#":".")+" ";e+="\n"+t.TAB}this.setValue(e,!1)}getYAxisWidth(){return this.yAxisLabel===LabelMode.None?0:t.Y_AXIS_WIDTH}getXAxisHeight(){return this.xAxisLabel===LabelMode.None?0:t.X_AXIS_HEIGHT}}function n(e){return"#"===e||"*"===e||"1"===e}t.CELL_WIDTH=25,t.CELL_HORIZONTAL_MARGIN=7,t.CELL_VERTICAL_MARGIN=5,t.CELL_CORNER_RADIUS=5,t.BOTTOM_MARGIN=9,t.Y_AXIS_WIDTH=9,t.X_AXIS_HEIGHT=10,t.TAB=" ",t.DEFAULT_OFF_COLOR="#000000",e.FieldMatrix=t;const o=["'",'"',"`"]}(pxtblockly||(pxtblockly={})),function(e){var t=pxt.svgUtil;e.HEADER_HEIGHT=50,e.TOTAL_WIDTH=300;class n extends Blockly.Field{constructor(e,t,n){super(e,n),this.isFieldCustom_=!0,this.SERIALIZABLE=!0,this.soundingKeys=0,this.numRow=8,this.numCol=8,this.tempo=120,this.isPlaying=!1,this.timeouts=[],this.params=t,this.createMelodyIfDoesntExist()}init(){super.init(),this.onInit()}showEditor_(){Blockly.DropDownDiv.hideWithoutAnimation(),Blockly.DropDownDiv.clearContent(),Blockly.DropDownDiv.setColour(this.getDropdownBackgroundColour(),this.getDropdownBorderColour());let e=Blockly.DropDownDiv.getContentDiv();pxt.BrowserUtils.addClass(e,"melody-content-div"),pxt.BrowserUtils.addClass(e.parentElement,"melody-editor-dropdown"),this.gallery=new pxtmelody.MelodyGallery,this.renderEditor(e),this.prevString=this.getValue(),Blockly.Events.fire(new Blockly.Events.Ui(this.sourceBlock_,"melody-editor",!1,!0)),Blockly.DropDownDiv.showPositionedByBlock(this,this.sourceBlock_,(()=>{this.onEditorClose(),pxt.BrowserUtils.removeClass(e,"melody-content-div"),pxt.BrowserUtils.removeClass(e.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_(e){null==e||""==e||'""'==e||this.stringRep&&this.stringRep===e||(this.stringRep=e,this.parseTypeScriptValue(e),super.doValueUpdate_(this.getValue()))}getText_(){return this.invalidString?pxt.Util.lf("Invalid Input"):this.getValue()}onInit(){this.render_(),this.createMelodyIfDoesntExist(),this.invalidString||(this.fieldGroup_||(this.fieldGroup_=Blockly.utils.dom.createSvgElement("g",{},null)),this.visible_||(this.fieldGroup_.style.display="none"),this.sourceBlock_.getSvgRoot().appendChild(this.fieldGroup_),this.updateFieldLabel())}render_(){super.render_(),this.invalidString||(this.size_.width=n.MUSIC_ICON_WIDTH+(n.COLOR_BLOCK_WIDTH+n.COLOR_BLOCK_SPACING)*this.numCol),this.sourceBlock_.setColour("#ffffff")}renderEditor(n){let o=this.getDropdownBackgroundColour(),r=this.getDropdownBorderColour();this.topDiv=document.createElement("div"),pxt.BrowserUtils.addClass(this.topDiv,"melody-top-bar-div"),this.root=new t.SVG(this.topDiv).id("melody-editor-header-controls"),this.toggle=new i(this.root,{leftText:lf("Editor"),rightText:lf("Gallery"),baseColor:o}),this.toggle.onStateChange((e=>{e?this.hideGallery():this.showGallery()})),this.toggle.layout(),this.toggle.translate((e.TOTAL_WIDTH-this.toggle.width())/2,0),n.appendChild(this.topDiv),n.appendChild(this.gallery.getElement()),this.editorDiv=document.createElement("div"),pxt.BrowserUtils.addClass(this.editorDiv,"melody-editor-div"),this.editorDiv.style.setProperty("background-color",r),this.gridDiv=this.createGridDisplay(),this.editorDiv.appendChild(this.gridDiv),this.bottomDiv=document.createElement("div"),pxt.BrowserUtils.addClass(this.bottomDiv,"melody-bottom-bar-div"),this.doneButton=document.createElement("button"),pxt.BrowserUtils.addClass(this.doneButton,"melody-confirm-button"),this.doneButton.innerText=lf("Done"),this.doneButton.addEventListener("click",(()=>this.onDone())),this.doneButton.style.setProperty("background-color",o),this.playButton=document.createElement("button"),this.playButton.id="melody-play-button",this.playButton.addEventListener("click",(()=>this.togglePlay())),this.playIcon=document.createElement("i"),this.playIcon.id="melody-play-icon",pxt.BrowserUtils.addClass(this.playIcon,"play icon"),this.playButton.appendChild(this.playIcon),this.tempoInput=document.createElement("input"),pxt.BrowserUtils.addClass(this.tempoInput,"ui input"),this.tempoInput.type="number",this.tempoInput.title=lf("tempo"),this.tempoInput.id="melody-tempo-input",this.tempoInput.addEventListener("input",(()=>this.setTempo(+this.tempoInput.value))),this.syncTempoField(!0),this.bottomDiv.appendChild(this.tempoInput),this.bottomDiv.appendChild(this.playButton),this.bottomDiv.appendChild(this.doneButton),this.editorDiv.appendChild(this.bottomDiv),n.appendChild(this.editorDiv)}onEditorClose(){this.stopMelody(),this.gallery&&this.gallery.stopMelody(),this.clearDomReferences(),this.sourceBlock_&&Blockly.Events.isEnabled()&&this.getValue()!==this.prevString&&Blockly.Events.fire(new Blockly.Events.BlockChange(this.sourceBlock_,"field",this.name,this.prevString,this.getValue())),this.prevString=void 0}onDone(){Blockly.DropDownDiv.hideIfOwner(this),this.onEditorClose()}clearDomReferences(){this.topDiv=null,this.editorDiv=null,this.gridDiv=null,this.bottomDiv=null,this.doneButton=null,this.playButton=null,this.playIcon=null,this.tempoInput=null,this.elt=null,this.cells=null,this.toggle=null,this.root=null,this.gallery.clearDomReferences()}getTypeScriptValue(){return this.invalidString?this.invalidString:this.melody?'"'+this.melody.getStringRepresentation()+'"':""}parseTypeScriptValue(e){let t=e;try{e=(e=e.slice(1,-1)).trim(),this.createMelodyIfDoesntExist();let t=e.split(" ");t.forEach((e=>{if(!this.isValidNote(e))throw new Error(lf("Invalid note '{0}'. Notes can be C D E F G A B C5",e))})),this.melody.resetMelody();for(let e=0;e<t.length;e++)if("-"!=t[e]){let n=pxtmelody.noteToRow(t[e]);this.melody.updateMelody(n,e)}this.updateFieldLabel()}catch(e){pxt.log(e),this.invalidString=t}}isValidNote(e){switch(e){case"C":case"D":case"E":case"F":case"G":case"A":case"B":case"C5":case"-":return!0}return!1}getPreviewWidth(){return this.updateSize_(),this.size_.width}getPreviewHeight(){var e;return(null===(e=this.getConstants())||void 0===e?void 0:e.FIELD_BORDER_RECT_HEIGHT)||16}getDropdownBackgroundColour(){return this.sourceBlock_.parentBlock_?this.sourceBlock_.parentBlock_.getColour():"#3D3D3D"}getDropdownBorderColour(){return this.sourceBlock_.parentBlock_?this.sourceBlock_.parentBlock_.getColourTertiary():"#2A2A2A"}updateFieldLabel(){if(!this.fieldGroup_)return;pxsim.U.clear(this.fieldGroup_);let e=s("").appendClass("melody-editor-field-icon").at(6,15);this.fieldGroup_.appendChild(e.el);let o=this.melody.getStringRepresentation().trim().split(" ");for(let e=0;e<o.length;e++){let r=pxtmelody.getColorClass(pxtmelody.noteToRow(o[e]));const i=(new t.Rect).at((n.COLOR_BLOCK_WIDTH+n.COLOR_BLOCK_SPACING)*e+n.COLOR_BLOCK_X,n.COLOR_BLOCK_Y).size(n.COLOR_BLOCK_WIDTH,n.COLOR_BLOCK_HEIGHT).stroke("#898989",1).corners(3,2);pxt.BrowserUtils.addClass(i.el,r),this.fieldGroup_.appendChild(i.el)}}setTempo(e){(isNaN(e)||e<=0)&&this.tempoInput?this.tempoInput.value=this.tempo+"":this.tempo!=e&&(this.tempo=e,this.melody&&this.melody.setTempo(this.tempo),this.tempoInput&&(this.tempoInput.value=this.tempo+""),this.syncTempoField(!1))}syncTempoField(e){const t=this.sourceBlock_;if(t.parentBlock_){const n=t.parentBlock_;for(const t of n.inputList)if("tempo"===t.name){const n=t.connection.targetBlock();n&&(e?n.getFieldValue("SLIDER")?(this.tempoInput.value=n.getFieldValue("SLIDER"),this.tempo=+this.tempoInput.value):this.tempoInput.value=this.tempo+"":("math_number_minmax"===n.type?n.setFieldValue(this.tempoInput.value,"SLIDER"):n.setFieldValue(this.tempoInput.value,"NUM"),this.tempoInput.focus()));break}}}getDuration(){return 6e4/this.tempo}createMelodyIfDoesntExist(){return!this.melody&&(this.melody=new pxtmelody.MelodyArray,!0)}onNoteSelect(e,t){this.invalidString=null,this.melody.updateMelody(e,t),this.melody.getValue(e,t)&&!this.isPlaying&&this.playNote(e,t),this.updateGrid(),this.updateFieldLabel()}updateGrid(){for(let e=0;e<this.numRow;e++){const t=pxtmelody.getColorClass(e);for(let n=0;n<this.numCol;n++){const o=this.cells[e][n];this.melody.getValue(e,n)?(pxt.BrowserUtils.removeClass(o,"melody-default"),pxt.BrowserUtils.addClass(o,t)):(pxt.BrowserUtils.addClass(o,"melody-default"),pxt.BrowserUtils.removeClass(o,t))}}}playNote(e,t){let n=++this.soundingKeys;this.isPlaying?(this.timeouts.push(setTimeout((()=>{this.playToneCore(e)}),t*this.getDuration())),this.timeouts.push(setTimeout((()=>{pxt.AudioContextManager.stop()}),(t+1)*this.getDuration()))):(this.playToneCore(e),this.timeouts.push(setTimeout((()=>{this.soundingKeys==n&&pxt.AudioContextManager.stop()}),this.getDuration())))}queueToneForColumn(e,t,n){const o=setTimeout((()=>{++this.soundingKeys,pxt.AudioContextManager.stop();for(let t=0;t<this.numRow;t++)this.melody.getValue(t,e)&&this.playToneCore(t);this.highlightColumn(e,!0),this.timeouts=this.timeouts.filter((e=>e!==o))}),t),r=setTimeout((()=>{this.timeouts=this.timeouts.filter((e=>e!==r)),this.highlightColumn(e,!1)}),t+n);this.timeouts.push(o),this.timeouts.push(r)}playToneCore(e){let t=0;switch(e){case 0:t=523;break;case 1:t=494;break;case 2:t=440;break;case 3:t=392;break;case 4:t=349;break;case 5:t=330;break;case 6:t=294;break;case 7:t=262}pxt.AudioContextManager.tone(t)}highlightColumn(e,t){this.cells.map((t=>t[e])).forEach((e=>{t?pxt.BrowserUtils.addClass(e,"playing"):pxt.BrowserUtils.removeClass(e,"playing")}))}createGridDisplay(){n.VIEWBOX_WIDTH=(n.CELL_WIDTH+n.CELL_VERTICAL_MARGIN)*this.numCol+n.CELL_VERTICAL_MARGIN,pxt.BrowserUtils.isEdge()&&(n.VIEWBOX_WIDTH+=37),n.VIEWBOX_HEIGHT=(n.CELL_WIDTH+n.CELL_HORIZONTAL_MARGIN)*this.numRow+n.CELL_HORIZONTAL_MARGIN,this.elt=pxsim.svg.parseString(`<svg xmlns="http://www.w3.org/2000/svg" class="melody-grid-div" viewBox="0 0 ${n.VIEWBOX_WIDTH} ${n.VIEWBOX_HEIGHT}"/>`),this.cells=[];for(let e=0;e<this.numRow;e++)this.cells.push([]);for(let e=0;e<this.numRow;e++)for(let t=0;t<this.numCol;t++)this.createCell(e,t);return this.elt}createCell(e,t){const o=e*(n.CELL_WIDTH+n.CELL_HORIZONTAL_MARGIN)+n.CELL_HORIZONTAL_MARGIN,r=t*(n.CELL_WIDTH+n.CELL_VERTICAL_MARGIN)+n.CELL_VERTICAL_MARGIN,i=pxsim.svg.child(this.elt,"g",{transform:`translate(${r} ${o})`}),s=pxsim.svg.child(i,"rect",{cursor:"pointer",width:n.CELL_WIDTH,height:n.CELL_WIDTH,stroke:"white","data-x":e,"data-y":t,rx:n.CELL_CORNER_RADIUS});this.melody.getValue(e,t)?pxt.BrowserUtils.addClass(s,pxtmelody.getColorClass(e)):pxt.BrowserUtils.addClass(s,"melody-default"),this.sourceBlock_.workspace.isFlyout||(pxsim.pointerEvents.down.forEach((n=>s.addEventListener(n,(n=>{this.onNoteSelect(e,t),n.stopPropagation(),n.preventDefault()}),!1))),this.cells[e][t]=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 e=0;e<this.numCol;e++)this.queueToneForColumn(e,e*this.getDuration(),this.getDuration());this.timeouts.push(setTimeout((()=>this.playMelody()),this.numCol*this.getDuration()))}else this.stopMelody()}stopMelody(){if(this.isPlaying){for(;this.timeouts.length;)clearTimeout(this.timeouts.shift());pxt.AudioContextManager.stop(),this.isPlaying=!1,this.cells.forEach((e=>e.forEach((e=>pxt.BrowserUtils.removeClass(e,"playing")))))}}showGallery(){this.stopMelody(),this.updatePlayButton(),this.gallery.show((e=>{e&&(this.melody.parseNotes(e),this.gallery.hide(),this.toggle.toggle(),this.updateFieldLabel(),this.updateGrid())}))}hideGallery(){this.gallery.hide()}}n.CELL_WIDTH=25,n.CELL_HORIZONTAL_MARGIN=7,n.CELL_VERTICAL_MARGIN=5,n.CELL_CORNER_RADIUS=5,n.COLOR_BLOCK_WIDTH=10,n.COLOR_BLOCK_HEIGHT=20,n.COLOR_BLOCK_X=20,n.COLOR_BLOCK_Y=5,n.COLOR_BLOCK_SPACING=2,n.MUSIC_ICON_WIDTH=20,e.FieldCustomMelody=n;const o=200,r=40;class i{constructor(e,t){this.props=function(e){e.baseColor||(e.baseColor="#e95153");e.backgroundColor||(e.backgroundColor="rgba(52,73,94,.2)");e.borderColor||(e.borderColor="rgba(52,73,94,.4)");e.selectedTextColor||(e.selectedTextColor=e.baseColor);e.unselectedTextColor||(e.unselectedTextColor="hsla(0,0%,100%,.9)");e.switchColor||(e.switchColor="#ffffff");return e}(t),this.root=e.group(),this.buildDom(),this.isLeft=!0}buildDom(){this.root.style().content("\n .toggle-left {\n transform: translateX(0px);\n animation: mvleft 0.2s 0s ease;\n }\n\n .toggle-right {\n transform: translateX(100px);\n animation: mvright 0.2s 0s ease;\n }\n\n @keyframes mvright {\n 0% {\n transform: translateX(0px);\n }\n 100% {\n transform: translateX(100px);\n }\n }\n\n @keyframes mvleft {\n 0% {\n transform: translateX(100px);\n }\n 100% {\n transform: translateX(0px);\n }\n }\n ");this.root.def().create("clipPath","sprite-editor-toggle-border").clipPathUnits(!0).draw("rect").at(0,0).corners(.02,.1).size(1,1),this.root.draw("rect").size(o,r).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(e=!1){this.isLeft?(this.switch.removeClass("toggle-left"),this.switch.appendClass("toggle-right"),this.leftText.fill(this.props.unselectedTextColor),this.rightText.fill(this.props.selectedTextColor)):(this.switch.removeClass("toggle-right"),this.switch.appendClass("toggle-left"),this.leftText.fill(this.props.selectedTextColor),this.rightText.fill(this.props.unselectedTextColor)),this.isLeft=!this.isLeft,!e&&this.changeHandler&&this.changeHandler(this.isLeft)}onStateChange(e){this.changeHandler=e}layout(){this.leftText.moveTo(51,20),this.rightText.moveTo(149,20)}translate(e,t){this.root.translate(e,t)}height(){return r}width(){return o}}function s(e){return new t.Text(e).anchor("middle").setAttribute("dominant-baseline","middle").setAttribute("dy",pxt.BrowserUtils.isIE()||pxt.BrowserUtils.isEdge()?"0.3em":"0.1em")}}(pxtblockly||(pxtblockly={})),function(e){let t;!function(e){e[e.C=262]="C",e[e.CSharp=277]="CSharp",e[e.D=294]="D",e[e.Eb=311]="Eb",e[e.E=330]="E",e[e.F=349]="F",e[e.FSharp=370]="FSharp",e[e.G=392]="G",e[e.GSharp=415]="GSharp",e[e.A=440]="A",e[e.Bb=466]="Bb",e[e.B=494]="B",e[e.C3=131]="C3",e[e.CSharp3=139]="CSharp3",e[e.D3=147]="D3",e[e.Eb3=156]="Eb3",e[e.E3=165]="E3",e[e.F3=175]="F3",e[e.FSharp3=185]="FSharp3",e[e.G3=196]="G3",e[e.GSharp3=208]="GSharp3",e[e.A3=220]="A3",e[e.Bb3=233]="Bb3",e[e.B3=247]="B3",e[e.C4=262]="C4",e[e.CSharp4=277]="CSharp4",e[e.D4=294]="D4",e[e.Eb4=311]="Eb4",e[e.E4=330]="E4",e[e.F4=349]="F4",e[e.FSharp4=370]="FSharp4",e[e.G4=392]="G4",e[e.GSharp4=415]="GSharp4",e[e.A4=440]="A4",e[e.Bb4=466]="Bb4",e[e.B4=494]="B4",e[e.C5=523]="C5",e[e.CSharp5=555]="CSharp5",e[e.D5=587]="D5",e[e.Eb5=622]="Eb5",e[e.E5=659]="E5",e[e.F5=698]="F5",e[e.FSharp5=740]="FSharp5",e[e.G5=784]="G5",e[e.GSharp5=831]="GSharp5",e[e.A5=880]="A5",e[e.Bb5=932]="Bb5",e[e.B5=988]="B5",e[e.C6=1047]="C6",e[e.CSharp6=1109]="CSharp6",e[e.D6=1175]="D6",e[e.Eb6=1245]="Eb6",e[e.E6=1319]="E6",e[e.F6=1397]="F6",e[e.FSharp6=1480]="FSharp6",e[e.G6=1568]="G6",e[e.GSharp6=1568]="GSharp6",e[e.A6=1760]="A6",e[e.Bb6=1865]="Bb6",e[e.B6=1976]="B6",e[e.C7=2093]="C7"}(t||(t={}));class n extends Blockly.FieldNumber{constructor(t,n,o){super(null,0,null,null,o),this.isFieldCustom_=!0,this.SERIALIZABLE=!0,this.isTextValid_=!0,this.nKeys_=36,this.minNote_=28,this.maxNote_=63,this.eps=2,this.setSpellcheck(!1),this.prepareNotes(),this.isExpanded=!1,this.currentPage=0,this.totalPlayCount=0,n.editorColour&&(this.primaryColour=e.parseColour(n.editorColour),this.borderColour=Blockly.utils.colour.darken(this.primaryColour,.2));const r=parseInt(n.eps);!Number.isNaN(r)&&r>=0&&(this.eps=r);const i=parseInt(n.minNote)||this.minNote_,s=parseInt(n.maxNote)||this.maxNote_;i>=28&&s<=75&&s>i&&(this.minNote_=i,this.maxNote_=s,this.nKeys_=this.maxNote_-this.minNote_+1),this.setValue(t)}doClassValidation_(e){const n=/^Note\.(.+)$/.exec(e),o=n&&n.length>1?n[1]:null;if(null===(e=t[o]?t[o]:String(parseFloat(e||"0"))))return null;const r=parseFloat(e||"0");if(isNaN(r)||r<0)return null;const i=Math.floor(r)!=r;return""+r.toFixed(i?2:0)}getValue(){return this.value_+""}doValueUpdate_(e){isNaN(Number(e))||Number(e)<0||(this.sourceBlock_&&Blockly.Events.isEnabled()&&this.value_!=e&&Blockly.Events.fire(new Blockly.Events.Change(this.sourceBlock_,"field",this.name,this.value_,e)),this.value_=e,this.refreshText())}getText(){if(this.isExpanded)return""+this.value_;{const e=+this.value_;for(let t=0;t<this.nKeys_;t++)if(Math.abs(this.getKeyFreq(t)-e)<this.eps)return this.getKeyName(t);let t=e.toString();return isNaN(e)||(t+=" Hz"),t}}refreshText(){this.forceRerender()}onHtmlInputChange_(e){super.onHtmlInputChange_(e),Blockly.DropDownDiv.hideWithoutAnimation(),this.htmlInput_.focus()}onFinishEditing_(e){this.refreshText()}onHide(){this.isExpanded=!1,this.refreshText()}showEditor_(e){this.isExpanded=!0,this.updateColor(),Blockly.DropDownDiv.hideWithoutAnimation(),Blockly.DropDownDiv.clearContent();const t=pxt.BrowserUtils.isMobile()||pxt.BrowserUtils.isIOS();n.superClass_.showEditor_.call(this,e,t,t),this.refreshText(),Blockly.Events.setGroup(!0),this.piano=[],this.currentSelectedKey=void 0;const r=this.nKeys_-this.nKeys_/n.notesPerOctave*n.blackKeysPerOctave,i=n.notesPerOctave-n.blackKeysPerOctave;let s=n.keyWidth*r,a=n.keyHeight+n.labelHeight;const l=window.innerWidth<s;l&&(s=i*n.keyWidth,a=n.keyHeight+n.labelHeight+n.prevNextHeight);const c=o("blocklyPianoDiv",`width: ${s}px;\n height: ${a}px;`);Blockly.DropDownDiv.getContentDiv().appendChild(c),this.noteLabel=o("blocklyNoteLabel",`top: ${n.keyHeight}px;\n width: ${s}px;\n background-color: ${this.primaryColour};\n border-color: ${this.primaryColour};`),c.appendChild(this.noteLabel),this.noteLabel.textContent="-";let u=0;for(let e=0;e<this.nKeys_;e++){const t=Math.floor(e/n.notesPerOctave);let o=this.getPosition(e);l&&e>=n.notesPerOctave&&(o-=i*t*n.keyWidth);const r=this.getKeyDiv(e,o);this.piano.push(r),c.appendChild(r),Math.abs(this.getKeyFreq(e)-Number(this.getValue()))<this.eps&&(pxt.BrowserUtils.addClass(r,"selected"),this.currentSelectedKey=r,u=t)}l&&(this.setPage(u),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(e,t){const n=++this.totalPlayCount;this.currentSelectedKey!==e&&(this.currentSelectedKey&&pxt.BrowserUtils.removeClass(this.currentSelectedKey,"selected"),pxt.BrowserUtils.addClass(e,"selected"),this.setValue(t)),this.currentSelectedKey=e,this.htmlInput_.value=this.getText(),pxt.AudioContextManager.tone(t),setTimeout((()=>{this.totalPlayCount==n&&pxt.AudioContextManager.stop()}),300)}dispose(){Blockly.DropDownDiv.hideIfOwner(this),super.dispose()}updateColor(){if(this.sourceBlock_.parentBlock_&&(this.sourceBlock_.isShadow()||1===(e=this.sourceBlock_).inputList.length&&1===e.inputList[0].fieldRow.length)){let e=this.sourceBlock_.parentBlock_;this.primaryColour=e.getColour(),this.borderColour=e.getColourTertiary()}else this.primaryColour="#3D3D3D",this.borderColour="#2A2A2A";var e}setPage(e){const t=this.nKeys_/n.notesPerOctave;e=Math.max(Math.min(e,t-1),0),this.noteLabel.textContent=`Octave #${e+1}`;const o=e*n.notesPerOctave;for(let e=0;e<this.piano.length;++e){const t=e>=o&&e<o+n.notesPerOctave;this.piano[e].style.display=t?"block":"none"}this.currentPage=e}getNextPrevDiv(e,t){const r=e?0:t/2,i=o("blocklyNotePrevNext",`top: ${n.keyHeight+n.labelHeight}px;\n left: ${r}px;\n width: ${Math.ceil(t/2)}px;\n ${e?"border-left-color":"border-right-color"}: ${this.primaryColour};\n background-color: ${this.primaryColour};\n border-bottom-color: ${this.primaryColour};`);return pxt.BrowserUtils.pointerEvents.down.forEach((t=>{Blockly.bindEventWithChecks_(i,t,this,(()=>this.setPage(e?this.currentPage-1:this.currentPage+1)),!0)})),i.textContent=e?"<":">",i}getKeyDiv(e,t){const n=o("blocklyNote "+(this.isWhite(e)?"":"black"),`width: ${this.getKeyWidth(e)}px;\n height: ${this.getKeyHeight(e)}px;\n left: ${t}px;\n border-color: ${this.primaryColour};`);return pxt.BrowserUtils.pointerEvents.down.forEach((t=>{Blockly.bindEventWithChecks_(n,t,this,(()=>this.playKey(n,this.getKeyFreq(e))),!0)})),Blockly.bindEventWithChecks_(n,"mouseover",this,(()=>this.noteLabel.textContent=this.getKeyName(e)),!0),n}isWhite(e){switch(e%12){case 1:case 3:case 6:case 8:case 10:return!1;default:return!0}}getKeyWidth(e){return this.isWhite(e)?n.keyWidth:n.keyWidth/2}getKeyHeight(e){return this.isWhite(e)?n.keyHeight:n.keyHeight/2}getKeyFreq(e){return this.getKeyNoteData(e).freq}getKeyName(e){const t=this.getKeyNoteData(e);let o=t.prefixedName;return this.nKeys_<=n.notesPerOctave?o=t.name:this.minNote_>=28&&this.maxNote_<=63&&(o=t.altPrefixedName||o),o}getKeyNoteData(e){return n.Notes[e+this.minNote_]}getPosition(e){const t=(e-Math.floor((e+1)/n.notesPerOctave*n.blackKeysPerOctave))*n.keyWidth;return this.isWhite(e)?t:t-n.keyWidth/4}prepareNotes(){n.Notes||(n.Notes={28:{name:lf("{id:note}C"),prefixedName:lf("Low C"),freq:131},29:{name:lf("C#"),prefixedName:lf("Low C#"),freq:139},30:{name:lf("{id:note}D"),prefixedName:lf("Low D"),freq:147},31:{name:lf("D#"),prefixedName:lf("Low D#"),freq:156},32:{name:lf("{id:note}E"),prefixedName:lf("Low E"),freq:165},33:{name:lf("{id:note}F"),prefixedName:lf("Low F"),freq:175},34:{name:lf("F#"),prefixedName:lf("Low F#"),freq:185},35:{name:lf("{id:note}G"),prefixedName:lf("Low G"),freq:196},36:{name:lf("G#"),prefixedName:lf("Low G#"),freq:208},37:{name:lf("{id:note}A"),prefixedName:lf("Low A"),freq:220},38:{name:lf("A#"),prefixedName:lf("Low A#"),freq:233},39:{name:lf("{id:note}B"),prefixedName:lf("Low B"),freq:247},40:{name:lf("{id:note}C"),prefixedName:lf("Middle C"),freq:262},41:{name:lf("C#"),prefixedName:lf("Middle C#"),freq:277},42:{name:lf("{id:note}D"),prefixedName:lf("Middle D"),freq:294},43:{name:lf("D#"),prefixedName:lf("Middle D#"),freq:311},44:{name:lf("{id:note}E"),prefixedName:lf("Middle E"),freq:330},45:{name:lf("{id:note}F"),prefixedName:lf("Middle F"),freq:349},46:{name:lf("F#"),prefixedName:lf("Middle F#"),freq:370},47:{name:lf("{id:note}G"),prefixedName:lf("Middle G"),freq:392},48:{name:lf("G#"),prefixedName:lf("Middle G#"),freq:415},49:{name:lf("{id:note}A"),prefixedName:lf("Middle A"),freq:440},50:{name:lf("A#"),prefixedName:lf("Middle A#"),freq:466},51:{name:lf("{id:note}B"),prefixedName:lf("Middle B"),freq:494},52:{name:lf("{id:note}C"),prefixedName:lf("Tenor C"),altPrefixedName:lf("High C"),freq:523},53:{name:lf("C#"),prefixedName:lf("Tenor C#"),altPrefixedName:lf("High C#"),freq:554},54:{name:lf("{id:note}D"),prefixedName:lf("Tenor D"),altPrefixedName:lf("High D"),freq:587},55:{name:lf("D#"),prefixedName:lf("Tenor D#"),altPrefixedName:lf("High D#"),freq:622},56:{name:lf("{id:note}E"),prefixedName:lf("Tenor E"),altPrefixedName:lf("High E"),freq:659},57:{name:lf("{id:note}F"),prefixedName:lf("Tenor F"),altPrefixedName:lf("High F"),freq:698},58:{name:lf("F#"),prefixedName:lf("Tenor F#"),altPrefixedName:lf("High F#"),freq:740},59:{name:lf("{id:note}G"),prefixedName:lf("Tenor G"),altPrefixedName:lf("High G"),freq:784},60:{name:lf("G#"),prefixedName:lf("Tenor G#"),altPrefixedName:lf("High G#"),freq:831},61:{name:lf("{id:note}A"),prefixedName:lf("Tenor A"),altPrefixedName:lf("High A"),freq:880},62:{name:lf("A#"),prefixedName:lf("Tenor A#"),altPrefixedName:lf("High A#"),freq:932},63:{name:lf("{id:note}B"),prefixedName:lf("Tenor B"),altPrefixedName:lf("High B"),freq:988},64:{name:lf("{id:note}C"),prefixedName:lf("High C"),freq:1046},65:{name:lf("C#"),prefixedName:lf("High C#"),freq:1109},66:{name:lf("{id:note}D"),prefixedName:lf("High D"),freq:1175},67:{name:lf("D#"),prefixedName:lf("High D#"),freq:1245},68:{name:lf("{id:note}E"),prefixedName:lf("High E"),freq:1319},69:{name:lf("{id:note}F"),prefixedName:lf("High F"),freq:1397},70:{name:lf("F#"),prefixedName:lf("High F#"),freq:1478},71:{name:lf("{id:note}G"),prefixedName:lf("High G"),freq:1568},72:{name:lf("G#"),prefixedName:lf("High G#"),freq:1661},73:{name:lf("{id:note}A"),prefixedName:lf("High A"),freq:1760},74:{name:lf("A#"),prefixedName:lf("High A#"),freq:1865},75:{name:lf("{id:note}B"),prefixedName:lf("High B"),freq:1976}})}}function o(e,t){const n=document.createElement("div");return pxt.BrowserUtils.addClass(n,e),n.setAttribute("style",t.replace(/\s+/g," ")),n}n.keyWidth=22,n.keyHeight=90,n.labelHeight=24,n.prevNextHeight=20,n.notesPerOctave=12,n.blackKeysPerOctave=5,e.FieldNote=n}(pxtblockly||(pxtblockly={})),function(e){class t extends Blockly.FieldNumberDropdown{constructor(e,t,n){super(e,t.data,t.min,t.max,t.precision,n),this.isFieldCustom_=!0}getOptions(){let e;return this.menuGenerator_&&(e=JSON.parse(this.menuGenerator_).map((e=>"object"==typeof e?e:[String(e),String(e)]))),e}}e.FieldNumberDropdown=t}(pxtblockly||(pxtblockly={})),function(e){class t extends Blockly.FieldSlider{constructor(e,t,n){super(e,"0","100","1","100","Value",n),this.isFieldCustom_=!0,this.params=t,this.params.screenHeight||(this.params.screenHeight=120),this.params.screenWidth||(this.params.screenWidth=160),this.params.xInputName||(this.params.xInputName="x"),this.params.yInputName||(this.params.yInputName="y"),this.params.min&&(this.min_=parseInt(this.params.min)),this.params.max&&(this.max_=parseInt(this.params.max))}showEditor_(e){this.getFieldByName(this.params.xInputName)===this&&(this.max_=this.params.screenWidth,this.labelText_=this.params.xInputName);this.getFieldByName(this.params.yInputName)===this&&(this.max_=this.params.screenHeight,this.labelText_=this.params.yInputName),super.showEditor_(e),this.renderScreenPicker()}doValueUpdate_(e){super.doValueUpdate_(e),this.resetCrosshair&&this.resetCrosshair()}renderScreenPicker(){let e=Blockly.DropDownDiv.getContentDiv();this.selectorDiv_=document.createElement("div"),this.selectorDiv_.className="blocklyCanvasOverlayOuter",e.appendChild(this.selectorDiv_);const t=document.createElement("div");t.className="blocklyCanvasOverlayDiv",this.selectorDiv_.appendChild(t);const n=document.createElement("div");n.className="cross-x",t.appendChild(n);const o=document.createElement("div");o.className="cross-y",t.appendChild(o);const r=document.createElement("div");r.className="label",t.appendChild(r);const i=1.5*this.params.screenWidth,s=1.5*this.params.screenHeight;t.style.height=s+"px",t.style.width=i+"px";const a=e.getElementsByClassName("goog-slider-horizontal")[0];if(a){a.style.width=i+"px";const e=parseFloat(this.getValue());!isNaN(e)&&e>this.getMin()&&(this.setValue(e-1+""),this.setValue(e+""))}const l=(e,t)=>{e=Math.round(Math.max(0,Math.min(i,e))),t=Math.round(Math.max(0,Math.min(s,t))),n.style.top=t+"px",o.style.left=e+"px",e=Math.round(Math.max(0,Math.min(this.params.screenWidth,e/i*this.params.screenWidth))),t=Math.round(Math.max(0,Math.min(this.params.screenHeight,t/s*this.params.screenHeight))),isNaN(e)?r.textContent=`${this.params.yInputName}=${t}`:isNaN(t)?r.textContent=`${this.params.xInputName}=${e}`:r.textContent=`${this.params.xInputName}=${e} ${this.params.yInputName}=${t}`;const a=r.getBoundingClientRect();e>this.params.screenWidth/2?r.style.left=e*(i/this.params.screenWidth)-a.width-8+"px":r.style.left=e*(i/this.params.screenWidth)+4+"px",t>this.params.screenHeight/2?r.style.top=t*(s/this.params.screenHeight)-a.height-6+"px":r.style.top=t*(s/this.params.screenHeight)+"px"};this.resetCrosshair=()=>{const{currentX:e,currentY:t}=this.getXY();l(e/this.params.screenWidth*i,t/this.params.screenHeight*s)},this.resetCrosshair(),Blockly.bindEvent_(this.selectorDiv_,"mousemove",this,(e=>{const n=t.getBoundingClientRect(),o=e.clientX-n.left,r=e.clientY-n.top;l(o,r)})),Blockly.bindEvent_(this.selectorDiv_,"mouseleave",this,this.resetCrosshair),Blockly.bindEvent_(this.selectorDiv_,"click",this,(e=>{const n=t.getBoundingClientRect(),o=e.clientX-n.left,r=e.clientY-n.top,a=Math.round(o/i*this.params.screenWidth),l=Math.round(r/s*this.params.screenHeight);this.close(),this.setXY(a,l)}))}resizeHandler(){this.close()}setXY(e,t){const n=this.getFieldByName(this.params.xInputName);n&&"number"==typeof n.getValue()&&n.setValue(String(e));const o=this.getFieldByName(this.params.yInputName);o&&"number"==typeof o.getValue()&&o.setValue(String(t))}getFieldByName(e){const t=this.sourceBlock_.parentBlock_;if(t)for(let n=0;n<t.inputList.length;n++){const o=t.inputList[n];if(o.name===e)return this.getTargetField(o)}}getXY(){let e,t;const n=this.getFieldByName(this.params.xInputName);n&&(e=n.getValue());const o=this.getFieldByName(this.params.yInputName);return o&&(t=o.getValue()),{currentX:parseInt(e),currentY:parseInt(t)}}getTargetField(e){const t=e.connection.targetBlock();if(!t)return null;const n=t.inputList[0];if(!n)return null;return n.fieldRow[0]}widgetDispose_(){Blockly.FieldNumber.superClass_.widgetDispose_.call(this),this.close(!0)}close(e){e||(Blockly.WidgetDiv.hideIfOwner(this),Blockly.DropDownDiv.hideIfOwner(this)),window.removeEventListener("resize",this.resizeHandler),this.resetCrosshair=void 0,this.selectorDiv_&&(goog.dom.removeNode(this.selectorDiv_),this.selectorDiv_=void 0)}}e.FieldPosition=t}(pxtblockly||(pxtblockly={})),function(e){class t extends Blockly.FieldDropdown{constructor(e,t){super([["Temp","Temp"]],t),this.setValue(e||"")}getOptions(){return this.dropdownCreate()}init(){this.fieldGroup_||super.init.call(this)}setSourceBlock(e){goog.asserts.assert(!e.isShadow(),"Procedure fields are not allowed to exist on shadow blocks."),super.setSourceBlock.call(this,e)}dropdownCreate(){let e=[];if(this.sourceBlock_&&this.sourceBlock_.workspace){let t=this.sourceBlock_.workspace.getAllBlocks(!1);for(let n=0;n<t.length;n++)if(t[n].getProcedureDef){let o=t[n].getProcedureDef();e.push(o[0])}}let t=this.getValue();t&&-1==e.indexOf(t)&&e.push(t),e.sort(goog.string.caseInsensitiveCompare),e.length||e.push("Temp");let n=[];for(let t=0;t<e.length;t++)n[t]=[e[t],e[t]];return n}onItemSelected(e,t){let n=t.getValue();null!==n&&this.setValue(n)}}e.FieldProcedure=t}(pxtblockly||(pxtblockly={})),function(e){class t extends Blockly.FieldSlider{constructor(e,t,n){super(String(e),"0","180","1","15",lf("Angle"),n),this.isFieldCustom_=!0,this.params=t}createLabelDom_(e){const t=document.createElement("div");this.circleSVG=document.createElementNS("http://www.w3.org/2000/svg","svg"),pxsim.svg.hydrate(this.circleSVG,{viewBox:"0 0 200 100",width:"170"}),t.appendChild(this.circleSVG);pxsim.svg.child(this.circleSVG,"circle",{"stroke-dasharray":"565.48","stroke-dashoffset":"0",cx:100,cy:100,r:"90",style:"fill:transparent; transition: stroke-dashoffset 0.1s linear;",stroke:"#a8aaa8","stroke-width":"1rem"});this.circleBar=pxsim.svg.child(this.circleSVG,"circle",{"stroke-dasharray":"565.48","stroke-dashoffset":"0",cx:100,cy:100,r:"90",style:"fill:transparent; transition: stroke-dashoffset 0.1s linear;",stroke:"#f12a21","stroke-width":"1rem"}),this.reporter=pxsim.svg.child(this.circleSVG,"text",{x:100,y:80,"text-anchor":"middle","dominant-baseline":"middle",style:"font-size: 50px",class:"sim-text inverted number"});const n=document.createElement("span");return n.setAttribute("class","blocklyFieldSliderReadout"),[t,n]}setReadout_(e,t){this.updateAngle(parseFloat(t)),this.reporter.textContent=`${t}°`}updateAngle(e){const t=(180-(e=Math.max(0,Math.min(180,e))))/180*Math.PI*90;this.circleBar.setAttribute("stroke-dashoffset",`${t}`)}}e.FieldProtractor=t}(pxtblockly||(pxtblockly={})),function(e){class t extends Blockly.FieldSlider{constructor(e,t,n){super(String(e),"-100","100","1","10","Speed",n),this.isFieldCustom_=!0,this.params=t,this.params.min&&(this.min_=parseFloat(this.params.min)),this.params.max&&(this.max_=parseFloat(this.params.max)),this.params.label&&(this.labelText_=this.params.label),this.params.format||(this.params.format="{0}%")}createLabelDom_(e){const t=document.createElement("div");this.speedSVG=document.createElementNS("http://www.w3.org/2000/svg","svg"),pxsim.svg.hydrate(this.speedSVG,{viewBox:"0 0 200 100",width:"170"}),t.appendChild(this.speedSVG);pxsim.svg.child(this.speedSVG,"circle",{"stroke-dasharray":"565.48","stroke-dashoffset":"0",cx:100,cy:100,r:"90",style:"fill:transparent; transition: stroke-dashoffset 0.1s linear;",stroke:"#a8aaa8","stroke-width":"1rem"});this.circleBar=pxsim.svg.child(this.speedSVG,"circle",{"stroke-dasharray":"565.48","stroke-dashoffset":"0",cx:100,cy:100,r:"90",style:"fill:transparent; transition: stroke-dashoffset 0.1s linear;",stroke:"#f12a21","stroke-width":"1rem"}),this.reporter=pxsim.svg.child(this.speedSVG,"text",{x:100,y:80,"text-anchor":"middle","dominant-baseline":"middle",style:`font-size: ${Math.max(14,50-5*(this.params.format.length-4))}px`,class:"sim-text inverted number"});const n=document.createElement("span");return n.setAttribute("class","blocklyFieldSliderReadout"),[t,n]}setReadout_(e,t){this.updateSpeed(parseFloat(t)),this.reporter.textContent=ts.pxtc.U.rlf(this.params.format,t)}updateSpeed(e){let t=this.sign(e);e=Math.abs(e)/100*50+50,-1==t&&(e=50-e);let n=(100-e)/100*(180*Math.PI);this.circleBar.setAttribute("stroke-dashoffset",`${n}`)}sign(e){return e?e<0?-1:1:0}}e.FieldSpeed=t}(pxtblockly||(pxtblockly={})),function(e){class t extends e.FieldAssetEditor{getAssetType(){return"image"}createNewAsset(e){const t=pxt.react.getTilemapProject();if(e){const n=pxt.lookupProjectAssetByTSReference(e,t);if(n)return n}if(this.getBlockData())return t.lookupAsset("image",this.getBlockData());const n=e?pxt.sprite.imageLiteralToBitmap(e):new pxt.sprite.Bitmap(this.params.initWidth,this.params.initHeight);if(!n)return this.isGreyBlock=!0,void(this.valueText=e);const o=n.data();return{internalID:-1,id:this.sourceBlock_.id,type:"image",jresData:pxt.sprite.base64EncodeBitmap(o),meta:{},bitmap:o}}getValueText(){return this.asset&&!this.isTemporaryAsset()?pxt.getTSReferenceForAsset(this.asset):pxt.sprite.bitmapToImageLiteral(this.asset&&pxt.sprite.Bitmap.fromData(this.asset.bitmap),"typescript")}parseFieldOptions(e){return function(e){const t={initColor:1,initWidth:16,initHeight:16,disableResize:!1,lightMode:!1};if(!e)return t;if(t.lightMode=e.lightMode,e.sizes){const n=e.sizes.split(";"),o=[];for(let e=0;e<n.length;e++){const t=n[e].split(",");if(2!==t.length)continue;let r=parseInt(t[0]),i=parseInt(t[1]);if(isNaN(r)||isNaN(i))continue;const s=pxt.appTarget.runtime&&pxt.appTarget.runtime.screenSize;r<0&&s&&(r=s.width),i<0&&s&&(i=s.height),o.push([r,i])}o.length>0&&(t.initWidth=o[0][0],t.initHeight=o[0][1])}e.filter&&(t.filter=e.filter);e.disableResize&&(t.disableResize="true"===e.disableResize.toLowerCase()||"1"===e.disableResize);return t.initColor=n(e.initColor,t.initColor),t.initWidth=n(e.initWidth,t.initWidth),t.initHeight=n(e.initHeight,t.initHeight),t;function n(e,t){const n=parseInt(e);return isNaN(n)?t:n}}(e)}}e.FieldSpriteEditor=t}(pxtblockly||(pxtblockly={})),function(e){class t extends Blockly.FieldLabel{constructor(e,t,n){super(e,function(e){if(e){if(e.bold&&e.italics)return"blocklyBoldItalicizedText";if(e.bold)return"blocklyBoldText";if(e.italics)return"blocklyItalicizedText"}return}(t)),this.isFieldCustom_=!0}}e.FieldStyledLabel=t}(pxtblockly||(pxtblockly={})),function(e){class t extends Blockly.FieldTextDropdown{constructor(e,t,n){super(e,t.values,n),this.isFieldCustom_=!0}}e.FieldTextDropdown=t}(pxtblockly||(pxtblockly={})),function(e){class t extends Blockly.FieldTextInput{constructor(e,t,n){super(e,n),this.isFieldCustom_=!0}}e.FieldTextInput=t}(pxtblockly||(pxtblockly={})),function(e){class t extends e.FieldAssetEditor{getInitText(){return this.initText}getTileset(){var e;return null===(e=this.asset)||void 0===e?void 0:e.data.tileset}getAssetType(){return"tilemap"}createNewAsset(e=""){e&&(e=e.replace(/`/g,"`"));const t=pxt.react.getTilemapProject(),n=pxt.lookupProjectAssetByTSReference(e,t);if(n)return n;const o=pxt.sprite.decodeTilemap(e,"typescript",t)||t.blankTilemap(this.params.tileWidth,this.params.initWidth,this.params.initHeight);let r;if(function(e){return!!(e&&e.tilemap&&e.tilemap.width&&e.tilemap.height)&&(!(!e.layers||e.layers.width!==e.tilemap.width||e.layers.height!==e.tilemap.height)&&!!e.tileset)}(o)){this.initText=e,this.isGreyBlock=!1;const[n]=t.createNewTilemapFromData(o);r=t.getTilemap(n)}else e.trim()&&(this.isGreyBlock=!0,this.valueText=e);return r}onEditorClose(e){pxt.sprite.updateTilemapReferencesFromResult(pxt.react.getTilemapProject(),e)}getValueText(){return this.isGreyBlock?pxt.Util.htmlUnescape(this.valueText):this.asset?pxt.getTSReferenceForAsset(this.asset):this.getInitText()}parseFieldOptions(e){return function(e){const t={initWidth:16,initHeight:16,disableResize:!1,tileWidth:16,lightMode:!1};if(!e)return t;t.lightMode=e.lightMode,e.filter&&(t.filter=e.filter);if(e.tileWidth)if("number"==typeof e.tileWidth)switch(e.tileWidth){case 8:t.tileWidth=8;break;case 16:t.tileWidth=16;break;case 32:t.tileWidth=32}else{switch(e.tileWidth.trim().toLowerCase()){case"8":case"eight":t.tileWidth=8;break;case"16":case"sixteen":t.tileWidth=16;break;case"32":case"thirtytwo":t.tileWidth=32}}return t.initWidth=n(e.initWidth,t.initWidth),t.initHeight=n(e.initHeight,t.initHeight),t;function n(e,t){const n=parseInt(e);return isNaN(n)?t:n}}(e)}}e.FieldTilemap=t}(pxtblockly||(pxtblockly={})),function(e){const t=32;class n extends e.FieldImages{constructor(t,r,i){super(t,r,i),this.isFieldCustom_=!0,this.menuGenerator_=()=>{var t,r;return(null===(t=this.sourceBlock_)||void 0===t?void 0:t.workspace)&&e.needsTilemapUpgrade(null===(r=this.sourceBlock_)||void 0===r?void 0:r.workspace)?[o()]:n.getReferencedTiles(this.sourceBlock_.workspace)},this.assetChangeListener=()=>{this.doValueUpdate_(this.getValue()),this.forceRerender()},this.blocksInfo=r.blocksInfo}static getReferencedTiles(o){const a=pxt.react.getTilemapProject();if(a.revision()!==n.cachedRevision||o.id!=n.cachedWorkspaceId){n.cachedRevision=a.revision(),n.cachedWorkspaceId=o.id;const l=e.getAllReferencedTiles(o),c=[16,8,32];for(const e of c){const t=a.getProjectTiles(e,16===e);if(t)for(const e of t.tiles)l.find((t=>t.id===e.id))||l.push(e)}let u={};l.sort(((e,t)=>e.id===t.id?0:e.bitmap.width!==t.bitmap.width?e.bitmap.width-t.bitmap.width:e.isProjectTile!==t.isProjectTile?e.isProjectTile?-1:1:(u[e.id]||(u[e.id]=i(e.id)))-(u[t.id]||(u[t.id]=i(t.id)))));const d=n=>i(n.id)<=2?r(n.bitmap.width):e.bitmapToImageURI(pxt.sprite.Bitmap.fromData(n.bitmap),t,!1);n.referencedTiles=l.map((e=>[{src:d(e),width:t,height:t,alt:s(e)},e.id,e]))}return n.referencedTiles}initView(){super.initView(),this.sourceBlock_&&this.sourceBlock_.isInFlyout&&this.setValue(this.getOptions()[0][1])}getValue(){if(this.selectedOption_){let e=this.selectedOption_[2];return e=pxt.react.getTilemapProject().lookupAsset(e.type,e.id),pxt.getTSReferenceForAsset(e)}const e=super.getValue();return"string"==typeof e&&-1===e.indexOf(".")&&-1===e.indexOf("`")?`img\`${e}\``:e}getText(){const e=this.getValue();return"string"==typeof e&&-1!==e.indexOf("`")?e:super.getText()}render_(){if(this.value_&&this.selectedOption_&&this.selectedOption_[1]!==this.value_){const o=pxt.react.getTilemapProject().resolveTile(this.value_);n.cachedRevision=-1,o&&(this.selectedOption_=[{src:e.bitmapToImageURI(pxt.sprite.Bitmap.fromData(o.bitmap),t,!1),width:t,height:t,alt:s(o)},this.value_,o])}super.render_()}doValueUpdate_(e){super.doValueUpdate_(e);const t=this.getOptions(!0);if(e){const n=pxt.parseAssetTSReference(e);n&&(e=n.name),e=e.trim();for(const n of t)if(e===n[2].id||e===n[2].meta.displayName||e===pxt.getShortIDForAsset(n[2]))return this.selectedOption_=n,this.value_=this.getValue(),void this.updateAssetListener();this.selectedOption_=null,this.updateAssetListener()}}getOptions(e){return"function"!=typeof this.menuGenerator_?(this.transparent=o(),[this.transparent]):this.menuGenerator_.call(this)}dispose(){super.dispose(),pxt.react.getTilemapProject().removeChangeListener("tile",this.assetChangeListener)}updateAssetListener(){const e=pxt.react.getTilemapProject();e.removeChangeListener("tile",this.assetChangeListener),this.selectedOption_&&e.addChangeListener(this.selectedOption_[2],this.assetChangeListener)}}function o(){const e=pxt.react.getTilemapProject().getTransparency(16);return[{src:r(16),width:t,height:t,alt:pxt.U.lf("transparency")},e.id,e]}function r(e){const t=document.createElement("canvas"),n=t.getContext("2d");t.width=e,t.height=e,n.fillStyle="#aeaeae",n.fillRect(0,0,e,e),n.fillStyle="#dedede";for(let t=0;t<e;t+=4)for(let o=0;o<e;o+=4)t+o>>2&1&&n.fillRect(t,o,4,4);return t.toDataURL()}function i(e){switch(e){case"myTiles.transparency16":return 1;case"myTiles.transparency8":case"myTiles.transparency32":return 2;default:if(e.startsWith("myTiles.tile")){const t=parseInt(e.slice(12));if(!Number.isNaN(t))return t+2}return 9999999999}}function s(e){return e.meta.displayName||pxt.getShortIDForAsset(e)}e.FieldTileset=n}(pxtblockly||(pxtblockly={})),function(e){class t extends Blockly.FieldNumber{constructor(e,t,n){super(e,void 0,void 0,void 0,n),this.isFieldCustom_=!0,this.CURSOR="pointer",this.params=t,this.setValue(e),this.addArgType("toggle"),this.type_=t.type}initView(){if(!this.fieldGroup_)return;null!==this.getArgTypes()&&(this.sourceBlock_.isShadow()?this.sourceBlock_.svgGroup_.setAttribute("data-argument-type",this.getArgTypes()):this.fieldGroup_.setAttribute("data-argument-type",this.getArgTypes())),!this.sourceBlock_.isShadow()&&this.sourceBlock_.inputList&&this.sourceBlock_.inputList.length>1&&(this.borderRect_=Blockly.utils.dom.createSvgElement("rect",{rx:Blockly.BlockSvg.CORNER_RADIUS,ry:Blockly.BlockSvg.CORNER_RADIUS,x:0,y:0,width:this.size_.width,height:this.size_.height,fill:this.sourceBlock_.getColour(),stroke:this.sourceBlock_.getColourTertiary()},null),this.fieldGroup_.insertBefore(this.borderRect_,this.textElement_));const e=this.getSize();switch(this.checkElement_=Blockly.utils.dom.createSvgElement("g",{class:"blocklyToggle "+(this.state_?"blocklyToggleOn":"blocklyToggleOff"),transform:`translate(8, ${e.height/2})`},this.fieldGroup_),this.getOutputShape()){case Blockly.OUTPUT_SHAPE_HEXAGONAL:this.toggleThumb_=Blockly.utils.dom.createSvgElement("polygon",{class:"blocklyToggleRect",points:"-7,-14 -21,0 -7,14 7,14 21,0 7,-14",cursor:"pointer"},this.checkElement_);break;case Blockly.OUTPUT_SHAPE_ROUND:this.toggleThumb_=Blockly.utils.dom.createSvgElement("rect",{class:"blocklyToggleCircle",x:-6,y:-14,height:28,width:28,rx:14,ry:14,cursor:"pointer"},this.checkElement_);break;case Blockly.OUTPUT_SHAPE_SQUARE:this.toggleThumb_=Blockly.utils.dom.createSvgElement("rect",{class:"blocklyToggleRect",x:-6,y:-14,height:28,width:28,rx:3,ry:3,cursor:"pointer"},this.checkElement_)}let t=this.sourceBlock_.RTL?-e.width/2:e.width/2;this.textElement_=Blockly.utils.dom.createSvgElement("text",{class:"blocklyText",x:t,dy:"0.6ex",y:e.height/2},this.fieldGroup_),this.updateEditable();const n=this.sourceBlock_.getSvgRoot();n.appendChild(this.fieldGroup_),n.querySelector(".blocklyBlockBackground").setAttribute("fill",this.sourceBlock_.getColourTertiary()),this.switchToggle(this.state_),this.setValue(this.getValue()),this.markDirty()}getDisplayText_(){return this.state_?this.getTrueText():this.getFalseText()}getTrueText(){return lf("True")}getFalseText(){return lf("False")}updateSize_(){switch(this.getOutputShape()){case Blockly.OUTPUT_SHAPE_ROUND:this.size_.width=2*this.getInnerWidth()-7;break;case Blockly.OUTPUT_SHAPE_HEXAGONAL:this.size_.width=2*this.getInnerWidth()+8-Math.floor(this.getInnerWidth()/2);break;case Blockly.OUTPUT_SHAPE_SQUARE:this.size_.width=9+2*this.getInnerWidth()}}getInnerWidth(){return 10*this.getMaxLength()}getMaxLength(){return Math.max(this.getTrueText().length,this.getFalseText().length)}getOutputShape(){return this.sourceBlock_.isShadow()?this.sourceBlock_.getOutputShape():Blockly.OUTPUT_SHAPE_SQUARE}doClassValidation_(e){return"boolean"==typeof this.fromVal(e)?e:"false"}applyColour(){let e=this.sourceBlock_.getColourTertiary();this.borderRect_?this.borderRect_.setAttribute("stroke",e):this.sourceBlock_.pathObject.svgPath.setAttribute("fill",e)}getValue(){return this.toVal(this.state_)}doValueUpdate_(e){let t=this.fromVal(e);this.state_!==t&&(this.sourceBlock_&&Blockly.Events.isEnabled()&&Blockly.Events.fire(new Blockly.Events.BlockChange(this.sourceBlock_,"field",this.name,this.state_,t)),this.state_=t,this.switchToggle(this.state_),this.isDirty_=!0)}switchToggle(e){if(this.checkElement_){this.updateSize_();const t=this.getSize(),n=this.getInnerWidth();e?(pxt.BrowserUtils.addClass(this.checkElement_,"blocklyToggleOn"),pxt.BrowserUtils.removeClass(this.checkElement_,"blocklyToggleOff")):(pxt.BrowserUtils.removeClass(this.checkElement_,"blocklyToggleOn"),pxt.BrowserUtils.addClass(this.checkElement_,"blocklyToggleOff"));const o=this.getOutputShape();let r=0,i=0,s=0,a=0;switch(o){case Blockly.OUTPUT_SHAPE_HEXAGONAL:r=n,i=r/2;let e=i/2;s=-i+e,a=-e;const t=-e,l=i;this.toggleThumb_.setAttribute("points",`${t},-14 ${t-14},0 ${t},14 ${l},14 ${l+14},0 ${l},-14`);break;case Blockly.OUTPUT_SHAPE_ROUND:case Blockly.OUTPUT_SHAPE_SQUARE:r=5+n,i=r/2,this.toggleThumb_.setAttribute("width",""+r),this.toggleThumb_.setAttribute("x",`-${i}`),s=a=o==Blockly.OUTPUT_SHAPE_SQUARE?2:-6}this.checkElement_.setAttribute("transform",`translate(${e?a+n+i:i+s}, ${t.height/2})`)}}render_(){if(this.visible_&&this.textElement_){goog.dom.removeChildren(this.textElement_);let e=document.createTextNode(this.getDisplayText_());this.textElement_.appendChild(e),pxt.BrowserUtils.addClass(this.textElement_,"blocklyToggleText"),this.updateSize_();let t=this.size_.width,n=(this.state_?t+t/8:t/2)-t/2;this.textElement_.setAttribute("x",`${n}`)}this.borderRect_&&(this.borderRect_.setAttribute("width",`${this.size_.width}`),this.borderRect_.setAttribute("height",`${this.size_.height}`))}showEditor_(){let e=!this.state_;null!==e&&this.setValue(this.toVal(e))}toVal(e){return"number"==this.type_?String(e?"1":"0"):String(e?"true":"false")}fromVal(e){return"string"==typeof e?"1"==e||"TRUE"==e.toUpperCase():!!e}}e.FieldToggle=t}(pxtblockly||(pxtblockly={})),function(e){class t extends e.FieldToggle{constructor(e,t,n){super(e,t,n),this.isFieldCustom_=!0}getTrueText(){return lf("HIGH")}getFalseText(){return lf("LOW")}}e.FieldToggleHighLow=t}(pxtblockly||(pxtblockly={})),function(e){class t extends e.FieldToggle{constructor(e,t,n){super(e,t,n),this.isFieldCustom_=!0}getTrueText(){return lf("ON")}getFalseText(){return lf("OFF")}}e.FieldToggleOnOff=t}(pxtblockly||(pxtblockly={})),function(e){class t extends e.FieldToggle{constructor(e,t,n){super(e,t,n),this.isFieldCustom_=!0}getTrueText(){return lf("UP")}getFalseText(){return lf("DOWN")}}e.FieldToggleUpDown=t;class n extends e.FieldToggle{constructor(e,t,n){super(e,t,n),this.isFieldCustom_=!0}getTrueText(){return lf("DOWN")}getFalseText(){return lf("UP")}}e.FieldToggleDownUp=n}(pxtblockly||(pxtblockly={})),function(e){class t extends e.FieldToggle{constructor(e,t,n){super(e,t,n),this.isFieldCustom_=!0}getTrueText(){return lf("WIN")}getFalseText(){return lf("LOSE")}}e.FieldToggleWinLose=t}(pxtblockly||(pxtblockly={})),function(e){class t extends e.FieldToggle{constructor(e,t,n){super(e,t,n),this.isFieldCustom_=!0}getTrueText(){return lf("Yes")}getFalseText(){return lf("No")}}e.FieldToggleYesNo=t}(pxtblockly||(pxtblockly={})),function(e){class t extends Blockly.FieldTextInput{constructor(){super(...arguments),this.isFieldCustom_=!0,this.pythonMode=!1}updateEditable(){let e=this.fieldGroup_;this.EDITABLE&&e&&(this.sourceBlock_.isEditable()?(pxt.BrowserUtils.addClass(e,"blocklyEditableText"),pxt.BrowserUtils.removeClass(e,"blocklyGreyExpressionBlockText"),this.fieldGroup_.style.cursor=this.CURSOR):(pxt.BrowserUtils.addClass(e,"blocklyGreyExpressionBlockText"),pxt.BrowserUtils.removeClass(e,"blocklyEditableText"),this.fieldGroup_.style.cursor=""))}setPythonEnabled(e){e!==this.pythonMode&&(this.pythonMode=e,this.forceRerender())}getText(){return this.pythonMode?pxt.Util.lf("<python code>"):this.getValue()}applyColour(){var e;this.sourceBlock_&&(null===(e=this.getConstants())||void 0===e?void 0:e.FULL_BLOCK_FIELDS)&&this.borderRect_&&this.borderRect_.setAttribute("stroke",this.sourceBlock_.style.colourTertiary)}}e.FieldTsExpression=t}(pxtblockly||(pxtblockly={})),function(e){class t extends Blockly.FieldSlider{constructor(e,t,n){super(String(e),"-200","200","1","10","TurnRatio",n),this.isFieldCustom_=!0,this.params=t,this.sliderColor_="#a8aaa8"}createLabelDom_(e){let n=document.createElement("div"),o=Blockly.utils.dom.createSvgElement("svg",{xmlns:"http://www.w3.org/2000/svg","xmlns:html":"http://www.w3.org/1999/xhtml","xmlns:xlink":"http://www.w3.org/1999/xlink",version:"1.1",height:t.HALF+t.HANDLE_RADIUS+10+"px",width:2*t.HALF+"px"},n),r=Blockly.utils.dom.createSvgElement("defs",{},o),i=Blockly.utils.dom.createSvgElement("marker",{id:"head",orient:"auto",markerWidth:"2",markerHeight:"4",refX:"0.1",refY:"1.5"},r);Blockly.utils.dom.createSvgElement("path",{d:"M0,0 V3 L1.5,1.5 Z",fill:"#f12a21"},i);this.reporter_=pxsim.svg.child(o,"text",{x:t.HALF,y:96,"text-anchor":"middle","dominant-baseline":"middle",style:"font-size: 50px",class:"sim-text inverted number"}),this.path_=Blockly.utils.dom.createSvgElement("path",{x1:t.HALF,y1:t.HALF,"marker-end":"url(#head)",style:"fill: none; stroke: #f12a21; stroke-width: 10"},o),this.updateGraph_();let s=document.createElement("span");return s.setAttribute("class","blocklyFieldSliderReadout"),[n,s]}updateGraph_(){if(!this.path_)return;let e=goog.math.clamp(this.getValue()||0,-200,200);const n=e/100,o=Math.max(-1,Math.min(1,n)),r=Math.max(o)*Math.PI/2,i=t.RADIUS-6;let s=t.HALF;const a=t.HALF-22;Math.abs(n)>1&&(s-=(n-(n>0?1:-1))*i/2);const l=.2+.5*Math.abs(o),c=i*l,u=i*Math.sin(Math.PI/2-r),d=i*Math.cos(Math.PI/2-r),p=u-i*l*Math.cos(2*r),g=`M ${s} ${a} C ${s} ${a-c} ${s+(d-i*l*Math.sin(2*r))} ${a-p} ${s+d} ${a-u}`;this.path_.setAttribute("d",g),this.reporter_.textContent=`${e}`}setReadout_(e,t){this.updateGraph_()}}t.HALF=80,t.HANDLE_RADIUS=30,t.RADIUS=t.HALF-t.HANDLE_RADIUS-1,e.FieldTurnRatio=t}(pxtblockly||(pxtblockly={})),function(e){class t extends Blockly.FieldDropdown{constructor(e){super(function(e){return function(){const t=[],n=this;if(n.sourceBlock_&&n.sourceBlock_.workspace){n.sourceBlock_.workspace.getVariablesOfType(e.name).forEach((e=>{const n=e.name.replace(/^\d+/,"");t.push([n,e.name])}))}else e.initialMembers.forEach((e=>t.push([e,e])));return t.push([lf("Add a new {0}...",e.memberName),"CREATE"]),t}}(e)),this.opts=e}init(){super.init(),this.initVariables()}onItemSelected_(e,t){"CREATE"===t.getValue()?n(this.sourceBlock_.workspace,this.opts,lf("New {0}:",this.opts.memberName),(e=>e&&this.setValue(e))):super.onItemSelected_(e,t)}doClassValidation_(e){var t;return(null===(t=this.opts)||void 0===t?void 0:t.initialMembers)&&!this.opts.initialMembers.find((t=>t==e))&&this.getOptions(),super.doClassValidation_(e)}initVariables(){if(this.sourceBlock_&&this.sourceBlock_.workspace){const e=this.sourceBlock_.workspace,t=r(e,this.opts.name);if(this.opts.initialMembers.forEach((n=>{t.some((([e,t])=>e===n))||s(e,this.opts,n)})),"CREATE"===this.getValue()){const t=function(e,t,n){const r=e.getVariablesOfType(t);if(r&&r.length)for(let e=0;e<r.length;e++){const[t]=o(r[e]);if(t===n)return r[e].name}return}(e,this.opts.name,this.opts.initialMembers[0]);t&&this.setValue(t)}}}}function n(e,t,o,i){Blockly.prompt(o,null,(a=>{if(a){let l=!1;if(pxtc.isIdentifierStart(a.charCodeAt(0),2)){l=!0;for(let e=1;e<a.length;e++)pxtc.isIdentifierPart(a.charCodeAt(e),2)||(l=!1)}if(!l)return void Blockly.alert(lf("Names must start with a letter and can only contain letters, numbers, '$', and '_'."),(()=>n(e,t,o,i)));const c=r(e,t.name);for(let r=0;r<c.length;r++){const[s,l]=c[r];if(s===a)return void Blockly.alert(lf("A {0} named '{1}' already exists.",t.memberName,a),(()=>n(e,t,o,i)))}i(s(e,t,a))}}),{placeholder:t.promptHint})}function o(e){const t=/^(\d+)([^0-9].*)$/.exec(e.name);return t?[t[2],parseInt(t[1])]:[e.name,-1]}function r(e,t){const n=e.getVariablesOfType(t);return n&&n.length?n.map(o):[]}function i(e,t){const n=e.map((([e,t])=>t));if(t.isBitMask){for(let e=0;e<n.length;e++){let t=1<<e;if(n.indexOf(t)<0)return t}return 1<<n.length}if(t.isHash)return 0;{const e=t.firstValue||0;for(let t=0;t<n.length;t++)if(n.indexOf(e+t)<0)return e+t;return e+n.length}}function s(e,t,n){const o=i(r(e,t.name),t)+n;return Blockly.Variables.getOrCreateVariablePackage(e,null,o,t.name),o}e.FieldUserEnum=t,e.getNextValue=i}(pxtblockly||(pxtblockly={})),function(e){let t;function n(e,t){const n=e.getVariablesOfType(pxt.sprite.BLOCKLY_TILESET_TYPE);for(const o of n)if(parseInt(o.name.substr(0,o.name.indexOf(";")))===t.projectId){e.deleteVariableById(o.getId());break}}function o(t){return i(t,(t=>t instanceof e.FieldTilemap&&!t.isGreyBlock))}function r(t){return i(t,(t=>t instanceof e.FieldTileset))}function i(e,t){const n=[];return e.getTopBlocks(!1).forEach((e=>o(e))),n;function o(e){for(const r of e.inputList){for(const o of r.fieldRow)t(o)&&n.push({block:e,field:o.name,ref:o});r.connection&&r.connection.targetBlock()&&o(r.connection.targetBlock())}e.nextConnection&&e.nextConnection.targetBlock()&&o(e.nextConnection.targetBlock())}}!function(e){e.hasClass=function(e,t){return pxt.BrowserUtils.containsClass(e,t)},e.addClass=function(e,t){pxt.BrowserUtils.addClass(e,t)},e.removeClass=function(e,t){pxt.BrowserUtils.removeClass(e,t)}}(t=e.svg||(e.svg={})),e.parseColour=function(e){const t=Number(e);return isNaN(t)?goog.isString(e)&&e.match(/^#[0-9a-fA-F]{6}$/)?e:"#000":Blockly.hueToRgb(t)},e.bitmapToImageURI=function(e,t,n){const o=pxt.appTarget.runtime.palette.slice(1),r=document.createElement("canvas");r.width=t,r.height=t;const i=Math.min(t/e.width,t/e.height),s=Math.max(Math.floor(t*(1-e.width/e.height)/2),0),a=Math.max(Math.floor(t*(1-e.height/e.width)/2),0);let l;n?(l=r.getContext("2d",{alpha:!1}),l.fillStyle="#dedede",l.fillRect(0,0,t,t)):l=r.getContext("2d");for(let t=0;t<e.width;t++)for(let r=0;r<e.height;r++){const c=e.get(t,r);c?(l.fillStyle=o[c-1],l.fillRect(s+t*i,a+r*i,i,i)):n&&(l.fillStyle="#dedede",l.fillRect(s+t*i,a+r*i,i,i))}return r.toDataURL()},e.tilemapToImageURI=function(e,t,n){const o=pxt.appTarget.runtime.palette.slice(),r=document.createElement("canvas");r.width=t,r.height=t;const i=Math.min(t/e.tilemap.width,t/e.tilemap.height),s=Math.max(Math.floor(t*(1-e.tilemap.width/e.tilemap.height)/2),0),a=Math.max(Math.floor(t*(1-e.tilemap.height/e.tilemap.width)/2),0);let l;n?(l=r.getContext("2d",{alpha:!1}),l.fillStyle="#dedede",l.fillRect(0,0,t,t)):l=r.getContext("2d");let c=[];for(let t=0;t<e.tilemap.width;t++)for(let r=0;r<e.tilemap.height;r++){const u=e.tilemap.get(t,r);if(u){if(!c[u]){const t=e.tileset.tiles[u];c[u]=t?pxt.sprite.computeAverageColor(pxt.sprite.Bitmap.fromData(t.bitmap),o):"#dedede"}l.fillStyle=c[u],l.fillRect(s+t*i,a+r*i,i,i)}else n&&(l.fillStyle="#dedede",l.fillRect(s+t*i,a+r*i,i,i))}return r.toDataURL()},e.getAllBlocksWithTilemaps=o,e.getAllBlocksWithTilesets=r,e.needsTilemapUpgrade=function(e){return!!e.getVariablesOfType(pxt.sprite.BLOCKLY_TILESET_TYPE).map((e=>pxt.sprite.legacy.blocklyVariableToTile(e.name))).length},e.upgradeTilemapsInWorkspace=function(e,t){const i=e.getVariablesOfType(pxt.sprite.BLOCKLY_TILESET_TYPE).map((e=>pxt.sprite.legacy.blocklyVariableToTile(e.name)));if(i.length)try{Blockly.Events.disable();let s=[];for(const o of i)o.qualifiedName?s[o.projectId]=t.resolveTile(o.qualifiedName):o.data&&(s[o.projectId]=t.createNewTile(o.data,"myTiles.tile"+o.projectId)),n(e,o);const a=o(e);for(const e of a){const n=pxt.sprite.legacy.decodeTilemap(e.ref.getInitText(),"typescript"),o=[],r=new pxt.sprite.TilemapData(n.tilemap,{tileWidth:n.tileset.tileWidth,tiles:n.tileset.tiles.map(((e,n)=>null!=e.projectId?s[e.projectId]:(o[n]||(o[n]=t.resolveTile(e.qualifiedName)),o[n])))},n.layers);e.ref.setValue(pxt.sprite.encodeTilemap(r,"typescript"))}const l=r(e);for(const e of l)e.ref.doValueUpdate_(e.ref.getValue()),e.ref.isDirty_&&e.ref.forceRerender()}finally{Blockly.Events.enable()}},e.getAllReferencedTiles=function(e,t){var n;let i={};const s=o(e),a=pxt.react.getTilemapProject();for(const e of s)if(e.block.id!==t)for(const t of(null===(n=e.ref.getTileset())||void 0===n?void 0:n.tiles)||[])i[t.id]=a.lookupAsset("tile",t.id);const l=a.getAssets("tilemap");for(const e of l)for(const t of e.data.tileset.tiles)i[t.id]=a.lookupAsset("tile",t.id);const c=r(e);for(const e of c){const t=e.ref.getValue(),n=/^\s*assets\s*\.\s*tile\s*`([^`]*)`\s*$/.exec(t);if(n){const e=a.lookupAssetByName("tile",n[1]);e&&!i[e.id]&&(i[e.id]=e)}else i[t]||(i[t]=a.resolveTile(t))}return Object.keys(i).map((e=>i[e])).filter((e=>!!e))},e.getTemporaryAssets=function(t,n){switch(n){case"image":return i(t,(t=>t instanceof e.FieldSpriteEditor&&t.isTemporaryAsset())).map((e=>e.ref.getAsset()));case"animation":return i(t,(t=>t instanceof e.FieldAnimationEditor&&t.isTemporaryAsset())).map((e=>e.ref.getAsset()));default:return[]}}}(pxtblockly||(pxtblockly={})),function(e){!function(t){let n,o,r,i;!function(e){e[e.Stopped=0]="Stopped",e[e.Pending=1]="Pending",e[e.Starting=2]="Starting",e[e.Running=3]="Running"}(n=t.SimState||(t.SimState={})),t.isBlocks=function(t){return e.U.endsWith(t.name,".blocks")},function(e){e.HeaderOnly="errorListHeader",e.Expanded="errorListExpanded"}(o=t.ErrorListState||(t.ErrorListState={})),function(e){e[e.Hidden=0]="Hidden",e[e.Visible=1]="Visible",e[e.Disabled=2]="Disabled"}(r=t.FilterState||(t.FilterState={})),t.initExtensionsAsync=e=>Promise.resolve({}),t.initFieldExtensionsAsync=e=>Promise.resolve({}),t.HELP_IMAGE_URI="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjYiIGhlaWdodD0iMjYiIHZpZXdCb3g9IjAgMCAyNiAyNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPGNpcmNsZSBjeD0iMTMiIGN5PSIxMyIgcj0iMTMiIGZpbGw9IndoaXRlIi8+CjxwYXRoIGQ9Ik0xNy45NTIgOS4xODQwMkMxNy45NTIgMTAuMjU2IDE3LjgxNiAxMS4wNzIgMTcuNTQ0IDExLjYzMkMxNy4yODggMTIuMTkyIDE2Ljc1MiAxMi43OTIgMTUuOTM2IDEzLjQzMkMxNS4xMiAxNC4wNzIgMTQuNTc2IDE0LjU4NCAxNC4zMDQgMTQuOTY4QzE0LjA0OCAxNS4zMzYgMTMuOTIgMTUuNzM2IDEzLjkyIDE2LjE2OFYxNi45NkgxMS44MDhDMTEuNDI0IDE2LjQ2NCAxMS4yMzIgMTUuODQgMTEuMjMyIDE1LjA4OEMxMS4yMzIgMTQuNjg4IDExLjM4NCAxNC4yODggMTEuNjg4IDEzLjg4OEMxMS45OTIgMTMuNDg4IDEyLjUzNiAxMi45NjggMTMuMzIgMTIuMzI4QzE0LjEwNCAxMS42NzIgMTQuNjI0IDExLjE2OCAxNC44OCAxMC44MTZDMTUuMTM2IDEwLjQ0OCAxNS4yNjQgOS45NjgwMiAxNS4yNjQgOS4zNzYwMkMxNS4yNjQgOC4yMDgwMiAxNC40MTYgNy42MjQwMiAxMi43MiA3LjYyNDAyQzExLjc2IDcuNjI0MDIgMTAuNzUyIDcuNzM2MDIgOS42OTYgNy45NjAwMkw5LjE0NCA4LjA4MDAyTDkgNi4wODgwMkMxMC40ODggNS41NjAwMiAxMS44NCA1LjI5NjAyIDEzLjA1NiA1LjI5NjAyQzE0LjczNiA1LjI5NjAyIDE1Ljk2OCA1LjYwODAyIDE2Ljc1MiA2LjIzMjAyQzE3LjU1MiA2Ljg0MDAyIDE3Ljk1MiA3LjgyNDAyIDE3Ljk1MiA5LjE4NDAyWk0xMS40IDIyVjE4LjY0SDE0LjE4NFYyMkgxMS40WiIgZmlsbD0iIzU5NUU3NCIvPgo8L3N2Zz4K",t.initEditorExtensionsAsync=function(){if(!i&&(i=Promise.resolve(),e.appTarget&&e.appTarget.appTheme&&e.appTarget.appTheme.extendFieldEditors)){const t={};i=i.then((()=>e.BrowserUtils.loadBlocklyAsync())).then((()=>e.BrowserUtils.loadScriptAsync("fieldeditors.js"))).then((()=>e.editor.initFieldExtensionsAsync(t))).then((t=>{t.fieldEditors&&t.fieldEditors.forEach((t=>{e.blocks.registerFieldEditor(t.selector,t.editor,t.validator)}))}))}return i}}(e.editor||(e.editor={}))}(pxt||(pxt={})),function(e){!function(t){const n={};function o(e,t,n,o){e.response&&window.parent.postMessage({type:e.type,id:e.id,resp:t,success:n,error:o},"*")}function r(t){return new Promise(((o,r)=>{const i=e.Util.clone(t);i.id=ts.pxtc.Util.guidGen(),t.response&&(n[i.id]={resolve:o,reject:r}),window.parent.postMessage(i,"*"),t.response||o(void 0)}))}t.bindEditorMessages=function(t){const r=(e.appTarget.appTheme.allowParentController||e.shell.isControllerMode())&&e.BrowserUtils.isIFrame(),i=e.appTarget.appTheme.allowPackageExtensions,s=e.appTarget.appTheme.allowSimulatorTelemetry;(r||i||s)&&window.addEventListener("message",(a=>{const l=a.data;if(!l||!/^pxt(host|editor|pkgext|sim)$/.test(l.type))return!1;if("pxtpkgext"===l.type&&i)t().then((e=>{e.handleExtensionRequest(l)}));else if("pxtsim"===l.type&&s){const t=l;"event"===t.action&&(t.category||t.message?e.reportError(t.category,t.message,t.data):e.tickEvent(t.tick,t.data))}else if(r){let r,i=Promise.resolve();if("pxthost"==l.type){const t=n[l.id];t?i=i.then((()=>t.resolve(l))):e.debug(`pxthost: unknown request ${l.id}`)}else"pxteditor"==l.type&&(i=i.then((()=>t().then((t=>{const n=l;switch(e.debug(`pxteditor: ${n.action}`),n.action.toLowerCase()){case"switchjavascript":return Promise.resolve().then((()=>t.openJavaScript()));case"switchpython":return Promise.resolve().then((()=>t.openPython()));case"switchblocks":return Promise.resolve().then((()=>t.openBlocks()));case"startsimulator":return Promise.resolve().then((()=>t.startSimulator()));case"restartsimulator":return Promise.resolve().then((()=>t.restartSimulator()));case"hidesimulator":return Promise.resolve().then((()=>t.collapseSimulator()));case"showsimulator":return Promise.resolve().then((()=>t.expandSimulator()));case"closeflyout":return Promise.resolve().then((()=>t.closeFlyout()));case"unloadproject":return Promise.resolve().then((()=>t.unloadProjectAsync()));case"saveproject":return t.saveProjectAsync();case"redo":return Promise.resolve().then((()=>{const e=t.editor;e&&e.hasRedo()&&e.redo()}));case"undo":return Promise.resolve().then((()=>{const e=t.editor;e&&e.hasUndo()&&e.undo()}));case"setscale":{const e=l;return Promise.resolve().then((()=>t.editor.setScale(e.scale)))}case"stopsimulator":{const e=l;return Promise.resolve().then((()=>t.stopSimulator(e.unload)))}case"newproject":{const e=l;return Promise.resolve().then((()=>t.newProject(e.options)))}case"importproject":{const e=l;return Promise.resolve().then((()=>t.importProjectAsync(e.project,{filters:e.filters,searchBar:e.searchBar})))}case"openheader":{const e=l;return t.openProjectByHeaderIdAsync(e.headerId)}case"startactivity":{const n=l;let o,r=n.path;return/^([jt]s|py|blocks?):/i.test(r)&&(o=/^py:/i.test(r)?e.PYTHON_PROJECT_NAME:/^[jt]s:/i.test(r)?e.JAVASCRIPT_PROJECT_NAME:e.BLOCKS_PROJECT_NAME,r=r.substr(r.indexOf(":")+1)),Promise.resolve().then((()=>t.startActivity({activity:n.activityType,path:r,title:n.title,editor:o,previousProjectHeaderId:n.previousProjectHeaderId,carryoverPreviousCode:n.carryoverPreviousCode})))}case"importtutorial":{const e=l;return Promise.resolve().then((()=>t.importTutorialAsync(e.markdown)))}case"proxytosim":{const e=l;return Promise.resolve().then((()=>t.proxySimulatorMessage(e.content)))}case"renderblocks":{const e=l;return Promise.resolve().then((()=>t.renderBlocksAsync(e))).then((e=>e.xml.then((e=>{r=e.xml}))))}case"renderpython":{const e=l;return Promise.resolve().then((()=>t.renderPythonAsync(e))).then((e=>{r=e.python}))}case"toggletrace":{const e=l;return Promise.resolve().then((()=>t.toggleTrace(e.intervalSpeed)))}case"settracestate":{const e=l;return Promise.resolve().then((()=>t.setTrace(e.enabled,e.intervalSpeed)))}case"setsimulatorfullscreen":{const e=l;return Promise.resolve().then((()=>t.setSimulatorFullScreen(e.enabled)))}case"togglehighcontrast":return Promise.resolve().then((()=>t.toggleHighContrast()));case"sethighcontrast":{const e=l;return Promise.resolve().then((()=>t.setHighContrast(e.on)))}case"togglegreenscreen":return Promise.resolve().then((()=>t.toggleGreenScreen()));case"print":return Promise.resolve().then((()=>t.printCode()));case"pair":return t.pairAsync();case"info":return Promise.resolve().then((()=>{r={versions:e.appTarget.versions,locale:ts.pxtc.Util.userLanguage(),availableLocales:e.appTarget.appTheme.availableLocales}}));case"shareproject":{const e=l;return t.anonymousPublishHeaderByIdAsync(e.headerId).then((e=>{r=e}))}case"savelocalprojectstocloud":{const e=l;return t.saveLocalProjectsToCloudAsync(e.headerIds).then((e=>{r={headerIdMap:e}}))}case"requestprojectcloudstatus":{const e=l;return t.requestProjectCloudStatus(e.headerIds)}case"convertcloudprojectstolocal":{const e=l;return t.convertCloudProjectsToLocal(e.userId)}case"setlanguagerestriction":{const e=l;if("no-blocks"===e.restriction)throw console.warn("no-blocks language restriction is not supported"),new Error("no-blocks language restriction is not supported");return t.setLanguageRestrictionAsync(e.restriction)}}return Promise.resolve()})))));i.then((()=>o(l,r,!0,void 0)),(e=>o(l,r,!1,e)))}return!0}),!1)},t.enableControllerAnalytics=function(){if(!e.appTarget.appTheme.allowParentController||!e.BrowserUtils.isIFrame())return;const t=e.tickEvent;e.tickEvent=function(e,n){t&&t(e,n),r({type:"pxthost",action:"event",tick:e,response:!1,data:n})};const n=e.reportException;e.reportException=function(e,t){n&&n(e,t);try{r({type:"pxthost",action:"event",tick:"error",message:e.message,response:!1,data:t})}catch(e){}};const o=e.reportError;e.reportError=function(e,t,n){o&&o(e,t,n),r({type:"pxthost",action:"event",tick:"error",category:e,message:t,data:n})}},t.shouldPostHostMessages=function(){return e.appTarget.appTheme.allowParentController&&e.BrowserUtils.isIFrame()},t.postHostMessageAsync=r}(e.editor||(e.editor={}))}(pxt||(pxt={})),function(e){!function(t){!function(t){function n(e){return`experiments-${"object"==typeof e?e.id:e}`}function o(){const t=e.savedAppTheme(),n={},o=r();return o.forEach((e=>{const o=i(e);t[e.id]=!!o,o&&(n[e.id]=o?1:0)})),o.length&&Object.keys(n).length&&(e.tickEvent("experiments.loaded",n),e.reloadAppTargetVariant()),e.appTarget.appTheme}function r(){const t=e.appTarget.appTheme.experiments;return t?[{id:"print",name:lf("Print Code"),description:lf("Print the code from the current project"),feedbackUrl:"https://github.com/microsoft/pxt/issues/4740"},{id:"greenScreen",name:lf("Green screen"),description:lf("Display a webcam video stream or a green background behind the code."),feedbackUrl:"https://github.com/microsoft/pxt/issues/4738"},{id:"allowPackageExtensions",name:lf("Editor Extensions"),description:lf("Allow Extensions to add buttons in the editor."),feedbackUrl:"https://github.com/microsoft/pxt/issues/4741"},{id:"instructions",name:lf("Wiring Instructions"),description:lf("Generate step-by-step assembly instructions for breadboard wiring."),feedbackUrl:"https://github.com/microsoft/pxt/issues/4739"},{id:"debugger",name:lf("Debugger"),description:lf("Step through code and inspect variables in the debugger"),feedbackUrl:"https://github.com/microsoft/pxt/issues/4729"},{id:"bluetoothUartConsole",name:"Bluetooth Console",description:lf("Receives UART message through Web Bluetooth"),feedbackUrl:"https://github.com/microsoft/pxt/issues/4796"},{id:"bluetoothPartialFlashing",name:"Bluetooth Download",description:lf("Download code via Web Bluetooth"),feedbackUrl:"https://github.com/microsoft/pxt/issues/4807"},{id:"simScreenshot",name:lf("Simulator Screenshots"),description:lf("Download screenshots of the simulator"),feedbackUrl:"https://github.com/microsoft/pxt/issues/5232"},{id:"python",name:lf("Static Python"),description:lf("Use Static Python to code your device"),feedbackUrl:"https://github.com/microsoft/pxt/issues/5390"},{id:"simGif",name:lf("Simulator Gifs"),description:lf("Download gifs of the simulator"),feedbackUrl:"https://github.com/microsoft/pxt/issues/5297"},{id:"qrCode",name:lf("Shared QR Code"),description:lf("Generate a QR Code form the shared project url"),feedbackUrl:"https://github.com/microsoft/pxt/issues/5456"},{id:"importExtensionFiles",name:lf("Import Extension Files"),description:lf("Import Extensions from compiled project files")},{id:"debugExtensionCode",name:lf("Debug Extension Code"),description:lf("Use the JavaScript debugger to debug extension code")},{id:"snippetBuilder",name:lf("Snippet Builder"),description:lf("Try out the new snippet dialogs.")},{id:"experimentalHw",name:lf("Experimental Hardware"),description:lf("Enable support for hardware marked 'experimental' in the hardware seletion dialog")},{id:"checkForHwVariantWebUSB",name:lf("Detect Hardware with WebUSB"),description:lf("When compiling, use WebUSB to detect hardware configuration.")},{id:"githubEditor",name:lf("GitHub editor"),description:lf("Review, commit and push to GitHub."),feedbackUrl:"https://github.com/microsoft/pxt/issues/6419",enableOnline:!0},{id:"githubCompiledJs",name:lf("GitHub Pages JavaScript"),description:lf("Commit compiled javascript when creating a release"),enableOnline:!0},{id:"blocksCollapsing",name:lf("Collapse blocks"),description:lf("Collapse and expand functions or event blocks")},{id:"tutorialBlocksDiff",name:lf("Tutorial Block Diffs"),description:lf("Automatially render blocks diff in tutorials")},{id:"openProjectNewTab",name:lf("Open in New Tab"),description:lf("Open an editor in a new tab.")},{id:"openProjectNewDependentTab",name:lf("Open in New Connected Tab"),description:lf("Open connected editors in different browser tabs.")},{id:"accessibleBlocks",name:lf("Accessible Blocks"),description:lf("Use the WASD keys to move and modify blocks."),feedbackUrl:"https://github.com/microsoft/pxt/issues/6850"},{id:"errorList",name:lf("Error List"),description:lf("Show an error list panel for JavaScript and Python.")},{id:"blocksErrorList",name:lf("Blocks Error List"),description:lf("Show an error list panel for Blocks")}].filter((n=>t.indexOf(n.id)>-1&&!(e.BrowserUtils.isPxtElectron()&&n.enableOnline))):[]}function i(t){return!!e.storage.getLocal(n(t))}function s(t,r){r!=i(t)&&(r?e.storage.setLocal(n(t),"1"):e.storage.removeLocal(n(t)),o())}t.syncTheme=o,t.all=r,t.clear=function(){r().forEach((t=>e.storage.removeLocal(n(t)))),o()},t.someEnabled=function(){return r().some((e=>i(e)))},t.isEnabled=i,t.toggle=function(e){s(e,!i(e))},t.state=function(){const e={};return r().forEach((t=>e[t.id]=i(t))),JSON.stringify(e)},t.setState=s}(t.experiments||(t.experiments={}))}(e.editor||(e.editor={}))}(pxt||(pxt={})),function(e){!function(t){function n(t){const n=e.appTarget.appTheme.invertedMonaco,o=!(!e.appTarget.appTheme.monacoFieldEditors||!e.appTarget.appTheme.monacoFieldEditors.length),r=e.BrowserUtils.isAndroid();let i=monaco.editor.create(t,{model:null,ariaLabel:e.Util.lf("JavaScript editor"),fontFamily:"'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', 'source-code-pro', 'monospace'",scrollBeyondLastLine:!0,language:"typescript",mouseWheelZoom:!1,wordBasedSuggestions:!0,lineNumbersMinChars:3,formatOnPaste:!0,folding:o,glyphMargin:o||e.appTarget.appTheme.debugger,minimap:{enabled:!1},fixedOverflowWidgets:!0,autoIndent:"full",useTabStops:!0,dragAndDrop:!0,matchBrackets:"always",occurrencesHighlight:!1,quickSuggestionsDelay:200,theme:n?"vs-dark":"vs",renderIndentGuides:!0,accessibilityHelpUrl:"",quickSuggestions:{other:!r,comments:!r,strings:!r},acceptSuggestionOnCommitCharacter:!r,acceptSuggestionOnEnter:r?"off":"on",accessibilitySupport:r?"off":"on"});return i.layout(),i}t.syncModels=function(e,t,n,o){if(o)return;let r=monaco.languages.typescript.typescriptDefaults.getExtraLibs(),i={};e.sortedDeps().forEach((e=>{e.getFiles().forEach((o=>{let r=e.id+"/"+o;if(/\.(ts)$/.test(o)&&r!=n){if(!monaco.languages.typescript.typescriptDefaults.getExtraLibs()[r]){let n=e.readFile(o)||"\n";t[r]=monaco.languages.typescript.typescriptDefaults.addExtraLib(n,r)}i[r]="1"}}))})),Object.keys(r).filter((e=>/\.(ts)$/.test(e)&&!i[e])).forEach((e=>{t[e].dispose()}))},t.initMonacoAsync=function(t){return new Promise(((o,r)=>{if("object"==typeof window.monaco)return void o(n(t));let i=window.MonacoPaths,s=()=>{let r=window.require;r.config({paths:i}),r(["vs/editor/editor.main"],(()=>{monaco.languages.register({id:"asm",extensions:[".asm"]}),monaco.languages.setMonarchTokensProvider("asm",{tokenPostfix:"",keywords:["movs","mov","adds","add","adcs","adr","subs","sbcs","sub","rsbs","muls","cmp","cmn","ands","eors","orrs","bics","mvns","tst","lsls","lsrs","asrs","rors","ldr","ldrh","ldrb","ldrsh","ldrsb","ldm","str","strh","strb","stm","push","pop","cbz","cbnz","b","bl","bx","blx","sxth","sxtb","uxth","uxtb","rev","rev16","revsh","svc","cpsid","cpsie","setend","bkpt","nop","sev","wfe","wfi","yield","beq","bne","bcs","bhs","bcc","blo","bmi","bpl","bvs","bvc","bhi","bls","bge","blt","bgt","ble","bal","r0","r1","r2","r3","r4","r5","r6","r7","r8","r9","r10","r11","r12","r13","r14","r15","pc","sp","lr"],typeKeywords:[".startaddr",".hex",".short",".space",".section",".string",".byte"],operators:[],symbols:/[:\*]+/,escapes:/\\(?:[abfnrtv\\"']|x[0-9A-Fa-f]{1,4}|u[0-9A-Fa-f]{4}|U[0-9A-Fa-f]{8})/,tokenizer:{root:[[/(\.)?[a-z_$\.][\w$]*/,{cases:{"@typeKeywords":"keyword","@keywords":"keyword","@default":"identifier"}}],{include:"@whitespace"},[/[{}()\[\]]/,"@brackets"],[/[<>](?!@symbols)/,"@brackets"],[/@symbols/,{cases:{"@operators":"operator","@default":""}}],[/@\s*[a-zA-Z_\$][\w\$]*/,{token:"annotation"}],[/(#|(0[xX]))?[0-9a-fA-F]+/,"number"],[/[;,.]/,"delimiter"],[/"([^"\\]|\\.)*$/,"string.invalid"],[/"/,{token:"string.quote",bracket:"@open",next:"@string"}],[/'[^\\']'/,"string"],[/(')(@escapes)(')/,["string","string.escape","string"]],[/'/,"string.invalid"]],comment:[],string:[[/[^\\"]+/,"string"],[/@escapes/,"string.escape"],[/\\./,"string.escape.invalid"],[/"/,{token:"string.quote",bracket:"@close",next:"@pop"}]],whitespace:[[/[ \t\r\n]+/,"white"],[/\/\*/,"comment","@comment"],[/;.*$/,"comment"]]}}),monaco.languages.typescript&&(monaco.languages.typescript.typescriptDefaults.setDiagnosticsOptions({noSyntaxValidation:!0,noSemanticValidation:!0}),monaco.languages.typescript.typescriptDefaults.setWorkerOptions({customWorkerPath:e.webConfig.typeScriptWorkerJs}),monaco.languages.typescript.typescriptDefaults.setCompilerOptions({allowUnreachableCode:!0,noImplicitAny:!0,allowJs:!1,allowUnusedLabels:!0,target:monaco.languages.typescript.ScriptTarget.ES5,outDir:"built",rootDir:".",noLib:!0,mouseWheelZoom:!1})),o(n(t))}))};if(window.require)s();else{let e=document.createElement("script");e.type="text/javascript",e.src=i["vs/loader"],e.addEventListener("load",s),document.body.appendChild(e)}}))},t.createEditor=n}(e.vs||(e.vs={}))}(pxt||(pxt={})),function(e){!function(t){t.freshHeader=function(t,n){return{target:e.appTarget.id,targetVersion:e.appTarget.versions.target,name:t,meta:{},editor:e.JAVASCRIPT_PROJECT_NAME,pubId:"",pubCurrent:!1,_rev:null,id:e.U.guidGen(),recentUse:n,modificationTime:n,cloudUserId:null,cloudCurrent:!1,cloudVersion:null,cloudLastSyncTime:0,isDeleted:!1}}}(e.workspace||(e.workspace={}))}(pxt||(pxt={})),function(e){!function(e){const t={};e.registerMonacoFieldEditor=function(e,n){t[e]=n},e.getMonacoFieldEditor=function(e){return t[e]}}(e.editor||(e.editor={}))}(pxt||(pxt={})),function(e){!function(t){t.MonacoReactFieldEditor=class{getId(){return"image-editor"}showEditorAsync(t,n,o){return this.fileType=t,this.editrange=n,this.host=o,this.initAsync().then((()=>{const t=this.textToValue(o.getText(n));return t?(this.fv=e.react.getFieldEditorView(this.getFieldEditorId(),t,this.getOptions()),this.fv.onHide((()=>{this.onClosed()})),this.fv.show(),new Promise(((e,t)=>{this.resolver=e,this.rejecter=t}))):Promise.resolve(null)}))}onClosed(){this.resolver&&(this.resolver({range:this.editrange,replacement:this.resultToText(this.fv.getResult())}),this.editrange=void 0,this.resolver=void 0,this.rejecter=void 0)}dispose(){this.onClosed()}initAsync(){return Promise.resolve()}textToValue(e){return null}resultToText(e){return e+""}getFieldEditorId(){return""}getOptions(){return null}}}(e.editor||(e.editor={}))}(pxt||(pxt={})),function(e){!function(t){const n="image-editor";class o extends t.MonacoReactFieldEditor{textToValue(t){this.isPython=-1===t.indexOf("`");const n=e.parseAssetTSReference(t);if(n){const{type:t,name:o}=n,r=o.trim(),i=e.react.getTilemapProject();this.isAsset=!0;const s=i.lookupAssetByName("image",r);if(s)return s;{const t=i.createNewImage();return r&&!i.isNameTaken("image",r)&&e.validateAssetName(r)&&(t.meta.displayName=r),t}}return{type:"image",id:"",internalID:0,bitmap:e.sprite.imageLiteralToBitmap(t).data(),meta:{},jresData:""}}resultToText(t){var n;if(null===(n=t.meta)||void 0===n?void 0:n.displayName){const n=e.react.getTilemapProject();return t=this.isAsset||n.lookupAsset(t.type,t.id)?n.updateAsset(t):n.createNewProjectImage(t.bitmap,t.meta.displayName),this.isAsset=!0,e.getTSReferenceForAsset(t,this.isPython)}return e.sprite.bitmapToImageLiteral(e.sprite.Bitmap.fromData(t.bitmap),this.isPython?"python":"typescript")}getFieldEditorId(){return"image-editor"}getOptions(){return{initWidth:16,initHeight:16,blocksInfo:this.host.blocksInfo()}}}t.MonacoSpriteEditor=o,t.spriteEditorDefinition={id:n,foldMatches:!0,glyphCssClass:"sprite-editor-glyph sprite-focus-hover",heightInPixels:510,matcher:{searchString:'(?:img|assets\\s*\\.\\s*image)\\s*(?:`|\\(\\s*""")(?:(?:[^(){}:\\[\\]"\';?/,+\\-=*&|^%!`~]|\\n)*)\\s*(?:`|"""\\s*\\))',isRegex:!0,matchCase:!0,matchWholeWord:!1},proto:o},t.registerMonacoFieldEditor(n,t.spriteEditorDefinition)}(e.editor||(e.editor={}))}(pxt||(pxt={})),function(e){!function(t){const n="tilemap-editor";class o extends t.MonacoReactFieldEditor{textToValue(t){const n=this.readTilemap(t),o=e.react.getTilemapProject();return e.sprite.addMissingTilemapTilesAndReferences(o,n),n}readTilemap(t){const n=e.react.getTilemapProject();if(/^\s*tiles\s*\./.test(t)&&(this.isTilemapLiteral=!1,t)){try{return function(e){return{type:"tilemap",id:"",internalID:0,meta:{},data:e}}(e.sprite.decodeTilemap(t,"typescript",n))}catch(e){}return null}this.isTilemapLiteral=!0;const o=/^\s*(tilemap(?:8|16|32)?)\s*(?:`([^`]*)`)|(?:\(\s*"""([^"]*)"""\s*\))\s*$/.exec(t),r=(o[2]||o[3]||"").trim();let i,s;if(this.tilemapLiteral=o[1],r){let e=ts.pxtc.escapeIdentifier(r);i=n.getTilemap(e)}if(!i){let e=16;"tilemap8"===this.tilemapLiteral?e=8:"tilemap32"===this.tilemapLiteral&&(e=32);const[t]=n.createNewTilemap(s,e,16,16);i=n.getTilemap(t),s=t}return i}resultToText(t){const n=e.react.getTilemapProject();return n.pushUndo(),e.sprite.updateTilemapReferencesFromResult(n,t),this.isTilemapLiteral?(n.updateAsset(t),e.getTSReferenceForAsset(t,"python"===this.fileType)):e.sprite.encodeTilemap(t.data,"typescript"===this.fileType?"typescript":"python")}getFieldEditorId(){return"tilemap-editor"}getOptions(){return{initWidth:16,initHeight:16,blocksInfo:this.host.blocksInfo()}}getCreateTilemapRange(){const e=this.editrange.getStartPosition();let t,n=this.editrange.getEndPosition(),o=1;for(;;){t=new monaco.Range(n.lineNumber,n.column,n.lineNumber+1,0);const r=this.host.getText(t);for(let t=0;t<r.length;t++)if("("===r.charAt(t))o++;else if(")"===r.charAt(t)&&(o--,0===o)){const o=new monaco.Position(n.lineNumber,n.column+t+2);return monaco.Range.fromPositions(e,o)}if(n=t.getEndPosition(),n.lineNumber>e.lineNumber+20)return null}}}t.MonacoTilemapEditor=o,t.tilemapEditorDefinition={id:n,foldMatches:!0,alwaysBuildOnClose:!0,glyphCssClass:"sprite-focus-hover ms-Icon ms-Icon--Nav2DMapView",heightInPixels:510,weight:5,matcher:{searchString:'(?:tilemap(?:8|16|32)?\\s*(?:`|\\(""")(?:[ a-zA-Z0-9_]|\\n)*\\s*(?:`|"""\\)))|(?:tiles\\s*\\.\\s*createTilemap\\s*\\([^\\)]+\\))',isRegex:!0,matchCase:!0,matchWholeWord:!1},proto:o},t.registerMonacoFieldEditor(n,t.tilemapEditorDefinition)}(e.editor||(e.editor={}))}(pxt||(pxt={})),function(e){!function(e){let t;e.makeFocusable=function(e){e.setAttribute("focusable","true"),e.setAttribute("tabindex","0")},e.enableKeyboardInteraction=function(e,t,n){t&&e.addEventListener("keydown",(e=>{const n="number"==typeof e.which?e.which:e.keyCode;32!==n&&13!==n||t()})),n&&e.addEventListener("keyup",(e=>{const t="number"==typeof e.which?e.which:e.keyCode;32!==t&&13!==t||n()}))},e.setAria=function(e,t,n){t&&!e.hasAttribute("role")&&e.setAttribute("role",t),n&&!e.hasAttribute("aria-label")&&e.setAttribute("aria-label",n)},e.setLiveContent=function(e){if(!t){let e="position: absolute !important;display: block;visibility: visible;overflow: hidden;width: 1px;height: 1px;margin: -1px;border: 0;padding: 0;clip: rect(0 0 0 0);";t=document.createElement("div"),t.setAttribute("role","status"),t.setAttribute("aria-live","polite"),t.setAttribute("aria-hidden","false"),t.setAttribute("style",e),document.body.appendChild(t)}t.textContent!==e&&(t.textContent=e)}}(e.accessibility||(e.accessibility={}))}(pxsim||(pxsim={})),function(e){const t="blue",n="red",o="orange";const r=e=>(e=>e.reduce(((e,t)=>e+(t?1:0)),0))(e)>0;function i(e,t){let n={};for(let t in e)n[t]=e[t];for(let e in t)n[e]=t[e];return n}function s(t){e.U.assert(!!t,"Invalid pin: "+t);const n=/^(\w+)\.\s*(?:[a-z]*)?([A-Z][A-Z\d_]+)$/.exec(t);return n?n[2]:void 0}function a(e){return"-Z"===e.orientation&&"male"===e.style}e.readPin=s;class l{constructor(t){this.availablePowerPins={top:{fiveVolt:e.mkRange(26,51).map((e=>({type:"breadboard",row:"+",col:`${e}`}))),threeVolt:e.mkRange(26,51).map((e=>({type:"breadboard",row:"+",col:`${e}`}))),ground:e.mkRange(26,51).map((e=>({type:"breadboard",row:"-",col:`${e}`})))},bottom:{fiveVolt:e.mkRange(1,26).map((e=>({type:"breadboard",row:"+",col:`${e}`}))),threeVolt:e.mkRange(1,26).map((e=>({type:"breadboard",row:"+",col:`${e}`}))),ground:e.mkRange(1,26).map((e=>({type:"breadboard",row:"-",col:`${e}`})))}},this.opts=t}allocPartIRs(e,t,n){let o=[];const r=(e,t,o,r)=>{let i=[];for(let t=0;t<e.numberOfPins;t++){let r,s=e.pinDefinitions[t];if("string"==typeof s.target)r=s.target;else{let e=s.target.pinInstantiationIdx;if(!o||void 0===o[e])return void console.log(`error: parts no pin found for PinInstantiationIdx: ${e}. (Is the part missing an ArgumentRole or "trackArgs=" annotations?)`);r=o[e]}let a=e.visual.pinLocations[t],l=n.yOffset+a.y,c=Math.round(l/e.visual.pinDistance),u=l-c*e.visual.pinDistance,d=n.xOffset+a.x,p=Math.round(d/e.visual.pinDistance),g={partRelativeRowIdx:c,partRelativeColIdx:p,xOffset:d-p*e.visual.pinDistance,yOffset:u};i.push({def:s,loc:a,target:r,bbFit:g})}return{name:t,def:e,pins:i,partParams:r||{},bbFit:n}},i=e.instantiations||[];return e.instantiation&&i.push(e.instantiation),i.forEach((n=>{if("singleton"===n.kind)o.push(r(e,t));else if("function"===n.kind){let i=n,a=i.fullyQualifiedName.split(","),l={};a.forEach((e=>{this.opts.fnArgs[e]&&this.opts.fnArgs[e].forEach((e=>{l[e]=1}))}));let c=Object.keys(l);if(!c||!c.length)return void console.log(`error: parts failed to read pin(s) from callsite for: ${a}`);c.forEach((n=>{const l=n.split(",");if(l.length!=i.argumentRoles.length)return void console.log(`error: parts mismatch between number of arguments at callsite (function name: ${a}) vs number of argument roles in part definition (part: ${t}).`);let c=[],u={};l.forEach(((e,t)=>{let n=i.argumentRoles[t];if(void 0!==n.partParameter&&(u[n.partParameter]=e),void 0!==n.pinInstantiationIdx){let t=n.pinInstantiationIdx,o=s(e);c[t]=o}})),o.push(r(e,t,c,u))}))}})),o.filter((e=>!!e))}computePartDimensions(t,n){let o=t.visual.pinLocations,r=t.pinDefinitions,s=t.numberOfPins;e.U.assert(o.length===s,`Mismatch between "numberOfPins" and length of "visual.pinLocations" for "${n}"`),e.U.assert(r.length===s,`Mismatch between "numberOfPins" and length of "pinDefinitions" for "${n}"`),e.U.assert(s>0,`Part "${n}" has no pins`);let a,l,c,u,d=o.map(((e,t)=>{return n={idx:t},o=e,s=r[t],i(i(n,o),s);var n,o,s})).filter((e=>"-Z"===e.orientation)),p=d.length>0,g=t.visual.pinDistance;if(p){let e=d[0],n=Math.ceil(e.x/g),o=Math.ceil(e.y/g);a=n*g-e.x,l=o*g-e.y,c=Math.ceil((a+t.visual.width)/g)+1,u=Math.ceil((l+t.visual.height)/g)+1}else c=Math.ceil(t.visual.width/g),u=Math.ceil(t.visual.height/g),a=c*g-t.visual.width,l=u*g-t.visual.height;return{xOffset:a,yOffset:l,rowCount:u,colCount:c}}allocColumns(t){let n=t.length;let o=e.visuals.BREADBOARD_MID_COLS-t.map((e=>e.colCount)).reduce(((e,t)=>e+t),0);o<=0&&console.log("Not enough breadboard space!");let r=Math.floor(o/(n-1+2)),i=o-r*(n-1),s=Math.floor(i/2),a=(Math.ceil(i/2),1+s);return t.map((e=>{let t=a;return a+=e.colCount+r,t}))}placeParts(t){const n=e.visuals.BREADBOARD_MID_ROWS+2;let o=this.allocColumns(t.map((e=>e.bbFit))),r=t.map((e=>{let t=n-e.bbFit.rowCount,o=Math.floor(t/2);return o>4&&(o=4),o<1&&(o=1),o}));return t.map(((e,t)=>{let n=r[t];return i({startColumnIdx:o[t],startRowIdx:n},e)}))}nextColor(){return(!this.availableWireColors||this.availableWireColors.length<=0)&&(this.availableWireColors=e.visuals.GPIO_WIRE_COLORS.map((e=>e))),this.availableWireColors.pop()}allocWireIRs(r){let s=[],l=r.pins.map(((i,l)=>{let c,u,d=i.target,p=r.startColumnIdx+i.bbFit.partRelativeColIdx,g=e.visuals.getColumnName(p),h=r.startRowIdx+i.bbFit.partRelativeRowIdx;if(h>=7&&(h-=2),a(i.def)){c={type:"breadboard",row:h<5?"j":"a",col:g,style:i.def.style}}else{c={type:"breadboard",row:e.visuals.getRowName(h),col:g,xOffset:i.bbFit.xOffset/r.def.visual.pinDistance,yOffset:i.bbFit.yOffset/r.def.visual.pinDistance,style:i.def.style}}return u="ground"===d?t:"threeVolt"===d?n:"fiveVolt"===d?o:"number"==typeof i.def.colorGroup?s[i.def.colorGroup]?s[i.def.colorGroup]:s[i.def.colorGroup]=this.nextColor():this.nextColor(),{start:c,end:d,color:u,pinIdx:l}}));return i(r,{wires:l})}allocLocation(t,n){if("ground"===t||"threeVolt"===t||"fiveVolt"==t){if("ground"===t&&this.powerUsage.singleGround){return{type:"dalboard",pin:this.getBoardGroundPin()}}if("threeVolt"===t&&this.powerUsage.singleThreeVolt){return{type:"dalboard",pin:this.getBoardThreeVoltPin()}}if("fiveVolt"===t&&this.powerUsage.singleFiveVolt){return{type:"dalboard",pin:this.getBoardFiveVoltPin()}}e.U.assert(!!n.referenceBBPin);let o=this.opts.getBBCoord(n.referenceBBPin),r=[this.availablePowerPins.top.ground[0]||this.availablePowerPins.top.threeVolt[0],this.availablePowerPins.bottom.ground[0]||this.availablePowerPins.bottom.threeVolt[0]].map((e=>this.opts.getBBCoord(e)));r[0]&&r[1]||console.debug(`No more available "${t}" locations!`);let i,s=0==e.visuals.findClosestCoordIdx(o,r);s?"ground"===t?i=this.availablePowerPins.top.ground:"threeVolt"===t?i=this.availablePowerPins.top.threeVolt:"fiveVolt"===t&&(i=this.availablePowerPins.top.fiveVolt):"ground"===t?i=this.availablePowerPins.bottom.ground:"threeVolt"===t?i=this.availablePowerPins.bottom.threeVolt:"fiveVolt"===t&&(i=this.availablePowerPins.bottom.fiveVolt);let a=i.map((e=>this.opts.getBBCoord(e))),l=e.visuals.findClosestCoordIdx(o,a),c=i[l];return s?(this.availablePowerPins.top.ground.splice(l,1),this.availablePowerPins.top.threeVolt.splice(l,1)):(this.availablePowerPins.bottom.ground.splice(l,1),this.availablePowerPins.bottom.threeVolt.splice(l,1)),c}if("breadboard"===t.type)return t;if("MOSI"===t||"MISO"===t||"SCK"===t){return this.opts.boardDef.spiPins||console.debug("No SPI pin mappings found!"),{type:"dalboard",pin:this.opts.boardDef.spiPins[t]}}if("SDA"===t||"SCL"===t){return this.opts.boardDef.i2cPins||console.debug("No I2C pin mappings found!"),{type:"dalboard",pin:this.opts.boardDef.i2cPins[t]}}{e.U.assert("string"==typeof t,"Unknown location type: "+t);let n=t,o=this.opts.boardDef.gpioPinMap[n]||n;return o?{type:"dalboard",pin:o}:void console.debug(`unknown pin location for ${n}`)}}getBoardGroundPin(){let e=this.opts.boardDef.groundPins&&this.opts.boardDef.groundPins[0]||null;return e||console.debug("No available ground pin on board!"),e}getBoardThreeVoltPin(){let e=this.opts.boardDef.threeVoltPins&&this.opts.boardDef.threeVoltPins[0]||null;return e||console.debug("No available 3.3V pin on board!"),e}getBoardFiveVoltPin(){let e=this.opts.boardDef.fiveVoltPins&&this.opts.boardDef.fiveVoltPins[0]||null;return e||console.debug("No available 5V pin on board!"),e}allocPowerWires(e){let r=this.getBoardGroundPin(),i=this.getBoardThreeVoltPin(),s=this.getBoardFiveVoltPin();const a={type:"breadboard",row:"-",col:"26"},l={type:"breadboard",row:"-",col:"1"},c={type:"breadboard",row:"-",col:"50"},u={type:"breadboard",row:"-",col:"25"};let d,p;this.opts.boardDef.attachPowerOnRight?(d=c,p=u):(d=a,p=l);let g=[],h=[],f=[];e.bottomGround&&e.topGround&&g.push({start:this.allocLocation("ground",{referenceBBPin:d}),end:this.allocLocation("ground",{referenceBBPin:p}),color:t}),e.topGround?g.push({start:this.allocLocation("ground",{referenceBBPin:d}),end:{type:"dalboard",pin:r},color:t}):e.bottomGround&&g.push({start:this.allocLocation("ground",{referenceBBPin:p}),end:{type:"dalboard",pin:r},color:t}),e.bottomThreeVolt&&e.bottomGround?h.push({start:this.allocLocation("threeVolt",{referenceBBPin:d}),end:this.allocLocation("threeVolt",{referenceBBPin:p}),color:n}):e.bottomFiveVolt&&e.bottomGround&&f.push({start:this.allocLocation("fiveVolt",{referenceBBPin:d}),end:this.allocLocation("fiveVolt",{referenceBBPin:p}),color:o}),e.topThreeVolt?h.push({start:this.allocLocation("threeVolt",{referenceBBPin:d}),end:{type:"dalboard",pin:i},color:n}):e.bottomThreeVolt&&h.push({start:this.allocLocation("threeVolt",{referenceBBPin:p}),end:{type:"dalboard",pin:i},color:o}),e.topFiveVolt&&!e.topThreeVolt?f.push({start:this.allocLocation("fiveVolt",{referenceBBPin:d}),end:{type:"dalboard",pin:s},color:n}):e.bottomFiveVolt&&!e.bottomThreeVolt&&f.push({start:this.allocLocation("fiveVolt",{referenceBBPin:p}),end:{type:"dalboard",pin:s},color:o});let _=[];g.length>0&&_.push({wireIndices:g.map(((e,t)=>t))});let m=g.length;return h.length>0&&_.push({wireIndices:h.map(((e,t)=>t+m))}),f.length>0&&_.push({wireIndices:h.map(((e,t)=>t+m+h.length))}),{wires:g.concat(h).concat(f),assembly:_}}allocWire(e){const t=[e.start,e.end],n=t.map((e=>"ground"===e||"threeVolt"===e||"fiveVolt"===e));let o=t.map(((e,t)=>n[t]?void 0:this.allocLocation(e,{})));if(o=o.map(((e,n)=>{if(e)return e;const r=o[1-n];return this.allocLocation(t[n],{referenceBBPin:r})})),o[0]&&o[1])return{start:o[0],end:o[1],color:e.color}}allocPart(t){let n=t.pins.filter((e=>a(e.def))).map((n=>{let o=t.startRowIdx+n.bbFit.partRelativeRowIdx;o>=7&&(o-=2);let r=e.visuals.getRowName(o),i=t.startColumnIdx+n.bbFit.partRelativeColIdx;return{type:"breadboard",row:r,col:e.visuals.getColumnName(i)}}));return{name:t.name,visual:t.def.visual,bbFit:t.bbFit,startColumnIdx:t.startColumnIdx,startRowIdx:t.startRowIdx,breadboardConnections:n,params:t.partParams,simulationBehavior:t.def.simulationBehavior}}allocAll(){let e=this.opts.partsList.map((e=>({name:e,def:this.opts.partDefs[e]}))).filter((e=>!!e.def));if(e.length>0){let t=e.map((e=>this.computePartDimensions(e.def,e.name))),n=[];e.forEach(((e,o)=>{let r=t[o],i=this.allocPartIRs(e.def,e.name,r);n=n.concat(i)}));const o=this.placeParts(n).map((e=>this.allocWireIRs(e))),i=o.map((e=>e.wires)).reduce(((e,t)=>e.concat(t)),[]).map((e=>function(e){let t=[e.start,e.end],n=t.map((e=>"ground"===e)),o=t.map((e=>"threeVolt"===e)),i=t.map((e=>"fiveVolt"===e)),s=t.map((e=>function(e){let t=!1;if("string"!=typeof e&&"breadboard"===e.type){let n=e.row;t=0<=["a","b","c","d","e"].indexOf(n)}return t}(e))),a=r(n),l=r(o),c=r(i),u=r(s);return{topGround:a&&!u,topThreeVolt:l&&!u,topFiveVolt:c&&!u,bottomGround:a&&u,bottomThreeVolt:l&&u,bottomFiveVolt:c&&u,singleGround:a,singleThreeVolt:l,singleFiveVolt:c}}(e)));this.powerUsage=function(e){const t=e.reduce(((e,t)=>({topGround:e.topGround||t.topGround,topThreeVolt:e.topThreeVolt||t.topThreeVolt,topFiveVolt:e.topFiveVolt||t.topFiveVolt,bottomGround:e.bottomGround||t.bottomGround,bottomThreeVolt:e.bottomThreeVolt||t.bottomThreeVolt,bottomFiveVolt:e.bottomFiveVolt||t.bottomFiveVolt,singleGround:t.singleGround?null===e.singleGround:e.singleGround,singleThreeVolt:t.singleThreeVolt?null===e.singleThreeVolt:e.singleThreeVolt,singleFiveVolt:t.singleFiveVolt?null===e.singleFiveVolt:e.singleFiveVolt})),{topGround:!1,topThreeVolt:!1,topFiveVolt:!1,bottomGround:!1,bottomThreeVolt:!1,bottomFiveVolt:!1,singleGround:null,singleThreeVolt:null,singleFiveVolt:null});return t.singleGround&&(t.topGround=t.bottomGround=!1),t.singleThreeVolt&&(t.topThreeVolt=t.bottomThreeVolt=!1),t.singleFiveVolt&&(t.topFiveVolt=t.bottomFiveVolt=!1),t}(i);const s=this.allocPowerWires(this.powerUsage),a=o.map(((e,t)=>{const n=this.allocPart(e),o=e.wires.map((e=>this.allocWire(e)));if(o.some((e=>!e)))return;const r=[];e.wires.forEach(((e,t)=>{r[e.pinIdx]=t}));return{part:n,wires:o,assembly:e.def.assembly.map((e=>({part:e.part,wireIndices:(e.pinIndices||[]).map((e=>r[e]))})))}})).filter((e=>!!e)),l=[s].concat(a).filter((e=>e.assembly&&e.assembly.length)),c=!l.some((e=>e.part&&e.part.breadboardConnections&&e.part.breadboardConnections.length>0||e.wires&&e.wires.some((e=>"breadboard"==e.end.type&&"croc"!=e.end.style||"breadboard"==e.start.type&&"croc"!=e.start.style))));return{partsAndWires:l,wires:[],parts:[],hideBreadboard:c}}return{partsAndWires:[],wires:[],parts:[]}}}e.allocateDefinitions=function(e){return new l(e).allocAll()}}(pxsim||(pxsim={})),function(e){!function(e){class t{constructor(e){this.seq=0,this.type=e}}e.Message=t;e.Response=class extends t{constructor(e,t){super("response"),this.request_seq=e.seq,this.command=e.command,t?(this.success=!1,this.message=t):this.success=!0}};class n extends t{constructor(e,t){super("event"),this.event=e,t&&(this.body=t)}}e.Event=n;e.Source=class{constructor(e,t,n=0,o,r){this.name=e,this.path=t,this.sourceReference=n,o&&(this.origin=o),r&&(this.adapterData=r)}};e.Scope=class{constructor(e,t,n=!1){this.name=e,this.variablesReference=t,this.expensive=n}};e.StackFrame=class{constructor(e,t,n,o=0,r=0){this.id=e,this.source=n,this.line=o,this.column=r,this.name=t}};e.Thread=class{constructor(e,t){this.id=e,this.name=t||"Thread #"+e}};e.Variable=class{constructor(e,t,n=0,o,r){this.name=e,this.value=t,this.variablesReference=n,"number"==typeof r&&(this.namedVariables=r),"number"==typeof o&&(this.indexedVariables=o)}};e.Breakpoint=class{constructor(e,t,n,o){this.verified=e;const r=this;"number"==typeof t&&(r.line=t),"number"==typeof n&&(r.column=n),o&&(r.source=o)}};e.Module=class{constructor(e,t){this.id=e,this.name=t}};e.CompletionItem=class{constructor(e,t,n=0){this.label=e,this.start=t,this.length=n}};e.StoppedEvent=class extends n{constructor(e,t,n=null){if(super("stopped"),this.body={reason:e,threadId:t},n){this.body.text=n}}};e.ContinuedEvent=class extends n{constructor(e,t){super("continued"),this.body={threadId:e},"boolean"==typeof t&&(this.body.allThreadsContinued=t)}};e.InitializedEvent=class extends n{constructor(){super("initialized")}};e.TerminatedEvent=class extends n{constructor(e){if(super("terminated"),"boolean"==typeof e){this.body={restart:e}}}};e.OutputEvent=class extends n{constructor(e,t="console",n){super("output"),this.body={category:t,output:e},void 0!==n&&(this.body.data=n)}};e.ThreadEvent=class extends n{constructor(e,t){super("thread"),this.body={reason:e,threadId:t}}};e.BreakpointEvent=class extends n{constructor(e,t){super("breakpoint"),this.body={reason:e,breakpoint:t}}};e.ModuleEvent=class extends n{constructor(e,t){super("module"),this.body={reason:e,module:t}}};class o{constructor(){this._pendingRequests={}}start(e){this._sequence=1,this.host=e,this.host.onData((e=>{if("request"===e.type)this.dispatchRequest(e);else if("response"===e.type){const t=e,n=this._pendingRequests[t.seq];n&&(delete this._pendingRequests[t.seq],n(t))}}))}stop(){this.host&&this.host.close()}sendEvent(e){this.send("event",e)}sendResponse(e){e.seq>0?console.error(`attempt to send more than one response for command ${e.command}`):this.send("response",e)}sendRequest(t,n,o,r){const i={command:t};if(n&&Object.keys(n).length>0&&(i.arguments=n),this.send("request",i),r){this._pendingRequests[i.seq]=r;const t=setTimeout((()=>{clearTimeout(t);const n=this._pendingRequests[i.seq];n&&(delete this._pendingRequests[i.seq],n(new e.Response(i,"timeout")))}),o)}}send(e,t){if(t.type=e,t.seq=this._sequence++,this.host){const e=JSON.stringify(t);this.host.send(e)}}dispatchRequest(e){}}e.ProtocolServer=o;class r extends o{constructor(){super(...arguments),this._debuggerLinesStartAt1=!1,this._debuggerColumnsStartAt1=!1,this._clientLinesStartAt1=!0,this._clientColumnsStartAt1=!0}shutdown(){}dispatchRequest(t){const n=new e.Response(t);try{if("initialize"===t.command){let e=t.arguments;if("boolean"==typeof e.linesStartAt1&&(this._clientLinesStartAt1=e.linesStartAt1),"boolean"==typeof e.columnsStartAt1&&(this._clientColumnsStartAt1=e.columnsStartAt1),"path"!==e.pathFormat)this.sendErrorResponse(n,2018,"debug adapter only supports native paths",null);else{const t=n;t.body={},this.initializeRequest(t,e)}}else"launch"===t.command?this.launchRequest(n,t.arguments):"attach"===t.command?this.attachRequest(n,t.arguments):"disconnect"===t.command?this.disconnectRequest(n,t.arguments):"setBreakpoints"===t.command?this.setBreakPointsRequest(n,t.arguments):"setFunctionBreakpoints"===t.command?this.setFunctionBreakPointsRequest(n,t.arguments):"setExceptionBreakpoints"===t.command?this.setExceptionBreakPointsRequest(n,t.arguments):"configurationDone"===t.command?this.configurationDoneRequest(n,t.arguments):"continue"===t.command?this.continueRequest(n,t.arguments):"next"===t.command?this.nextRequest(n,t.arguments):"stepIn"===t.command?this.stepInRequest(n,t.arguments):"stepOut"===t.command?this.stepOutRequest(n,t.arguments):"stepBack"===t.command?this.stepBackRequest(n,t.arguments):"restartFrame"===t.command?this.restartFrameRequest(n,t.arguments):"goto"===t.command?this.gotoRequest(n,t.arguments):"pause"===t.command?this.pauseRequest(n,t.arguments):"stackTrace"===t.command?this.stackTraceRequest(n,t.arguments):"scopes"===t.command?this.scopesRequest(n,t.arguments):"variables"===t.command?this.variablesRequest(n,t.arguments):"setVariable"===t.command?this.setVariableRequest(n,t.arguments):"source"===t.command?this.sourceRequest(n,t.arguments):"threads"===t.command?this.threadsRequest(n):"evaluate"===t.command?this.evaluateRequest(n,t.arguments):"stepInTargets"===t.command?this.stepInTargetsRequest(n,t.arguments):"gotoTargets"===t.command?this.gotoTargetsRequest(n,t.arguments):"completions"===t.command?this.completionsRequest(n,t.arguments):this.customRequest(t.command,n,t.arguments)}catch(e){this.sendErrorResponse(n,1104,"{_stack}",{_exception:e.message,_stack:e.stack})}}initializeRequest(e,t){e.body.supportsConditionalBreakpoints=!1,e.body.supportsHitConditionalBreakpoints=!1,e.body.supportsFunctionBreakpoints=!1,e.body.supportsConfigurationDoneRequest=!0,e.body.supportsEvaluateForHovers=!1,e.body.supportsStepBack=!1,e.body.supportsSetVariable=!1,e.body.supportsRestartFrame=!1,e.body.supportsStepInTargetsRequest=!1,e.body.supportsGotoTargetsRequest=!1,e.body.supportsCompletionsRequest=!1,this.sendResponse(e)}disconnectRequest(e,t){this.sendResponse(e),this.shutdown()}launchRequest(e,t){this.sendResponse(e)}attachRequest(e,t){this.sendResponse(e)}setBreakPointsRequest(e,t){this.sendResponse(e)}setFunctionBreakPointsRequest(e,t){this.sendResponse(e)}setExceptionBreakPointsRequest(e,t){this.sendResponse(e)}configurationDoneRequest(e,t){this.sendResponse(e)}continueRequest(e,t){this.sendResponse(e)}nextRequest(e,t){this.sendResponse(e)}stepInRequest(e,t){this.sendResponse(e)}stepOutRequest(e,t){this.sendResponse(e)}stepBackRequest(e,t){this.sendResponse(e)}restartFrameRequest(e,t){this.sendResponse(e)}gotoRequest(e,t){this.sendResponse(e)}pauseRequest(e,t){this.sendResponse(e)}sourceRequest(e,t){this.sendResponse(e)}threadsRequest(e){this.sendResponse(e)}stackTraceRequest(e,t){this.sendResponse(e)}scopesRequest(e,t){this.sendResponse(e)}variablesRequest(e,t){this.sendResponse(e)}setVariableRequest(e,t){this.sendResponse(e)}evaluateRequest(e,t){this.sendResponse(e)}stepInTargetsRequest(e,t){this.sendResponse(e)}gotoTargetsRequest(e,t){this.sendResponse(e)}completionsRequest(e,t){this.sendResponse(e)}customRequest(e,t,n){this.sendErrorResponse(t,1014,"unrecognized request",null)}sendErrorResponse(e,t,n,o){let i;"number"==typeof t?(i={id:t,format:n},o&&(i.variables=o),i.showUser=!0):i=t,e.success=!1,r.formatPII(i.format,!0,i.variables),e.body||(e.body={}),e.body.error=i,this.sendResponse(e)}convertClientLineToDebugger(e){return this._debuggerLinesStartAt1?this._clientLinesStartAt1?e:e+1:this._clientLinesStartAt1?e-1:e}convertDebuggerLineToClient(e){return this._debuggerLinesStartAt1?this._clientLinesStartAt1?e:e-1:this._clientLinesStartAt1?e+1:e}convertClientColumnToDebugger(e){return this._debuggerColumnsStartAt1?this._clientColumnsStartAt1?e:e+1:this._clientColumnsStartAt1?e-1:e}convertDebuggerColumnToClient(e){return this._debuggerColumnsStartAt1?this._clientColumnsStartAt1?e:e-1:this._clientColumnsStartAt1?e+1:e}convertClientPathToDebugger(e){return this._clientPathsAreURIs!=this._debuggerPathsAreURIs?this._clientPathsAreURIs?r.uri2path(e):r.path2uri(e):e}convertDebuggerPathToClient(e){return this._debuggerPathsAreURIs!=this._clientPathsAreURIs?this._debuggerPathsAreURIs?r.uri2path(e):r.path2uri(e):e}static path2uri(e){let t=e.replace(/\\/g,"/");return"/"!==t[0]&&(t="/"+t),encodeURI("file://"+t)}static uri2path(e){return e}static formatPII(e,t,n){return e.replace(r._formatPIIRegexp,(function(e,o){return t&&o.length>0&&"_"!==o[0]?e:n[o]&&n.hasOwnProperty(o)?n[o]:e}))}}r._formatPIIRegexp=/{([^}]+)}/g,e.DebugSession=r}(e.protocol||(e.protocol={}))}(pxsim||(pxsim={})),function(e){!function(e){e.injectPolyphils=function(){String.prototype.startsWith||Object.defineProperty(String.prototype,"startsWith",{value:function(e,t){return void 0!==e&&null!=e&&(t=!t||t<0?0:+t,this.substring(t,t+e.length)===e)}}),Array.prototype.fill||Object.defineProperty(Array.prototype,"fill",{writable:!0,enumerable:!0,value:function(e){if(null==this)throw new TypeError("this is null or not defined");let t=Object(this),n=t.length>>>0,o=arguments[1],r=o>>0,i=r<0?Math.max(n+r,0):Math.min(r,n),s=arguments[2],a=void 0===s?n:s>>0,l=a<0?Math.max(n+a,0):Math.min(a,n);for(;i<l;)t[i]=e,i++;return t}}),Array.prototype.find||Object.defineProperty(Array.prototype,"find",{writable:!0,enumerable:!0,value:function(e){if(null==this)throw new TypeError('"this" is null or not defined');let t=Object(this);const n=t.length>>>0;if("function"!=typeof e)throw new TypeError("predicate must be a function");const o=arguments[1];let r=0;for(;r<n;){const n=t[r];if(e.call(o,n,r,t))return n;r++}}}),Uint8Array.prototype.slice||Object.defineProperty(Uint8Array.prototype,"slice",{value:Array.prototype.slice,writable:!0,enumerable:!0}),Uint16Array.prototype.slice||Object.defineProperty(Uint16Array.prototype,"slice",{value:Array.prototype.slice,writable:!0,enumerable:!0}),Uint32Array.prototype.slice||Object.defineProperty(Uint32Array.prototype,"slice",{value:Array.prototype.slice,writable:!0,enumerable:!0}),Uint8Array.prototype.fill||Object.defineProperty(Uint8Array.prototype,"fill",{value:Array.prototype.fill,writable:!0,enumerable:!0}),Uint16Array.prototype.fill||Object.defineProperty(Uint16Array.prototype,"fill",{value:Array.prototype.fill,writable:!0,enumerable:!0}),Uint32Array.prototype.fill||Object.defineProperty(Uint32Array.prototype,"fill",{value:Array.prototype.fill,writable:!0,enumerable:!0}),Uint8Array.prototype.some||Object.defineProperty(Uint8Array.prototype,"some",{value:Array.prototype.some,writable:!0,enumerable:!0}),Uint16Array.prototype.some||Object.defineProperty(Uint16Array.prototype,"some",{value:Array.prototype.some,writable:!0,enumerable:!0}),Uint32Array.prototype.some||Object.defineProperty(Uint32Array.prototype,"some",{value:Array.prototype.some,writable:!0,enumerable:!0}),Uint8Array.prototype.reverse||Object.defineProperty(Uint8Array.prototype,"reverse",{value:Array.prototype.reverse,writable:!0,enumerable:!0}),Uint16Array.prototype.reverse||Object.defineProperty(Uint16Array.prototype,"reverse",{value:Array.prototype.reverse,writable:!0,enumerable:!0}),Uint32Array.prototype.reverse||Object.defineProperty(Uint32Array.prototype,"reverse",{value:Array.prototype.reverse,writable:!0,enumerable:!0}),Math.imul||(Math.imul=function(e,t){const n=65535&e,o=65535&t;return n*o+((e>>>16&65535)*o+n*(t>>>16&65535)<<16>>>0)|0}),"function"!=typeof Object.assign&&Object.defineProperty(Object,"assign",{value:function(e,t){if(null==e)throw new TypeError("Cannot convert undefined or null to object");let n=Object(e);for(let e=1;e<arguments.length;e++){let t=arguments[e];if(null!=t)for(let e in t)Object.prototype.hasOwnProperty.call(t,e)&&(n[e]=t[e])}return n},writable:!0,configurable:!0}),Promise.prototype.finally||(Promise.prototype.finally=Promise.prototype.finally||{finally(e){const t=t=>Promise.resolve(e()).then(t);return this.then((e=>t((()=>e))),(e=>t((()=>Promise.reject(e)))))}}.finally)};function t(e){e=e.replace(/\\/g,"/");const t=[];return e.split("/").forEach((e=>{".."===e&&t.length?t.pop():e&&"."!==e&&t.push(e)})),t}e.Lazy=class{constructor(e){this._func=e,this._evaluated=!1}get value(){return this._evaluated||(this._value=this._func(),this._evaluated=!0),this._value}},e.getNormalizedParts=t,e.normalizePath=function(e){return t(e).join("/")},e.relativePath=function(e,n){const o=t(e),r=t(n);let i=0;for(;o[i]===r[i]&&(i++,i!==o.length&&i!==r.length););const s=o.slice(i),a=r.slice(i);for(let e=0;e<s.length;e++)a.unshift("..");return a.join("/")},e.pathJoin=function(...e){let t="";return e.forEach((e=>{e.replace(/\\/g,"/"),e.lastIndexOf("/")===e.length-1&&(e=e.slice(0,e.length-1)),t+="/"+e})),t},e.toArray=function(e){if(Array.isArray(e))return e;let t=[];for(let n=0;n<e.length;++n)t.push(e[n]);return t}}(e.util||(e.util={}))}(pxsim||(pxsim={})),function(e){e.getWarningMessage=function(t){let n={type:"debugger",subtype:"warning",breakpointIds:[],message:t},o=e.runtime.currFrame;for(;null!=o;)n.breakpointIds.push(o.lastBrkId),o=o.parent;return n};function t(t,n){switch(typeof t){case"string":case"number":case"boolean":return t;case"function":return{text:"(function)",type:"function"};case"undefined":return null;case"object":if(!t)return null;if(t instanceof e.RefObject){n&&(n[t.id]=t);let o=e.RefObject.toDebugString(t),r=o.startsWith("[")?"array":o;return{id:t.id,preview:o,hasFields:null!==t.fields||o.startsWith("["),type:r}}return t._width&&t._height?{text:t._width+"x"+t._height,type:"image"}:{text:"(object)",type:"object"};default:throw new Error}}function n(e,n,r,i){return function(e,r){const s={};for(let o of Object.keys(e))/^__/.test(o)||!/___\d+$/.test(o)||i&&-1===i.indexOf(o)||(s[o]=t(e[o],n));if(e.fields&&r)for(let i of r)i=i.substring(i.lastIndexOf(".")+1),s[i]=t(o(e.vtable.iface[i],e),n);if(e.fields)for(let o of Object.keys(e.fields).filter((e=>!e.startsWith("_"))))s[o]=t(e.fields[o],n);else Array.isArray(e.data)&&e.data.forEach(((e,o)=>{s[o]=t(e,n)}));return s}(e,r)}function o(e,t){let n={pc:0,arg0:t,fn:e,parent:{}};for(;n.fn;)n=n.fn(n);return n.retval}function r(e,o){let r=e.fn?e.fn.info:null;if(r){let i={thisParam:t(e.argL,o),params:[]};if(r.argumentNames){const n=r.argumentNames;i.params=n.map(((n,r)=>({name:n,value:t(e["arg"+r],o)})))}return{locals:n(e,o),funcInfo:r,breakpointId:e.lastBrkId,callLocationId:e.callLocIdx,arguments:i}}}e.BreakpointMap=class{constructor(e){this.fileMap={},this.idMap={},e.forEach((e=>{const[t,n]=e;this.fileMap[n.source.path]||(this.fileMap[n.source.path]=[]),this.fileMap[n.source.path].push(e),this.idMap[t]=n}));for(const e in this.fileMap){const t=this.fileMap[e];this.fileMap[e]=t.sort((([,e],[,t])=>e.line===t.line?t.endLine===e.endLine?e.column-t.column:t.endLine-e.endLine:e.line-t.line))}}getById(e){return this.idMap[e]}verifyBreakpoint(e,t){const n=this.fileMap[e];let o;if(n)for(const[e,r]of n)r.line<=t.line&&r.endLine>=t.line&&(o=[e,r]);return o?(o[1].verified=!0,o):[-1,{verified:!1}]}},e.dumpHeap=n,e.injectEnvironmentGlobals=function(n,o){const r=e.runtime.environmentGlobals;if(!Object.keys(r).length)return;const i=n.environmentGlobals={};Object.keys(r).forEach((n=>i[n]=t(e.runtime.environmentGlobals[n],o)))},e.getBreakpointMsg=function(t,o,i){const s={},a={type:"debugger",subtype:"breakpoint",breakpointId:o,globals:n(e.runtime.globals,s,void 0,i),stackframes:[]};for(;null!=t;){let e=r(t,s);e&&a.stackframes.push(e),t=t.parent}return{msg:a,heap:s}};class i extends e.protocol.DebugSession{constructor(t){super();let n={onDebuggerBreakpoint:e=>this.onDebuggerBreakpoint(e),onDebuggerWarning:e=>this.onDebuggerWarning(e),onDebuggerResume:()=>this.onDebuggerResume(),onStateChanged:e=>this.onStateChanged(e)};this.driver=new e.SimulatorDriver(t,n)}runCode(t,n,o,r,i){this.breakpoints=r,this.projectDir&&this.fixBreakpoints(),this.sendEvent(new e.protocol.InitializedEvent),this.driver.run(t,{parts:n,fnArgs:o,boardDefinition:i})}stopSimulator(e=!1){this.driver.stop(e)}initializeRequest(e,t){e.body.supportsConditionalBreakpoints=!1,e.body.supportsHitConditionalBreakpoints=!1,e.body.supportsFunctionBreakpoints=!1,e.body.supportsEvaluateForHovers=!1,e.body.supportsStepBack=!1,e.body.supportsSetVariable=!1,e.body.supportsRestartFrame=!1,e.body.supportsStepInTargetsRequest=!1,e.body.supportsGotoTargetsRequest=!1,e.body.supportsCompletionsRequest=!1,e.body.supportsConfigurationDoneRequest=!0,this.sendResponse(e)}disconnectRequest(e,t){this.sendResponse(e),this.shutdown()}launchRequest(t,n){this.projectDir||(this.projectDir=e.util.normalizePath(n.projectDir),this.breakpoints&&this.fixBreakpoints()),this.sendResponse(t)}setBreakPointsRequest(t,n){t.body={breakpoints:[]};const o=[];n.breakpoints.forEach((r=>{if(this.breakpoints){const[i,s]=this.breakpoints.verifyBreakpoint(e.util.relativePath(this.projectDir,n.source.path),r);t.body.breakpoints.push(s),s.verified&&o.push(i)}else t.body.breakpoints.push({verified:!1})})),this.driver.setBreakpoints(o),this.sendResponse(t)}continueRequest(t,n){this.driver.resume(e.SimulatorDebuggerCommand.Resume),this.sendResponse(t)}nextRequest(t,n){this.driver.resume(e.SimulatorDebuggerCommand.StepOver),this.sendResponse(t)}stepInRequest(t,n){this.driver.resume(e.SimulatorDebuggerCommand.StepInto),this.sendResponse(t)}stepOutRequest(t,n){this.driver.resume(e.SimulatorDebuggerCommand.StepOut),this.sendResponse(t)}pauseRequest(t,n){this.driver.resume(e.SimulatorDebuggerCommand.Pause),this.sendResponse(t)}threadsRequest(e){e.body={threads:[{id:i.THREAD_ID,name:"main"}]},this.sendResponse(e)}stackTraceRequest(e,t){if(this.lastBreak){const t=this.state.getFrames();e.body={stackFrames:t}}this.sendResponse(e)}scopesRequest(e,t){this.state&&(e.body={scopes:this.state.getScopes(t.frameId)}),this.sendResponse(e)}variablesRequest(e,t){this.state&&(e.body={variables:this.state.getVariables(t.variablesReference)}),this.sendResponse(e)}onDebuggerBreakpoint(t){if(this.lastBreak=t,this.state=new s(this.lastBreak,this.breakpoints,this.projectDir),t.exceptionMessage){const n=t.exceptionMessage.replace(/___\d+/g,"");this.sendEvent(new e.protocol.StoppedEvent("exception",i.THREAD_ID,n))}else this.sendEvent(new e.protocol.StoppedEvent("breakpoint",i.THREAD_ID))}onDebuggerWarning(e){}onDebuggerResume(){this.sendEvent(new e.protocol.ContinuedEvent(i.THREAD_ID,!0))}onStateChanged(t){switch(t){case e.SimulatorState.Paused:break;case e.SimulatorState.Running:this.sendEvent(new e.protocol.ContinuedEvent(i.THREAD_ID,!0));break;case e.SimulatorState.Stopped:this.sendEvent(new e.protocol.TerminatedEvent)}}fixBreakpoints(){for(const t in this.breakpoints.idMap){const n=this.breakpoints.idMap[t];n.source.path=e.util.pathJoin(this.projectDir,n.source.path),n.line=this.convertDebuggerLineToClient(n.line),n.endLine=this.convertDebuggerLineToClient(n.endLine),n.column=this.convertDebuggerColumnToClient(n.column),n.endColumn=this.convertDebuggerColumnToClient(n.endColumn)}}}i.THREAD_ID=1,e.SimDebugSession=i;class s{constructor(e,t,n){this._message=e,this._map=t,this._dir=n,this._currentId=1,this._frames={},this._vars={};const o=this.nextId();this._vars[o]=this.getVariableValues(this._message.globals),this._globalScope={name:"Globals",variablesReference:o,expensive:!1}}getFrames(){return this._message.stackframes.map(((e,t)=>{const n=this._map.getById(e.breakpointId);if(n)return this._frames[e.breakpointId]=e,{id:e.breakpointId,name:e.funcInfo?e.funcInfo.functionName:0===t?"main":"anonymous",line:n.line,column:n.column,endLine:n.endLine,endColumn:n.endLine,source:n.source}})).filter((e=>!!e))}getScopes(e){const t=this._frames[e];if(t){const e=this.nextId();return this._vars[e]=this.getVariableValues(t.locals),[{name:"Locals",variablesReference:e,expensive:!1},this._globalScope]}return[this._globalScope]}getVariables(e){const t=this._vars[e];return t&&t.value||[]}getVariableValues(t){return new e.util.Lazy((()=>{const e=[];for(const n in t){const o=t[n];let r,i=0;null===o?r="null":void 0===o?r="undefined":"object"==typeof o?(r="(object)",i=this.nextId(),this._vars[i]=this.getVariableValues(o)):r=o.toString();const s=n.substr(0,n.lastIndexOf("___"));e.push({name:s,value:r,variablesReference:i})}return e}))}nextId(){return this._currentId++}}}(pxsim||(pxsim={})),function(e){function t(e=0){function t(){try{window.print()}catch(e){}}e?setTimeout(t,e):t()}let n;function o(e,t){r({type:"pxtsim",action:"event",tick:e,data:t})}function r(e){"undefined"!=typeof window&&window.parent&&window.parent!==window&&window.parent.postMessage(e,"*")}function i(){setInterval((()=>{e.Runtime.postMessage({type:"simulator",command:"reload"})}),3e3)}e.print=t,function(n){function r(n){n.origin;let r=n.data||{},i=r.type;if(i)switch(i){case"run":l(r);break;case"instructions":e.instructions.renderInstructions(r);break;case"stop":a();break;case"mute":c(r.mute);break;case"stopsound":e.AudioContextManager.stopAll();break;case"print":t();break;case"recorder":!function(e){if(!s)return;switch(e.action){case"start":s.startRecording(e.width);break;case"stop":s.stopRecording()}}(r);break;case"screenshot":e.Runtime.postScreenshotAsync(r);break;case"custom":e.handleCustomMessage&&e.handleCustomMessage(r);break;case"pxteditor":break;case"debugger":s&&s.handleDebuggerMsg(r);break;case"simulator":let n=r;switch(n.command){case"focus":o("simulator.focus",{timestamp:n.timestamp});break;case"blur":o("simulator.blur",{timestamp:n.timestamp})}default:!function(e){if(!s||s.dead)return;s.board.receiveMessage(e)}(r)}}let s;function a(){s&&(s.kill(),s.board&&s.board.kill())}function l(t){a(),t.mute&&c(t.mute),t.localizedStrings&&e.localization.setLocalizedStrings(t.localizedStrings);const n=new e.Runtime(t);s=n,n.board.initAsync(t).then((()=>{n===s&&n.run((t=>{e.dumpLivePointers(),e.Runtime.postMessage({type:"toplevelcodefinished"})}))}))}function c(t){e.AudioContextManager.mute(t)}n.start=function(){window.addEventListener("message",r,!1),n.frameid=window.location.hash.slice(1),function(){if("serviceWorker"in navigator&&-1!==window.location.href.indexOf("---simulator")&&!e.U.isLocalHost()){const e=window.location.pathname,t=e.substring(1,e.indexOf("---"));navigator.serviceWorker.controller&&navigator.serviceWorker.addEventListener("message",(e=>{const n=e.data;n&&"serviceworker"===n.type&&"activated"===n.state&&n.ref===t&&i()}));const n=window.location.href.replace(/---simulator.*$/,"---simserviceworker");navigator.serviceWorker.register(n).then((function(e){console.log("Simulator ServiceWorker registration successful with scope: ",e.scope)}),(function(e){console.log("Simulator ServiceWorker registration failed: ",e)}))}}(),e.Runtime.postMessage({type:"ready",frameid:n.frameid})},n.stop=a,n.run=l}(n=e.Embed||(e.Embed={})),e.tickEvent=o,e.reportError=function(e,t,n){r({type:"pxtsim",action:"event",tick:"error",category:e,message:t,data:n})},e.reload=i}(pxsim||(pxsim={})),pxsim.util.injectPolyphils(),"undefined"!=typeof window&&window.addEventListener("load",(function(e){pxsim.Embed.start()})),function(e){!function(t){const n=e=>`${e}x`,o=.95,[r,i]=[816*o,1056*o],s=r-86.4,a=i-86.4,[l,c]=[1,1],u=24,d=s/c-48*c,p=`\n .instr-panel {\n margin: 20px;\n padding: 24px;\n border-width: 4px;\n border-color: gray;\n border-style: solid;\n border-radius: 20px;\n display: inline-block;\n width: ${d}px;\n height: ${a/l-48*l}px;\n position: relative;\n overflow: hidden;\n page-break-inside: avoid;\n }\n .board-svg {\n margin: 0 auto;\n display: block;\n position: absolute;\n bottom: 24px;\n left: ${(d-465)/2+u}px;\n }\n .panel-num-outer {\n position: absolute;\n left: -4px;\n top: -4px;\n width: 120px;\n height: 120px;\n border-width: 4px;\n border-style: solid;\n border-color: gray;\n border-radius: 20px 0 20px 0;\n }\n .panel-num {\n margin: 10px 0;\n text-align: center;\n font-size: 80px;\n }\n .cmp-div {\n display: inline-block;\n }\n .reqs-div {\n margin-left: 144px;\n margin-top: 5px;\n }\n .partslist-wire,\n .partslist-cmp {\n margin: 10px;\n }\n .partslist-wire {\n display: inline-block;\n }\n `;function g(t,n){let o=document.createElementNS("http://www.w3.org/2000/svg","svg"),r={l:0,t:0,w:0,h:0},i=document.createElementNS("http://www.w3.org/2000/svg","svg");o.appendChild(i),i.appendChild(t.el);let s={viewBox:`${t.x} ${t.y} ${t.w} ${t.h}`,preserveAspectRatio:"xMidYMid"};r.w=t.w,r.h=t.h;let a=e=>{r.h*=e,r.w*=e,s.width=r.w,s.height=r.h};n.cmpScale&&a(n.cmpScale),n.cmpWidth&&n.cmpWidth<r.w?a(n.cmpWidth/r.w):n.cmpHeight&&n.cmpHeight<r.h&&a(n.cmpHeight/r.h),e.svg.hydrate(i,s);let l=r.l,c=r.t,u=r.w,d=r.h,p=e=>{if(e<r.l){let t=r.l-e;r.l=e,r.w+=t}},g=e=>{let t=r.l+r.w;if(t<e){let n=e-t;r.w+=n}},h=e=>{if(e<r.t){let t=r.t-e;r.t=e,r.h+=t}},f=e=>{let t=r.t+r.h;if(t<e){let n=e-t;r.h+=n}},[_,m]=[-.3,.3];const y=[1.4,1];if(n&&n.top){let t=n.topSize,r=t/y[0],i=t/y[1],[s,a]=[l+u/2,c-3-i/2],d=e.visuals.mkTxt(s,a,t,0,n.top,_,m);e.U.addClass(d,"cmp-lbl"),o.appendChild(d);let f=r*n.top.length;h(a-i/2),p(s-f/2),g(s+f/2)}if(n&&n.bot){let t=n.botSize,r=t/y[0],i=t/y[1],[s,a]=[l+u/2,c+d+3+i/2],h=e.visuals.mkTxt(s,a,t,0,n.bot,_,m);e.U.addClass(h,"cmp-lbl"),o.appendChild(h);let k=r*n.bot.length;f(a+i/2),p(s-k/2),g(s+k/2)}if(n&&n.right){let t=n.rightSize,r=t/y[1],i=t/y[0]*n.right.length,[s,a]=[l+u+5+i/2,c+d/2],p=e.visuals.mkTxt(s,a,t,0,n.right,_,m);e.U.addClass(p,"cmp-lbl"),o.appendChild(p),h(a-r/2),g(s+i/2),f(a+r/2)}if(n&&n.left){let t=n.leftSize,r=t/y[1],i=t/y[0]*n.left.length,[s,a]=[l-5-i/2,c+d/2],u=e.visuals.mkTxt(s,a,t,0,n.left,_,m);e.U.addClass(u,"cmp-lbl"),o.appendChild(u),h(a-r/2),p(s-i/2),f(a+r/2)}let k={viewBox:`${r.l} ${r.t} ${r.w} ${r.h}`,width:1.7*r.w,height:1.7*r.h,preserveAspectRatio:"xMidYMid"};e.svg.hydrate(o,k);let b=document.createElement("div");return b.appendChild(o),b}function h(t,n){let o,r=e.runtime.board;if("wire"==t)o=e.visuals.mkWirePart([0,0],n.wireClr||"red",n.crocClips);else{let n=t;if("string"==typeof n.builtIn){o=(0,r.builtinPartVisuals[n.builtIn])([0,0])}else o=e.visuals.mkGenericPartSVG(n)}return g(o,n)}function f(t,n,o=!1){const r={state:e.runtime.board,boardDef:t.boardDef,forceBreadboardLayout:!0,forceBreadboardRender:t.allAlloc.requiresBreadboard,partDefs:t.cmpDefs,maxWidth:`${n}px`,fnArgs:t.fnArgs,wireframe:o,partsList:[]};let i=new e.visuals.BoardHost(e.visuals.mkBoardView({visual:r.boardDef.visual,boardDef:r.boardDef,wireframe:r.wireframe}),r),s=i.getView();return e.U.addClass(s,"board-svg"),i}function _(){let t=document.createElement("div");return e.U.addClass(t,"instr-panel"),t}function m(t){let o=_();var r;let i=g((r=t.boardDef,e.visuals.mkBoardView({visual:r.visual,boardDef:r}).getView()),{left:n(1),leftSize:30,cmpScale:.17});o.appendChild(i);let s=g(new e.visuals.Breadboard({}).getSVGAndSize(),{left:n(1),leftSize:30,cmpScale:.25});return o.appendChild(s),t.allCmps.forEach((t=>{let r=1;"buttonpair"===t.visual.builtIn&&(r=2);let i=h(t.visual,{left:n(r),leftSize:30,cmpScale:.3});e.U.addClass(i,"partslist-cmp"),o.appendChild(i)})),t.allWireColors.forEach((r=>{let i=t.colorToWires[r].length,s=t.boardDef.pinStyles[r]||"female",a=h("wire",{left:n(i),leftSize:20,wireClr:r,cmpScale:.23,crocClips:"croc"==s});e.U.addClass(a,"partslist-wire"),o.appendChild(a)})),o}function y(t,n){let o=_(),r=f(n,465,!0);!function(t,n,o){let r=t.getView();n>0&&e.U.addClass(r,"grayed");for(let r=0;r<=n;r++){let i=o.stepToCmps[r];i&&i.forEach((o=>{let i=t.addPart(o);r===n&&(o.breadboardConnections.forEach((e=>t.highlightBreadboardPin(e))),e.U.addClass(i.element,"notgrayed"))}));let s=o.stepToWires[r];s&&s.forEach((e=>{let o=t.addWire(e);o&&r===n&&("breadboard"==e.start.type?t.highlightBreadboardPin(e.start):t.highlightBoardPin(e.start.pin),"breadboard"==e.end.type?t.highlightBreadboardPin(e.end):t.highlightBoardPin(e.end.pin),t.highlightWire(o))}))}}(r,t,n),o.appendChild(r.getView());let i=document.createElement("div");e.U.addClass(i,"panel-num-outer"),e.U.addClass(i,"noselect"),o.appendChild(i);let s=document.createElement("div");e.U.addClass(s,"panel-num"),s.textContent=t+1+"",i.appendChild(s);let a=document.createElement("div");e.U.addClass(a,"reqs-div"),o.appendChild(a);let l=n.stepToWires[t]||[],c=e=>{if("breadboard"===e.type){let{row:t,col:n}=e;return`(${t},${n})`}return e.pin};return l.forEach((t=>{let o=!1;"dalboard"==t.end.type&&(o="croc"==n.boardDef.pinStyles[t.end.pin]);let r=h("wire",{top:c(t.end),topSize:10,bot:c(t.start),botSize:10,wireClr:t.color,cmpHeight:40,crocClips:o});e.U.addClass(r,"cmp-div"),a.appendChild(r)})),(n.stepToCmps[t]||[]).forEach((t=>{let n;n="buttonpair"===t.visual.builtIn?[t.breadboardConnections[0],t.breadboardConnections[2]]:[t.breadboardConnections[0]],n.forEach(((n,o)=>{let r;if(n){let{row:e,col:t}=n;r=`(${e},${t})`}else r="";let i=1.5;"buttonpair"===t.visual.builtIn&&(i*=.5);let s=h(t.visual,{top:r,topSize:10,cmpHeight:50,cmpScale:i});e.U.addClass(s,"cmp-div"),a.appendChild(s)}))})),o}function k(t,n){n.boardDef.pinStyles||(n.boardDef.pinStyles={}),n.configData&&e.setConfigData(n.configData.cfg,n.configData.cfgKey);const o={type:"run",code:"",boardDefinition:n.boardDef,partDefinitions:n.partDefinitions};e.runtime=new e.Runtime(o),e.runtime.board=null,e.initCurrentRuntime(o);let r=document.createElement("style");r.textContent+=p,document.head.appendChild(r);const i=n.partDefinitions;let s=new e.visuals.Breadboard({}),a=function(t){let n=e.allocateDefinitions(t),o=[],r=[],i=1;n.partsAndWires.forEach((e=>{let t=e.part,n=e.wires;e.assembly.forEach(((e,s)=>{e.part&&t&&(r[i+s]=[t]),e.wireIndices&&e.wireIndices.length>0&&n&&(o[i+s]=e.wireIndices.map((e=>n[e])))})),i+=e.assembly.length}));let s=i-1,a=n.partsAndWires.map((e=>e.part)).filter((e=>!!e)),l=n.partsAndWires.map((e=>e.wires||[])).reduce(((e,t)=>e.concat(t)),[]),c={},u=[];return l.forEach((e=>{c[e.color]||(c[e.color]=[],u.push(e.color)),c[e.color].push(e)})),{boardDef:t.boardDef,cmpDefs:t.partDefs,fnArgs:t.fnArgs,allAlloc:n,stepToWires:o,stepToCmps:r,allWires:l,allCmps:a,lastStep:s,colorToWires:c,allWireColors:u}}({boardDef:n.boardDef,partDefs:i,partsList:n.parts,fnArgs:n.fnArgs,getBBCoord:s.getCoord.bind(s)});a.allAlloc.requiresBreadboard=!0;!function(e){let t=document.getElementById("front-panel"),n=f(e,400,!1);n.addAll(e.allAlloc),t.appendChild(n.getView())}(a);let l=m(a);t.appendChild(l);for(let e=0;e<=a.lastStep;e++){let n=y(e,a);t.appendChild(n)}n.print&&e.print(2e3)}t.renderParts=k,t.renderInstructions=function(e){document.getElementById("proj-title").innerText=e.options.name||"",k(document.body,e.options)}}(e.instructions||(e.instructions={}))}(pxsim||(pxsim={})),function(e){function t(e,t="sim: check failed"){if(!e)throw new Error(t)}e.quiet=!1,e.check=t,e.title="";let n,o,r,i,s,a={},l={};e.getConfig=function(e){return l.hasOwnProperty(e+"")?l[e+""]:null},e.getConfigKey=function(e){return a.hasOwnProperty(e)?a[e]:null},e.getAllConfigKeys=function(){return Object.keys(a)},e.setConfigKey=function(e,t){a[e]=t},e.setConfig=function(e,t){l[e]=t},e.setConfigData=function(e,t){l=e,a=t},e.getConfigData=function(){return{cfg:l,cfgKey:a}},e.setTitle=function(t){e.title=t};class c{constructor(){e.runtime?this.id=e.runtime.registerLiveObject(this):this.id=0}destroy(){}scan(t){throw e.U.userError("scan not implemented")}gcKey(){throw e.U.userError("gcKey not implemented")}gcSize(){throw e.U.userError("gcSize not implemented")}gcIsStatic(){return!1}print(){e.runtime&&e.runtime.refCountingDebug&&console.log(`RefObject id:${this.id}`)}toDebugString(){return"(object)"}static toAny(e){return e&&e.toAny?e.toAny():e}static toDebugString(e){return null===e?"null":void 0===e?"undefined;":e.vtable&&e.vtable.name?e.vtable.name:e.toDebugString?e.toDebugString():"string"==typeof e?JSON.stringify(e):e.toString()}}e.RefObject=c;class u{constructor(e,t,n){this.func=e,this.caps=t,this.args=n}}e.FnWrapper=u;class d extends c{constructor(){super(...arguments),this.fields={}}scan(e){for(let t of Object.keys(this.fields))e(t,this.fields[t])}gcKey(){return this.vtable.name}gcSize(){return this.vtable.numFields+1}destroy(){this.fields=null,this.vtable=null}print(){e.runtime&&e.runtime.refCountingDebug&&console.log(`RefRecord id:${this.id} (${this.vtable.name})`)}}e.RefRecord=d;class p extends c{constructor(){super(...arguments),this.fields=[]}scan(e){for(let t=0;t<this.fields.length;++t)e("_cap"+t,this.fields[t])}gcKey(){return e.functionName(this.func)}gcSize(){return this.fields.length+3}isRef(e){return t(0<=e&&e<this.fields.length),e<this.len}ldclo(e){return t(0<=(e>>=2)&&e<this.fields.length),this.fields[e]}destroy(){this.fields=null,this.func=null}print(){e.runtime&&e.runtime.refCountingDebug&&console.log(`RefAction id:${this.id} len:${this.fields.length}`)}}e.RefAction=p,function(t){t.seedAddRandom=function(e){},t.mkAction=function(e,t){let n=new p;n.len=e,n.func=t;for(let t=0;t<e;++t)n.fields.push(null);return n},t.runAction=function(t,n){let o=e.getResume();o(t instanceof p?new u(t.func,t.fields,n):new u(t,null,n))};let n={};t.dumpPerfCounters=function(){if(!e.runtime||!e.runtime.perfCounters)return;let t="calls,us,name\n";for(let n of e.runtime.perfCounters){n.lastFew.sort();const e=n.lastFew[n.lastFew.length>>1];t+=`${n.numstops},${n.value},${n.name},${e}\n`}!function(e){let t="";const o=(e,n)=>{t+=e.length>=n?e:(" "+e).slice(-n)},r=e=>o(""+Math.round(e),6),i=(e,n)=>{o(Math.round(n)+"",8),t+=" /",r(e),t+=" =",r(n/e)};for(let o of e.split(/\n/)){if(!o)continue;if(!/^\d/.test(o))continue;const e=o.split(/,/);let l=n[e[2]];l||(n[e[2]]=l={stops:0,us:0,meds:[]}),s=e[2],a=25,t+=s.length>=a?s:(s+" ").slice(0,a);const c=parseInt(e[0]),u=parseInt(e[1]);i(c,u),t+=" |",i(c-l.stops,u-l.us),t+=" ~";const d=parseInt(e[3]);r(d),l.meds.length>10&&l.meds.shift(),l.meds.push(d);const p=l.meds.slice();p.sort(((e,t)=>e-t));const g=p[p.length>>1];t+=" ~~",r(g),l.stops=c,l.us=u,t+="\n"}var s,a;console.log(t)}(t)}}(n=e.pxtcore||(e.pxtcore={}));class g extends c{constructor(){super(...arguments),this.v=void 0}scan(e){e("*",this.v)}gcKey(){return"LOC"}gcSize(){return 2}destroy(){}print(){e.runtime&&e.runtime.refCountingDebug&&console.log(`RefRefLocal id:${this.id} v:${this.v}`)}}e.RefRefLocal=g;class h extends c{constructor(){super(...arguments),this.vtable=e.mkMapVTable(),this.data=[]}scan(e){for(let t of this.data)e(t.key,t.val)}gcKey(){return"{...}"}gcSize(){return 2*this.data.length+4}findIdx(e){e+="";for(let t=0;t<this.data.length;++t)if(this.data[t].key==e)return t;return-1}destroy(){super.destroy();for(let e=0;e<this.data.length;++e)this.data[e].val=0;this.data=[]}print(){e.runtime&&e.runtime.refCountingDebug&&console.log(`RefMap id:${this.id} size:${this.data.length}`)}toAny(){const e={};return this.data.forEach((t=>{e[t.key]=c.toAny(t.val)})),e}}function f(){e.runtime&&e.runtime.dumpLivePointers()}e.RefMap=h,e.dumpLivePointers=f,function(e){e.toString=function(e){return null===e?"null":void 0===e?"undefined":e.toString()},e.toBoolDecr=function(e){return!!e},e.toBool=function(e){return!!e}}(o=e.numops||(e.numops={})),function(e){e.toInt=function(e){return 0|e},e.toFloat=function(e){return e},e.ignore=function(e){return e}}(r=e.langsupp||(e.langsupp={})),function(t){t.ptrOfLiteral=function(e){return e},t.debugMemLeaks=function(){f()},t.templateHash=function(){return 0},t.programHash=function(){return 0},t.programName=function(){return e.title},t.programSize=function(){return 0},t.afterProgramPage=function(){return 0},t.getConfig=function(t,n){let o=e.getConfig(t);return null==o?n:o},t.toInt=function(e){return e>>0},t.toUInt=function(e){return e>>>0},t.toDouble=function(e){return e},t.toFloat=function(e){return e},t.fromInt=function(e){return e},t.fromUInt=function(e){return e},t.fromDouble=function(e){return e},t.fromFloat=function(e){return e},t.fromBool=function(e){return!!e}}(n=e.pxtcore||(e.pxtcore={})),function(n){function o(e,t){if(t+="",e instanceof d){return e.fields[t]}let n=e.findIdx(t);if(!(n<0))return e.data[n].val}function r(e,t,n){if(t+="",e instanceof d){return void(e.fields[t]=n)}let o=e.findIdx(t);o<0?e.data.push({key:t,val:n}):e.data[o].val=n}n.toInt8=function(e){return(255&e)<<24>>24},n.toInt16=function(e){return(65535&e)<<16>>16},n.toInt32=function(e){return 0|e},n.toUInt32=function(e){return e>>>0},n.toUInt8=function(e){return 255&e},n.toUInt16=function(e){return 65535&e},n.nullFix=function(e){return null==e||!1===e?0:!0===e?1:e},n.nullCheck=function(t){null==t&&e.U.userError("Dereferencing null/undefined value.")},n.panic=function(t){e.U.userError("PANIC! Code "+t)},n.stringToBool=function(e){return e?1:0},n.ptrToBool=function(e){return e?1:0},n.emptyToNull=function(e){return""==e?0:e},n.ldlocRef=function(e){return e.v},n.stlocRef=function(e,t){e.v=t},n.mklocRef=function(){return new g},n.stclo=function(e,n,o){return t(0<=n&&n<e.fields.length),t(null===e.fields[n]),e.fields[n]=o,e},n.runtimeWarning=function(t){e.Runtime.postMessage(e.getWarningMessage(t))},n.mkMap=function(){return new h},n.mapGet=function(e,t){return o(e,n.mapKeyNames[t])},n.mapSet=function(e,t,o){return r(e,n.mapKeyNames[t],o)},n.mapGetByString=o,n.mapDeleteByString=function(e,t){e instanceof h||n.panic(923);let o=e.findIdx(t);return o>=0&&e.data.splice(o,1),!0},n.mapSetGeneric=r,n.mapGetGeneric=o,n.mapSetByString=r,n.keysOf=function(t){let n=new e.RefCollection;if(t instanceof h)for(let e of t.data)n.push(e.key);return n}}(i=e.pxtrt||(e.pxtrt={})),function(e){e.mkClassInstance=function(e){t(!!e.methods);let n=new d;return n.vtable=e,n},e.switch_eq=function(e,t){return e==t},e.typeOf=function(e){return typeof e}}(n=e.pxtcore||(e.pxtcore={})),function(t){t.panic=i.panic,t.pause=function(t){let n=e.getResume();e.runtime.schedule((()=>{n()}),t)},t.runInBackground=function(t){e.runtime.runFiberAsync(t)},t.forever=function(t){i.nullCheck(t),function n(){e.runtime.runFiberAsync(t).then((()=>e.U.delay(20))).then(n)}()}}(s=e.thread||(e.thread={}))}(pxsim||(pxsim={})),function(e){class t extends e.RefObject{constructor(){super(),this.data=[]}scan(e){for(let t=0;t<this.data.length;++t)e("["+t+"]",this.data[t])}gcKey(){return"[...]"}gcSize(){return this.data.length+2}toArray(){return this.data.slice(0)}toAny(){return this.data.map((t=>e.RefObject.toAny(t)))}toDebugString(){let t="[";for(let n=0;n<this.data.length;++n){n>0&&(t+=",");let o=e.RefObject.toDebugString(this.data[n]);if(t.length+o.length>100){0==n&&(t+=o.substr(0,100)),t+="...";break}t+=o}return t+="]",t}destroy(){let e=this.data;for(let t=0;t<e.length;++t)e[t]=0;this.data=[]}isValidIndex(e){return e>=0&&e<this.data.length}push(e){this.data.push(e)}pop(){return this.data.pop()}getLength(){return this.data.length}setLength(e){this.data.length=e}getAt(e){return this.data[e]}setAt(e,t){this.data[e]=t}insertAt(e,t){this.data.splice(e,0,t)}removeAt(e){return this.data.splice(e,1)[0]}indexOf(e,t){return this.data.indexOf(e,t)}print(){}}let n,o,r,i,s,a,l,c;e.RefCollection=t,function(n){function o(t,n){if(e.pxtrt.nullCheck(t),t.isValidIndex(n))return t.removeAt(n)}function r(t,n,o){return e.pxtrt.nullCheck(t),t.indexOf(n,o)}n.mk=function(){return new t},n.isArray=function(e){return e instanceof t},n.length=function(t){return e.pxtrt.nullCheck(t),t.getLength()},n.setLength=function(t,n){e.pxtrt.nullCheck(t),t.setLength(n)},n.push=function(t,n){e.pxtrt.nullCheck(t),t.push(n)},n.pop=function(t,n){return e.pxtrt.nullCheck(t),t.pop()},n.getAt=function(t,n){return e.pxtrt.nullCheck(t),t.getAt(n)},n.removeAt=o,n.insertAt=function(t,n,o){e.pxtrt.nullCheck(t),t.insertAt(n,o)},n.setAt=function(t,n,o){e.pxtrt.nullCheck(t),t.setAt(n,o)},n.indexOf=r,n.removeElement=function(t,n){e.pxtrt.nullCheck(t);let i=r(t,n,0);return i>=0?(o(t,i),1):0}}(n=e.Array_||(e.Array_={})),function(e){e.imul=Math.imul||function(e,t){const n=65535&e,o=65535&t;return n*o+((e>>>16&65535)*o+n*(t>>>16&65535)<<16>>>0)|0},e.idiv=function(e,t){return(0|e)/(0|t)|0},e.round=function(e){return Math.round(e)},e.roundWithPrecision=function(e,t){if((t|=0)<=0)return Math.round(e);if(0==e)return 0;let n=0;for(;0==n&&t<21;){const o=Math.pow(10,t++);n=Math.round(e*o+Number.EPSILON)/o}return n},e.ceil=function(e){return Math.ceil(e)},e.floor=function(e){return Math.floor(e)},e.sqrt=function(e){return Math.sqrt(e)},e.pow=function(e,t){return Math.pow(e,t)},e.clz32=function(e){return Math.clz32(e)},e.log=function(e){return Math.log(e)},e.log10=function(e){return Math.log10(e)},e.log2=function(e){return Math.log2(e)},e.exp=function(e){return Math.exp(e)},e.sin=function(e){return Math.sin(e)},e.sinh=function(e){return Math.sinh(e)},e.cos=function(e){return Math.cos(e)},e.cosh=function(e){return Math.cosh(e)},e.tan=function(e){return Math.tan(e)},e.tanh=function(e){return Math.tanh(e)},e.asin=function(e){return Math.asin(e)},e.asinh=function(e){return Math.asinh(e)},e.acos=function(e){return Math.acos(e)},e.acosh=function(e){return Math.acosh(e)},e.atan=function(e){return Math.atan(e)},e.atanh=function(e){return Math.atanh(e)},e.atan2=function(e,t){return Math.atan2(e,t)},e.trunc=function(e){return e>0?Math.floor(e):Math.ceil(e)},e.random=function(){return Math.random()},e.randomRange=function(e,t){if(e==t)return e;if(e>t){let n=e;e=t,t=n}return Math.floor(e)==e&&Math.floor(t)==t?e+Math.floor(Math.random()*(t-e+1)):e+Math.random()*(t-e)}}(o=e.Math_||(e.Math_={})),function(t){function n(t,n){return e.pxtrt.nullFix(t)==e.pxtrt.nullFix(n)}t.lt=function(e,t){return e<t},t.le=function(e,t){return e<=t},t.neq=function(e,t){return!n(e,t)},t.eq=n,t.eqDecr=function(t,n){return e.pxtrt.nullFix(t)==e.pxtrt.nullFix(n)},t.gt=function(e,t){return e>t},t.ge=function(e,t){return e>=t},t.div=function(e,t){return 0|Math.floor(e/t)},t.mod=function(e,t){return e%t},t.bnot=function(e){return~e},t.toString=function(e){return e+""}}(r=e.Number_||(e.Number_={})),function(e){e.adds=function(e,t){return e+t|0},e.subs=function(e,t){return e-t|0},e.divs=function(e,t){return 0|Math.floor(e/t)},e.muls=function(e,t){return o.imul(e,t)},e.ands=function(e,t){return e&t},e.orrs=function(e,t){return e|t},e.eors=function(e,t){return e^t},e.lsls=function(e,t){return e<<t},e.lsrs=function(e,t){return e>>>t},e.asrs=function(e,t){return e>>t},e.bnot=function(e){return~e},e.ignore=function(e){return e}}(i=e.thumb||(e.thumb={})),function(e){function t(e){return e<<16>>16}e.adds=function(e,n){return t(e+n)},e.subs=function(e,n){return t(e-n)},e.divs=function(e,n){return t(Math.floor(e/n))},e.muls=function(e,n){return t(o.imul(e,n))},e.ands=function(e,n){return t(e&n)},e.orrs=function(e,n){return t(e|n)},e.eors=function(e,n){return t(e^n)},e.lsls=function(e,n){return t(e<<n)},e.lsrs=function(e,t){return(65535&e)>>>t},e.asrs=function(e,n){return t(e>>n)},e.bnot=function(e){return~e},e.ignore=function(e){return e}}(s=e.avr||(e.avr={})),function(t){t.stringConv=function(t){const n=e.getResume();t instanceof e.RefRecord&&t.vtable.toStringMethod?e.runtime.runFiberAsync(t.vtable.toStringMethod,t).then((()=>{n(e.runtime.currFrame.retval+"")})):n(t+"")},t.mkEmpty=function(){return""},t.fromCharCode=function(e){return String.fromCharCode(e)},t.toNumber=function(e){return parseFloat(e)},t.concat=function(e,t){return e+t},t.substring=function(t,n,o){return e.pxtrt.nullCheck(t),t.slice(n,n+o)},t.equals=function(e,t){return e==t},t.compare=function(e,t){return e==t?0:e<t?-1:1},t.compareDecr=function(e,t){return e==t?0:e<t?-1:1},t.length=function(e){return e.length},t.substr=function(e,t,n){return e.substr(t,n)},t.charAt=function(e,t){return e.charAt(t)},t.charCodeAt=function(t,n){return e.pxtrt.nullCheck(t),function(t,n){return e.pxtrt.nullCheck(t),0<=n&&n<t.length}(t,n)?t.charCodeAt(n):0},t.indexOf=function(t,n,o){return e.pxtrt.nullCheck(t),null==n?-1:t.indexOf(n,o)},t.lastIndexOf=function(t,n,o){return e.pxtrt.nullCheck(t),null==n?-1:t.lastIndexOf(n,o)},t.includes=function(t,n,o){return e.pxtrt.nullCheck(t),null!=n&&t.includes(n,o)}}(a=e.String_||(e.String_={})),function(e){e.toString=function(e){return e?"true":"false"},e.bang=function(e){return!e}}(l=e.Boolean_||(e.Boolean_={}));class u extends e.RefObject{constructor(e){super(),this.data=e,this.isStatic=!1}scan(e){}gcKey(){return"Buffer"}gcSize(){return 2+(this.data.length+3>>2)}gcIsStatic(){return this.isStatic}print(){}toDebugString(){return c.toHex(this)}}e.RefBuffer=u,function(t){let n;function o(t){let o=function(t){switch(t){case n.Int8LE:return-1;case n.UInt8LE:return 1;case n.Int16LE:return-2;case n.UInt16LE:return 2;case n.Int32LE:return-4;case n.UInt32LE:return 4;case n.Int8BE:return-10;case n.UInt8BE:return 10;case n.Int16BE:return-20;case n.UInt16BE:return 20;case n.Int32BE:return-40;case n.UInt32BE:return 40;case n.Float32LE:return 4;case n.Float32BE:return 40;case n.Float64LE:return 8;case n.Float64BE:return 80;default:throw e.U.userError("bad format")}}(t),r=!1;o<0&&(r=!0,o=-o);let i=!1;return o>=10&&(i=!0,o/=10),{size:o,signed:r,swap:i,isFloat:t>=n.Float32LE}}function r(e){return new u(new Uint8Array(e))}function i(t,n){return e.pxtrt.nullCheck(t),0<=n&&n<t.data.length}function s(e,t){return i(e,t)?e.data[t]:0}function a(t){t.isStatic&&e.U.userError("Writing to read only buffer.")}function l(e,t,n){i(e,t)&&(a(e),e.data[t]=n)}function c(e,t,n=0,o=-1){n<0||n>e.data.length||(o<0&&(o=e.data.length),o=Math.min(o,e.data.length-n),a(e),e.data.fill(t,n,n+o))}function d(e,t,n,o,r){if(n.buffer===e.buffer)d(e,t,n.slice(o,o+r),0,r);else for(let i=0;i<r;++i)e[t+i]=n[o+i]}!function(e){e[e.Int8LE=1]="Int8LE",e[e.UInt8LE=2]="UInt8LE",e[e.Int16LE=3]="Int16LE",e[e.UInt16LE=4]="UInt16LE",e[e.Int32LE=5]="Int32LE",e[e.Int8BE=6]="Int8BE",e[e.UInt8BE=7]="UInt8BE",e[e.Int16BE=8]="Int16BE",e[e.UInt16BE=9]="UInt16BE",e[e.Int32BE=10]="Int32BE",e[e.UInt32LE=11]="UInt32LE",e[e.UInt32BE=12]="UInt32BE",e[e.Float32LE=13]="Float32LE",e[e.Float64LE=14]="Float64LE",e[e.Float32BE=15]="Float32BE",e[e.Float64BE=16]="Float64BE"}(n=t.NumberFormat||(t.NumberFormat={})),t.getNumber=function(e,t,n){let r=o(t);if(r.isFloat){let t=e.data.buffer.slice(n,n+r.size);if(r.swap){new Uint8Array(t).reverse()}return 4==r.size?new Float32Array(t)[0]:new Float64Array(t)[0]}let i=0;for(let t=0;t<r.size;++t){i<<=8;let o=r.swap?n+t:n+r.size-t-1;i|=e.data[o]}if(r.signed){let e=32-8*r.size;i=i<<e>>e}else i>>>=0;return i},t.setNumber=function(e,t,n,r){let i=o(t);if(i.isFloat){let t=new Uint8Array(i.size);4==i.size?new Float32Array(t.buffer)[0]=r:new Float64Array(t.buffer)[0]=r,i.swap&&t.reverse();for(let o=0;o<i.size;++o)e.data[n+o]=t[o]}else for(let t=0;t<i.size;++t){let o=i.swap?n+i.size-t-1:n+t;e.data[o]=255&r,r>>=8}},t.createBuffer=r,t.createBufferFromHex=function(e){let t=r(e.length>>1);for(let n=0;n<e.length;n+=2)t.data[n>>1]=parseInt(e.slice(n,n+2),16);return t.isStatic=!0,t},t.isReadOnly=function(e){return e.isStatic},t.getBytes=function(e){return e.data},t.getUint8=function(e,t){return s(e,t)},t.getByte=s,t.setUint8=function(e,t,n){l(e,t,n)},t.setByte=l,t.length=function(e){return e.data.length},t.fill=c,t.slice=function(e,t,n){return t=Math.min(e.data.length,t),n<0&&(n=e.data.length),n=Math.min(n,e.data.length-t),new u(e.data.slice(t,t+n))},t.toHex=function(e){const t="0123456789abcdef";let n="";for(let o=0;o<e.data.length;++o)n+=t[e.data[o]>>4],n+=t[15&e.data[o]];return n},t.toString=function(t){return e.U.fromUTF8Array(t.data)};const p=-2147483648;t.shift=function(e,t,n,o){o<0&&(o=e.data.length-n),n<0||n+o>e.data.length||n+o<n||0==o||0==t||t==p||0!=o&&0!=t&&t!=p&&(t<=-o||t>=o?c(e,0):(a(e),t<0?(t=-t,d(e.data,n+t,e.data,n,o-t),e.data.fill(0,n,n+t)):(o-=t,d(e.data,n,e.data,n+t,o),e.data.fill(0,n+o,n+o+t))))},t.rotate=function(e,t,n,o){if(o<0&&(o=e.data.length-n),n<0||n+o>e.data.length||n+o<n||0==o||0==t||t==p)return;a(e),t<0&&(t+=o<<8),(t%=o)<0&&(t+=o);let r=e.data,i=t,s=0,l=i,c=o;for(;s!=l;){let e=r[s+n];r[s+++n]=r[l+n],r[l+++n]=e,l==c?l=i:s==i&&(i=l)}},t.write=function(e,t,n,o=0,r=-1){r<0&&(r=n.data.length),o<0||t<0||t>e.data.length||(r=Math.min(n.data.length-o,e.data.length-t))<0||(a(e),d(e.data,t,n.data,o,r))}}(c=e.BufferMethods||(e.BufferMethods={}))}(pxsim||(pxsim={})),function(e){!function(t){t.createBufferFromUTF8=function(t){return new e.RefBuffer(e.U.toUTF8Array(t))}}(e.control||(e.control={}))}(pxsim||(pxsim={})),function(e){!function(e){let t={};e.setLocalizedStrings=function(e){t=e||{}};function n(e,t){return 0==t.length?e:e.replace(/\{([0-9]+)(\:[^\}]+)?\}/g,(function(e,n,i){let s=t[parseInt(n)],a="",l=/^:f(\d*)\.(\d+)/.exec(i);if(l){let e=parseInt(l[2]),t=parseInt(l[1])||0,n=/^0/.test(l[1])?"0":" ",o=s.toFixed(e);if(t>0&&e>0&&(t+=e+1),t>0)for(;o.length<t;)o=n+o;a=o}else a=":x"==i?"0x"+s.toString(16):void 0===s?"(undef)":null===s?"(null)":s.toString?s.toString():s+"";return":a"==i?/^\s*[euioah]/.test(a.toLowerCase())?a="an "+a:/^\s*[bcdfgjklmnpqrstvwxz]/.test(a.toLowerCase())&&(a="a "+a):":s"==i?a=1==s?"":"s":":q"==i?a=o(a):":jq"==i?a=r(a):":uri"==i?a=encodeURIComponent(a).replace(/'/g,"%27").replace(/"/g,"%22"):":url"==i?a=encodeURI(a).replace(/'/g,"%27").replace(/"/g,"%22"):":%"==i&&(a=(100*s).toFixed(1).toString()+"%"),a}))}function o(e){return e?e.replace(/([^\w .!?\-$])/g,(e=>"&#"+e.charCodeAt(0)+";")):e}function r(e){return e.replace(/[^\w .!?\-$]/g,(e=>{let t=e.charCodeAt(0).toString(16);return"\\u"+"0000".substr(0,4-t.length)+t}))}e.lf=function(e,...o){let r=t[e]||e;return r=r.replace(/^\{(id|loc):[^\}]+\}/g,""),n(r,o)},e.fmt_va=n,e.htmlEscape=o,e.jsStringQuote=r}(e.localization||(e.localization={}))}(pxsim||(pxsim={})),function(pxsim){const MIN_MESSAGE_WAIT_MS=200;let tracePauseMs=0,U,pxtcore;!function(e){function t(e){return e.split(/\s+/).filter((e=>!!e))}function n(e){for(;e.firstChild;)e.removeChild(e.firstChild)}let o;e.containsClass=function(e,n){return t(n).every((t=>function(e,t){if(e.classList)return e.classList.contains(t);return!((e.className+"").split(/\s+/).indexOf(t)<0)}(e,t)))},e.addClass=function(e,n){t(n).forEach((t=>function(e,t){if(e.classList)e.classList.add(t);else{(e.className+"").split(/\s+/).indexOf(t)<0&&(e.className.baseVal+=" "+t)}}(e,t)))},e.removeClass=function(e,n){t(n).forEach((t=>function(e,t){e.classList?e.classList.remove(t):e.className.baseVal=(e.className+"").split(/\s+/).filter((e=>e!=t)).join(" ")}(e,t)))},e.remove=function(e){e.parentElement.removeChild(e)},e.removeChildren=n,e.clear=function(e){n(e)},e.assert=function(e,t="Assertion failed"){if(!e)throw new Error(t)},e.repeatMap=function(e,t){e=e||0;let n=[];for(let o=0;o<e;++o)n.push(t(o));return n},e.userError=function(e){let t=new Error(e);throw t.isUserError=!0,t},e.now=function(){return Date.now()},e.perfNowUs=function(){return o||(o="undefined"!=typeof performance?performance.now.bind(performance)||performance.moznow.bind(performance)||performance.msNow.bind(performance)||performance.webkitNow.bind(performance)||performance.oNow.bind(performance):Date.now),1e3*o()};const r=Promise.resolve();async function i(e,t,n){let o=0;const r=[],i=[];for(let s=0;s<e;s++){const e=(async()=>{for(;o<t.length;){const e=o++,r=t[e];i[e]=await n(r)}})();r.push(e)}try{await Promise.all(r)}catch(e){throw o=t.length,e}return i}function s(){return"undefined"!=typeof window&&!!window.pxtElectron}function a(){return"undefined"!=typeof window&&!!window.ipcRenderer}function l(){return s()||a()}function c(){try{return"undefined"!=typeof window&&/^http:\/\/(localhost|127\.0\.0\.1):\d+\//.test(window.location.href)&&!/nolocalhost=1/.test(window.location.href)}catch(e){return!1}}e.nextTick=function(e){r.then(e)},e.delay=async function(e,t){const n=await t;return await new Promise((t=>setTimeout((()=>t()),e))),n},e.promiseMapAll=function(e,t){return Promise.all(e.map((e=>t(e))))},e.promiseMapAllSeries=function(e,t){return i(1,e,t)},e.promisePoolAsync=i,e.promiseTimeout=async function(e,t,n){let o,r;const i=new Promise(((t,i)=>{r=t,o=setTimeout((()=>{r=void 0,clearTimeout(o),i(n||`Promise timed out after ${e}ms`)}),e)}));return Promise.race([t,i]).then((e=>(r&&(clearTimeout(o),r()),e)))},e.stringToUint8Array=function(e){let t=e.length,n=new Uint8Array(t);for(let o=0;o<t;++o)n[o]=255&e.charCodeAt(o);return n},e.uint8ArrayToString=function(e){let t=e.length,n="";for(let o=0;o<t;++o)n+=String.fromCharCode(e[o]);return n},e.fromUTF8=function(e){if(!e)return"";let t="";for(let n=0;n<e.length;++n){let o=255&e.charCodeAt(n);t+=37==o||o>127?"%"+o.toString(16):e.charAt(n)}return decodeURIComponent(t)},e.toUTF8=function(e,t){let n="";if(!e)return n;for(let o=0;o<e.length;++o){let r=e.charCodeAt(o);if(r<=127)n+=e.charAt(o);else if(r<=2047)n+=String.fromCharCode(192|r>>6,128|63&r);else{if(!t&&55296<=r&&r<=56319){let t=e.charCodeAt(++o);isNaN(t)||(r=65536+(r-55296<<10)+(t-56320))}n+=r<=65535?String.fromCharCode(224|r>>12,128|r>>6&63,128|63&r):String.fromCharCode(240|r>>18,128|r>>12&63,128|r>>6&63,128|63&r)}}return n},e.toUTF8Array=function(e){return(new TextEncoder).encode(e)},e.fromUTF8Array=function(e){return(new TextDecoder).decode(e)},e.isPxtElectron=s,e.isIpcRenderer=a,e.isElectron=l,e.isLocalHost=c,e.isLocalHostDev=function(){return c()&&!l()},e.unique=function(e,t){let n=[],o={};return e.forEach((e=>{let r=t(e);o.hasOwnProperty(r)||(o[r]=null,n.push(e))})),n}}(U=pxsim.U||(pxsim.U={}));class BreakLoopException{}function getResume(){return pxsim.runtime.getResume()}pxsim.BreakLoopException=BreakLoopException,function(e){function t(e){let t=pxsim.runtime.currTryFrame();t||U.userError("unhandled exception: "+e);const n=t.handlerFrame;throw pxsim.runtime.currFrame=n,n.pc=t.handlerPC,n.tryFrame=t.parent,n.thrownValue=e,n.hasThrownValue=!0,new BreakLoopException}e.beginTry=function(e){pxsim.runtime.currFrame.tryFrame={parent:pxsim.runtime.currTryFrame(),handlerPC:e,handlerFrame:pxsim.runtime.currFrame}},e.endTry=function(){const e=pxsim.runtime.currFrame;e.tryFrame=e.tryFrame.parent},e.throwValue=t,e.getThrownValue=function(){const e=pxsim.runtime.currFrame;return U.assert(e.hasThrownValue),e.hasThrownValue=!1,e.thrownValue},e.endFinally=function(){const e=pxsim.runtime.currFrame;e.hasThrownValue&&(e.hasThrownValue=!1,t(e.thrownValue))}}(pxtcore=pxsim.pxtcore||(pxsim.pxtcore={})),pxsim.getResume=getResume;const SERIAL_BUFFER_LENGTH=16;class BaseBoard{constructor(){this.messageListeners=[],this.serialOutBuffer="",this.messages=[],this.lastSerialTime=0,this.debouncedPostAll=()=>{const e=Date.now();e-this.lastSerialTime>MIN_MESSAGE_WAIT_MS?(clearTimeout(this.serialTimeout),this.messages.length&&(Runtime.postMessage({type:"bulkserial",data:this.messages,id:pxsim.runtime.id,sim:!0}),this.messages=[],this.lastSerialTime=e)):this.serialTimeout=setTimeout(this.debouncedPostAll,50)},this.id=pxsim.Embed.frameid||"b"+Math.round(2147483647*Math.random()),this.bus=new pxsim.EventBus(pxsim.runtime,this)}updateView(){}receiveMessage(e){pxsim.runtime&&!pxsim.runtime.dead&&this.dispatchMessage(e)}dispatchMessage(e){for(const t of this.messageListeners)t(e)}addMessageListener(e){this.messageListeners.push(e)}get storedState(){return this.runOptions?(this.runOptions.storedState||(this.runOptions.storedState={}),this.runOptions.storedState):{}}initAsync(e){return this.runOptions=e,Promise.resolve()}setStoredState(e,t){null==t?delete this.storedState[e]:this.storedState[e]=t,Runtime.postMessage({type:"simulator",command:"setstate",stateKey:e,stateValue:t})}onDebuggerResume(){}screenshotAsync(e){return Promise.resolve(void 0)}kill(){}writeSerial(e){this.serialOutBuffer+=e,(/\n/.test(this.serialOutBuffer)||this.serialOutBuffer.length>SERIAL_BUFFER_LENGTH)&&(this.messages.push({time:Date.now(),data:this.serialOutBuffer}),this.debouncedPostAll(),this.serialOutBuffer="")}}pxsim.BaseBoard=BaseBoard;class CoreBoard extends BaseBoard{constructor(){super(),this.updateSubscribers=[],this.updateView=()=>{this.updateSubscribers.forEach((e=>e()))},this.builtinParts={},this.builtinVisuals={},this.builtinPartVisuals={}}kill(){super.kill(),pxsim.AudioContextManager.stopAll()}}pxsim.CoreBoard=CoreBoard;class BareBoard extends BaseBoard{}function initBareRuntime(){pxsim.runtime.board=new BareBoard;let e=pxsim;e.basic={pause:pxsim.thread.pause,showNumber:e=>{let t=getResume();console.log("SHOW NUMBER:",e),U.nextTick(t)}},e.serial={writeString:e=>pxsim.runtime.board.writeSerial(e)},e.pins={createBuffer:pxsim.BufferMethods.createBuffer},e.control={inBackground:pxsim.thread.runInBackground,createBuffer:pxsim.BufferMethods.createBuffer,dmesg:e=>console.log("DMESG: "+e),deviceDalVersion:()=>"sim",__log:(e,t)=>console.log("LOG: "+t.trim())}}let LogType;pxsim.initBareRuntime=initBareRuntime,function(e){e[e.UserSet=0]="UserSet",e[e.BackAdd=1]="BackAdd",e[e.BackRemove=2]="BackRemove"}(LogType||(LogType={}));class EventQueue{constructor(e,t){this.runtime=e,this.valueToArgs=t,this.max=5,this.events=[],this.awaiters=[],this._handlers=[],this._addRemoveLog=[]}push(e,t){if(this.awaiters.length>0)if(t){const e=this.awaiters.shift();e&&e()}else{const e=this.awaiters.slice();this.awaiters=[],e.forEach((e=>e()))}return 0==this.handlers.length||this.events.length>this.max?Promise.resolve():(this.events.push(e),this.lock?Promise.resolve():this.poke())}poke(){this.lock=!0;let e=this.events;return this.events=[],U.promiseMapAllSeries(e,(e=>U.promiseMapAllSeries(this.handlers,(t=>this.runtime.runFiberAsync(t,...this.valueToArgs?this.valueToArgs(e):[e]))))).then((()=>this.events.length>0?this.poke():(this.lock=!1,this._addRemoveLog.forEach((e=>{e.log===LogType.BackAdd?this.addHandler(e.act):e.log===LogType.BackRemove?this.removeHandler(e.act):this.setHandler(e.act)})),this._addRemoveLog=[],Promise.resolve())))}get handlers(){return this._handlers}setHandler(e){this.lock?this._addRemoveLog.push({act:e,log:LogType.UserSet}):this._handlers=[e]}addHandler(e){if(this.lock)this._addRemoveLog.push({act:e,log:LogType.BackAdd});else{-1==this._handlers.indexOf(e)&&this._handlers.push(e)}}removeHandler(e){if(this.lock)this._addRemoveLog.push({act:e,log:LogType.BackRemove});else{let t=this._handlers.indexOf(e);-1!=t&&this._handlers.splice(t,1)}}addAwaiter(e){this.awaiters.push(e)}}function bind(e){const t=e.arg0,n=e.fn;return e=>{let o=0;for(;e.hasOwnProperty("arg"+o);)o++;const r=e;for(let e=o;e>0;e--)r["arg"+e]=r["arg"+(e-1)];return e.arg0=t,n(e)}}function _leave(e,t){return e.parent.retval=t,e.parent}function syntheticRefAction(e){return pxtcore.mkAction(0,(t=>_leave(t,e(t))))}pxsim.EventQueue=EventQueue,pxsim.initCurrentRuntime=void 0,pxsim.handleCustomMessage=void 0,pxsim.syntheticRefAction=syntheticRefAction;class TimeoutScheduled{constructor(e,t,n,o){this.id=e,this.fn=t,this.totalRuntime=n,this.timestampCall=o}}pxsim.TimeoutScheduled=TimeoutScheduled;class PausedTimeout{constructor(e,t){this.fn=e,this.timeRemaining=t}}function mkVTable(e){return{name:e.name,numFields:e.numFields,classNo:e.classNo,methods:e.methods,iface:e.iface,lastSubtypeNo:e.lastSubtypeNo,toStringMethod:e.toStringMethod,maxBgInstances:e.maxBgInstances}}pxsim.PausedTimeout=PausedTimeout,pxsim.mkVTable=mkVTable;let mapVTable=null;function mkMapVTable(){return mapVTable||(mapVTable=mkVTable({name:"_Map",numFields:0,classNo:0,lastSubtypeNo:0,methods:null})),mapVTable}function functionName(e){const t=e.info;return t?`${t.functionName} (${t.fileName}:${t.line+1}:${t.column+1})`:"()"}pxsim.mkMapVTable=mkMapVTable,pxsim.functionName=functionName;class Runtime{constructor(msg){this.numGlobals=1e3,this.dead=!1,this.running=!1,this.idleTimer=void 0,this.recording=!1,this.recordingTimer=0,this.recordingLastImageData=void 0,this.recordingWidth=void 0,this.startTime=0,this.startTimeUs=0,this.pausedTime=0,this.lastPauseTimestamp=0,this.globals={},this.environmentGlobals={},this.otherFrames=[],this.loopLock=null,this.loopLockWaitList=[],this.heapSnapshots=[],this.timeoutsScheduled=[],this.timeoutsPausedOnBreakpoint=[],this.pausedOnBreakpoint=!1,this.traceDisabled=!1,this.perfOffset=0,this.perfElapsed=0,this.perfStack=0,this.refCountingDebug=!1,this.refObjId=1,this.numDisplayUpdates=0,U.assert(!!pxsim.initCurrentRuntime),this.id=msg.id,this.refCountingDebug=!!msg.refCountingDebug;let threadId=0,breakpoints=null,currResume,dbgHeap,dbgResume,breakFrame=null,lastYield=Date.now(),userGlobals,__this=this;this.traceDisabled=!!msg.traceDisabled;const evalIface={runtime:this,oops:oops,doNothing:doNothing,pxsim:pxsim,globals:this.globals,setupYield:setupYield,maybeYield:maybeYield,setupDebugger:setupDebugger,isBreakFrame:isBreakFrame,breakpoint:breakpoint,trace:trace,checkStack:checkStack,leave:_leave,checkResumeConsumed:checkResumeConsumed,setupResume:setupResume,setupLambda:setupLambda,checkSubtype:checkSubtype,failedCast:failedCast,buildResume:buildResume,mkVTable:mkVTable,bind:bind,leaveAccessor:leaveAccessor};function oops(e){throw new Error("sim error: "+e)}function doNothing(e){return e.pc=-1,_leave(e,e.parent.retval)}function flushLoopLock(){for(;__this.loopLockWaitList.length>0&&!__this.loopLock;){__this.loopLockWaitList.shift()()}}let yieldReset=()=>{};function setupYield(e){yieldReset=e}function loopForSchedule(e){const t=new Object,n=e.pc;return __this.loopLock=t,__this.otherFrames.push(e),()=>{__this.dead||(U.assert(e.pc==n),U.assert(__this.loopLock===t),__this.loopLock=null,loop(e),flushLoopLock())}}function maybeYield(e,t,n){if(__this.pausedOnBreakpoint)return!1;__this.cleanScheduledExpired(),yieldReset();let o=Date.now();return o-lastYield>=20&&(lastYield=o,e.pc=t,e.r0=n,setTimeout(loopForSchedule(e),5),!0)}function setupDebugger(e,t){return breakpoints=new Uint8Array(e),breakpoints[0]=msg.breakOnStart?1:0,userGlobals=t,breakpoints}function isBreakFrame(e){if(!breakFrame)return!0;for(let t=breakFrame;t;t=t.parent)if(t==e)return!0;return!1}function breakpoint(e,t,n,o){let r={};__this.loopLock=r,U.assert(!dbgResume),U.assert(!dbgHeap),e.pc=t,e.r0=o;const{msg:i,heap:s}=pxsim.getBreakpointMsg(e,n,userGlobals);return dbgHeap=s,pxsim.injectEnvironmentGlobals(i,s),Runtime.postMessage(i),breakpoints[0]=0,breakFrame=null,__this.pauseScheduled(),dbgResume=n=>{if(dbgResume=null,dbgHeap=null,__this.dead)return null;switch(__this.resumeAllPausedScheduled(),__this.board.onDebuggerResume(),pxsim.runtime=__this,U.assert(e.pc==t),breakpoints[0]=0,breakFrame=null,n.subtype){case"resume":break;case"stepover":breakpoints[0]=1,breakFrame=e;break;case"stepinto":breakpoints[0]=1;break;case"stepout":breakpoints[0]=1,breakFrame=e.parent||e}U.assert(__this.loopLock==r),__this.loopLock=null,__this.otherFrames.push(e),loop(e),flushLoopLock()},null}function trace(e,t,n,o){if(setupResume(t,n),"<main>"===o.functionName||"main.ts"===o.fileName){if(!pxsim.runtime.traceDisabled){const{msg:n}=pxsim.getBreakpointMsg(t,e,userGlobals);n.subtype="trace",Runtime.postMessage(n)}pxsim.thread.pause(tracePauseMs||1)}else pxsim.thread.pause(0);checkResumeConsumed()}function handleDebuggerMsg(e){switch(e.subtype){case"config":let t=e;if(t.setBreakpoints&&breakpoints){breakpoints.fill(0);for(let e of t.setBreakpoints)breakpoints[e]=1}break;case"traceConfig":tracePauseMs=e.interval;break;case"pause":breakpoints[0]=1,breakFrame=null;break;case"resume":case"stepover":case"stepinto":case"stepout":dbgResume&&dbgResume(e);break;case"variables":const n=e;let o;if(dbgHeap){const e=dbgHeap[n.variablesReference];void 0!==e&&(o=pxsim.dumpHeap(e,dbgHeap,n.fields))}Runtime.postMessage({type:"debugger",subtype:"variables",req_seq:e.seq,variables:o})}}function removeFrame(e){const t=__this.otherFrames;for(let n=t.length-1;n>=0;--n)if(t[n]===e)return void t.splice(n,1);U.userError("frame cannot be removed!")}function loop(e){if(__this.dead)console.log("Runtime terminated");else{U.assert(!__this.loopLock),__this.perfStartRuntime(),removeFrame(e);try{for(pxsim.runtime=__this;e;)__this.currFrame=e,__this.currFrame.overwrittenPC=!1,e=e.fn(e),__this.maybeUpdateDisplay(),__this.currFrame.overwrittenPC&&(e=__this.currFrame);__this.perfStopRuntime()}catch(t){if(t instanceof BreakLoopException)return void U.nextTick(loopForSchedule(__this.currFrame));if(__this.perfStopRuntime(),__this.errorHandler)__this.errorHandler(t);else{console.error("Simulator crashed, no error handler",t.stack);const{msg:n,heap:o}=pxsim.getBreakpointMsg(e,e.lastBrkId,userGlobals);pxsim.injectEnvironmentGlobals(n,o),n.exceptionMessage=t.message,n.exceptionStack=t.stack,Runtime.postMessage(n),__this.postError&&__this.postError(t)}}}}function checkStack(e){e>100&&U.userError("Stack overflow")}function actionCall(e){return e.depth=e.parent.depth+1,checkStack(e.depth),e.pc=0,e}function setupTop(e){let t=setupTopCore(e);return setupResume(t,0),t}function setupTopCore(e){let t={parent:null,pc:0,depth:0,threadId:++threadId,fn:()=>(e&&e(t.retval),null)};return t}function topCall(e,t){U.assert(!!__this.board),U.assert(!__this.running),__this.setRunning(!0);let n={parent:setupTopCore(t),fn:e,depth:0,pc:0};__this.otherFrames=[n],loop(actionCall(n))}function checkResumeConsumed(){currResume&&oops("getResume() not called")}function setupResume(e,t){currResume=buildResume(e,t)}function leaveAccessor(e,t){if(e.stage2Call){const n={pc:0,fn:null,depth:e.depth,parent:e.parent};let o=1;for(;e.hasOwnProperty("arg"+o);)n["arg"+(o-1)]=e["arg"+o],o++;return setupLambda(n,t),n}return e.parent.retval=t,e.parent}function setupLambda(e,t,n){if(n){const t=e;for(let e=1;e<n;++e)t["arg"+(e-1)]=t["arg"+e];delete t["arg"+(n-1)]}t instanceof pxsim.RefAction?(e.fn=t.func,e.caps=t.fields):"function"==typeof t?e.fn=t:oops("calling non-function")}function checkSubtype(e,t){if(!e)return!1;const n=e.vtable;return t===n||n&&t.classNo<=n.classNo&&n.classNo<=t.lastSubtypeNo}function failedCast(e){pxsim.control&&pxsim.control.dmesgValue&&pxsim.control.dmesgValue(e),oops("failed cast on "+e)}function buildResume(e,t){currResume&&oops("already has resume"),e.pc=t;let n=Date.now();__this.otherFrames.push(e);let o=r=>{if(__this.dead)return;if(__this.loopLock)return void __this.loopLockWaitList.push((()=>o(r)));pxsim.runtime=__this;let i=Date.now();if(i-n>3&&(lastYield=i),U.assert(e.pc==t),r instanceof pxsim.FnWrapper){let t=r,n={parent:e,fn:t.func,lambdaArgs:t.args,pc:0,caps:t.caps,depth:e.depth+1},o={};return __this.loopLock=o,removeFrame(e),__this.otherFrames.push(n),U.nextTick((()=>{U.assert(__this.loopLock===o),__this.loopLock=null,loop(actionCall(n)),flushLoopLock()}))}return e.retval=r,loop(e)};return o}const entryPoint=msg.code&&eval(msg.code)(evalIface);this.run=e=>topCall(entryPoint,e),this.getResume=()=>{currResume||oops("noresume");let e=currResume;return currResume=null,e},this.setupTop=setupTop,this.handleDebuggerMsg=handleDebuggerMsg,this.entry=entryPoint,this.overwriteResume=e=>{currResume=null,e>=0&&(this.currFrame.pc=e),this.currFrame.overwrittenPC=!0},pxsim.runtime=this,pxsim.initCurrentRuntime(msg)}registerLiveObject(e){return this.refObjId++}runningTime(){return U.now()-this.startTime-this.pausedTime}runningTimeUs(){return 4294967295&U.perfNowUs()-this.startTimeUs>>0}runFiberAsync(e,t,n,o){return new Promise(((r,i)=>U.nextTick((()=>{pxsim.runtime=this,this.setupTop(r),pxtcore.runAction(e,[t,n,o])}))))}currTryFrame(){for(let e=this.currFrame;e;e=e.parent)if(e.tryFrame)return e.tryFrame;return null}traceObjects(){const e={};for(;this.heapSnapshots.length>2;)this.heapSnapshots.shift();const t={count:0,size:0,name:"TOTAL"},n={TOTAL:t};function o(t,n,r=null){if(!(n instanceof pxsim.RefObject))return;const i=n;if(i.gcIsStatic())return;const s=e[i.id];if(s)return void(r&&s.pointers.push([r,t]));const a={obj:i,path:null,pointers:[[r,t]]};e[i.id]=a,i.scan(((t,n)=>{n instanceof pxsim.RefObject&&!e[n.id]&&o(t,n,a)}))}this.heapSnapshots.push({visited:e,statsByType:n});for(let e of Object.keys(this.globals))o(e.replace(/___\d+$/,""),this.globals[e]);const r=this.otherFrames.slice();this.currFrame&&r.indexOf(this.currFrame)<0&&r.unshift(this.currFrame);for(const e of this.getThreads()){const t="Thread-"+this.rootFrame(e).threadId;for(let n=e;n;n=n.parent){const e=t+"."+functionName(n.fn);for(let t of Object.keys(n))if(/^(r0|arg\d+|.*___\d+)/.test(t)){const r=n[t];r instanceof pxsim.RefObject&&(t=t.replace(/___.*/,""),o(e+"."+t,r))}if(n.caps)for(let t of n.caps)o(e+".cap",t)}}const i=Object.keys(e).map((t=>e[t]));i.sort(((e,t)=>t.obj.gcSize()-e.obj.gcSize()));const s=e=>{if(null!=e.path)return;let t="";e.path="(cycle)";for(let[n,o]of e.pointers){if(null==n)return void(e.path=o);s(n);const r=n.path+"."+o;(!t||t.length>r.length)&&(t=r)}e.path=t};i.forEach(s);const a=[t];for(const e of i){const o=e.obj.gcSize(),r=e.obj.gcKey();n.hasOwnProperty(r)||a.push(n[r]={count:0,size:0,name:r});const i=n[r];i.size+=o,i.count++,t.size+=o,t.count++}a.sort(((e,t)=>e.size-t.size));let l="";const c=e=>(" "+e.toString()).slice(-7);for(const e of a)l+=c(4*e.size)+c(e.count)+" "+e.name+"\n";const u=e=>c(4*e.obj.gcSize())+" "+e.obj.gcKey()+" "+e.path,d=i.slice(0,20).map(u).join("\n");let p="";if(this.heapSnapshots.length>=3){const e=this.heapSnapshots[this.heapSnapshots.length-3].visited,t=this.heapSnapshots[this.heapSnapshots.length-2].visited,o=e=>e instanceof pxsim.RefRecord&&!!(e.vtable&&e.vtable.maxBgInstances&&n[e.gcKey()].count<=e.vtable.maxBgInstances);p=i.filter((n=>!e[n.obj.id]&&t[n.obj.id])).filter((e=>!o(e.obj))).map(u).join("\n")}return"Threads:\n"+this.threadInfo()+"\n\nSummary:\n"+l+"\n\nLarge Objects:\n"+d+"\n\nNew Objects:\n"+p}getThreads(){const e=this.otherFrames.slice();return this.currFrame&&e.indexOf(this.currFrame)<0&&e.unshift(this.currFrame),e}rootFrame(e){let t=e;for(;t.parent;)t=t.parent;return t}threadInfo(){const e=this.getThreads();let t="";for(let n of e){t+=`Thread ${this.rootFrame(n).threadId}:\n`;for(let e of pxsim.getBreakpointMsg(n,n.lastBrkId).msg.stackframes){let n=e.funcInfo;t+=` at ${n.functionName} (${n.fileName}:${n.line+1}:${n.column+1})\n`}t+="\n"}return t}static postMessage(e){e&&("undefined"!=typeof window&&window.parent&&window.parent.postMessage&&window.parent.postMessage(e,"*"),Runtime.messagePosted&&Runtime.messagePosted(e))}static postScreenshotAsync(e){const t=pxsim.runtime&&pxsim.runtime.board;return(t?t.screenshotAsync().catch((e=>{console.debug("screenshot failed")})):Promise.resolve(void 0)).then((t=>Runtime.postMessage({type:"screenshot",data:t,delay:e&&e.delay})))}static requestToggleRecording(){const e=pxsim.runtime;e&&Runtime.postMessage({type:"recorder",action:e.recording?"stop":"start"})}restart(){this.kill(),setTimeout((()=>pxsim.Runtime.postMessage({type:"simulator",command:"restart"})),500)}kill(){this.dead=!0,this.stopRecording(),this.stopIdle(),this.setRunning(!1)}updateDisplay(){this.board.updateView(),this.postFrame()}startRecording(e){!this.recording&&this.running&&(this.recording=!0,this.recordingTimer=setInterval((()=>this.postFrame()),66),this.recordingLastImageData=void 0,this.recordingWidth=e)}stopRecording(){this.recording&&(this.recordingTimer&&clearInterval(this.recordingTimer),this.recording=!1,this.recordingTimer=0,this.recordingLastImageData=void 0,this.recordingWidth=void 0)}postFrame(){if(!this.recording||!this.running)return;let e=pxsim.U.now();this.board.screenshotAsync(this.recordingWidth).then((t=>{if(this.recordingLastImageData&&t&&this.recordingLastImageData.data.byteLength==t.data.byteLength){const e=this.recordingLastImageData.data,n=t.data,o=e.byteLength;let r=0;for(r=0;r<o&&e[r]==n[r];++r);if(r==o)return}this.recordingLastImageData=t,Runtime.postMessage({type:"screenshot",data:t,time:e})}))}queueDisplayUpdate(){this.numDisplayUpdates++}maybeUpdateDisplay(){this.numDisplayUpdates&&(this.numDisplayUpdates=0,this.updateDisplay())}setRunning(e){this.running!=e&&(this.running=e,this.running?(this.startTime=U.now(),this.startTimeUs=U.perfNowUs(),Runtime.postMessage({type:"status",frameid:pxsim.Embed.frameid,runtimeid:this.id,state:"running"})):(this.stopRecording(),this.stopIdle(),Runtime.postMessage({type:"status",frameid:pxsim.Embed.frameid,runtimeid:this.id,state:"killed"})),this.stateChanged&&this.stateChanged())}dumpLivePointers(){}setupPerfCounters(e){e&&e.length&&(this.perfCounters=e.map((e=>new PerfCounter(e))))}perfStartRuntime(){0!==this.perfOffset?this.perfStack++:this.perfOffset=U.perfNowUs()-this.perfElapsed}perfStopRuntime(){this.perfStack?this.perfStack--:(this.perfElapsed=this.perfNow(),this.perfOffset=0)}perfNow(){return 0===this.perfOffset&&U.userError("bad time now"),U.perfNowUs()-this.perfOffset|0}startPerfCounter(e){if(!this.perfCounters)return;const t=this.perfCounters[e];t.start&&U.userError("startPerf"),t.start=this.perfNow()}stopPerfCounter(e){if(!this.perfCounters)return;const t=this.perfCounters[e];t.start||U.userError("stopPerf");const n=this.perfNow()-t.start;t.start=0,t.value+=n,t.numstops++;let o=t.lastFewPtr++;o>=t.lastFew.length&&(o=0,t.lastFewPtr=1),t.lastFew[o]=n}startIdle(){void 0===this.idleTimer&&(this.idleTimer=setInterval((()=>{if(!this.running||this.pausedOnBreakpoint)return;const e=this.board.bus;e&&e.queueIdle()}),20))}stopIdle(){void 0!==this.idleTimer&&(clearInterval(this.idleTimer),this.idleTimer=void 0)}schedule(e,t){if(t<=0&&(t=0),this.pausedOnBreakpoint)return this.timeoutsPausedOnBreakpoint.push(new PausedTimeout(e,t)),-1;const n=U.now(),o=new TimeoutScheduled(-1,e,t,n);return o.id=setTimeout((()=>{const t=this.timeoutsScheduled.indexOf(o);t>=0&&this.timeoutsScheduled.splice(t,1),e()}),t),this.timeoutsScheduled.push(o),o.id}pauseScheduled(){this.pausedOnBreakpoint=!0,this.timeoutsScheduled.forEach((e=>{clearTimeout(e.id);let t=U.now()-e.timestampCall,n=e.totalRuntime-t;n<=0&&(n=1),this.timeoutsPausedOnBreakpoint.push(new PausedTimeout(e.fn,n))})),this.lastPauseTimestamp=U.now(),this.timeoutsScheduled=[]}resumeAllPausedScheduled(){this.pausedOnBreakpoint=!1,this.timeoutsPausedOnBreakpoint.forEach((e=>{this.schedule(e.fn,e.timeRemaining)})),this.lastPauseTimestamp&&(this.pausedTime+=U.now()-this.lastPauseTimestamp,this.lastPauseTimestamp=0),this.timeoutsPausedOnBreakpoint=[]}cleanScheduledExpired(){let e=U.now();this.timeoutsScheduled=this.timeoutsScheduled.filter((t=>{let n=e-t.timestampCall;return t.totalRuntime>n}))}}pxsim.Runtime=Runtime;class PerfCounter{constructor(e){this.name=e,this.start=0,this.numstops=0,this.value=0,this.lastFew=new Uint32Array(32),this.lastFewPtr=0}}pxsim.PerfCounter=PerfCounter}(pxsim||(pxsim={})),function(e){let t,n;!function(e){e[e.Unloaded=0]="Unloaded",e[e.Stopped=1]="Stopped",e[e.Pending=2]="Pending",e[e.Starting=3]="Starting",e[e.Running=4]="Running",e[e.Paused=5]="Paused",e[e.Suspended=6]="Suspended"}(t=e.SimulatorState||(e.SimulatorState={})),function(e){e[e.StepInto=0]="StepInto",e[e.StepOver=1]="StepOver",e[e.StepOut=2]="StepOut",e[e.Resume=3]="Resume",e[e.Pause=4]="Pause"}(n=e.SimulatorDebuggerCommand||(e.SimulatorDebuggerCommand={}));const o="pxtdriver";e.SimulatorDriver=class{constructor(n,o={}){this.container=n,this.options=o,this.themes=["blue","red","green","yellow"],this.runId="",this.nextFrameId=0,this.frameCounter=0,this.traceInterval=0,this.breakpointsSet=!1,this._runOptions={},this.state=t.Unloaded,this._allowedOrigins=[],this.frameCleanupTimeout=void 0,this.debuggerSeq=1,this.debuggerResolvers={},this._allowedOrigins.push(window.location.origin),o.parentOrigin&&this._allowedOrigins.push(o.parentOrigin),this._allowedOrigins.push(this.getSimUrl().origin);const r=null==o?void 0:o.messageSimulators;r&&Object.keys(r).map((e=>r[e])).forEach((e=>{this._allowedOrigins.push(new URL(e.url).origin),e.localHostUrl&&this._allowedOrigins.push(new URL(e.localHostUrl).origin)})),this._allowedOrigins=e.U.unique(this._allowedOrigins,(e=>e))}isDebug(){return this._runOptions&&!!this._runOptions.debug}isTracing(){return this._runOptions&&!!this._runOptions.trace}hasParts(){return this._runOptions&&this._runOptions.parts&&!!this._runOptions.parts.length}setDirty(){this.state==e.SimulatorState.Running&&this.suspend()}setPending(){this.setState(t.Pending)}focus(){const e=this.simFrames()[0];e&&e.focus()}registerDependentEditor(e){e&&(this._dependentEditors||(this._dependentEditors=[]),this._dependentEditors.push(e))}dependentEditors(){return this._dependentEditors&&(this._dependentEditors=this._dependentEditors.filter((e=>!!e.parent)),this._dependentEditors.length||(this._dependentEditors=void 0)),this._dependentEditors}setStarting(){this.setState(t.Starting)}setHwDebugger(e){e?(this.hwdbg=e,this.setState(t.Running),this.container.style.opacity="0.3"):(delete this.container.style.opacity,this.hwdbg=null,this.setState(t.Running),this.stop())}handleHwDebuggerMsg(e){this.hwdbg&&this.handleMessage(e)}setThemes(t){e.U.assert(t&&t.length>0),this.themes=t}startRecording(e){this.simFrames()[0]&&this.postMessage({type:"recorder",action:"start",source:o,width:e})}stopRecording(){this.postMessage({type:"recorder",source:o,action:"stop"})}setFrameState(n){const o=n.nextElementSibling,r=o.nextElementSibling;switch(this.state){case t.Pending:case t.Starting:o.style.display="",o.className="",r.style.display="";break;case t.Stopped:case t.Suspended:e.U.addClass(n,this.state==t.Stopped||this._runOptions&&this._runOptions.autoRun?this.stoppedClass:this.invalidatedClass),this._runOptions&&this._runOptions.autoRun?o.style.display="none":(o.style.display="",o.className="videoplay xicon icon"),r.style.display="none",this.scheduleFrameCleanup();break;default:e.U.removeClass(n,this.stoppedClass),e.U.removeClass(n,this.invalidatedClass),o.style.display="none",r.style.display="none"}}setState(e){this.state!=e&&(this.state=e,this.freeze(this.state==t.Paused),this.simFrames().forEach((e=>this.setFrameState(e))),this.options.onStateChanged&&this.options.onStateChanged(this.state))}freeze(t){const n="pause-overlay";t?e.util.toArray(this.container.querySelectorAll("div.simframe")).forEach((e=>{if(e.querySelector(`div.${n}`))return;const t=document.createElement("div");t.className=n,t.onclick=e=>(e.preventDefault(),!1),e.appendChild(t)})):e.util.toArray(this.container.querySelectorAll(`div.simframe div.${n}`)).forEach((e=>e.parentElement.removeChild(e)))}simFrames(t=!1){let n=e.util.toArray(this.container.getElementsByTagName("iframe"));const o=this.loanedIFrame();return o&&!t&&n.unshift(o),n}getSimUrl(){const e=this.options.simUrl||(window.pxtConfig||{}).simUrl||`${location.origin}/sim/simulator.html`;try{return new URL(e)}catch(t){return new URL(e,location.origin)}}postMessage(t,n,o){var r;if(this.hwdbg)return void this.hwdbg.postMessage(t);const i=this.dependentEditors();let s=this.simFrames();o&&(s=s.filter((e=>e.id===o)));const a=t;if(n&&(null==a?void 0:a.broadcast)){const o=!!(null===(r=this._currentRuntime)||void 0===r?void 0:r.single),a=window.parent&&window.parent!==window.window?window.parent:window.opener;if(this.options.nestedEditorSim&&a){if(n!==a){const e=this.options.parentOrigin||window.location.origin;a.postMessage(t,e)}}else if(i)i.forEach((e=>{n!==e&&e.postMessage(t,window.location.origin)}));else if(!o){const n="messagepacket"===t.type&&t.channel,o=n&&this.options.messageSimulators&&this.options.messageSimulators[n];if(o){let t=s.find((e=>e.dataset.messagechannel===n));if(t)t.dataset.runid!=this.runId&&this.startFrame(t);else{const r=(e.U.isLocalHost()&&/localhostmessagesims=1/i.test(window.location.href)&&o.localHostUrl||o.url).replace("$PARENT_ORIGIN$",encodeURIComponent(this.options.parentOrigin||""));let i=this.createFrame(r);this.container.appendChild(i),t=i.firstElementChild,t.dataset.messagechannel=n,e.U.addClass(i,"simmsg"),e.U.addClass(i,"simmsg"+n),o.permanent&&(t.dataset.permanent="true"),this.startFrame(t),s=this.simFrames()}}else{const e=s.filter((e=>!e.dataset.messagechannel));e.length<2?(this.container.appendChild(this.createFrame()),s=this.simFrames()):e[1].dataset.runid!=this.runId&&this.startFrame(e[1])}}}for(let e=0;e<s.length;++e){const o=s[e];if((!n||o.contentWindow!=n)&&(o.contentWindow&&(this.postMessageCore(o,t),"recorder"==t.type&&"start"==t.action)))break}}postMessageCore(t,n){var o,r,i,s;if(t.contentWindow.postMessage(n,t.dataset.origin),e.U.isLocalHostDev()&&(null===(r=null===(o=pxt)||void 0===o?void 0:o.appTarget)||void 0===r?void 0:r.id))try{t.contentWindow.postMessage(n,`https://trg-${null===(s=null===(i=pxt)||void 0===i?void 0:i.appTarget)||void 0===s?void 0:s.id}.userpxt.io/---simulator`)}catch(e){}}createFrame(n){const o=document.createElement("div");o.className="simframe ui embed";const r=document.createElement("iframe");r.id="sim-frame-"+this.nextId(),r.title=e.localization.lf("Simulator"),r.allowFullscreen=!0,r.setAttribute("allow","autoplay"),r.setAttribute("sandbox","allow-same-origin allow-scripts"),r.className="no-select";const i=(n||this.getSimUrl())+"#"+r.id;r.src=i,r.frameBorder="0",r.dataset.runid=this.runId,r.dataset.origin=new URL(i).origin||"*",o.appendChild(r);const s=document.createElement("i");s.className="videoplay xicon icon",s.style.display="none",s.onclick=e=>(e.preventDefault(),this.state!=t.Running&&this.state!=t.Starting&&(this.options.restart?this.options.restart():this.start()),r.focus(),!1),o.appendChild(s);const a=document.createElement("div");return a.className="ui active loader",s.style.display="none",o.appendChild(a),this._runOptions&&this.applyAspectRatioToFrame(r),o}preload(e){this.simFrames().length||(this.container.appendChild(this.createFrame()),this.applyAspectRatio(e),this.setStarting())}stop(e=!1,n=!1){this.clearDebugger(),this.postMessage({type:"stop",source:o}),this.setState(n?t.Starting:t.Stopped),e&&this.unload()}suspend(){this.postMessage({type:"stop",source:o}),this.setState(t.Suspended)}unload(){this.cancelFrameCleanup(),e.U.removeChildren(this.container),this.setState(t.Unloaded),this._runOptions=void 0,this._currentRuntime=void 0,this.runId=void 0}mute(e){this._currentRuntime&&(this._currentRuntime.mute=e),this.postMessage({type:"mute",source:o,mute:e})}stopSound(){this.postMessage({type:"stopsound",source:o})}isLoanedSimulator(e){return!!this.loanedSimulator&&this.loanedIFrame()==e}loanSimulator(){return this.loanedSimulator||(this.loanedSimulator=this.container.firstElementChild||this.createFrame(),this.loanedSimulator.parentNode&&this.container.removeChild(this.loanedSimulator)),this.loanedSimulator}unloanSimulator(){this.loanedSimulator&&(this.loanedSimulator.parentNode&&this.loanedSimulator.parentNode.removeChild(this.loanedSimulator),this.container.insertBefore(this.loanedSimulator,this.container.firstElementChild),delete this.loanedSimulator)}loanedIFrame(){return this.loanedSimulator&&this.loanedSimulator.parentNode&&this.loanedSimulator.querySelector("iframe")}cancelFrameCleanup(){this.frameCleanupTimeout&&(clearTimeout(this.frameCleanupTimeout),this.frameCleanupTimeout=void 0)}scheduleFrameCleanup(){this.cancelFrameCleanup(),this.frameCleanupTimeout=setTimeout((()=>{this.frameCleanupTimeout=void 0,this.cleanupFrames()}),5e3)}applyAspectRatio(e){if(!e&&!this._runOptions)return;this.simFrames().forEach((t=>this.applyAspectRatioToFrame(t,e)))}applyAspectRatioToFrame(e,t){var n,o,r,i;let s=t;if(void 0===s){const t=parseFloat(e.dataset.aspectratio);isNaN(t)||(s=t)}if(void 0===s){const t=e.dataset.messagechannel;if(t){const e=null===(r=null===(o=null===(n=this.options)||void 0===n?void 0:n.messageSimulators)||void 0===o?void 0:o[t])||void 0===r?void 0:r.aspectRatio;e&&(s=e)}}void 0===s&&(s=(null===(i=this._runOptions)||void 0===i?void 0:i.aspectRatio)||1.22),e.parentElement.style.paddingBottom=100/s+"%"}cleanupFrames(){const e=this.simFrames(!0);e.shift(),e.filter((e=>!e.dataset.permanent)).forEach((e=>{this.state!=t.Stopped&&e.dataset.runid==this.runId||(this.options.removeElement?this.options.removeElement(e.parentElement):e.parentElement.remove())}))}hide(e){if(this.suspend(),!this.options.removeElement)return;const t=this.simFrames();t.forEach((t=>{this.options.removeElement(t.parentElement,e)})),0==t.length&&e&&e()}unhide(){if(!this.options.unhideElement)return;this.simFrames().forEach((e=>{this.options.unhideElement(e.parentElement)}))}run(e,t={}){this._runOptions=t,this.runId=this.nextId(),this._currentRuntime={type:"run",source:o,boardDefinition:t.boardDefinition,parts:t.parts,builtinParts:t.builtinParts,fnArgs:t.fnArgs,code:e,partDefinitions:t.partDefinitions,mute:t.mute,highContrast:t.highContrast,light:t.light,cdnUrl:t.cdnUrl,localizedStrings:t.localizedStrings,refCountingDebug:t.refCountingDebug,version:t.version,clickTrigger:t.clickTrigger,breakOnStart:t.breakOnStart,storedState:t.storedState,ipc:t.ipc,single:t.single,dependencies:t.dependencies},this.start()}restart(){this.stop(),this.cleanupFrames(),this.start()}areBreakpointsSet(){return this.breakpointsSet}start(){if(this.clearDebugger(),this.addEventListeners(),this.applyAspectRatio(),this.scheduleFrameCleanup(),!this._currentRuntime)return;this.breakpointsSet=!1;let e=this.simFrames()[0];if(e)this.startFrame(e);else{let t=this.createFrame();this.container.appendChild(t),e=t.firstElementChild}this.debuggingFrame=e.id,this.setState(t.Running),this.setTraceInterval(this.traceInterval)}startFrame(e){if(!this._currentRuntime||!e.contentWindow)return!1;const t=JSON.parse(JSON.stringify(this._currentRuntime));return t.frameCounter=++this.frameCounter,t.options={theme:this.themes[this.nextFrameId++%this.themes.length]},t.id=`${t.options.theme}-${this.nextId()}`,e.dataset.runid=this.runId,e.dataset.runtimeid=t.id,e.id!==this.debuggingFrame&&(t.traceDisabled=!0,t.breakOnStart=!1),this.postMessageCore(e,t),this.traceInterval&&this.setTraceInterval(this.traceInterval),this.applyAspectRatioToFrame(e),this.setFrameState(e),!0}handleMessage(e,n){switch(e.type||""){case"ready":{const t=e.frameid,n=document.getElementById(t);n&&(this.startFrame(n),this.options.revealElement&&this.options.revealElement(n)),this.options.onSimulatorReady&&this.options.onSimulatorReady();break}case"status":{const n=e.frameid,o=document.getElementById(n);if(o){const n=e;if(n.runtimeid==o.dataset.runtimeid)switch(n.state){case"running":this.setState(t.Running);break;case"killed":this.setState(t.Stopped)}}break}case"simulator":this.handleSimulatorCommand(e);break;case"serial":case"pxteditor":case"screenshot":case"custom":case"recorder":case"addextensions":break;case"aspectratio":{const t=e,n=t.frameid,o=document.getElementById(n);o&&(o.dataset.aspectratio=t.value+"",this.applyAspectRatioToFrame(o));break}case"debugger":this.handleDebuggerMessage(e);break;case"toplevelcodefinished":this.options.onTopLevelCodeEnd&&this.options.onTopLevelCodeEnd();break;default:this.postMessage(e,n)}}addEventListeners(){this.listener||(this.listener=t=>{if(!this.hwdbg){if(e.U.isLocalHost());else if(this._allowedOrigins.indexOf(t.origin)<0)return;this.handleMessage(t.data,t.source)}},window.addEventListener("message",this.listener,!1))}removeEventListeners(){this.listener&&(window.removeEventListener("message",this.listener,!1),this.listener=void 0)}resume(e){let r;switch(e){case n.Resume:r="resume",this.setState(t.Running);break;case n.StepInto:r="stepinto",this.setState(t.Running);break;case n.StepOut:r="stepout",this.setState(t.Running);break;case n.StepOver:r="stepover",this.setState(t.Running);break;case n.Pause:r="pause";break;default:return void console.debug("unknown command")}this.postMessage({type:"debugger",subtype:r,source:o})}setBreakpoints(e){this.breakpointsSet=!0,this.postDebuggerMessage("config",{setBreakpoints:e},void 0,this.debuggingFrame)}setTraceInterval(e){this.traceInterval=e,this.postDebuggerMessage("traceConfig",{interval:e})}variablesAsync(e,t){return this.postDebuggerMessageAsync("variables",{variablesReference:e,fields:t},this.debuggingFrame).then((e=>e),(e=>{}))}handleSimulatorCommand(e){this.options.onSimulatorCommand&&this.options.onSimulatorCommand(e)}clearDebugger(){const e=new Error("Debugging cancelled");Object.keys(this.debuggerResolvers).forEach((t=>{const{reject:n}=this.debuggerResolvers[t];n(e)})),this.debuggerResolvers={},this.debuggerSeq++}handleDebuggerMessage(e){if("trace"!==e.subtype&&console.log("DBG-MSG",e.subtype,e),e.seq){const{resolve:t}=this.debuggerResolvers[e.seq];t&&t(e)}switch(e.subtype){case"warning":this.options.onDebuggerWarning&&this.options.onDebuggerWarning(e);break;case"breakpoint":{const o=e;if(this.state==t.Running){if(o.exceptionMessage)this.suspend();else{this.setState(t.Paused);this.simFrames(!0).length>1&&this.resume(n.Pause)}this.options.onDebuggerBreakpoint&&this.options.onDebuggerBreakpoint(o);let e=o.exceptionMessage+"\n";for(let t of o.stackframes){let n=t.funcInfo;e+=` at ${n.functionName} (${n.fileName}:${n.line+1}:${n.column+1})\n`}o.exceptionMessage&&console.error(e)}else console.error("debugger: trying to pause from "+this.state);break}case"trace":{const n=e;this.state==t.Running&&this.options.onTraceMessage&&this.options.onTraceMessage(n);break}default:const o=e.req_seq;if(o){const{resolve:t}=this.debuggerResolvers[o];t&&(delete this.debuggerResolvers[o],t(e))}}}postDebuggerMessageAsync(e,t={},n){return new Promise(((o,r)=>{const i=this.debuggerSeq++;this.debuggerResolvers[i.toString()]={resolve:o,reject:r},this.postDebuggerMessage(e,t,i,n)}))}postDebuggerMessage(e,t={},n,r){const i=JSON.parse(JSON.stringify(t));i.type="debugger",i.subtype=e,i.source=o,n&&(i.seq=n),this.postMessage(i,void 0,r)}nextId(){return this.nextFrameId+++(Math.random()+""+Math.random()).replace(/[^\d]/,"")}get stoppedClass(){return this.options&&this.options.stoppedClass||"grayscale"}get invalidatedClass(){return this.options&&this.options.invalidatedClass||"sepia"}}}(pxsim||(pxsim={})),function(e){e.mkRange=function(e,t){let n=[];for(;e<t;e++)n.push(e);return n};e.EventBus=class{constructor(e,t,n){this.runtime=e,this.board=t,this.valueToArgs=n,this.queues={},this.backgroundHandlerFlag=!1,this.nextNotifyEvent=1024,this.schedulerID=15,this.idleEventID=2,this.board.addMessageListener(this.handleMessage.bind(this))}handleMessage(e){if("eventbus"===e.type){const t=e;this.queue(t.id,t.eventid,t.value)}}setBackgroundHandlerFlag(){this.backgroundHandlerFlag=!0}setNotify(e,t){this.notifyID=e,this.notifyOneID=t}setIdle(e,t){this.schedulerID=e,this.idleEventID=t}start(t,n,o,r=!1){let i=(o?"back":"fore")+":"+t+":"+n;return!this.queues[i]&&r&&(this.queues[i]=new e.EventQueue(this.runtime,this.valueToArgs)),this.queues[i]}listen(e,t,n){e==this.schedulerID&&t==this.idleEventID&&this.runtime.startIdle();let o=this.start(e,t,this.backgroundHandlerFlag,!0);this.backgroundHandlerFlag?o.addHandler(n):o.setHandler(n),this.backgroundHandlerFlag=!1}removeBackgroundHandler(e){Object.keys(this.queues).forEach((t=>{t.startsWith("back:")&&this.queues[t].removeHandler(e)}))}getQueues(e,t,n){let o=[this.start(0,0,n)];return 0==e&&0==t||(t&&o.push(this.start(0,t,n)),e&&o.push(this.start(e,0,n)),e&&t&&o.push(this.start(e,t,n))),o}queue(t,n,o=null){if(e.runtime.pausedOnBreakpoint)return;const r=this.notifyID&&this.notifyOneID&&t==this.notifyOneID;r&&(t=this.notifyID);let i=this.getQueues(t,n,!0).concat(this.getQueues(t,n,!1));this.lastEventValue=n,this.lastEventTimestampUs=e.U.perfNowUs(),e.U.promiseMapAllSeries(i,(e=>e?e.push(o,r):Promise.resolve()))}queueIdle(){this.schedulerID&&this.idleEventID&&this.queue(this.schedulerID,this.idleEventID)}wait(e,t,n){this.start(e,t,!1,!0).addAwaiter(n)}getLastEventValue(){return this.lastEventValue}getLastEventTime(){return 4294967295&this.lastEventTimestampUs-e.runtime.startTimeUs}};let t;function n(){return"undefined"!=typeof window&&("ontouchstart"in window||navigator&&navigator.maxTouchPoints>0)}function o(){return"undefined"!=typeof window&&!!window.PointerEvent}e.AnimationQueue=class{constructor(e){this.runtime=e,this.queue=[],this.process=()=>{let t=this.queue[0];if(!t)return;if(this.runtime.dead)return;e=this.runtime;let n=t.frame();e.queueDisplayUpdate(),e.maybeUpdateDisplay(),!1===n?(this.queue.shift(),this.queue[0]&&(this.queue[0].setTimeoutHandle=setTimeout(this.process,this.queue[0].interval)),t.whenDone(!1)):t.setTimeoutHandle=setTimeout(this.process,t.interval)}}cancelAll(){let e=this.queue;this.queue=[];for(let t of e)t.whenDone(!0),t.setTimeoutHandle&&clearTimeout(t.setTimeoutHandle)}cancelCurrent(){let e=this.queue[0];e&&(this.queue.shift(),e.whenDone(!0),e.setTimeoutHandle&&clearTimeout(e.setTimeoutHandle))}enqueue(e){e.whenDone||(e.whenDone=()=>{}),this.queue.push(e),1==this.queue.length&&this.process()}executeAsync(t){return e.U.assert(!t.whenDone),new Promise(((e,n)=>{t.whenDone=e,this.enqueue(t)}))}},function(t){let n,o,r,i,s=0,a=!1;function l(){return n||(n=function(){if(window.AudioContext=window.AudioContext||window.webkitAudioContext,window.AudioContext)try{return new window.AudioContext}catch(e){}return}()),n}function c(){S(0),s=0,i&&i.pause()}function u(){c(),v()}function d(e,t){e.gain.value&&e.gain.setTargetAtTime(0,l().currentTime,.015),setTimeout((()=>{e.disconnect(),t&&t.disconnect()}),450)}t.mute=function(e){a=e,u();const t=l();!e&&t&&"suspended"===t.state&&t.resume()},t.stopAll=u,t.stop=function(){c(),function(){if(r){try{d(r,o)}catch(e){}r=void 0,o=void 0}}()},t.frequency=function(){return s};const p=[null,"triangle","sawtooth","sine"];let g,h,f=[],_=[];function m(e,t){let n,o=p[e];if(o){let e=l().createOscillator();return e.type=o,e.frequency.value=t,e}if(4==e)n=function(){if(!h){const e=131072;h=l().createBuffer(1,e,l().sampleRate);const t=h.getChannelData(0);let n=251771520;for(let o=0;o<e;o+=4)n^=n<<13,n^=n>>17,n^=n<<5,32768&n?(t[o]=1,t[o+1]=1,t[o+2]=-1,t[o+3]=-1):(t[o]=0,t[o+1]=0,t[o+2]=0,t[o+3]=0)}return h}();else if(5==e)n=function(){if(!g){const e=1e5;g=l().createBuffer(1,e,l().sampleRate);const t=g.getChannelData(0);let n=251771520;for(let o=0;o<e;o++)n^=n<<13,n^=n>>17,n^=n<<5,t[o]=(1023&n)/512-1}return g}();else if(11<=e&&e<=15)n=function(e){if(!_[e]){const t=1024,n=l().createBuffer(1,t,l().sampleRate),o=n.getChannelData(0);for(let n=0;n<t;n++)o[n]=n<e/100*t?1:-1;_[e]=n}return _[e]}(10*(e-10));else{if(!(16<=e&&e<=18))return null;n=function(e){if(!f[e]){const t=1024,n=l().createBuffer(1,t,l().sampleRate),o=n.getChannelData(0),r=[770763591,3356908179],i=[15,31,63];for(let n=0;n<t;n+=4){let t,s=n/4;s&=i[e-4],t=0!=(r[s>>5]&1<<(31&s)),t?(o[n]=1,o[n+1]=1,o[n+2]=-1,o[n+3]=-1):(o[n]=0,o[n+1]=0,o[n+2]=0,o[n+3]=0)}f[e]=n}return f[e]}(e-16+4)}let r=l().createBufferSource();r.buffer=n,r.loop=!0;return 4==e||16<=e&&e<=18?r.playbackRate.value=t/(l().sampleRate/4):5!=e&&(r.playbackRate.value=t/(l().sampleRate/1024)),r}const y=[];class k{mute(){this.gain?d(this.gain,this.generator):this.generator&&(this.generator.stop(),this.generator.disconnect()),this.gain=null,this.generator=null}remove(){const e=y.indexOf(this);e>=0&&y.splice(e,1),this.mute()}}let b=1;function v(){for(b++;y.length;)y[0].remove()}function T(t){const o=b;let r=l(),i=0,s=new k,c=-1,u=-1,d=0;y.length>5&&y[0].remove(),y.push(s);const p=(e,t)=>e/1024/4*(t?.5:1),g=()=>{s.mute(),d=0,c=-1,u=-1},h=()=>{if(i>=t.data.length||!t.data[i])return e.U.delay(d).then(g);const f=t.data[i],_=e.BufferMethods.getNumber(t,e.BufferMethods.NumberFormat.UInt16LE,i+2),y=e.BufferMethods.getNumber(t,e.BufferMethods.NumberFormat.UInt16LE,i+4),k=e.BufferMethods.getNumber(t,e.BufferMethods.NumberFormat.UInt16LE,i+6),v=e.BufferMethods.getNumber(t,e.BufferMethods.NumberFormat.UInt16LE,i+8),T=e.BufferMethods.getNumber(t,e.BufferMethods.NumberFormat.UInt16LE,i+10),E=11<=f&&f<=15,S=4==f||16<=f&&f<=18,C=p(k,E),x=p(v,E);if(!r||o!=b)return e.U.delay(y);if(c!=f||u!=_||_!=T){if(s.generator)return e.U.delay(d).then((()=>(g(),h())));if(s.generator=a?null:m(f,_),!s.generator)return e.U.delay(y);if(c=f,u=_,s.gain=r.createGain(),s.gain.gain.value=0,s.gain.gain.setTargetAtTime(C,n.currentTime,.015),T!=_)if(null!=s.generator.frequency){s.generator.frequency.linearRampToValueAtTime(T,r.currentTime+(d+y)/1e3)}else if(null!=s.generator.playbackRate){const e=S?4:1024;s.generator.playbackRate.linearRampToValueAtTime(T/(l().sampleRate/e),r.currentTime+(d+y)/1e3)}s.generator.connect(s.gain),s.gain.connect(r.destination),s.generator.start()}i+=12,s.gain.gain.setValueAtTime(C,r.currentTime+d/1e3),d+=y;const B=0!==x&&y>50?(d-50)/1e3:(d-10)/1e3;return s.gain.gain.linearRampToValueAtTime(x,r.currentTime+B),h()};return h().then((()=>s.remove()))}function E(e,t){if(e<0)return;s=e;let n=l();if(n){t=Math.max(0,Math.min(1,t));try{o||(o=n.createOscillator(),r=n.createGain(),r.gain.value=0,o.type="triangle",o.connect(r),r.connect(n.destination),o.start(0)),S(t)}catch(e){return o=void 0,void(r=void 0)}o.frequency.value=e,S(t)}}function S(e){(null==r?void 0:r.gain)&&r.gain.setTargetAtTime(a?0:e,n.currentTime,.015)}t.muteAllChannels=v,t.queuePlayInstructions=function(t,n){const o=b;e.U.delay(t).then((()=>o!=b?Promise.resolve():T(n)))},t.playInstructionsAsync=T,t.tone=E,t.setCurrentToneGain=S,t.playBufferAsync=function(e){return e?new Promise((t=>{function n(){t&&t(),t=void 0}const o="data:audio/wav;base64,"+window.btoa(function(e){let t=e.length,n="";for(let o=0;o<t;++o)n+=String.fromCharCode(e[o]);return n}(e.data));i=new Audio(o),a&&(i.volume=0),i.onended=()=>n(),i.onpause=()=>n(),i.onerror=()=>n(),i.play()})):Promise.resolve()};t.playPCMBufferStreamAsync=function(e,t,n=.3,o){return new Promise((r=>{let i=[],s=l().currentTime,c=!1;function u(){const t=o&&o();for(;!c&&i.length<3&&!t;){const t=e();if(!t||!t.length){c=!0;break}d(t)}c&&0===i.length&&(p.remove(),r&&r(),r=void 0)}function d(e){const n=l().createBuffer(1,e.length,t);if(n.copyToChannel)n.copyToChannel(e,0);else{const t=n.getChannelData(0);for(let n=0;n<e.length;n++)t[n]=e[n]}const o=l().createBufferSource();i.push(o),o.connect(p.gain),o.buffer=n,o.addEventListener("ended",(()=>{i.shift().disconnect(),u()})),o.start(s),s+=n.duration}const p=new k;p.gain=l().createGain(),p.gain.gain.value=0,a||p.gain.gain.setValueAtTime(n,l().currentTime),p.gain.connect(l().destination),y.length>5&&y[0].remove(),y.push(p),u()}))},t.sendMidiMessage=function(e){const t=e.data;if(!t.length)return;const n=t[0]>>4,o=15&t[0],r=t[1]||0,i=(s=r,440*Math.pow(2,(s-69)/12));var s;const a=t[2]||0;8==n||9==n&&0==a?c():9==n&&(E(i,1),9==o&&setTimeout((()=>c()),500))}}(t=e.AudioContextManager||(e.AudioContextManager={})),e.isTouchEnabled=n,e.hasPointerEvents=o,e.pointerEvents=o()?{up:"pointerup",down:["pointerdown"],move:"pointermove",enter:"pointerenter",leave:"pointerleave"}:n()?{up:"mouseup",down:["mousedown","touchstart"],move:"touchmove",enter:"touchenter",leave:"touchend"}:{up:"mouseup",down:["mousedown"],move:"mousemove",enter:"mouseenter",leave:"mouseleave"}}(pxsim||(pxsim={})),function(e){!function(t){function n(e,t){return n=>n*(t/e)}function o(e,t){let n=e[0]-t[0],o=e[1]-t[1];return n*n+o*o}t.translateEl=function(t,n){e.svg.hydrate(t,{transform:`translate(${n[0]} ${n[1]})`})},t.composeSVG=function(t){let[n,o]=[t.el1,t.el2];e.U.assert(0==n.x&&0==n.y&&0==o.x&&0==o.y,"el1 and el2 x,y offsets not supported");let r=(t,n,o)=>e.svg.hydrate(t,{x:n,y:o}),i=(t,n,o)=>e.svg.hydrate(t,{width:`${n}px`,height:`${o}px`}),s=t.scaleUnit2,a=t.scaleUnit2/t.scaleUnit1,l=n.w*a,c=n.h*a;i(n.el,l,c);let u=1*o.w,d=1*o.h;i(o.el,u,d);let[p,g,h,f]=t.margin,_=t.middleMargin,m=Math.max(l,u),y=g+(m-l)/2,k=p;r(n.el,y,k);let b=g+(m-u)/2,v=k+c+_;r(o.el,b,v);let T=[k,k+c,v,v+d],E=g+m+f,S=p+c+_+d+h,C=e.svg.elt("svg",{version:"1.0",viewBox:`0 0 ${E} ${S}`,class:"sim-bb"});((t,n,o)=>{n&&e.svg.hydrate(t,{width:n}),o&&e.svg.hydrate(t,{height:o})})(C,t.maxWidth,t.maxHeight),r(C,0,0);let x=e.svg.child(C,"g");return C.appendChild(n.el),C.appendChild(o.el),{under:x,over:e.svg.child(C,"g"),host:C,edges:T,scaleUnit:s,toHostCoord1:e=>{let[t,n]=e;return[t*a+y,n*a+k]},toHostCoord2:e=>{let[t,n]=e;return[1*t+b,1*n+v]}}},t.mkScaleFn=n,t.mkImageSVG=function(t){let o=n(t.imageUnitDist,t.targetUnitDist),r=o(t.width),i=o(t.height),s=e.svg.elt("image",{width:r,height:i});return s.setAttributeNS("http://www.w3.org/1999/xlink","href",`${t.image}`),{el:s,w:r,h:i,x:0,y:0}},t.findDistSqrd=o,t.findClosestCoordIdx=function(e,t){return t.map((t=>o(e,t))).reduce(((e,t,n,o)=>t<o[e]?n:e),0)},t.mkTxt=function(t,n,o,r,i,s,a){let l=e.svg.elt("text");a=a||.3;const c=(s=s||-.33333)*o*i.length,u=a*o;return e.svg.hydrate(l,{style:`font-size:${o}px;`,transform:`translate(${t} ${n}) rotate(${r}) translate(${c} ${u})`}),e.U.addClass(l,"noselect"),l.textContent=i,l},t.GPIO_WIRE_COLORS=["pink","orange","yellow","green","purple"],t.WIRE_COLOR_MAP={black:"#514f4d",white:"#fcfdfc",gray:"#acabab",purple:"#a772a1",blue:"#01a6e8",green:"#3cce73",yellow:"#ece600",orange:"#fdb262",red:"#f44f43",brown:"#c89764",pink:"#ff80fa"},t.mapWireColor=function(e){return t.WIRE_COLOR_MAP[e]||e},t.PIN_DIST=15,t.rgbToHsl=function(e){let t,n,o,[r,i,s]=e,[a,l,c]=[r/255,i/255,s/255],u=Math.min(a,l,c),d=Math.max(a,l,c),p=d-u,g=d+u;return o=g/2*100,0===p?n=t=0:(d===a?t=(l-c)/p%6*60:d===l?t=60*((c-a)/p+2):d===c&&(t=60*((a-l)/p+4)),n=o>50?p/(2-g)*100:p/g*100),[Math.floor(t),Math.floor(n),Math.floor(o)]}}(e.visuals||(e.visuals={}))}(pxsim||(pxsim={})),function(e){var t;!function(n){function o(e,n,o){let r={class:e,d:n};o&&(r.title=o);let i=t.elt("path");return t.hydrate(i,r),i}function r(e,n=!1){let o=t.elt("linearGradient");t.hydrate(o,{id:e,x1:"0%",y1:"0%",x2:n?"100%":"0%",y2:n?"0%":"100%"});t.child(o,"stop",{offset:"0%"}),t.child(o,"stop",{offset:"100%"}),t.child(o,"stop",{offset:"100%"}),t.child(o,"stop",{offset:"100%"});return o}function i(e){let n=t.elt("title");return n.textContent=e,n}n.parseString=function(e){return(new DOMParser).parseFromString(e,"image/svg+xml").getElementsByTagName("svg").item(0)},n.toDataUri=function(e){return"data:image/svg+xml,"+encodeURI(e)},n.cursorPoint=function(e,t,n){return e.x=null!=n.clientX?n.clientX:n.pageX,e.y=null!=n.clientY?n.clientY:n.pageY,e.matrixTransform(t.getScreenCTM().inverse())},n.rotateElement=function(e,t,n,o){e.setAttribute("transform",`translate(${t},${n}) rotate(${o+90}) translate(${-t},${-n})`)},n.hydrate=function(e,n){for(let o in n)"title"==o?t.title(e,n[o]):e.setAttributeNS(null,o,n[o])},n.elt=function(e,n){let o=document.createElementNS("http://www.w3.org/2000/svg",e);return n&&t.hydrate(o,n),o},n.child=function(e,n,o){let r=t.elt(n,o);return e.appendChild(r),r},n.mkPath=o,n.path=function(e,t,n,r){let i=o(t,n,r);return e.appendChild(i),i},n.fill=function(e,t){e.style.fill=t},n.filter=function(e,t){e.style.filter=t},n.fills=function(e,t){e.forEach((e=>e.style.fill=t))},n.isTouchEnabled=function(){return"undefined"!=typeof window&&("ontouchstart"in window||navigator.maxTouchPoints>0)},n.onClick=function(t,n){let o=!1;e.pointerEvents.down.forEach((e=>t.addEventListener(e,(e=>(o=!0,!0)),!1))),t.addEventListener(e.pointerEvents.up,(e=>!o||(o=!1,n(e),e.preventDefault(),!1)),!1)},n.buttonEvents=function(t,n,o,r,i){let s=!1;e.pointerEvents.down.forEach((e=>t.addEventListener(e,(e=>(s=!0,o&&o(e),!0)),!1))),t.addEventListener(e.pointerEvents.move,(e=>!s||(n&&n(e),e.preventDefault(),!1)),!1),t.addEventListener(e.pointerEvents.up,(e=>{s=!1,r&&r(e)}),!1),t.addEventListener(e.pointerEvents.leave,(e=>{s=!1,r&&r(e)}),!1),t.addEventListener("keydown",(e=>{s=!1,i&&i(e)}))},n.mkLinearGradient=r,n.linearGradient=function(e,t,n=!1){let o=r(t,n);return e.appendChild(o),o},n.setGradientColors=function(e,t,n){e&&(e.childNodes[0].style.stopColor=t,e.childNodes[1].style.stopColor=t,e.childNodes[2].style.stopColor=n,e.childNodes[3].style.stopColor=n)},n.setGradientValue=function(e,t){e.childNodes[1].getAttribute("offset")!=t&&(e.childNodes[1].setAttribute("offset",t),e.childNodes[2].setAttribute("offset",t))},n.animate=function(t,n){e.U.addClass(t,n);let o=t.parentElement;o&&(o.removeChild(t),o.appendChild(t))},n.mkTitle=i,n.title=function(e,t){let n=i(t);return e.appendChild(n),n},n.toHtmlColor=function(e){return`rgba(${e>>16&255}, ${e>>8&255}, ${255&e}, ${e>>24&1})`}}(t=e.svg||(e.svg={}))}(pxsim||(pxsim={})),function(e){class t{constructor(e){this.id=e}}e.Button=t;e.ButtonPairState=class{constructor(e){this.props=e,this.usesButtonAB=!1,this.aBtn=new t(this.props.ID_BUTTON_A),this.bBtn=new t(this.props.ID_BUTTON_B),this.abBtn=new t(this.props.ID_BUTTON_AB),this.abBtn.virtual=!0}}}(pxsim||(pxsim={})),function(e){e.CompassState=class{constructor(){this.usesHeading=!1,this.heading=90}}}(pxsim||(pxsim={})),function(e){e.FileSystemState=class{constructor(){this.files={}}append(e,t){this.files[e]=(this.files[e]||"")+t}remove(e){delete this.files[e]}}}(pxsim||(pxsim={})),function(e){e.LightSensorState=class{constructor(){this.usesLightLevel=!1,this.lightLevel=128}}}(pxsim||(pxsim={})),function(e){!function(t){t.mkBoardView=e=>{const n=e.visual;return new t.GenericBoardSvg({visualDef:n,boardDef:e.boardDef,wireframe:e.wireframe})};t.BoardHost=class{constructor(n,o){this.parts=[],this.boardView=n,this.opts=o,o.boardDef.pinStyles||(o.boardDef.pinStyles={}),this.state=o.state;let r=o.partsList,i=0<r.length||o.forceBreadboardLayout;if(i){this.breadboard=new t.Breadboard({wireframe:o.wireframe});const n=o.boardDef.marginWhenBreadboarding||[0,0,40,0],s=t.composeSVG({el1:this.boardView.getView(),scaleUnit1:this.boardView.getPinDist(),el2:this.breadboard.getSVGAndSize(),scaleUnit2:this.breadboard.getPinDist(),margin:[n[0],n[1],20,n[3]],middleMargin:n[2],maxWidth:o.maxWidth,maxHeight:o.maxHeight}),a=s.under,l=s.over;this.view=s.host;const c=s.edges;this.fromMBCoord=s.toHostCoord1,this.fromBBCoord=s.toHostCoord2,this.partGroup=l,this.partOverGroup=e.svg.child(this.view,"g"),this.style=e.svg.child(this.view,"style",{}),this.defs=e.svg.child(this.view,"defs",{}),this.wireFactory=new t.WireFactory(a,l,c,this.style,this.getLocCoord.bind(this),this.getPinStyle.bind(this));const u=e.allocateDefinitions({boardDef:o.boardDef,partDefs:o.partDefs,fnArgs:o.fnArgs,getBBCoord:this.breadboard.getCoord.bind(this.breadboard),partsList:r});u.partsAndWires.length||o.forceBreadboardLayout?(this.addAll(u),u.requiresBreadboard||o.forceBreadboardRender?u.hideBreadboard&&this.breadboard&&this.breadboard.hide():i=!1):i=!1}if(!i){delete this.breadboard,delete this.wireFactory,delete this.partOverGroup,delete this.partGroup,delete this.style,delete this.defs,delete this.fromBBCoord,delete this.fromMBCoord;const t=this.boardView.getView().el;this.view=t,this.partGroup=e.svg.child(this.view,"g"),this.partOverGroup=e.svg.child(this.view,"g"),o.maxWidth&&e.svg.hydrate(this.view,{width:o.maxWidth}),o.maxHeight&&e.svg.hydrate(this.view,{height:o.maxHeight})}this.state.updateSubscribers.push((()=>this.updateState()))}highlightBoardPin(e){this.boardView.highlightPin(e)}highlightBreadboardPin(e){this.breadboard.highlightLoc(e)}highlightWire(t){t.wires.forEach((t=>{e.U.addClass(t,"highlight"),t.style.visibility="visible"})),e.U.addClass(t.endG,"highlight")}getView(){return this.view}screenshotAsync(e){const t=this.view.cloneNode(!0);t.setAttribute("width",this.view.width.baseVal.value+""),t.setAttribute("height",this.view.height.baseVal.value+"");const n=(new XMLSerializer).serializeToString(t),o="data:image/svg+xml,"+encodeURIComponent(n.replace(/\s+/g," ").replace(/"/g,"'"));return new Promise(((t,n)=>{const r=document.createElement("img");r.onload=()=>{const n=document.createElement("canvas");n.width=r.width,n.height=r.height,e>0?(n.width=e,n.height=r.height*e/r.width|0):n.width<200?(n.width*=2,n.height*=2):n.width>480&&(n.width/=2,n.height/=2);const o=n.getContext("2d");o.drawImage(r,0,0,n.width,n.height),t(o.getImageData(0,0,n.width,n.height))},r.onerror=e=>{console.log(e),t(void 0)},r.src=o}))}updateState(){this.parts.forEach((e=>e.updateState()))}getBBCoord(e){let t=this.breadboard.getCoord(e);return this.fromBBCoord(t)}getPinCoord(e){let t=this.boardView.getCoord(e);if(t)return this.fromMBCoord(t);console.error(`Unable to find coord for pin: ${e}`)}getLocCoord(e){let t;if("breadboard"===e.type){let n=e;t=this.getBBCoord(n)}else{let n=e.pin;t=this.getPinCoord(n)}return t||console.debug("Unknown location: "+name),t}getPinStyle(e){return"breadboard"==e.type?"female":this.opts.boardDef.pinStyles[e.pin]||"female"}addPart(n){let o=null;if(n.simulationBehavior){let e=n.simulationBehavior,t=this.state.builtinVisuals[e],r=this.state.builtinParts[e];o=t(),o.init(this.state.bus,r,this.view,n.params)}else{let e=n.visual;o=new t.GenericPart(e)}this.parts.push(o),this.partGroup.appendChild(o.element),o.overElement&&this.partOverGroup.appendChild(o.overElement),o.defs&&o.defs.forEach((e=>this.defs.appendChild(e))),this.style.textContent+=o.style||"";let r=n.startColumnIdx,i=n.startRowIdx,s={type:"breadboard",row:t.getRowName(i),col:t.getColumnName(r),xOffset:n.bbFit.xOffset/n.visual.pinDistance,yOffset:n.bbFit.yOffset/n.visual.pinDistance},a=this.getBBCoord(s);o.moveToCoord(a);let l=`sim-${n.name}-cmp`;return e.U.addClass(o.element,l),e.U.addClass(o.element,"sim-cmp"),o.updateTheme(),o.updateState(),o}addWire(e){return this.wireFactory.addWire(e.start,e.end,e.color)}addAll(e){e.partsAndWires.forEach((t=>{const n=t.wires,o=n&&n.every((e=>this.wireFactory.checkWire(e.start,e.end)));o&&n.forEach((t=>e.wires.push(this.addWire(t))));let r=t.part;!r||n&&!o||e.parts.push(this.addPart(r))})),e.requiresBreadboard=!!e.wires.length||!!e.parts.length}}}(e.visuals||(e.visuals={}))}(pxsim||(pxsim={})),function(e){!function(t){const n=15,o="#DD4BA0",r=`\n /* bread board */\n .sim-bb-background {\n fill:#E0E0E0;\n }\n .sim-bb-pin {\n fill:#999;\n }\n .sim-bb-pin-hover {\n visibility: hidden;\n pointer-events: all;\n stroke-width: 7.5px;\n stroke: transparent;\n fill: #777;\n }\n .sim-bb-pin-hover:hover {\n visibility: visible;\n fill:#444;\n }\n .sim-bb-group-wire {\n stroke: #999;\n stroke-width: 3.75px;\n visibility: hidden;\n }\n .sim-bb-pin-group {\n pointer-events: all;\n }\n .sim-bb-label,\n .sim-bb-label-hover {\n font-family:"Lucida Console", Monaco, monospace;\n fill:#555;\n pointer-events: all;\n stroke-width: 0;\n cursor: default;\n }\n .sim-bb-label-hover {\n visibility: hidden;\n fill:#000;\n font-weight: bold;\n }\n .sim-bb-bar {\n stroke-width: 0;\n }\n .sim-bb-blue {\n fill:#1AA5D7;\n stroke:#1AA5D7\n }\n .sim-bb-red {\n fill:${o};\n stroke:${o};\n }\n .sim-bb-pin-group:hover .sim-bb-pin-hover,\n .sim-bb-pin-group:hover .sim-bb-group-wire,\n .sim-bb-pin-group:hover .sim-bb-label-hover {\n visibility: visible;\n }\n .sim-bb-pin-group:hover .sim-bb-label {\n visibility: hidden;\n }\n /* outline mode */\n .sim-bb-outline .sim-bb-background {\n stroke-width: ${n/7}px;\n fill: #FFF;\n stroke: #000;\n }\n .sim-bb-outline .sim-bb-mid-channel {\n fill: #FFF;\n stroke: #888;\n stroke-width: 2px;\n }\n /* grayed out */\n .grayed .sim-bb-background {\n stroke-width: 3px;\n }\n .grayed .sim-bb-red,\n .grayed .sim-bb-blue {\n fill: #BBB;\n }\n .grayed .sim-bb-bar {\n fill: #FFF;\n }\n .grayed .sim-bb-pin {\n fill: #000;\n stroke: #FFF;\n stroke-width: 3px;\n }\n .grayed .sim-bb-label {\n fill: none;\n }\n .grayed .sim-bb-background {\n stroke-width: 7.5px;\n stroke: #555;\n }\n .grayed .sim-bb-group-wire {\n stroke: #DDD;\n }\n .grayed .sim-bb-channel {\n visibility: hidden;\n }\n /* highlighted */\n .sim-bb-label.highlight {\n visibility: hidden;\n }\n .sim-bb-label-hover.highlight {\n visibility: visible;\n }\n .sim-bb-blue.highlight {\n fill:#1AA5D7;\n }\n .sim-bb-red.highlight {\n fill:${o};\n }\n .sim-bb-bar.highlight {\n stroke-width: 0px;\n }\n `;t.BREADBOARD_MID_ROWS=10,t.BREADBOARD_MID_COLS=30;const i=[4,4],s=t.BREADBOARD_MID_ROWS+i.length,a=25,l=[4,9,14,19],c=a+l.length,u=n*(t.BREADBOARD_MID_COLS+3),d=n*(s+4+5.5),p=2/3,g=d*p,h=.16666666666666669*d,f=(t.BREADBOARD_MID_COLS-1)*n,_=(u-f)/2,m=h+(g-(s-1)*n)/2,y=(c-1)*n,k=(u-y)/2,b=(h-15)/2,v=k,T=b+h+g,E=25.5,S=12,C=1.05,x=-90,B="abcdefghij".split("").reverse();function A(e){return`${e+1}`}function I(e){return B[e]}function D(t){let n=t.xOffset||0,o=t.yOffset||0,r=[],i=e.svg.elt("g"),s=t.colStartIdx||0,a=t.rowStartIdx||0,l=e=>e?e.slice(0,e.length):[],c=(e,t)=>{let n,o=0;for(;0<=(n=e.indexOf(t));)e.splice(n,1),o+=1;return o},u=0,d=l(t.rowIdxsWithGap);for(let p=0;p<t.rowCount;p++){let g=0,h=l(t.colIdxsWithGap),f=o+p*t.pinDist+u*t.pinDist,_=p+a;for(let o=0;o<t.colCount;o++){let a=n+o*t.pinDist+g*t.pinDist,l=o+s;const u=t=>(e.svg.hydrate(t.el,"circle"==t.el.tagName?{cx:a,cy:f}:{x:a-.5*t.w,y:f-.5*t.h}),i.appendChild(t.el),t.el);let d=u(t.mkPin()),p=u(t.mkHoverPin()),m=t.getRowName(_),y=t.getColName(l),k=t.getGroupName?t.getGroupName(_,l):null,b={el:d,hoverEl:p,cx:a,cy:f,row:m,col:y,group:k};r.push(b),g+=c(h,l)}u+=c(d,_)}return{g:i,allPins:r}}function N(){let t=e.svg.elt("rect");return e.svg.hydrate(t,{class:"sim-bb-pin",rx:2,ry:2,width:6,height:6}),{el:t,w:6,h:6,x:0,y:0}}function w(){let t=e.svg.elt("rect"),n=6*1.3;return e.svg.hydrate(t,{class:"sim-bb-pin-hover",rx:2,ry:2,width:n,height:n}),{el:t,w:n,h:n,x:0,y:0}}function R(n,o,r,i,s,a,l){let c=t.mkTxt(n,o,r,i,s);e.U.addClass(c,"sim-bb-label"),l&&l.forEach((t=>e.U.addClass(c,t)));let u=t.mkTxt(n,o,1.3*r,i,s);return e.U.addClass(u,"sim-bb-label-hover"),l&&l.forEach((t=>e.U.addClass(u,t))),{el:c,hoverEl:u,txt:s,group:a}}t.getColumnName=A,t.getRowName=I,t.mkGrid=D;t.Breadboard=class{constructor(t){this.allPins=[],this.allLabels=[],this.allPowerBars=[],this.rowColToPin={},this.rowColToLbls={},this.buildDom(),t.wireframe&&e.U.addClass(this.bb,"sim-bb-outline")}hide(){this.bb.style.display="none"}updateLocation(t,n){e.svg.hydrate(this.bb,{x:`${t}px`,y:`${n}px`})}getPin(e,t){let n=this.rowColToPin[e];if(!n)return null;let o=n[t];return o||null}getCoord(e){let{row:t,col:o,xOffset:r,yOffset:i}=e,s=this.getPin(t,o);if(!s)return null;let a=(r||0)*n,l=(i||0)*n;return[s.cx+a,s.cy+l]}getPinDist(){return n}buildDom(){this.bb=e.svg.elt("svg",{version:"1.0",viewBox:`0 0 ${u} ${d}`,class:"sim-bb",width:u+"px",height:d+"px"}),this.styleEl=e.svg.child(this.bb,"style",{}),this.styleEl.textContent+=r,this.defs=e.svg.child(this.bb,"defs",{}),e.svg.child(this.bb,"rect",{class:"sim-bb-background",width:u,height:d,rx:4.5,ry:4.5});let o="sim-bb-channel-grad",s=e.svg.elt("linearGradient");e.svg.hydrate(s,{id:o,x1:"0%",y1:"0%",x2:"0%",y2:"100%"}),this.defs.appendChild(s);e.svg.child(s,"stop",{offset:"0%",style:"stop-color: #AAA;"}),e.svg.child(s,"stop",{offset:"20%",style:"stop-color: #CCC;"}),e.svg.child(s,"stop",{offset:"80%",style:"stop-color: #CCC;"}),e.svg.child(s,"stop",{offset:"100%",style:"stop-color: #AAA;"});const c=(t,n,r)=>{let i=e.svg.child(this.bb,"rect",{class:`sim-bb-channel ${r||""}`,y:t-n/2,width:u,height:n});return i.setAttribute("fill",`url(#${o})`),i};c(h+g/2,15,"sim-bb-mid-channel"),c(h,.75,"sim-bb-sml-channel"),c(h+g,.75,"sim-bb-sml-channel");const p=(e,n)=>`${(e=>e<t.BREADBOARD_MID_ROWS/2?"b":"t")(e)}${A(n)}`,f=e=>0===e?"-":"+",B=(e,t)=>{let n=(e=>e<25?"b":"t")(t);return`${f(e)}${n}`};let O=D({xOffset:_,yOffset:m,rowCount:t.BREADBOARD_MID_ROWS,colCount:t.BREADBOARD_MID_COLS,pinDist:n,mkPin:N,mkHoverPin:w,getRowName:I,getColName:A,getGroupName:p,rowIdxsWithGap:i});O.g;this.allPins=this.allPins.concat(O.allPins);let P=D({xOffset:v,yOffset:T,rowCount:2,colCount:a,pinDist:n,mkPin:N,mkHoverPin:w,getRowName:f,getColName:A,getGroupName:B,colIdxsWithGap:l});P.g;this.allPins=this.allPins.concat(P.allPins);let L=D({xOffset:k,yOffset:b,rowCount:2,colCount:a,colStartIdx:a,pinDist:n,mkPin:N,mkHoverPin:w,getRowName:f,getColName:A,getGroupName:B,colIdxsWithGap:l.map((e=>e+a))});L.g;this.allPins=this.allPins.concat(L.allPins),this.allPins.forEach((t=>{let{el:n,row:o,col:r,hoverEl:i}=t,s=`(${o},${r})`;e.svg.hydrate(n,{title:s}),e.svg.hydrate(i,{title:s})})),this.allPins.forEach((e=>{let t=this.rowColToPin[e.row];t||(t=this.rowColToPin[e.row]={}),t[e.col]=e}));const M=(e,t,n,o,r,i)=>{let s=this.getCoord({type:"breadboard",row:e,col:t}),[a,l]=s;return R(a+n,l+o,10.5,-90,r,i)};for(let e=0;e<t.BREADBOARD_MID_COLS;e++){let n=A(e),o=0,r=M(I(o),n,0,-15,n,p(o,e));this.allLabels.push(r);let i=t.BREADBOARD_MID_ROWS-1,s=M(I(i),n,0,15,n,p(i,e));this.allLabels.push(s)}for(let e=0;e<t.BREADBOARD_MID_ROWS;e++){let n=I(e),o=M(n,A(0),-15,0,n);this.allLabels.push(o);let r=M(n,A(t.BREADBOARD_MID_COLS-1),15,0,n);this.allLabels.push(r)}let F=[R(13.05,h+g+S,30,x,"-",B(0,0),["sim-bb-blue"]),R(12,h+g+h-S,E,x,"+",B(1,0),["sim-bb-red"]),R(u-S+C,h+g+S,30,x,"-",B(0,24),["sim-bb-blue"]),R(u-S,h+g+h-S,E,x,"+",B(1,24),["sim-bb-red"])];this.allLabels=this.allLabels.concat(F);let U=[R(13.05,12,30,x,"-",B(0,a),["sim-bb-blue"]),R(12,h-S,E,x,"+",B(1,a),["sim-bb-red"]),R(u-S+C,12,30,x,"-",B(0,49),["sim-bb-blue"]),R(u-S,h-S,E,x,"+",B(1,49),["sim-bb-red"])];this.allLabels=this.allLabels.concat(U);let H={};this.allLabels.forEach((e=>{let{el:t,txt:n}=e;(H[n]=H[n]||[]).push(e)}));this.allPins.forEach((e=>{let{row:t,col:n,group:o}=e,r=this.rowColToLbls[t]||(this.rowColToLbls[t]={}),i=r[n]||(r[n]=[]);if((e=>"-"===e.row||"+"===e.row)(e)){Number(n)<=a?F.filter((t=>t.group==e.group)).forEach((e=>i.push(e))):U.filter((t=>t.group==e.group)).forEach((e=>i.push(e)))}else{H[t].forEach((e=>i.push(e))),H[n].forEach((e=>i.push(e)))}}));const V=y+22.5,G=(V-y)/2,W=(t,n,o,r)=>{let i=e.svg.elt("rect");return e.svg.hydrate(i,{class:`sim-bb-bar ${r}`,x:t,y:n-1.5,width:V,height:3}),{el:i,group:o}};let K=[W(v-G,T-9,B(0,49),"sim-bb-blue"),W(v-G,T+n+9,B(1,49),"sim-bb-red"),W(k-G,b-9,B(0,0),"sim-bb-blue"),W(k-G,b+n+9,B(1,0),"sim-bb-red")];this.allPowerBars=this.allPowerBars.concat(K),this.allPowerBars.forEach((e=>this.bb.appendChild(e.el)));let j=this.allPins.map((e=>e.group)).filter(((e,t,n)=>n.indexOf(e)==t)),z=j.map((t=>e.svg.elt("g")));z.forEach((t=>e.U.addClass(t,"sim-bb-pin-group"))),z.forEach(((t,n)=>e.U.addClass(t,`group-${j[n]}`)));let $={};j.forEach(((e,t)=>$[e]=z[t]));let X={};this.allPins.forEach(((e,t)=>{let n=e.group;(X[n]||(X[n]=[])).push(e)})),j.forEach((t=>{let n=X[t],[o,r]=[n.map((e=>e.cx)),n.map((e=>e.cy))],i=e=>e.reduce(((e,t)=>e<t?e:t)),s=e=>e.reduce(((e,t)=>e>t?e:t)),[a,l,c,u]=[i(o),s(o),i(r),s(r)],d=e.svg.elt("rect"),p=Math.max(l-a,1e-4),g=Math.max(u-c,1e-4);e.svg.hydrate(d,{x:a,y:c,width:p,height:g}),e.U.addClass(d,"sim-bb-group-wire"),$[t].appendChild(d)})),this.allPins.forEach((e=>{let t=$[e.group];t.appendChild(e.el),t.appendChild(e.hoverEl)}));let Y=e.svg.elt("g");e.svg.hydrate(Y,{class:"sim-bb-group-misc"}),z.push(Y),this.allLabels.forEach((e=>{if(e.group){let t=$[e.group];t.appendChild(e.el),t.appendChild(e.hoverEl)}else Y.appendChild(e.el),Y.appendChild(e.hoverEl)})),z.forEach((e=>this.bb.appendChild(e)))}getSVGAndSize(){return{el:this.bb,y:0,x:0,w:u,h:d}}highlightLoc(t){let{row:n,col:o}=t,r=this.rowColToPin[n][o],{cx:i,cy:s}=r;this.rowColToLbls[n][o].forEach((t=>{e.U.addClass(t.el,"highlight"),e.U.addClass(t.hoverEl,"highlight")}))}}}(e.visuals||(e.visuals={}))}(pxsim||(pxsim={})),function(e){!function(t){t.BOARD_SYTLE=`\n .noselect {\n -webkit-touch-callout: none; /* iOS Safari */\n -webkit-user-select: none; /* Chrome/Safari/Opera */\n -khtml-user-select: none; /* Konqueror */\n -moz-user-select: none; /* Firefox */\n -ms-user-select: none; /* Internet Explorer/Microsoft Edge */\n user-select: none; /* Non-prefixed version, currently\n not supported by any browser */\n }\n\n .sim-board-pin {\n fill:#999;\n stroke:#000;\n stroke-width:${t.PIN_DIST/3}px;\n }\n .sim-board-pin-lbl {\n fill: #333;\n }\n .gray-cover {\n fill:#FFF;\n opacity: 0.3;\n stroke-width:0;\n visibility: hidden;\n }\n .sim-board-pin-hover {\n visibility: hidden;\n pointer-events: all;\n stroke-width:${t.PIN_DIST/6}px;\n }\n .sim-board-pin-hover:hover {\n visibility: visible;\n }\n .sim-board-pin-lbl {\n visibility: hidden;\n }\n .sim-board-outline .sim-board-pin-lbl {\n visibility: visible;\n }\n .sim-board-pin-lbl {\n fill: #555;\n }\n .sim-board-pin-lbl-hover {\n fill: red;\n }\n .sim-board-outline .sim-board-pin-lbl-hover {\n fill: black;\n }\n .sim-board-pin-lbl,\n .sim-board-pin-lbl-hover {\n font-family:"Lucida Console", Monaco, monospace;\n pointer-events: all;\n stroke-width: 0;\n }\n .sim-board-pin-lbl-hover {\n visibility: hidden;\n }\n .sim-board-outline .sim-board-pin-hover:hover + .sim-board-pin-lbl,\n .sim-board-pin-lbl.highlight {\n visibility: hidden;\n }\n .sim-board-outline .sim-board-pin-hover:hover + * + .sim-board-pin-lbl-hover,\n .sim-board-pin-lbl-hover.highlight {\n visibility: visible;\n }\n /* Graying out */\n .grayed .sim-board-pin-lbl:not(.highlight) {\n fill: #AAA;\n }\n .grayed .sim-board-pin:not(.highlight) {\n fill:#BBB;\n stroke:#777;\n }\n .grayed .gray-cover {\n visibility: inherit;\n }\n .grayed .sim-cmp:not(.notgrayed) {\n opacity: 0.3;\n }\n /* Highlighting */\n .sim-board-pin-lbl.highlight {\n fill: #000;\n font-weight: bold;\n }\n .sim-board-pin.highlight {\n fill:#999;\n stroke:#000;\n }\n `;const n=.7*t.PIN_DIST,o=1.5*n,r=.66666*t.PIN_DIST,i=.66666*t.PIN_DIST+t.PIN_DIST/3;let s=0;t.GenericBoardSvg=class{constructor(a){this.props=a,this.allPins=[],this.allLabels=[],this.pinNmToLbl={},this.pinNmToPin={},this.id=s++;let l=a.visualDef,c=a.wireframe&&l.outlineImage?l.outlineImage:l.image,u=t.mkImageSVG({image:c,width:l.width,height:l.height,imageUnitDist:l.pinDist,targetUnitDist:t.PIN_DIST}),d=t.mkScaleFn(l.pinDist,t.PIN_DIST);this.width=u.w,this.height=u.h;let p=u.el;this.element=e.svg.elt("svg"),e.svg.hydrate(this.element,{version:"1.0",viewBox:`0 0 ${this.width} ${this.height}`,class:`sim sim-board-id-${this.id}`,x:"0px",y:"0px"}),a.wireframe&&e.U.addClass(this.element,"sim-board-outline"),this.style=e.svg.child(this.element,"style",{}),this.style.textContent+=t.BOARD_SYTLE,this.defs=e.svg.child(this.element,"defs",{}),this.g=e.svg.elt("g"),this.element.appendChild(this.g),this.g.appendChild(p),this.background=p,e.svg.hydrate(p,{class:"sim-board"});const g=()=>{let t=e.svg.elt("circle"),n=r;return e.svg.hydrate(t,{class:"sim-board-pin",r:n/2}),{el:t,w:n,h:n,x:0,y:0}},h=()=>{let t=e.svg.elt("circle"),n=i;return e.svg.hydrate(t,{class:"sim-board-pin-hover",r:n/2}),{el:t,w:n,h:n,x:0,y:0}},f=()=>{let t=e.svg.elt("rect"),n=r;return e.svg.hydrate(t,{class:"sim-board-pin",width:n,height:n}),{el:t,w:n,h:n,x:0,y:0}},_=()=>{let t=e.svg.elt("rect"),n=i;return e.svg.hydrate(t,{class:"sim-board-pin-hover",width:n,height:n}),{el:t,w:n,h:n,x:0,y:0}};let m=l.pinBlocks.map(((n,o)=>{let r=d(n.x)+t.PIN_DIST/2,i=d(n.y)+t.PIN_DIST/2,s=n.labels.length,a=t.mkGrid({xOffset:r,yOffset:i,rowCount:1,colCount:s,pinDist:t.PIN_DIST,mkPin:l.useCrocClips?g:f,mkHoverPin:l.useCrocClips?h:_,getRowName:()=>`${o+1}`,getColName:e=>n.labels[e],getGroupName:()=>n.labels.join(" ")});a.allPins,a.g;return e.U.addClass(a.g,"sim-board-pin-group"),a})),y=[];m.forEach(((e,t)=>e.allPins.forEach(((e,n)=>{this.allPins.push(e),y.push(l.pinBlocks[t])})))),this.allPins.forEach((t=>{let n=t.col;e.svg.hydrate(t.el,{title:n}),e.svg.hydrate(t.hoverEl,{title:n})})),this.allPins.forEach((e=>{this.pinNmToPin[e.col]=e}));const k=(e,n,o,r,i)=>{let s,a;if("below"===i){a=e,s=n+12+.25*o*r.length}else{a=e,s=n-11-.32*o*r.length}return t.mkTxt(a,s,o,-90,r)};this.allLabels=this.allPins.map(((t,r)=>{let i=y[r];return((t,r,i,s)=>{let a=k(t,r,n,i,s);e.U.addClass(a,"sim-board-pin-lbl");let l=k(t,r,o,i,s);return e.U.addClass(l,"sim-board-pin-lbl-hover"),{el:a,hoverEl:l,txt:i}})(t.cx,t.cy,t.col,i.labelPosition||"above")})),this.allPins.forEach(((e,t)=>{let n=this.allLabels[t];this.pinNmToLbl[e.col]=n})),this.allPins.forEach(((e,t)=>{let n=this.allLabels[t];this.g.appendChild(e.el),this.g.appendChild(e.hoverEl),this.g.appendChild(n.el),this.g.appendChild(n.hoverEl)}))}findPin(e){let t=this.pinNmToPin[e];return!t&&this.props.boardDef.gpioPinMap&&(e=this.props.boardDef.gpioPinMap[e])&&(t=this.pinNmToPin[e]),t}findPinLabel(e){let t=this.pinNmToLbl[e];return!t&&this.props.boardDef.gpioPinMap&&(e=this.props.boardDef.gpioPinMap[e])&&(t=this.pinNmToLbl[e]),t}getCoord(e){let t=this.findPin(e);return t?[t.cx,t.cy]:null}mkGrayCover(t,n,o,r){let i=e.svg.elt("rect");return e.svg.hydrate(i,{x:t,y:n,width:o,height:r,class:"gray-cover"}),i}getView(){return{el:this.element,w:this.width,h:this.height,x:0,y:0}}getPinDist(){return t.PIN_DIST}highlightPin(t){let n=this.findPinLabel(t),o=this.findPin(t);n&&o&&(e.U.addClass(n.el,"highlight"),e.U.addClass(n.hoverEl,"highlight"),e.U.addClass(o.el,"highlight"),e.U.addClass(o.hoverEl,"highlight"))}}}(e.visuals||(e.visuals={}))}(pxsim||(pxsim={})),function(e){!function(t){function n(e){return t.mkImageSVG({image:e.image,width:e.width,height:e.height,imageUnitDist:e.pinDistance,targetUnitDist:t.PIN_DIST})}t.mkGenericPartSVG=n;t.GenericPart=class{constructor(t){this.style="",this.defs=[];let o=n(t).el;this.element=e.svg.elt("g"),this.element.appendChild(o)}moveToCoord(e){t.translateEl(this.element,e)}init(e,t,n){}updateState(){}updateTheme(){}}}(e.visuals||(e.visuals={}))}(pxsim||(pxsim={})),function(e){!function(t){const n=t.PIN_DIST/2.5,o=.7;function r(e){return e.replace(/\#/g,"-").replace(/\(/g,"-").replace(/\)/g,"-").replace(/\,/g,"-").replace(/\./g,"-").replace(/\s/g,"")}let i;function s(t,n,o,r){const i=e=>`${e[0]}, ${e[1]}`;let[s,a]=t,[l,c]=n,u=c-a,d=[s,a+u*o],p=[l,c-u*o],g=e.svg.mkPath("sim-bb-wire",`M${i(t)} C${i(d)} ${i(p)} ${i(n)}`);return e.U.addClass(g,`wire-stroke-${r}`),g}function a(t,n,o){const r=e=>`${e[0]}, ${e[1]}`;let i=e.svg.mkPath("sim-bb-wire",`M${r(t)} L${r(n)}`);return e.U.addClass(i,`wire-stroke-${o}`),i}function l(o,r){const i=t.PIN_DIST/4;let s=e.svg.elt("circle"),a=o[0],l=o[1],c=n/2+i/2;return e.svg.hydrate(s,{cx:a,cy:l,r:c,class:"sim-bb-wire-end"}),e.U.addClass(s,`wire-fill-${r}`),s.style["stroke-width"]=`${i}px`,s}function c(n,o,r){let i=.24*t.PIN_DIST,s=10*i,a=2*i,l=6*i,c=i;const u=t.PIN_DIST/4;let[d,p]=n,g=o?-1:1,h=e.svg.elt("g"),f=e.svg.elt("rect"),_=s,m=a,y=d-m/2,k=p-_/2;e.svg.hydrate(f,{x:y,y:k,width:m,height:_,rx:.5,ry:.5,class:"sim-bb-wire-end"}),f.style["stroke-width"]=`${u}px`;let b=e.svg.elt("rect"),v=l,T=c,E=d-T/2,S=p+g*(_/2+v/2)-v/2;return e.svg.hydrate(b,{x:E,y:S,width:T,height:v,class:"sim-bb-wire-bare-end"}),b.style.fill="#bbb",h.appendChild(b),h.appendChild(f),{el:h,x:y-u,y:Math.min(k,S),w:m+2*u,h:_+v}}function u(n,o,r){let i=.24*t.PIN_DIST;const s=4*i,a=10*i,l=3.5*i,c=3.5*i,u=t.PIN_DIST/4;let[d,p]=n,g=o?-1:1,h=e.svg.elt("g"),f=e.svg.elt("polygon"),_=a,m=s,y=d-m/2,k=p-_/2;const b=o?.15:.3,v=o?.7:1-.7,T=o?.3:.15;e.svg.hydrate(f,{points:((...e)=>e.map((e=>(e=>`${e[0]},${e[1]}`)(e))).join(" "))([y+m*b,k],[y+m*(1-b),k],[y+m,k+_*v],[y+m*(1-T),k+_],[y+m*T,k+_],[y,k+_*v])}),e.svg.hydrate(f,{rx:.5,ry:.5,class:"sim-bb-wire-end"}),f.style["stroke-width"]=`${u}px`;let E=e.svg.elt("rect"),S=l,C=c,x=d-C/2,B=p+g*(_/2+S/2)-S/2;return e.svg.hydrate(E,{x:x,y:B,width:C,height:S,class:"sim-bb-wire-bare-end"}),h.appendChild(E),h.appendChild(f),{el:h,x:y-u,y:Math.min(k,B),w:m+2*u,h:_+S}}t.WIRES_CSS=`\n .sim-bb-wire {\n fill:none;\n stroke-linecap: round;\n stroke-width:${n}px;\n pointer-events: none;\n }\n .sim-bb-wire-end {\n stroke:#333;\n fill:#333;\n }\n .sim-bb-wire-bare-end {\n fill: #ccc;\n }\n .sim-bb-wire-hover {\n stroke-width: ${n}px;\n visibility: hidden;\n stroke-dasharray: ${t.PIN_DIST/10},${t.PIN_DIST/1.5};\n /*stroke-opacity: 0.4;*/\n }\n .grayed .sim-bb-wire-ends-g:not(.highlight) .sim-bb-wire-end {\n stroke: #777;\n fill: #777;\n }\n .grayed .sim-bb-wire:not(.highlight) {\n stroke: #CCC;\n }\n .sim-bb-wire-ends-g:hover .sim-bb-wire-end {\n stroke: red;\n fill: red;\n }\n .sim-bb-wire-ends-g:hover .sim-bb-wire-bare-end {\n stroke: #FFF;\n fill: #FFF;\n }\n `,function(e){e[e.BBJumper=0]="BBJumper",e[e.OpenJumper=1]="OpenJumper",e[e.Croc=2]="Croc"}(i=t.WireEndStyle||(t.WireEndStyle={})),t.mkWirePart=function(n,o,r=!1){let i,s=e.svg.elt("g"),[a,l]=n,d=[a-15,l-50],p=[a+15,l+50];o=t.mapWireColor(o),i=r?u(d,!0,o):c(d,!0,o);let g=function(t,n,o){const r=e=>`${e[0]}, ${e[1]}`;let[i,s]=t,[a,l]=n,c=l-s,u=[i,s+.8*c],d=[a,l-.8*c],p=e.svg.mkPath("sim-bb-wire",`M${r(t)} C${r(u)} ${r(d)} ${r(n)}`);return p.style.stroke=o,{el:p,x:Math.min(i,a),y:Math.min(s,l),w:Math.abs(i-a),h:Math.abs(s-l)}}(d,p,o),h=c(p,!1,o);s.appendChild(g.el),s.appendChild(i.el),s.appendChild(h.el);let f=Math.min(i.x,h.x),_=Math.max(i.x+i.w,h.x+h.w),m=Math.min(i.y,h.y);return{el:s,x:f,y:m,w:_-f,h:Math.max(i.y+i.h,h.y+h.h)-m}};t.WireFactory=class{constructor(e,n,o,r,i,s){this.nextWireId=0,this.styleEl=r,this.styleEl.textContent+=t.WIRES_CSS,this.underboard=e,this.overboard=n,this.boardEdges=o,this.getLocCoord=i,this.getPinStyle=s}indexOfMin(e){let t=0,n=e[0];for(let o=1;o<e.length;o++)e[o]<n&&(n=e[o],t=o);return t}closestEdgeIdx(e){let t=this.boardEdges.map((t=>Math.abs(e[1]-t)));return this.indexOfMin(t)}closestEdge(e){return this.boardEdges[this.closestEdgeIdx(e)]}drawWire(n,i,c){let u=[],d=e.svg.child(this.overboard,"g",{class:"sim-bb-wire-group"});const p=e=>{const n=t.PIN_DIST/2;let o,r=this.closestEdge(e);return o=r-e[1]<0?r-n:r+n,[e[0],o]};let g=this.nextWireId++,h=r(c),f=l(n,h),_=l(i,h),m=e.svg.child(d,"g",{class:"sim-bb-wire-ends-g"});m.appendChild(f),m.appendChild(_);let y=this.closestEdgeIdx(n),k=this.closestEdgeIdx(i);if(y==k){let e=a(n,i,h);d.appendChild(e),u.push(e)}else{let t,r,l=p(n),c=p(i),f=a(n,l,h),_=a(i,c,h);!(1!=y&&2!=y||1!=k&&2!=k)?(t=s(l,c,o,h),r=s(l,c,o,h)):(t=a(l,c,h),r=a(l,c,h)),e.U.addClass(r,"sim-bb-wire-hover"),d.appendChild(f),u.push(f),d.appendChild(_),u.push(_),this.underboard.appendChild(t),u.push(t),d.appendChild(r),u.push(r);let b=`sim-bb-wire-id-${g}`;const v=t=>e.U.addClass(t,b);v(m),v(r),this.styleEl.textContent+=`\n .${b}:hover ~ .${b}.sim-bb-wire-hover {\n visibility: visible;\n }`}let b=`\n .wire-stroke-${h} {\n stroke: ${t.mapWireColor(c)};\n }\n .wire-fill-${h} {\n fill: ${t.mapWireColor(c)};\n }\n `;return this.styleEl.textContent+=b,{endG:m,end1:f,end2:_,wires:u}}drawWireWithCrocs(n,i,c,d=!1){let p=[],g=e.svg.child(this.overboard,"g",{class:"sim-bb-wire-group"});const h=e=>{const n=t.PIN_DIST/2;let o,r=this.closestEdge(e);return o=r-e[1]<0?r-n:r+n,[e[0],o]};let f=this.nextWireId++,_=r(c),m=l(n,_),y=i,[k,b]=i;i=[k,b+40],[k,b]=i;let v,T=[k,b+-17];v=d?function(n,o,r){let i=.24*t.PIN_DIST,s=4*i,a=1.2*i,l=10*i,c=i;const u=t.PIN_DIST/4;let[d,p]=n,g=o?-1:1,h=e.svg.elt("g"),f=e.svg.elt("rect"),_=s,m=a,y=d-m/2,k=p+10-_/2;e.svg.hydrate(f,{x:y,y:k,width:m,height:_,rx:.5,ry:.5,class:"sim-bb-wire-end"}),f.style["stroke-width"]=`${u}px`;let b=e.svg.elt("rect"),v=l,T=c,E=d-T/2,S=p+10+g*(_/2+v/2)-v/2;return e.svg.hydrate(b,{x:E,y:S,width:T,height:v,class:"sim-bb-wire-bare-end"}),b.style.fill="#bbb",h.appendChild(b),h.appendChild(f),{el:h,x:y-u,y:Math.min(k,S),w:m+2*u,h:_+v}}(T,!0):u(T,!0);let E=v.el,S=e.svg.child(g,"g",{class:"sim-bb-wire-ends-g"});S.appendChild(m);let C=this.closestEdgeIdx(n),x=this.closestEdgeIdx(y);if(C==x){let e=a(n,i,_);g.appendChild(e),p.push(e)}else{let t,r,l=h(n),c=a(n,l,_);!(1!=C&&2!=C||1!=x&&2!=x)?(t=s(l,i,o,_),r=s(l,i,o,_)):(t=a(l,i,_),r=a(l,i,_)),e.U.addClass(r,"sim-bb-wire-hover"),g.appendChild(c),p.push(c),this.underboard.appendChild(t),p.push(t);let u=`sim-bb-wire-id-${f}`;const d=t=>e.U.addClass(t,u);d(S),d(r),this.styleEl.textContent+=`\n .${u}:hover ~ .${u}.sim-bb-wire-hover {\n visibility: visible;\n }`}S.appendChild(E);let B=`\n .wire-stroke-${_} {\n stroke: ${t.mapWireColor(c)};\n }\n .wire-fill-${_} {\n fill: ${t.mapWireColor(c)};\n }\n `;return this.styleEl.textContent+=B,{endG:S,end1:m,end2:E,wires:p}}checkWire(e,t){let n=this.getLocCoord(e),o=this.getLocCoord(t);return!!n&&!!o}addWire(e,t,n){let o=this.getLocCoord(e),r=this.getLocCoord(t);if(!o||!r)return void console.debug(`unable to allocate wire for ${e} or ${t}`);let i,s=this.getPinStyle(t);return i="dalboard"==t.type&&"croc"==s?this.drawWireWithCrocs(o,r,n):this.drawWire(o,r,n),i}}}(e.visuals||(e.visuals={}))}(pxsim||(pxsim={})),function(e){!function(t){t.startDebuggerAsync=function(e){new n(e).start()};class n{constructor(e){this.container=e,this.pkgLoaded=!1,this.intervalRunning=!1}start(){this.initializeWebsocket(),this.intervalRunning||(this.intervalRunning=!0,this.intervalId=setInterval((()=>{if(!this.ws)try{this.initializeWebsocket()}catch(e){console.warn(`Connection to server failed, retrying in ${n.RETRY_MS} ms`)}}),n.RETRY_MS)),this.session=new pxsim.SimDebugSession(this.container),this.session.start(this)}initializeWebsocket(){e.BrowserUtils.isLocalHost()&&e.Cloud.localToken&&(e.debug("initializing debug pipe"),this.ws=new WebSocket("ws://localhost:3234/"+e.Cloud.localToken+"/simdebug"),this.ws.onopen=t=>{e.debug("debug: socket opened")},this.ws.onclose=t=>{e.debug("debug: socket closed"),this.closeListener&&this.closeListener(),this.session.stopSimulator(),this.ws=void 0},this.ws.onerror=t=>{e.debug("debug: socket closed due to error"),this.errorListener&&this.errorListener(t.type),this.session.stopSimulator(),this.ws=void 0},this.ws.onmessage=t=>{let n;try{n=JSON.parse(t.data)}catch(t){e.debug("debug: could not parse message")}n&&("runner"===n.type?this.handleRunnerMessage(n):("request"===n.type&&"launch"===n.command&&this.sendRunnerMessage("configure",{projectDir:n.arguments.projectDir}),this.dataListener(n)))})}send(e){this.ws.send(e)}onData(e){this.dataListener=e}onError(e){this.errorListener=e}onClose(e){this.closeListener=e}close(){this.session&&this.session.stopSimulator(!0),this.intervalRunning&&(clearInterval(this.intervalId),this.intervalId=void 0),this.ws&&this.ws.close()}handleRunnerMessage(e){switch(e.subtype){case"ready":this.sendRunnerMessage("ready");break;case"runcode":this.runCode(e)}}runCode(t){const n=[];t.breakpoints.forEach((e=>{n.push([e.id,{verified:!0,line:e.line,column:e.column,endLine:e.endLine,endColumn:e.endColumn,source:{path:e.fileName}}])})),this.session.runCode(t.code,t.usedParts,t.usedArguments,new pxsim.BreakpointMap(n),e.appTarget.simulator.boardDefinition)}sendRunnerMessage(e,t={}){t.subtype=e,t.type="runner",this.send(JSON.stringify(t))}}n.RETRY_MS=2500,t.DebugRunner=n}(e.runner||(e.runner={}))}(pxt||(pxt={})),function(e){!function(t){function n(){return{blocksAspectRatio:window.innerHeight<window.innerWidth?1.62:1/1.62,snippetClass:"lang-blocks",signatureClass:"lang-sig",blocksClass:"lang-block",blocksXmlClass:"lang-blocksxml",diffBlocksXmlClass:"lang-diffblocksxml",diffClass:"lang-diff",diffStaticPythonClass:"lang-diffspy",diffBlocksClass:"lang-diffblocks",staticPythonClass:"lang-spy",simulatorClass:"lang-sim",linksClass:"lang-cards",namespacesClass:"lang-namespaces",apisClass:"lang-apis",codeCardClass:"lang-codecard",packageClass:"lang-package",jresClass:"lang-jres",assetJSONClass:"lang-assetsjson",projectClass:"lang-project",snippetReplaceParent:!0,simulator:!0,showEdit:!0,hex:!0,tutorial:!1,showJavaScript:!1,hexName:e.appTarget.id}}function o(e){"undefined"!=typeof hljs&&(e.hasClass("highlight")?hljs.highlightBlock(e[0]):e.find("code.highlight").each((function(e,t){hljs.highlightBlock(t)})),r(e))}function r(t){t.find("span.hljs-comment:contains(@highlight)").each(((t,n)=>{try{!function(e){const t=$(e),n=document.createElement("span");n.className="highlight-line";let o=e.nextSibling;if(!o||o.nodeType!=Node.TEXT_NODE)return;let r=o.textContent,i=r.indexOf("\n");if(i<0)return;o.textContent=r.substring(0,i+1),$(document.createTextNode(r.substring(i+1).replace(/^\s+/,""))).insertAfter($(o)),o=o.nextSibling;for(;o;){let e=o.nextSibling;if(o.nodeType==Node.TEXT_NODE){r=o.textContent;const t=r.indexOf("\n");if(!(t<0)){n.appendChild(document.createTextNode(r.substring(0,t))),o.textContent=r.substring(t+1);break}n.appendChild(o),o=e}else n.appendChild(o),o=e}$(n).insertAfter(t),t.remove()}(n)}catch(t){e.reportException(t)}}))}function i(e,t){e.append($('<div class="ui content blocks"/>').append(t))}function s(e,t,n){e.append($('<div class="ui content js"><div class="subheading"><i class="ui icon xicon js"></i>JavaScript</div></div>').append(t)),o(t)}function a(e,t,n){e.append($('<div class="ui content py"><div class="subheading"><i class="ui icon xicon python"></i>Python</div></div>').append(t)),o(t)}function l(e,t){const n=$('<a class="item" role="button" tabindex="0"><i role="presentation" aria-hidden="true"></i><span class="ui desktop only"></span></a>');return n.attr("aria-label",e),n.attr("title",e),n.find("i").attr("class",t),n.find("span").text(e),n.keypress((e=>{const t="number"==typeof e.which?e.which:e.keyCode;13!==t&&32!==t||(e.preventDefault(),e.currentTarget.click())})),n}function c(t,n,o,r,c,u,d={}){let p=$('<div class="ui bottom attached tabular icon small compact menu hideprint"> <div class="right icon menu"></div></div>'),g=$('<div class="ui top attached segment codewidget"></div>'),h=p.find(".right.menu");const f=e.appTarget.appTheme||{};if(d.showEdit&&!f.hideDocsEdit&&u){const n=l(lf("Edit"),"edit icon"),{package:o,compileBlocks:i,compilePython:s}=u,a=o.host();if(c&&i?(o.setPreferredEditor(e.BLOCKS_PROJECT_NAME),a.writeFile(o,e.MAIN_BLOCKS,i.outfiles[e.MAIN_BLOCKS])):r&&s?(o.setPreferredEditor(e.PYTHON_PROJECT_NAME),a.writeFile(o,e.MAIN_PY,i.outfiles[e.MAIN_PY])):o.setPreferredEditor(e.JAVASCRIPT_PROJECT_NAME),t.assetJSON)for(const e of Object.keys(t.assetJSON))o.config.files.indexOf(e)<0&&o.config.files.push(e),a.writeFile(o,e,t.assetJSON[e]);const d=o.compressToFileAsync();n.click((()=>{e.tickEvent("docs.btn",{button:"edit"}),d.then((n=>{window.open(`${function(t){return(t.pxtUrl||e.appTarget.appTheme.homeUrl||"").replace(/\/$/,"")}(t)}/#project:${ts.pxtc.encodeBase64(e.Util.uint8ArrayToString(n))}`,"pxt")}))})),h.append(n)}if(t.showJavaScript||!c&&!r?(g.append(o),m(),b()):c?(g.append(c),y(),b()):r&&(g.append(r),m(),y()),d.run&&!f.hideDocsSimulator){let n=l(lf("Run"),"play icon").click((()=>{if(e.tickEvent("docs.btn",{button:"sim"}),g.find(".sim")[0])g.find(".sim").remove(),v(g);else{let n="81.97%";e.appTarget.simulator&&(n=100/e.appTarget.simulator.aspectRatio+"%");const r=t.package?"&deps="+encodeURIComponent(t.package):"",i=k(t)+"#nofooter=1"+r,s=t.assetJSON?`data-assets="${encodeURIComponent(JSON.stringify(t.assetJSON))}"`:"",a=encodeURIComponent(o.text());let l=$(`<div class="ui card sim"><div class="ui content"><div style="position:relative;height:0;padding-bottom:${n};overflow:hidden;"><iframe style="position:absolute;top:0;left:0;width:100%;height:100%;" src="${i}" data-code="${a}" ${s} allowfullscreen="allowfullscreen" sandbox="allow-popups allow-forms allow-scripts allow-same-origin" frameborder="0"></iframe></div></div></div>`);g.append(l),v(l)}}));h.append(n)}if(d.hexname&&d.hex){let t=l(lf("Download"),"download icon").click((()=>{e.tickEvent("docs.btn",{button:"hex"}),e.BrowserUtils.browserDownloadBinText(d.hex,d.hexname,{contentType:e.appTarget.compile.hexMimeType})}));h.append(t)}let _=$("<div class=codesnippet></div>");function m(){if(!c)return;const t=l(lf("Blocks"),"icon xicon blocks").click((()=>{e.tickEvent("docs.btn",{button:"blocks"}),g.find(".blocks")[0]?(g.find(".blocks").remove(),v(g)):(i(o?o.parent():g,c),v(c))}));h.append(t)}function y(){if(o)if(d.showJs)s(g,o);else{const t=l("JavaScript","icon xicon js").click((()=>{e.tickEvent("docs.btn",{button:"js"}),g.find(".js")[0]?(g.find(".js").remove(),v(g)):(s(c?c.parent():g,o),v(o))}));h.append(t)}}function b(){if(r)if(d.showPy)a(g,r);else{const t=l("Python","icon xicon python").click((()=>{e.tickEvent("docs.btn",{button:"py"}),g.find(".py")[0]?(g.find(".py").remove(),v(g)):(a(c?c.parent():g,r),v(r))}));h.append(t)}}function v(e){var t;null===(t=e[0])||void 0===t||t.scrollIntoView({behavior:"smooth",block:"center"})}h.children().length&&_.append(p),_.append(g),n.replaceWith(_)}t.defaultClientRenderOptions=n;let u,d=[];function p(t,n,o){if(!t)return Promise.resolve();let r=$("."+t).first();return r[0]?(o.emPixels||(o.emPixels=18),o.layout||(o.layout=e.blocks.BlockLayout.Align),o.splitSvg=!0,d.push({el:r,source:r.text(),options:o,render:n}),r.addClass("lang-shadow"),r.removeClass(t),p(t,n,o)):Promise.resolve()}function g(e){if(!e||e.kind!=ts.SyntaxKind.ExpressionStatement)return null;let t=e;if(!t.expression||t.expression.kind!=ts.SyntaxKind.CallExpression)return null;let n=t.expression;return pxtc.pxtInfo(n).callInfo}function h(t){return u||(u=e.runner.decompileSnippetAsync("",t)),u}function f(t,n){if(!n)return;const o=/^\/(v\d+)/.exec(n.url),r=/^\/(v\d+)/.exec(window.location.pathname),i=/#doc/i.test(window.location.href);n.url&&!o&&r&&!i&&(n.url=`/${r[1]}/${n.url}`),t.append(e.docs.codeCard.render(n,{hideHeader:!0,shortName:!0}))}function _(t,n,o){const r=n.attributes,i=!r.blockHidden&&Blockly.Blocks[r.blockId];if(null==i?void 0:i.codeCard){const n=e.U.clone(i.codeCard);o&&(n.style=o),f(t,n)}else f(t,{name:n.qName,description:r.jsDoc,url:r.help||void 0,style:o})}function m(t,n,o,r){return p(n,((t,n)=>{const i=n.compileProgram;if(!i)return;const s=i.getSourceFile(e.MAIN_TS).statements.slice(0),a=$("<div />").addClass("ui cards");a.attr("role","listbox"),s.forEach((t=>{const o=t.kind,i=g(t);if(i&&n.apiInfo&&n.apiInfo.byQName[i.qName]){const e=n.apiInfo.byQName[i.qName],t=e.attributes,o=Blockly.Blocks[t.blockId];if(r){const r=e,i=n.compileBlocks.blocksInfo.apis.byQName[r.namespace];f(a,{name:i.attributes.blockNamespace||i.name,url:i.attributes.help||"reference/"+(i.attributes.blockNamespace||i.name).toLowerCase(),description:i.attributes.jsDoc,blocksXml:o&&o.codeCard?o.codeCard.blocksXml:t.blockId?`<xml xmlns="http://www.w3.org/1999/xhtml"><block type="${t.blockId}"></block></xml>`:void 0})}else _(a,e)}else switch(o){case ts.SyntaxKind.ExpressionStatement:{const n=t;switch(n.expression.kind){case ts.SyntaxKind.TrueKeyword:case ts.SyntaxKind.FalseKeyword:f(a,{name:"Boolean",url:"blocks/logic/boolean",description:lf("True or false values"),blocksXml:'<xml xmlns="http://www.w3.org/1999/xhtml"><block type="logic_boolean"><field name="BOOL">TRUE</field></block></xml>'});break;default:e.debug(`card expr kind: ${n.expression.kind}`)}break}case ts.SyntaxKind.IfStatement:f(a,{name:r?"Logic":"if",url:"blocks/logic"+(r?"":"/if"),description:lf(r?"Logic operators and constants":"Conditional statement"),blocksXml:'<xml xmlns="http://www.w3.org/1999/xhtml"><block type="controls_if"></block></xml>'});break;case ts.SyntaxKind.WhileStatement:f(a,{name:r?"Loops":"while",url:"blocks/loops"+(r?"":"/while"),description:lf(r?"Loops and repetition":"Repeat code while a condition is true."),blocksXml:'<xml xmlns="http://www.w3.org/1999/xhtml"><block type="device_while"></block></xml>'});break;case ts.SyntaxKind.ForOfStatement:f(a,{name:r?"Loops":"for of",url:"blocks/loops"+(r?"":"/for-of"),description:lf(r?"Loops and repetition":"Repeat code for each item in a list."),blocksXml:'<xml xmlns="http://www.w3.org/1999/xhtml"><block type="controls_for_of"></block></xml>'});break;case ts.SyntaxKind.BreakStatement:f(a,{name:r?"Loops":"break",url:"blocks/loops"+(r?"":"/break"),description:lf(r?"Loops and repetition":"Break out of the current loop."),blocksXml:'<xml xmlns="http://www.w3.org/1999/xhtml"><block type="break_keyword"></block></xml>'});break;case ts.SyntaxKind.ContinueStatement:f(a,{name:r?"Loops":"continue",url:"blocks/loops"+(r?"":"/continue"),description:lf(r?"Loops and repetition":"Skip iteration and continue the current loop."),blocksXml:'<xml xmlns="http://www.w3.org/1999/xhtml"><block type="continue_keyboard"></block></xml>'});break;case ts.SyntaxKind.ForStatement:{let e=t,n=!0;3==e.condition.getChildCount()&&(n=!("0"==e.condition.getChildAt(0).getText()||e.condition.getChildAt(1).kind==ts.SyntaxKind.LessThanToken)),f(a,n?{name:r?"Loops":"for",url:"blocks/loops"+(r?"":"/for"),description:lf(r?"Loops and repetition":"Repeat code for a given number of times using an index."),blocksXml:'<xml xmlns="http://www.w3.org/1999/xhtml"><block type="controls_simple_for"></block></xml>'}:{name:r?"Loops":"repeat",url:"blocks/loops"+(r?"":"/repeat"),description:lf(r?"Loops and repetition":"Repeat code for a given number of times."),blocksXml:'<xml xmlns="http://www.w3.org/1999/xhtml"><block type="controls_repeat_ext"></block></xml>'});break}case ts.SyntaxKind.VariableStatement:f(a,{name:r?"Variables":"variable declaration",url:"blocks/variables"+(r?"":"/assign"),description:lf(r?"Variables":"Assign a value to a named variable."),blocksXml:'<xml xmlns="http://www.w3.org/1999/xhtml"><block type="variables_set"></block></xml>'});break;default:e.debug(`card kind: ${o}`)}})),o&&(t=t.parent()),t.replaceWith(a)}),{package:t.package,aspectRatio:t.blocksAspectRatio,assets:t.assetJSON})}function y(t,n){if(!t)return Promise.resolve();let o=$("."+t).first();if(!o[0])return Promise.resolve();o.removeClass(t);const r=e.gallery.parseCodeCardsHtml(o[0]);return r||o.append($("<div/>").addClass("ui segment warning").text("invalid codecard format")),n.snippetReplaceParent&&(o=o.parent()),function(t,n,o){if(!n||0==n.length)return Promise.resolve();if(0==n.length){let r=e.docs.codeCard.render(n[0],o);t.replaceWith(r)}else{let r=document.createElement("div");r.className="ui cards",r.setAttribute("role","listbox"),n.forEach((t=>{const n=/^\/(v\d+)/.exec(t.url),i=/^\/(v\d+)/.exec(window.location.pathname),s=/#doc/i.test(window.location.href);t.url&&!n&&i&&!s&&(t.url=`/${i[1]}${t.url}`);const a=e.docs.codeCard.render(t,o);if(r.appendChild(a),"package"==t.cardType){const n=e.github.parseRepoId((t.url||"").replace(/^\/pkg\//,""));n&&e.packagesConfigAsync().then((i=>{switch(e.github.repoStatus(n,i)){case e.github.GitRepoStatus.Banned:a.remove();break;case e.github.GitRepoStatus.Approved:t.imageUrl=e.github.mkRepoIconUrl(n),r.insertBefore(e.docs.codeCard.render(t,o),a),a.remove()}})).catch((n=>{e.reportException(n),e.debug(`failed to load repo ${t.url}`)}))}})),t.replaceWith(r)}return Promise.resolve()}(o,r,{hideHeader:!0}).then((()=>e.U.delay(1,y(t,n))))}function k(t){return t.pxtUrl?t.pxtUrl+"/--run":e.webConfig&&e.webConfig.runUrl?e.webConfig.runUrl:"/--run"}function b(t){const n={showEdit:!!t.showEdit,run:!!t.simulator};$("code.lang-python").each(((o,i)=>{!function(o,i){"undefined"!=typeof hljs&&($(o).text($(o).text().replace(/^\s*\r?\n/,"")),hljs.highlightBlock(o),r($(o)));const s=e.U.clone(n);i&&(s.run=!1,s.showEdit=!1),c(t,$(o).parent(),$(o),void 0,void 0,void 0,s)}(i,!1),$(i).removeClass("lang-python")}))}t.renderAsync=function(t){return e.analytics.enable(),t||(t=n()),t.pxtUrl&&(t.pxtUrl=t.pxtUrl.replace(/\/$/,"")),t.showEdit&&(t.showEdit=!e.BrowserUtils.isIFrame()),function(e){e.packageClass&&($("."+e.packageClass).each(((t,n)=>{let o=$(n),r=o.text().split("\n").map((e=>e.replace(/\s*/g,""))).filter((e=>!!e)).join(",");e.package=e.package?`${e.package},${r}`:r,e.snippetReplaceParent&&(o=o.parent()),o.remove()})),$(".lang-config").each(((t,n)=>{let o=$(n);e.snippetReplaceParent&&(o=o.parent()),o.remove()})))}(t),function(t){let n,o;t.jresClass&&$(`.${t.jresClass}`).each(((e,t)=>{const n=$(t);o=n.text(),t.parentElement.remove()})),t.assetJSONClass&&$(`.${t.assetJSONClass}`).each(((e,t)=>{const o=$(t);n=o.text(),t.parentElement.remove()})),t.assetJSON=function(t,n){if(!t&&!n)return;const o=e.tutorial.parseAssetJson(t)||{};if(n){const t=JSON.parse(n);o[e.TILEMAP_JRES]=JSON.stringify(t),o[e.TILEMAP_CODE]=e.emitTilemapsFromJRes(t)}return o}(n,o)}(t),d=[],function(e){let t=$("code.lang-ghost");e.snippetReplaceParent&&(t=t.parent()),t.remove()}(t),function(t){t.simulatorClass&&$("."+t.simulatorClass).each(((n,o)=>{let r=$(o),i="81.97%";e.appTarget.simulator&&(i=100/e.appTarget.simulator.aspectRatio+"%");let s=$(`<div class="ui card"><div class="ui content">\n <div style="position:relative;height:0;padding-bottom:${i};overflow:hidden;">\n <iframe style="position:absolute;top:0;left:0;width:100%;height:100%;" allowfullscreen="allowfullscreen" frameborder="0" sandbox="allow-popups allow-forms allow-scripts allow-same-origin"></iframe>\n </div>\n </div></div>`);const a=t.package?"&deps="+encodeURIComponent(t.package):"",l=k(t)+"#nofooter=1"+a,c=encodeURIComponent(r.text().trim()),u=s.find("iframe");u.attr("src",l),u.attr("data-code",c),t.assetJSON&&u.attr("data-assets",JSON.stringify(t.assetJSON)),t.snippetReplaceParent&&(r=r.parent()),r.replaceWith(s)}))}(t),function(t){const n={showEdit:!!t.showEdit,run:!!t.simulator};function o(o,i){"undefined"!=typeof hljs&&($(o).text($(o).text().replace(/^\s*\r?\n/,"")),hljs.highlightBlock(o),r($(o)));const s=e.U.clone(n);i&&(s.run=!1,s.showEdit=!1),c(t,$(o).parent(),$(o),void 0,void 0,void 0,s)}$("code.lang-typescript").each(((e,t)=>{o(t,!1),$(t).removeClass("lang-typescript")})),$("code.lang-typescript-ignore").each(((e,t)=>{$(t).removeClass("lang-typescript-ignore"),$(t).addClass("lang-typescript"),o(t,!0),$(t).removeClass("lang-typescript")})),$("code.lang-typescript-invalid").each(((e,t)=>{$(t).removeClass("lang-typescript-invalid"),$(t).addClass("lang-typescript"),o(t,!0),$(t).removeClass("lang-typescript"),$(t).parent("div").addClass("invalid"),$(t).parent("div").prepend($("<i>",{class:"icon ban"})),$(t).addClass("invalid")})),$("code.lang-typescript-valid").each(((e,t)=>{$(t).removeClass("lang-typescript-valid"),$(t).addClass("lang-typescript"),o(t,!0),$(t).removeClass("lang-typescript"),$(t).parent("div").addClass("valid"),$(t).parent("div").prepend($("<i>",{class:"icon check"})),$(t).addClass("valid")}))}(t),b(t),Promise.resolve().then((()=>y(t.codeCardClass,t))).then((()=>function(t){return"core"==e.appTarget.id?Promise.resolve():h(t).then((t=>{let n={};const o=t.compileBlocks.blocksInfo;o.blocks.forEach((e=>{const t=(e.attributes.blockNamespace||e.namespace).split(".")[0];if(!n[t]){const e=o.apis.byQName[t];e&&e.attributes.color&&(n[t]=e.attributes.color)}}));let r="";return Object.keys(n).forEach((t=>{const o=n[t]||"#dddddd";r+=`\n span.docs.${t.toLowerCase()} {\n background-color: ${o} !important;\n border-color: ${e.toolbox.fadeColor(o,.1,!1)} !important;\n }\n `})),r})).then((t=>(Object.keys(e.toolbox.blockColors).forEach((n=>{const o=e.toolbox.getNamespaceColor(n);t+=`\n span.docs.${n.toLowerCase()} {\n background-color: ${o} !important;\n border-color: ${e.toolbox.fadeColor(o,.1,!1)} !important;\n }\n `})),t))).then((e=>{let t=document.createElement("style");t.id="namespaceColors",t.type="text/css",(document.head||document.getElementsByTagName("head")[0]).appendChild(t),t.appendChild(document.createTextNode(e))}))}(t))).then((()=>function(t){(t=e.Util.clone(t)).emPixels=18,t.snippetMode=!0;const n=$(":not(pre) > code");let o=0;return function r(){if(o>=n.length)return Promise.resolve();const i=$(n[o++]),s=i.text(),a=/^(\|+)([^\|]+)\|+$/.exec(s);if(a){const t=/^(([^\:\.]*?)[\:\.])?(.*)$/.exec(a[2]),n=t[2]?t[2].trim().toLowerCase():"",o=1==a[1].length?`docs inlinebutton ${n}`:`docs inlineblock ${n}`,s=t[3].trim();return i.replaceWith($(`<span class="${o}"/>`).text(e.U.rlf(s))),r()}const l=/^\[(.+)\]$/.exec(s);if(!l)return r();const c=l[1];return e.runner.decompileSnippetAsync(c,t).then((t=>{if(t.blocksSvg){let n=$('<span class="block"/>').append(t.blocksSvg);const o=g(t.compileProgram.getSourceFile(e.MAIN_TS).statements[0]);if(o&&t.apiInfo){const e=t.apiInfo.byQName[o.qName];e&&e.attributes.help&&(n=$('<a class="ui link"/>').attr("href",`/reference/${e.attributes.help}`).append(n))}i.replaceWith(n)}return e.U.delay(1,r())}))}()}(t))).then((()=>m(t,t.linksClass,t.snippetReplaceParent,!1))).then((()=>m(t,t.namespacesClass,t.snippetReplaceParent,!0))).then((()=>function(t,n){const o=t.apisClass;if(!o)return Promise.resolve();const r=$("."+o);return r.length?h(t).then((t=>{const o=t.compileBlocks.blocksInfo,i=e.Util.values(o.apis.byQName).filter((e=>!(e.attributes.hidden||e.attributes.deprecated||e.attributes.blockAliasFor||!e.attributes.jsDoc||!e.attributes.block||/^__/.test(e.name))));r.each(((t,o)=>{let r=$(o);const s=e.Util.toDictionary(r.text().split("\n"),(e=>e)),a=i.filter((e=>!!s[e.attributes.blockNamespace||e.namespace]));if(!a.length)return;a.sort(((e,t)=>{const n=!e.attributes.blockHidden&&Blockly.Blocks[e.attributes.blockId],o=!t.attributes.blockHidden&&Blockly.Blocks[t.attributes.blockId];return!!n!=!!o?(o?1:0)-(n?1:0):e.name.localeCompare(t.name)}));const l=$("<div />").addClass("ui divided items");l.attr("role","listbox"),a.forEach((e=>_(l,e,"item"))),n&&(r=r.parent()),r.replaceWith(l)}))})):Promise.resolve()}(t,t.snippetReplaceParent))).then((()=>function(t){return p(t.signatureClass,((n,o)=>{var r,i,s,a;let l=o.compileProgram;if(!l)return;let u=g(l.getSourceFile(e.MAIN_TS).statements[0]);if(!u||!o.apiInfo)return;const d=o.apiInfo.byQName[u.qName];if(!d)return;let p=Blockly.Blocks[d.attributes.blockId],h=(null===(r=null==p?void 0:p.codeCard)||void 0===r?void 0:r.blocksXml)||void 0;const f=h?e.blocks.render(h):(null===(i=o.compileBlocks)||void 0===i?void 0:i.success)?o.blocksSvg:void 0,_=f?$(f):void 0;let m=ts.pxtc.service.displayStringForSymbol(d,!1,o.apiInfo).split("\n")[1]+";";const y=$('<code class="lang-typescript highlight"/>').text(m),k=(null===(a=null===(s=e.appTarget)||void 0===s?void 0:s.appTheme)||void 0===a?void 0:a.python)&&ts.pxtc.service.displayStringForSymbol(d,!0,o.apiInfo).split("\n")[1],b=k&&$('<code class="lang-python highlight"/>').text(k);if(t.snippetReplaceParent&&(n=n.parent()),e.Util.isTranslationMode()){const e=$('<div class="ui segment" />');e.append($('<div class="ui header"><i class="ui xicon globe"></i></div>')),d.attributes.translationId&&e.append($('<div class="ui message">').text(d.attributes.translationId)),d.attributes.jsDoc&&e.append($('<div class="ui message">').text(d.attributes.jsDoc)),e.insertAfter(n)}c(t,n,y,b,_,o,{showJs:!0,showPy:!0,hideGutter:!0})}),{package:t.package,snippetMode:!0,aspectRatio:t.blocksAspectRatio,assets:t.assetJSON})}(t))).then((()=>function(t){if(t.tutorial)return p(t.snippetClass,((e,n)=>{const o=n.blocksSvg;t.snippetReplaceParent&&(e=e.parent());const r=$('<div class="ui segment codewidget"/>').append(o);e.replaceWith(r)}),{package:t.package,snippetMode:!1,aspectRatio:t.blocksAspectRatio,assets:t.assetJSON});let n=0;return p(t.snippetClass,((o,r)=>{const i=r.compileBlocks&&r.compileBlocks.success?$(r.blocksSvg):void 0,s=r.compilePython&&r.compilePython.success&&r.compilePython.outfiles[e.MAIN_PY],a=$('<code class="lang-typescript highlight"/>').text(o.text().trim()),l=s?$('<code class="lang-python highlight"/>').text(s.trim()):void 0;t.snippetReplaceParent&&(o=o.parent());const u=r.compileJS&&r.compileJS.success,d=t.hex&&u&&r.compileJS.outfiles[pxtc.BINARY_HEX]?r.compileJS.outfiles[pxtc.BINARY_HEX]:void 0,p=`${e.appTarget.nickname||e.appTarget.id}-${t.hexName||""}-${n++}.hex`;c(t,o,a,l,i,r,{showEdit:t.showEdit,run:t.simulator,hexname:p,hex:d})}),{package:t.package,aspectRatio:t.blocksAspectRatio,assets:t.assetJSON})}(t))).then((()=>function(e){return p(e.blocksClass,((t,n)=>{const o=n.blocksSvg;e.snippetReplaceParent&&(t=t.parent());const r=$('<div class="ui segment codewidget"/>').append(o);t.replaceWith(r)}),{package:e.package,snippetMode:!0,aspectRatio:e.blocksAspectRatio,assets:e.assetJSON})}(t))).then((()=>{return(n=t).blocksXmlClass?function t(n,o,r){let i=$("."+n).first();return i[0]?(r.emPixels||(r.emPixels=18),r.splitSvg=!0,e.runner.compileBlocksAsync(i.text(),r).then((s=>{try{o(i,s)}catch(t){e.reportException(t),i.append($("<div/>").addClass("ui segment warning").text(t.message))}return i.removeClass(n),e.U.delay(1,t(n,o,r))}))):Promise.resolve()}(n.blocksXmlClass,((e,t)=>{const o=t.blocksSvg;n.snippetReplaceParent&&(e=e.parent());const r=$('<div class="ui segment codewidget"/>').append(o);e.replaceWith(r)}),{package:n.package,snippetMode:!0,aspectRatio:n.blocksAspectRatio,assets:n.assetJSON}):Promise.resolve();var n})).then((()=>{return(n=t).diffBlocksXmlClass?function t(n,o,r){let i=$("."+n).first();if(!i[0])return Promise.resolve();r.emPixels||(r.emPixels=18),r.splitSvg=!0;const s=i.text().split(/-{10,}/),a=s[0],l=s[1];return e.runner.compileBlocksAsync("",r).then((s=>{i.removeClass(n);try{const t=e.blocks.diffXml(a,l);t?(s.blocksSvg=t.svg,o(i,s)):i.text("no changes")}catch(t){e.reportException(t),i.append($("<div/>").addClass("ui segment warning").text(t.message))}return e.U.delay(1,t(n,o,r))}))}(n.diffBlocksXmlClass,((e,t)=>{const o=t.blocksSvg;n.snippetReplaceParent&&(e=e.parent());const r=$('<div class="ui segment codewidget"/>').append(o);e.replaceWith(r)}),{package:n.package,snippetMode:!0,aspectRatio:n.blocksAspectRatio,assets:n.assetJSON}):Promise.resolve();var n})).then((()=>{return(n=t).diffBlocksClass?function t(o){let r=$("."+o).first();if(!r[0])return Promise.resolve();const{fileA:i,fileB:s}=e.diff.split(r.text(),{removeTrailingSemiColumns:!0});return e.U.promiseMapAllSeries([i,s],(t=>e.runner.decompileSnippetAsync(t,{generateSourceMap:!0}))).then((a=>{try{const t=e.blocks.decompiledDiffAsync(i,a[0].compileBlocks,s,a[1].compileBlocks,{hideDeletedTopBlocks:!0,hideDeletedBlocks:!0}),o=e.diff.render(i,s,{hideLineNumbers:!0,hideMarkerLine:!0,hideMarker:!0,hideRemoved:!0,update:!0,ignoreWhitespace:!0});let l;const[u,d]=a.map((t=>t.compilePython&&t.compilePython.outfiles&&t.compilePython.outfiles[e.MAIN_PY]));u&&d&&(l=e.diff.render(u,d,{hideLineNumbers:!0,hideMarkerLine:!0,hideMarker:!0,hideRemoved:!0,update:!0,ignoreWhitespace:!0})),c(n,r.parent(),$(o),l&&$(l),$(t.svg),void 0,{showEdit:!1,run:!1,hexname:void 0,hex:void 0})}catch(t){e.reportException(t),r.append($("<div/>").addClass("ui segment warning").text(t.message))}return e.U.delay(1,t(o))}))}(n.diffBlocksClass):Promise.resolve();var n})).then((()=>{return(n=t).diffClass?function t(o){let r=$("."+o).first();if(!r[0])return Promise.resolve();const{fileA:i,fileB:s}=e.diff.split(r.text());try{const t=e.diff.render(i,s,{hideLineNumbers:!0,hideMarkerLine:!0,hideMarker:!0,hideRemoved:!0,update:!0,ignoreWhitespace:!0});n.snippetReplaceParent&&(r=r.parent());const a=$('<div class="ui segment codewidget"/>').append(t);r.removeClass(o),r.replaceWith(a)}catch(t){e.reportException(t),r.append($("<div/>").addClass("ui segment warning").text(t.message))}return e.U.delay(1,t(o))}(n.diffClass):Promise.resolve();var n})).then((()=>function(t){const n={showEdit:!!t.showEdit,run:!!t.simulator};return p(t.staticPythonClass,((r,i)=>{const s=i.compilePython;if(s&&s.success){const a=r.clone().removeClass("lang-shadow").addClass("highlight"),l=a.clone().addClass("lang-python").text(s.outfiles[e.MAIN_PY]);a.addClass("lang-typescript"),o(l),c(t,r.parent(),a,l,void 0,i,n)}}),{package:t.package,snippetMode:!0,assets:t.assetJSON})}(t))).then((()=>function(t){return t.projectClass?function n(){let o=$("."+t.projectClass).first(),r=o[0];if(!r)return Promise.resolve();o.removeClass(t.projectClass);let i=e.Cloud.parseScriptId(r.innerText);if(i){if(t.snippetReplaceParent){r=r.parentElement;let e=document.createElement("div");r.parentElement.insertBefore(e,r),r.parentElement.removeChild(r),r=e}return e.runner.renderProjectAsync(r,i).then((()=>n()))}return n()}():Promise.resolve()}(t))).then((()=>function(){const t={};return function n(){const o=d.shift();if(!o)return Promise.resolve();const{el:r,options:i,render:s}=o;return e.runner.decompileSnippetAsync(r.text(),i).then((n=>{const o=n.compileJS&&n.compileJS.diagnostics&&n.compileJS.diagnostics.filter((e=>e.category==pxtc.DiagnosticCategory.Error));o&&o.length&&o.forEach((t=>e.reportError("docs.decompile",""+t.messageText,{code:t.code+""}))),n.blocksSvg.querySelectorAll("defs *").forEach((e=>{t[e.id]?e.remove():t[e.id]=!0})),s(r,n)}),(t=>{e.reportException(t),r.append($("<div/>").addClass("ui segment warning").text(t.message))})).finally((()=>(r.removeClass("lang-shadow"),n())))}().then((()=>{Blockly.Workspace.getAll().forEach((e=>e.dispose())),e.blocks.cleanRenderingWorkspace()}))}()))}}(e.runner||(e.runner={}))}(pxt||(pxt={})),function(e){!function(t){class n{constructor(e,t){this.ksPkg=e,this.topPkg=t,this.files={}}getKsPkg(){return this.ksPkg}getPkgId(){return this.ksPkg?this.ksPkg.id:this.id}isTopLevel(){return this.ksPkg&&0==this.ksPkg.level}setFiles(e){this.files=e}getAllFiles(){return e.Util.mapMap(this.files,((e,t)=>t))}}class o{constructor(){this.githubPackageCache={}}readFile(t,n){let o=l(t);return e.U.lookup(o.files,n)}writeFile(e,t,n){l(e).files[t]=n}getHexInfoAsync(t){return e.hexloader.getHexInfoAsync(this,t)}cacheStoreAsync(e,t){return Promise.resolve()}cacheGetAsync(e){return Promise.resolve(null)}patchDependencies(t,n,o){if(!o)return!1;const r=e.github.parseRepoId(o);if(!r)return!1;for(const n of Object.keys(t.dependencies)){const i=t.dependencies[n],s=e.github.parseRepoId(i);if(s&&r.fullName==s.fullName)return e.semver.strcmp(r.tag,s.tag)<0&&(t.dependencies[n]=o),!0}return!1}downloadPackageAsync(t,n){let o,r=t.verProtocol();"github"==r&&(o=this.githubPackageCache[t._verspec]);let i=l(t);return(o?Promise.resolve(o):t.commonDownloadAsync()).then((s=>{if(s)return"github"!=r||o||(this.githubPackageCache[t._verspec]=e.Util.clone(s)),i.setFiles(s),Promise.resolve();if("empty"==r){if(0==Object.keys(i.files).length&&i.setFiles(c()),n&&n.length){const o=l(t).files,r=JSON.parse(o[e.CONFIG_NAME]);n.forEach((e=>{a(r,e)})),o[e.CONFIG_NAME]=e.Package.stringifyConfig(r)}return Promise.resolve()}if("docs"==r){let n=c(),o=JSON.parse(n[e.CONFIG_NAME]);return t.verArgument().split(",").forEach((e=>{a(o,e)})),o.yotta||(o.yotta={}),o.yotta.ignoreConflicts=!0,n[e.CONFIG_NAME]=e.Package.stringifyConfig(o),i.setFiles(n),Promise.resolve()}return"invalid"==r?(e.log(`skipping invalid pkg ${t.id}`),Promise.resolve()):Promise.reject(`Cannot download ${t.version()}; unknown protocol`)}))}}let r,i,s;function a(e,t){let n=/^([a-zA-Z0-9_-]+)(=(.+))?$/.exec(t);if(n){if(n[3]&&this&&this.patchDependencies(e,n[1],n[3]))return!1;e.dependencies[n[1]]=n[3]||"*"}else console.warn(`unknown package syntax ${t}`);return!0}function l(e){let o=e._editorPkg;if(o)return o;let r=null;e!=t.mainPkg&&(r=l(t.mainPkg));let i=new n(e,r);return e==t.mainPkg&&(i.topPkg=i),e._editorPkg=i,i}function c(){let t=e.appTarget.tsprj,n=e.U.clone(t.files);return n[e.CONFIG_NAME]=e.Package.stringifyConfig(t.config),n[e.MAIN_BLOCKS]="",n}function u(){e.setAppTarget(window.pxtTargetBundle),e.Util.assert(!!e.appTarget);const n=window.location.href;let r,i=!1;if(/[&?]translate=1/.test(n)&&!e.BrowserUtils.isIE())r=ts.pxtc.Util.TRANSLATION_LOCALE,i=!0,e.Util.enableLiveLocalizationUpdates();else{const t=/PXT_LANG=(.*?)(?:;|$)/.exec(document.cookie),o=/(live)?(force)?lang=([a-z]{2,}(-[A-Z]+)?)/i.exec(n);r=o?o[3]:t&&t[1]||e.appTarget.appTheme.defaultLocale||navigator.userLanguage||navigator.language;const s=e.appTarget.appTheme.defaultLocale,a=null==r?void 0:r.toLocaleLowerCase(),l=e.BrowserUtils.isLocalHostDev()&&(!a||(s?s.toLocaleLowerCase()===a:"en"===a||"en-us"===a));(e.BrowserUtils.isPxtElectron()||l||e.appTarget.appTheme.disableLiveTranslations)&&!(null==o?void 0:o[1])||e.Util.enableLiveLocalizationUpdates(),i=!!o&&!!o[2]}const s=e.appTarget.versions;$&&$.fn&&$.fn.embed&&$.fn.embed.settings&&$.fn.embed.settings.sources&&$.fn.embed.settings.sources.youtube&&($.fn.embed.settings.sources.youtube.url="//www.youtube.com/embed/{id}?rel=0");const a=e.webConfig;return e.Util.updateLocalizationAsync({targetId:e.appTarget.id,baseUrl:a.commitCdnUrl,code:r,pxtBranch:s?s.pxtCrowdinBranch:"",targetBranch:s?s.targetCrowdinBranch:"",force:i}).then((()=>{t.mainPkg=new e.MainPackage(new o)}))}function d(e){console.error(e)}function p(n,o,r){const s=n?/\w+:\w+/.test(n)?n:"pub:"+n:"empty:tsprj";let a,c,u;return i&&i._verspec==s?(t.mainPkg=i,a=t.mainPkg.host(),c=Promise.resolve(),u=Promise.resolve()):(a=t.mainPkg.host(),t.mainPkg=new e.MainPackage(a),t.mainPkg._verspec=n?/\w+:\w+/.test(n)?n:"pub:"+n:"empty:tsprj",c=a.downloadPackageAsync(t.mainPkg,r),u=t.mainPkg.installAllAsync(),i=t.mainPkg),c.then((()=>a.readFile(t.mainPkg,e.CONFIG_NAME))).then((n=>n?u.then((()=>{if(o){let n=l(t.mainPkg);n.files[e.MAIN_TS]=o;let r=JSON.parse(n.files[e.CONFIG_NAME]);r.name=window.location.href.split("/").pop().split(/[?#]/)[0],n.files[e.CONFIG_NAME]=e.Package.stringifyConfig(r),t.mainPkg.config.name=r.name,-1==t.mainPkg.config.files.indexOf(e.MAIN_BLOCKS)&&t.mainPkg.config.files.push(e.MAIN_BLOCKS)}})).catch((e=>{d(lf("Cannot load extension: {0}",e.message))})):Promise.resolve()))}function g(e){let n=t.mainPkg.getTargetOptions();return n.isNative=!!e,n.hasHex=!!e,t.mainPkg.getCompileOptionsAsync(n)}function h(e,t){return g(e).then((e=>{t&&t(e);let n=pxtc.compile(e);return n.diagnostics&&n.diagnostics.length>0&&n.diagnostics.forEach((e=>{console.error(e.messageText)})),n}))}async function f(n){var o;await p(n.id,n.code,n.dependencies);let r=!1;const i=e.appTarget.versions.target;let s=await h(!1,(o=>{var s;if(n.assets){const t=JSON.parse(n.assets);for(const n of Object.keys(t)){const r=t[n];if(o.fileSystem[n]=r,o.sourceFiles.indexOf(n)<0&&o.sourceFiles.push(n),/\.jres$/.test(n)){const t=JSON.parse(r);o.jres=e.inflateJRes(t,o.jres)}}}if(n.code&&(o.fileSystem[e.MAIN_TS]=n.code),o.target.preferredEditor===e.PYTHON_PROJECT_NAME){o.target.preferredEditor=e.JAVASCRIPT_PROJECT_NAME,o.ast=!0;const t=S(pxtc.compile(o).ast,o);o.apisInfo=t,o.target.preferredEditor=e.PYTHON_PROJECT_NAME}const a=null===(s=t.mainPkg.config.targetVersions)||void 0===s?void 0:s.target;if(a&&i&&e.semver.cmp(e.semver.parse(a),e.semver.parse(i))<0)for(const t of Object.keys(o.fileSystem))!e.Util.startsWith(t,"pxt_modules")&&e.Util.endsWith(t,".ts")&&(r=!0,o.fileSystem[t]=e.patching.patchJavaScript(a,o.fileSystem[t]))}));return(null===(o=s.diagnostics)||void 0===o?void 0:o.length)>0&&r&&(e.log("Compile with upgrade rules failed, trying again with original code"),s=await h(!1,(t=>{n.code&&(t.fileSystem[e.MAIN_TS]=n.code)}))),s.diagnostics&&s.diagnostics.length>0&&console.error("Diagnostics",s.diagnostics),pxtc.buildSimJsInfo(s)}function _(e){let t={};try{let n=window.localStorage.getItem(e);n&&(t=JSON.parse(n))}catch(e){}return t}function m(n,o){if(t.editorLanguageMode=n,o!=e.Util.localeInfo()){const t=/^live-/;return t.test(o)&&e.Util.enableLiveLocalizationUpdates(),e.Util.updateLocalizationAsync({targetId:e.appTarget.id,baseUrl:e.webConfig.commitCdnUrl,code:o.replace(t,""),pxtBranch:e.appTarget.versions.pxtCrowdinBranch,targetBranch:e.appTarget.versions.targetCrowdinBranch})}return Promise.resolve()}function y(t){let n=t.data;if(n)switch(n.type){case"fileloaded":let t=n,o=t.name;m(/\.ts$/i.test(o)?s.TypeScript:s.Blocks,t.locale);break;case"popout":let r=/((\/v[0-9+])\/)?[^\/]*#(doc|md):([^&?:]+)/i.exec(window.location.href);if(r){const t=e.webConfig.docsUrl||"/--docs";let n=r[2]||"",o="doc"==r[3]?e.webConfig.isStatic?`/docs${r[4]}.html`:`${r[4]}`:`${t}?md=${r[4]}`;window.parent&&window.parent.postMessage({type:"opendoc",url:e.BrowserUtils.urlJoin(n,o)},"*")}break;case"localtoken":let i=n;i&&i.localToken&&(e.Cloud.localToken=i.localToken,C.forEach((e=>e())),C=[])}}function k(t,n){return e.Cloud.privateGetTextAsync(n+"/text").then((e=>JSON.parse(e))).then((e=>b(t,e,n)))}function b(n,o,r=null,i=!1){const a=JSON.parse(o[e.CONFIG_NAME])||{};let l=`# ${a.name} ${a.version?a.version:""}\n\n`;const c="README.md";o[c]&&(l+=o[c].replace(/^#+/,"$0#")+"\n"),a.files.filter((t=>t!=e.CONFIG_NAME&&t!=c)).filter((e=>t.editorLanguageMode==s.Blocks==/\.blocks?$/.test(e))).forEach((e=>{/^main\.(ts|blocks)$/.test(e)||(l+=`\n## ${e}\n`),/\.ts$/.test(e)?l+=`\`\`\`typescript\n${o[e]}\n\`\`\`\n`:/\.blocks?$/.test(e)?l+=`\`\`\`blocksxml\n${o[e]}\n\`\`\`\n`:l+=`\`\`\`${e.substr(e.indexOf("."))}\n${o[e]}\n\`\`\`\n`}));const u=a&&a.dependencies&&Object.keys(a.dependencies).filter((t=>t!=e.appTarget.corepkg));if(u&&u.length&&(l+=`\n## ${lf("Extensions")} #extensions\n\n${u.map((e=>`* ${e}, ${a.dependencies[e]}`)).join("\n")}\n\n\`\`\`package\n${u.map((e=>`${e}=${a.dependencies[e]}`)).join("\n")}\n\`\`\`\n`),r){let t=(e.appTarget.appTheme.shareUrl||"https://makecode.com/")+r;i&&(t="`"+t+"`"),l+=`\n${t}\n\n`}console.debug(`print md: ${l}`);return v(n,l,{print:!0})}e.react.getTilemapProject||(e.react.getTilemapProject=()=>(r||(r=new e.TilemapProject,r.loadPackage(t.mainPkg)),r)),t.initFooter=function(t,n){if(!t)return;let o=e.appTarget.appTheme,r=$("body"),i=$(t),s=$("<a/>").attr("href",o.homeUrl).attr("target","_blank");i.append(s),o.organizationLogo?s.append($("<img/>").attr("src",e.Util.toDataUri(o.organizationLogo))):s.append(lf("powered by {0}",o.title)),r.mouseenter((e=>i.fadeOut())),r.mouseleave((e=>i.fadeIn()))},t.showError=d,t.generateHexFileAsync=function(t){return p(t.id).then((()=>h(!0,(n=>{t.code&&(n.fileSystem[e.MAIN_TS]=t.code)})))).then((e=>(e.diagnostics&&e.diagnostics.length>0&&console.error("Diagnostics",e.diagnostics),e.outfiles[pxtc.BINARY_HEX])))},t.generateVMFileAsync=function(t){return e.setHwVariant("vm"),p(t.id).then((()=>h(!0,(n=>{t.code&&(n.fileSystem[e.MAIN_TS]=t.code)})))).then((e=>(console.log(e),e)))},t.simulateAsync=async function(t,n){var o,r;const i=n.builtJsInfo||await f(n),{js:s,fnArgs:a,parts:l,usedBuiltinParts:c}=i;if(!s)return void console.error("Program failed to compile");let u={};u.onSimulatorCommand=e=>{"restart"===e.command&&(h.storedState=_(n.id),d.run(s,h)),"setstate"==e.command&&e.stateKey&&e.stateValue&&function(e,t,n){let o=_(e);if(!e)return;n?o[t]=n:delete o[t];try{window.localStorage.setItem(e,JSON.stringify(o))}catch(e){}}(n.id,e.stateKey,e.stateValue)},u.messageSimulators=null===(r=null===(o=e.appTarget)||void 0===o?void 0:o.simulator)||void 0===r?void 0:r.messageSimulators;let d=new pxsim.SimulatorDriver(t,u),p=e.appTarget.simulator.boardDefinition,g=_(n.id),h={boardDefinition:p,parts:l,builtinParts:c,fnArgs:a,cdnUrl:e.webConfig.commitCdnUrl,localizedStrings:e.Util.getLocalizedStrings(),highContrast:n.highContrast,storedState:g,light:n.light,single:n.single};return e.appTarget.simulator&&!n.fullScreen&&(h.aspectRatio=l.length&&e.appTarget.simulator.partsAspectRatio?e.appTarget.simulator.partsAspectRatio:e.appTarget.simulator.aspectRatio),d.run(s,h),i},t.buildSimJsInfo=f,function(e){e[e.Blocks=0]="Blocks",e[e.TypeScript=1]="TypeScript"}(s=t.LanguageMode||(t.LanguageMode={})),t.editorLanguageMode=s.Blocks,t.setEditorContextAsync=m,t.startRenderServer=function(){e.tickEvent("renderer.ready");const n=[];let o;function r(){if(o)return;const i=n.shift();if(!i)return;const s=i.options||{};s.splitSvg=!1,e.tickEvent("renderer.job");const a=/^\s*<xml/.test(i.code);o=(async()=>{await e.BrowserUtils.loadBlocklyAsync();const n=(a?await e.runner.compileBlocksAsync(i.code,s):await t.decompileSnippetAsync(i.code,i.options)).blocksSvg,o=n.viewBox.baseVal.width,r=n.viewBox.baseVal.height,l=n?await e.blocks.layout.blocklyToSvgAsync(n,0,0,o,r):void 0;let c;try{c=l?await e.BrowserUtils.encodeToPngAsync(l.xml,{width:o,height:r}):void 0}catch(e){console.warn(e)}window.parent.postMessage({source:"makecode",type:"renderblocks",id:i.id,width:null==l?void 0:l.width,height:null==l?void 0:l.height,svg:null==l?void 0:l.svg,uri:c||(null==l?void 0:l.xml),css:null==l?void 0:l.css},"*")})().catch((e=>{window.parent.postMessage({source:"makecode",type:"renderblocks",id:i.id,error:e.message},"*")})).finally((()=>{o=void 0,r()}))}e.editor.initEditorExtensionsAsync().then((()=>{window.addEventListener("message",(function(e){const t=e.data;"renderblocks"==t.type&&(n.push(t),r())}),!1),window.parent.postMessage({source:"makecode",type:"renderready",versions:e.appTarget.versions},"*")}))},t.startDocsServer=function(t,n,o){e.tickEvent("docrenderer.ready");const r=[];function i(r,s){e.debug(`rendering ${r}`),o&&$(o).hide(),$(n).hide(),$(t).show(),e.U.delay(100).then((()=>{switch(r){case"print":const t=window.localStorage.printjob;return delete window.localStorage.printjob,b(n,JSON.parse(t),void 0,!0).then((()=>pxsim.print(1e3)));case"project":return b(n,JSON.parse(s)).then((()=>pxsim.print(1e3)));case"projectid":return k(n,JSON.parse(s)).then((()=>pxsim.print(1e3)));case"doc":return function(t,n){return n=n.replace(/^\//,""),e.Cloud.markdownAsync(n).then((e=>v(t,e,{path:n})))}(n,s);case"book":return function(t,n){n=n.replace(/^\//,""),e.tickEvent("book",{id:n}),e.log(`rendering book from ${n}`);let o;return $("#loading").find(".loader").addClass("text").text(lf("Compiling your book (this may take a minute)")),e.U.delay(100).then((()=>e.Cloud.markdownAsync(n))).then((t=>{o=e.docs.buildTOC(t),e.log(`TOC: ${JSON.stringify(o,null,2)}`);const n=[];return e.docs.visitTOC(o,(e=>{/^\//.test(e.path)&&!/^\/pkg\//.test(e.path)&&n.push(e)})),e.U.promisePoolAsync(4,n,(async t=>{try{const n=await e.Cloud.markdownAsync(t.path);t.markdown=n}catch(e){t.markdown=`_${t.path} failed to load._`}}))})).then((n=>{let r=o[0].name;return e.docs.visitTOC(o,(e=>{e.markdown&&(r+="\n\n"+e.markdown)})),v(t,r)}))}(n,s);default:return v(n,s)}})).catch((t=>{$(n).html(`\n <img style="height:4em;" src="${e.appTarget.appTheme.docsLogo}" />\n <h1>${lf("Oops")}</h1>\n <h3>${lf("We could not load the documentation, please check your internet connection.")}</h3>\n <button class="ui button primary" id="tryagain">${lf("Try Again")}</button>`),$(n).find("#tryagain").click((()=>{i(r,s)})),window.parent&&window.parent.postMessage({type:"docfailed",docType:r,src:s},"*")})).finally((()=>{$(t).hide(),o&&$(o).show(),$(n).show()})).then((()=>{}))}function a(e,t){t?(pxsim.U.addClass(e,"disabled"),e.setAttribute("aria-disabled","true")):(pxsim.U.removeClass(e,"disabled"),e.setAttribute("aria-disabled","false"))}function l(){let e=/^#(doc|md|tutorial|book|project|projectid|print):([^&?:]+)(:([^&?:]+):([^&?:]+))?/i.exec(window.location.hash);if(e){o&&(r.push(window.location.hash),r.length>10&&r.shift(),r.length>1&&a(o,!1));(e[4]?m(/^blocks$/.test(e[4])?s.Blocks:s.TypeScript,e[5]):Promise.resolve()).then((()=>i(e[1],decodeURIComponent(e[2]))))}}o&&(o.addEventListener("click",(()=>{!function(){if(!o)return;r.length>1&&(r.pop(),window.location.hash=r.pop());r.length<=1&&a(o,!0)}()})),a(o,!0)),e.editor.initEditorExtensionsAsync().then((()=>{window.addEventListener("message",y,!1),window.addEventListener("hashchange",(()=>{l()}),!1),parent.postMessage({type:"sidedocready"},"*"),setTimeout((()=>l()),1)}))},t.renderProjectAsync=k,t.renderProjectFilesAsync=b;function v(n,o,r={}){const i=e.docs.renderMarkdown({template:'\n<aside id=button class=box>\n <a class="ui primary button" href="@ARGS@">@BODY@</a>\n</aside>\n\n<aside id=vimeo>\n<div class="ui two column stackable grid container">\n<div class="column">\n <div class="ui embed mdvid" data-source="vimeo" data-id="@ARGS@" data-placeholder="/thumbnail/1024/vimeo/@ARGS@" data-icon="video play">\n </div>\n</div></div>\n</aside>\n\n<aside id=youtube>\n<div class="ui two column stackable grid container">\n<div class="column">\n <div class="ui embed mdvid" data-source="youtube" data-id="@ARGS@" data-placeholder="https://img.youtube.com/vi/@ARGS@/0.jpg">\n </div>\n</div></div>\n</aside>\n\n<aside id=section>\n \x3c!-- section @ARGS@ --\x3e\n</aside>\n\n<aside id=hide class=box>\n <div style=\'display:none\'>\n @BODY@\n </div>\n</aside>\n\n<aside id=avatar class=box>\n <div class=\'avatar @ARGS@\'>\n <div class=\'avatar-image\'></div>\n <div class=\'ui compact message\'>\n @BODY@\n </div>\n </div>\n</aside>\n\n<aside id=hint class=box>\n <div class="ui info message">\n <div class="content">\n @BODY@\n </div>\n </div>\n</aside>\n\n<aside id=codecard class=box>\n <pre><code class="lang-codecard">@BODY@</code></pre>\n</aside>\n\n<aside id=tutorialhint class=box>\n <div class="ui hint message">\n <div class="content">\n @BODY@\n </div>\n </div>\n</aside>\n\n<aside id=reminder class=box>\n <div class="ui warning message">\n <div class="content">\n @BODY@\n </div>\n </div>\n</aside>\n\n<aside id=alert class=box>\n <div class="ui negative message">\n <div class="content">\n @BODY@\n </div>\n </div>\n</aside>\n\n<aside id=tip class=box>\n <div class="ui positive message">\n <div class="content">\n @BODY@\n </div>\n </div>\n</aside>\n\n\x3c!-- wrapped around ordinary content --\x3e\n<aside id=main-container class=box>\n <div class="ui text">\n @BODY@\n </div>\n</aside>\n\n\x3c!-- used for \'column\' box - they are collected and wrapped in \'column-container\' --\x3e\n<aside id=column class=aside>\n <div class=\'column\'>\n @BODY@\n </div>\n</aside>\n<aside id=column-container class=box>\n <div class="ui three column stackable grid text">\n @BODY@\n </div>\n</aside>\n@breadcrumb@\n@body@',markdown:o,theme:e.appTarget.appTheme});let a=r.blocksAspectRatio||window.innerHeight<window.innerWidth?1.62:1/1.62;$(n).html(i),$(n).find("a").attr("target","_blank");const l=e.runner.defaultClientRenderOptions();return l.tutorial=!!r.tutorial,l.blocksAspectRatio=a||l.blocksAspectRatio,l.showJavaScript=t.editorLanguageMode==s.TypeScript,r.print&&(l.showEdit=!1,l.simulator=!1),e.runner.renderAsync(l).then((()=>{$(n).find('a[href^="/"]').removeAttr("target").each(((e,t)=>{$(t).attr("href","#doc:"+$(t).attr("href").replace(/^\//,""))})),$(n).find(".ui.embed").embed()}))}let T,E;function S(e,t){E||(E={});const n=Object.keys(t.fileSystem).sort().join(";");return E[n]||(E[n]=pxtc.getApiInfo(e,t.jres)),E[n]}t.renderMarkdownAsync=v,t.decompileSnippetAsync=function(n,o){const{assets:i,forceCompilation:s,snippetMode:a,generateSourceMap:l}=o||{};return p(o&&o.packageId?"pub:"+o.packageId:o&&o.package?"docs:"+o.package:null,n).then((()=>g(!!e.appTarget.compile&&e.appTarget.compile.hasHex))).then((c=>{if(n&&(c.fileSystem[e.MAIN_TS]=n),c.ast=!0,i)for(const e of Object.keys(i))c.sourceFiles.indexOf(e)<0&&c.sourceFiles.push(e),c.fileSystem[e]=i[e];let u,d,p;s?(u=pxtc.compile(c),d=u&&u.ast):d=pxtc.getTSProgram(c,T),T=d,e.appTarget.appTheme.python&&(p=ts.pxtc.transpile.tsToPy(d,e.MAIN_TS));let g=S(d,c);return ts.pxtc.localizeApisAsync(g,t.mainPkg).then((()=>{let n=pxtc.getBlocksInfo(g);e.blocks.initializeAndInject(n);const s=null==i?void 0:i[e.TILEMAP_JRES],c=null==i?void 0:i[e.IMAGES_JRES];(s||c)&&(r=new e.TilemapProject,r.loadPackage(t.mainPkg),s&&r.loadTilemapJRes(JSON.parse(s),!0),c&&r.loadAssetsJRes(JSON.parse(c)));let h=pxtc.decompiler.decompileToBlocks(n,d.getSourceFile(e.MAIN_TS),{snippetMode:a,generateSourceMap:l});if(h.diagnostics&&h.diagnostics.length>0&&h.diagnostics.forEach((e=>console.error(e.messageText))),!h.success)return{package:t.mainPkg,compileProgram:d,compileJS:u,compileBlocks:h,apiInfo:g};e.debug(h.outfiles[e.MAIN_BLOCKS]);const f=e.blocks.render(h.outfiles[e.MAIN_BLOCKS],o);return(s||c)&&(r=null),{package:t.mainPkg,compileProgram:d,compileJS:u,compileBlocks:h,compilePython:p,apiInfo:g,blocksSvg:f}}))}))},t.compileBlocksAsync=function(n,o){const{assets:i}=o||{};return p(o&&o.packageId?"pub:"+o.packageId:o&&o.package?"docs:"+o.package:null,"").then((()=>g(!!e.appTarget.compile&&e.appTarget.compile.hasHex))).then((s=>{if(s.ast=!0,i)for(const e of Object.keys(i))s.sourceFiles.indexOf(e)<0&&s.sourceFiles.push(e),s.fileSystem[e]=i[e];const a=S(pxtc.compile(s).ast,s);return ts.pxtc.localizeApisAsync(a,t.mainPkg).then((()=>{const s=pxtc.getBlocksInfo(a);e.blocks.initializeAndInject(s);const l=null==i?void 0:i[e.TILEMAP_JRES],c=null==i?void 0:i[e.IMAGES_JRES];(l||c)&&(r=new e.TilemapProject,r.loadPackage(t.mainPkg),l&&r.loadTilemapJRes(JSON.parse(l),!0),c&&r.loadAssetsJRes(JSON.parse(c)));const u=e.blocks.render(n,o);return(l||c)&&(r=null),{package:t.mainPkg,blocksSvg:u,apiInfo:a}}))}))};let C=[];t.initCallbacks=[],t.init=function(){u().then((()=>{for(let e=0;e<t.initCallbacks.length;++e)t.initCallbacks[e]()}))},function(){let e=window.ksRunnerWhenLoaded;e&&e()}()}(e.runner||(e.runner={}))}(pxt||(pxt={}));
|