From: Steve Myers Date: Thu, 7 Jan 2021 04:50:24 +0000 (-0800) Subject: Rename repl to bdk-cli and update related docs X-Git-Url: http://internal-gitweb-vhost/script/%22https:/database/scripts/struct.EncoderStringWriter.html?a=commitdiff_plain;h=02157bcc5136f83c98e228805dfa32e5460749d3;p=bitcoindevkit.org Rename repl to bdk-cli and update related docs --- diff --git a/config.toml b/config.toml index a670f79e16..60e9bb6ab2 100644 --- a/config.toml +++ b/config.toml @@ -58,7 +58,7 @@ weight = 5 [[Languages.en.menu.shortcuts]] name = " Playground" -url = "/repl/playground" +url = "/bdk-cli/playground" weight = 10 [[Languages.en.menu.shortcuts]] diff --git a/content/_index.md b/content/_index.md index f256540f99..90fbd26b7f 100644 --- a/content/_index.md +++ b/content/_index.md @@ -20,11 +20,11 @@ server to chat with us. ## Playground -As a way of demonstrating the flexibly of this project, a minimalistic command line tool (also called "repl") is available as a debugging tool in the main [`bdk`](https://github.com/bitcoindevkit/bdk) -repo. It has been compiled to WebAssembly and can be used directly from the browser. See the [playground](/repl/playground) section to give it a try! +As a way of demonstrating the flexibly of this project, a minimalistic command line tool (called `bdk-cli`) is available as a debugging tool in the [`bdk-cli`](https://github.com/bitcoindevkit/bdk-cli) +repo. It has been compiled to WebAssembly and can be used directly from the browser. See the [playground](/bdk-cli/playground) section to give it a try! The playground relies on [Esplora](https://blockstream.info) to monitor the blockchain and is currently locked in testnet-only mode, for obvious safety reasons. The native command line tool can also be used in regtest mode when installed on -a computer. See the [REPL](/repl) section to learn more. +a computer. See the [bdk-cli](/bdk-cli) section to learn more. ## Descriptors diff --git a/content/bdk-cli/_index.md b/content/bdk-cli/_index.md new file mode 100644 index 0000000000..92b80b0b48 --- /dev/null +++ b/content/bdk-cli/_index.md @@ -0,0 +1,13 @@ ++++ +title = "BDK CLI" +date = 2020-04-28T17:03:00+02:00 +weight = 1 +chapter = true +pre = ' ' ++++ + +# BDK-CLI + +The [bdk-cli](https://github.com/bitcoindevkit/bdk-cli) repo has an example interactive shell built +using the `bdk` library called `bdk-cli` that acts both as a reference implementation of a wallet +and a tool to quickly experiment with descriptors and transactions. diff --git a/content/bdk-cli/compiler.md b/content/bdk-cli/compiler.md new file mode 100644 index 0000000000..39ebea09c2 --- /dev/null +++ b/content/bdk-cli/compiler.md @@ -0,0 +1,151 @@ +--- +title: "Compiler" +date: 2020-04-29T12:06:50+02:00 +draft: false +weight: 5 +pre: "5. " +--- + +## Introduction + +If you want to play around with more complicated spending policies, you'll start to find it harder and harder to manually create the descriptors. This is where the miniscript compiler comes in! The `bdk` library +includes a very simple compiler that can produce a descriptor given a spending policy. The syntax used to encode the spending policy is very well described [in this page](http://bitcoin.sipa.be/miniscript/), +specifically in the "Policy to Miniscript compiler". The compiler included in BDK does basically the same job, but produces descriptors for `rust-miniscript` that have some minor differences from +the ones made by the C++ implementation used in that website. + +## Installation + +To install the miniscript compiler run the following command: + +```bash +cargo install --git https://github.com/bitcoindevkit/bdk --features="compiler" --example miniscriptc +``` + +Once the command is done, you should have a `miniscriptc` command available. You can check if that's the case by running `miniscriptc --help`. + +## Usage + +In this case the interface is very simple: it accepts two arguments called "POLICY" and "TYPE", in this order. The first one, as the name implies, sets the spending policy to compile. The latter defines the type +of address that should be used to encapsulate the produced script, like a P2SH, P2WSH, etc. + +Optionally, the `--parsed_policy` flag can be enabled and it will make the compiler print the JSON "human-readable" version of the spending policy, as described in the [`policies subcommand`](/bdk-cli/interface/#policies) of the CLI. + +The `--network` flag can be used to change the network encoding of the address shown. + +{{% notice tip %}} +Keep in mind that since the compiler loads and interprets the descriptor, all the public keys specified in the policy must be valid public keys. This differs from the web tool linked above that also accepts +placeholders too. As described in the previous sections of this guide, the keys can be either `xpub`/`xprv` with or without metadata and a derivation path, WIF keys or raw hex public keys. +{{% /notice %}} + +## Example + +Let's take this policy for example: + +```bash +miniscriptc --parsed_policy and(pk(cSQPHDBwXGjVzWRqAHm6zfvQhaTuj1f2bFH58h55ghbjtFwvmeXR),or(50@pk(02e96fe52ef0e22d2f131dd425ce1893073a3c6ad20e8cac36726393dfb4856a4c),older(1000)))) sh-wsh +``` + +The compiler should print something like: + +```text +[2020-04-29T10:42:05Z INFO miniscriptc] Compiling policy: and(pk(cSQPHDBwXGjVzWRqAHm6zfvQhaTuj1f2bFH58h55ghbjtFwvmeXR),or(50@pk(02e96fe52ef0e22d2f131dd425ce1893073a3c6ad20e8cac36726393dfb4856a4c),older(1000))) +[2020-04-29T10:42:05Z INFO miniscriptc] ... Descriptor: sh(wsh(and_v(or_c(c:pk(02e96fe52ef0e22d2f131dd425ce1893073a3c6ad20e8cac36726393dfb4856a4c),v:older(1000)),c:pk(cSQPHDBwXGjVzWRqAHm6zfvQhaTuj1f2bFH58h55ghbjtFwvmeXR)))) +[2020-04-29T10:42:05Z INFO miniscriptc] ... First address: 2MsqrJuZewY3o3ADAy1Uhi5vsBqTANjH3Cf +``` + +JSON policy: + +{{% json %}} +{ + "type":"THRESH", + "items":[ + { + "type":"THRESH", + "items":[ + { + "type":"SIGNATURE", + "pubkey":"02e96fe52ef0e22d2f131dd425ce1893073a3c6ad20e8cac36726393dfb4856a4c", + "satisfaction":{ + "type":"NONE" + }, + "contribution":{ + "type":"NONE" + } + }, + { + "type":"RELATIVETIMELOCK", + "value":1000, + "satisfaction":{ + "type":"NONE" + }, + "contribution":{ + "type":"COMPLETE", + "condition":{ + "csv":1000 + } + } + } + ], + "threshold":1, + "satisfaction":{ + "type":"NONE" + }, + "contribution":{ + "type":"PARTIALCOMPLETE", + "n":2, + "m":1, + "items":[ + 1 + ], + "conditions":{ + "[1]":[ + { + "csv":1000 + } + ] + } + } + }, + { + "type":"SIGNATURE", + "pubkey":"02e96fe52ef0e22d2f131dd425ce1893073a3c6ad20e8cac36726393dfb4856a4c", + "satisfaction":{ + "type":"NONE" + }, + "contribution":{ + "type":"COMPLETE", + "condition":{ + + } + } + } + ], + "threshold":2, + "satisfaction":{ + "type":"NONE" + }, + "contribution":{ + "type":"PARTIALCOMPLETE", + "n":2, + "m":2, + "items":[ + 0, + 1 + ], + "conditions":{ + "[0, 1]":[ + { + "csv":1000 + } + ] + } + } +} +{{% /json %}} + +## Troubleshooting + +#### Nothing is printed + +This might mean that you have a `RUST_LOG` variable set to a value that suppresses the compiler's log. You can try adding `miniscriptc=info` to your `RUST_LOG` value and see if that works, or open a new clean +shell. diff --git a/content/bdk-cli/concept.md b/content/bdk-cli/concept.md new file mode 100644 index 0000000000..96078eacd1 --- /dev/null +++ b/content/bdk-cli/concept.md @@ -0,0 +1,26 @@ +--- +title: "Concept" +date: 2020-04-28T17:38:20+02:00 +draft: false +weight: 2 +pre: "2. " +--- + +Now, in order to better grasp some of the design choices made by BDK, it's important to understand the main concept driving the development of this project, and the goal that it's trying to +achieve. + +BDK is aiming first of all to be a **set of libraries and tools**, all meant to be very reusable and adaptable. Developers working on their own wallets or other projects that are trying to integrate +Bitcoin can pick the tools they need and piece them together to prototype and quickly ship a working product. This means that the `bdk-cli` that we've just installed is designed to be a **very thin layer** over the +APIs exposed by the various components of the library, **not a full, end-user-ready Bitcoin wallet**. + +This concept leads to a few design choices that are arguably very bad for the "UX" of this wallet, but that allow developers to work more directly with the underlying library. For instance: + +* BDK has an internal database that's used to store data about received transactions, spendable UTXOs, etc. This database is stored by default in your home folder, in `~/.bdk-bitcoin`. The database + **will never** contain any data that can't be recreated purely by looking at the blockchain. Keys, descriptors, Electrum endpoints **are not stored in the database**. This explains why you'll have to specify them every + time in the command line. It can be seen more like a *cache* and can be safely deleted without risking funds. +* BDK doesn't automatically "monitor" the blockchain, instead there's a `sync` command that has to be called by the user. +* When you create a transaction and then sign it, it's not automatically broadcast to the network. There's a `broadcast` command that does this. Moreover, the command doesn't accept a normal Bitcoin raw transaction, + but instead a *PSBT*. That's because internally transactions are always moved as PSBTs, and again, the `broadcast` command is just a very thin wrapper over the raw library call. + +There are probably more of these examples, but hopefully by this point you'll have more or less understood the gist of it. If you are not a developer, some parts of this will feel weird, inefficient, hard +to understand, and that's absolutely normal. Just try to survive through the pain and you'll be rewarded! diff --git a/content/bdk-cli/installation.md b/content/bdk-cli/installation.md new file mode 100644 index 0000000000..4fa8b00c97 --- /dev/null +++ b/content/bdk-cli/installation.md @@ -0,0 +1,92 @@ +--- +title: "Installation" +date: 2020-04-28T17:11:29+02:00 +draft: false +weight: 1 +pre: "1. " +--- + +## Requirements + +The only requirement to run the `bdk-cli` tool is a Linux/macOS system with a fairly recent Rust +toolchain installed. Since Linux distros tend to lag behind with updates, the quickest way to +install the Rust compiler and Cargo is [rustup.rs](https://rustup.rs/). You can head there and +follow their instructions, after which you can test if everything went fine by running +`cargo version`, which should print something like: + +``` +cargo 1.45.0 (744bd1fbb 2020-06-15) +``` + +If you really don't want to pipe the output of `curl` into `sh`, you can also try using a +[Docker image](https://hub.docker.com/_/rust) and working inside of it, but that's meant for more +advanced users and won't be covered in this guide. + +{{% notice note %}} +At the time of writing, the project requires cargo >= 1.45.0, which is the latest stable as of +June 2020. If you have an older version installed with rustup.rs, you can upgrade it with +`rustup update`. +{{% /notice %}} + +## Installing the `bdk-cli` tool + +Once Cargo is installed, you can proceed to install the interactive `bdk-cli` tool directly from +the GitHub repository, by running: + +```bash +cargo install --git https://github.com/bitcoindevkit/bdk-cli --features=esplora +``` + +This command may take a while to finish, since it will fetch and compile all the +dependencies and the `bdk` library itself. Once it's done, you can check if everything went fine by +running `bdk-cli --help` which should print something like this: + +```text +BDK CLI 0.1.0 +Alekos Filini :Riccardo Casatta +A modern, lightweight, descriptor-based wallet + +USAGE: + bdk-cli [OPTIONS] --descriptor + +FLAGS: + -h, --help Prints help information + -V, --version Prints version information + +OPTIONS: + -c, --change_descriptor Sets the descriptor to use for internal addresses + -d, --descriptor Sets the descriptor to use for the external addresses + --esplora_concurrency Concurrency of requests made to the esplora server [default: 4] + -e, --esplora Use the esplora server if given as parameter + -n, --network Sets the network [default: testnet] + -p, --proxy Sets the SOCKS5 proxy for the Electrum client + -s, --server + Sets the Electrum server to use [default: ssl://electrum.blockstream.info:60002] + + -w, --wallet Selects the wallet to use [default: main] + +SUBCOMMANDS: + broadcast Broadcasts a transaction to the network. Takes either a raw transaction or a PSBT to + extract + bump_fee Bumps the fees of an RBF transaction + combine_psbt Combines multiple PSBTs into one + create_tx Creates a new unsigned transaction + extract_psbt Extracts a raw transaction from a PSBT + finalize_psbt Finalizes a PSBT + get_balance Returns the current wallet balance + get_new_address Generates a new external address + help Prints this message or the help of the given subcommand(s) + list_transactions Lists all the incoming and outgoing transactions of the wallet + list_unspent Lists the available spendable UTXOs + policies Returns the available spending policies for the descriptor + public_descriptor Returns the public version of the wallet's descriptor(s) + repl Enter REPL command loop mode + sign Signs and tries to finalize a PSBT + sync Syncs with the chosen blockchain server +``` + +An example command to sync a testnet wallet looks like this: + +``` +bdk-cli --descriptor "wpkh(tprv8ZgxMBicQKsPexGYyaFwnAsCXCjmz2FaTm6LtesyyihjbQE3gRMfXqQBXKM43DvC1UgRVv1qom1qFxNMSqVAs88qx9PhgFnfGVUdiiDf6j4/0/*)" --network testnet --server ssl://electrum.blockstream.info:60002 sync +``` \ No newline at end of file diff --git a/content/bdk-cli/interface.md b/content/bdk-cli/interface.md new file mode 100644 index 0000000000..83f966610d --- /dev/null +++ b/content/bdk-cli/interface.md @@ -0,0 +1,531 @@ +--- +title: "Interface" +date: 2020-04-28T18:20:28+02:00 +draft: false +weight: 3 +pre: "3. " +--- + +Remember the `bdk-cli --help` command you ran before? Let's analyze its output here to figure out the interface: + +## Flags + +```text +FLAGS: + -h, --help Prints help information + -V, --version Prints version information +``` + +These are the optional flags that can be set with every command. The `-h` flag prints the help message, the `-V` flag only prints the version. + +### Verbosity + +If you want to increase the verbosity of the output, you should use the `RUST_LOG` environment variable. You can set it like so to see a lot more of what's going on behind the scenes, before running the `bdk-cli` +command. You only have to do this once when you open a new shell, after that you can run the `bdk-cli` command multiple times. + +```bash +export RUST_LOG="bdk=debug" +``` + +## Options + +```text +OPTIONS: + -c, --change_descriptor Sets the descriptor to use for internal addresses + -d, --descriptor Sets the descriptor to use for the external addresses + --esplora_concurrency Concurrency of requests made to the esplora server [default: 4] + -e, --esplora Use the esplora server if given as parameter + -n, --network Sets the network [default: testnet] + -p, --proxy Sets the SOCKS5 proxy for the Electrum client + -s, --server + Sets the Electrum server to use [default: ssl://electrum.blockstream.info:60002] + + -w, --wallet Selects the wallet to use [default: main] +``` + +These are the global options that can be set. They are pretty much like the flags, but they also take a value. The only **required** one is the `--descriptor` or `-d` flag, since every wallet **must have an +associated descriptor**. + +The `--change-descriptor` flag can be used to set a different descriptor for the change addresses, sometimes called "internal" addresses in Bitcoin Core. Unfortunately there isn't +[really consensus](https://freenode.irclog.whitequark.org/bitcoin-wizards/2020-01-25#26222504;) on a nice way to encode information about the change derivation inside the standard descriptor, so we are +stuck with having two separate ones. Keep in mind though, that even if you don't specify a change descriptor, you'll still be able to create transactions - the change address will simply be generated from the +standard descriptor. + +The `--network` flag can be used to change the network. Right now only `testnet` and `regtest` are supported since the code is very much not production-ready yet. + +The `--server` flag can be used to select the Electrum server to use. By default it's connecting to Blockstream's electrum servers, which seems pretty stable. +If you are having connection issues, you can also try with one of the other servers [listed here](https://1209k.com/bitcoin-eye/ele.php?chain=tbtc) and see if you have more luck with those. +Right now both plaintext and ssl servers are supported (prefix `tcp://` or no prefix at all for tcp, prefix `ssl://` for ssl). + +The `--esplora` flag can be used to connect to an Esplora instance instead of using Electrum. It should be set to the API's "base url". For public instances of Esplora this is `https://blockstream.info/api` for mainnet +and `https://blockstream.info/testnet/api` for testnet. + +The `--proxy` flag can be optionally used to specify a SOCKS5 proxy to use when connecting to the Electrum server. Spawning a local Tor daemon and using it as a proxy will allow you to connect to `.onion` Electrum +URLs. **Keep in mind that only plaintext server are supported over a proxy.** + +The `--wallet` flag can be used to select which wallet to use, if you have more than one of them. If you get a `ChecksumMismatch` error when you make some changes to your descriptor, it's because it does not +match anymore the one you've used to initialize the cache. One solution could be to switch to a new wallet name, or delete the cache directory at `~/.bdk-bitcoin` and start from scratch. + +## Subcommands + +| Command | Description | +| ------- | ----------- | +| [broadcast](#broadcast) | Broadcasts a transaction to the network. Takes either a raw transaction or a PSBT to extract | +| [bump_fee](#bump_fee) | Bumps the fees of an RBF transaction | +| [combine_psbt](#combine_psbt) | Combines multiple PSBTs into one | +| [create_tx](#create_tx) | Creates a new unsigned tranasaction | +| [extract_psbt](#extract_psbt) | Extracts a raw transaction from a PSBT | +| [finalize_psbt](#finalize_psbt) | Finalizes a psbt | +| [get_balance](#get_balance) | Returns the current wallet balance | +| [get_new_address](#get_new_address) | Generates a new external address | +| [list_transactions](#list_transactions) | Lists all the incoming and outgoing transactions of the wallet | +| [list_unspent](#list_unspent) | Lists the available spendable UTXOs | +| [policies](#policies) | Returns the available spending policies for the descriptor | +| [public_descriptor](#public_descriptor) | Returns the public version of the wallet's descriptor(s) | +| [repl](#repl) | Opens an interactive shell | +| [sign](#sign) | Signs and tries to finalize a PSBT | +| [sync](#sync) | Syncs with the chosen Electrum server | + +These are the main "functions" of the wallet. Most of them are pretty self explanatory, but we'll go over them quickly anyways. You can get more details about every single command by running `bdk-cli --help`. + +### broadcast + +```text +OPTIONS: + --psbt Sets the PSBT to extract and broadcast + --tx Sets the raw transaction to broadcast +``` + +Broadcasts a transaction. The transaction can be a raw hex transaction or a PSBT, in which case it also has to be "finalizable" (i.e. it should contain enough partial signatures to construct a finalized valid scriptsig/witness). + +### bump\_fee + +```text +FLAGS: + -a, --send_all Allows the wallet to reduce the amount of the only output in order to increase fees. This is + generally the expected behavior for transactions originally created with `send_all` + +OPTIONS: + -f, --fee_rate The new targeted fee rate in sat/vbyte + -t, --txid TXID of the transaction to update + --unspendable ... Marks an utxo as unspendable, in case more inputs are needed to cover the extra + fees + --utxos ... Selects which utxos *must* be added to the tx. Unconfirmed utxos cannot be used +``` + +Bumps the fee of a transaction made with RBF. The transaction to bump is specified using the `--txid` flag and the new fee rate with `--fee_rate`. + +The `--send_all` flag should be enabled if the original transaction was also made with `--send_all`. + +### combine\_psbt + +```text +OPTIONS: + --psbt ... Add one PSBT to comine. This option can be repeated multiple times, one for each PSBT +``` + +Combines multiple PSBTs by merging metadata and partial signatures. It can be used to merge multiple signed PSBTs into a single PSBT that contains every signature and is ready to be [finalized](#finalize_psbt). + +### create\_tx + +```text +FLAGS: + -r, --enable_rbf Enables Replace-By-Fee (BIP125) + --offline_signer Make a PSBT that can be signed by offline signers and hardware wallets. Forces the addition + of `non_witness_utxo` and more details to let the signer identify the change output + -a, --send_all Sends all the funds (or all the selected utxos). Requires only one recipients of value 0 + +OPTIONS: + --to ... Adds a recipient to the transaction + --unspendable ... Marks a utxo as unspendable + --external_policy + Selects which policy should be used to satisfy the external descriptor + + --internal_policy + Selects which policy should be used to satisfy the internal descriptor + + --utxos ... Selects which utxos *must* be spent + -f, --fee_rate Fee rate to use in sat/vbyte +``` + +Creates a new unsigned PSBT. The flags allow to set a custom fee rate (the default is 1.0 sat/vbyte) with `--fee_rate` or `-f`, the list of UTXOs that should be considered unspendable with `--unspendable` (this +option can be specified multiple times) and a list of UTXOs that must be spent with `--utxos` (again, this option can also be specified multiple times). + +The `--to` option sets the receiver address of the transaction, and should contain the address and amount in Satoshi separated by a colon, like: `--to 2NErbQPsooXRatRJdrXDm9wKR2fRiZDT9wL:50000`. This option +can also be specified multiple times to send to multiple addresses at once. + +The `--send_all` flag can be used to send the value of all the spendable UTXOs to a single address, without creating a change output. If this flag is set, there must be only one `--to` address, and its value will +be ignored (it can be set to 0). + +The `--external_policy` and `--internal_policy` options are two advanced flags that can be used to select the spending policy that the sender intends to satisfy in this transaction. They are normally not required if there's no ambiguity, but sometimes +with a complex descriptor one or both of them have to be specified, or you'll get a `SpendingPolicyRequired` error. Those flags should be set to a JSON object that maps a policy node id to the list of child indexes that +the user intends to satisfy for that node. This is probably better explained with an example: + +Let's assume our descriptor is: `sh(thresh(2,pk(A),sj:and_v(v:pk(B),n:older(6)),snj:and_v(v:pk(C),after(630000))))`. There are three conditions and we need to satisfy two of them to be able to spend. The conditions are: + +1. Sign with the key corresponding to `pk(A)` +2. Sign with the key corresponding to `pk(B)` AND wait 6 blocks +2. Sign with the key corresponding to `pk(C)` AND wait that block 630,000 is reached + +So if we write down all the possible outcomes when we combine them, we get: + +1. Sign with `pk(A)` + `pk(B)` + wait 6 blocks +2. Sign with `pk(A)` + `pk(C)` + wait block 630,000 +3. Sign with `pk(B)` + `pk(C)` + wait 6 blocks + wait block 630,000 + +In other words: + +* If we choose option #1, the final transaction will need to have the `nSequence` of its inputs set to a value greather than or equal to 6, but the `nLockTime` can stay at 0. +* If we choose option #2, the final transaction will need to have its `nLockTime` set to a value greater than or equal to 630,000, but the `nSequence` can be set to a final value. +* If we choose option #3, both the `nSequence` and `nLockTime` must be set. + +The wallet can't choose by itself which one of these combination to use, so the user has to provide this information with the `--external_policy` flag. + +Now, let's draw the condition tree to understand better how the chosen policy is represented: every node has its id shown right next to its name, like `qd3um656` for the root node. These ids can be seen by running the [policies](#policies) command. +Some ids have been omitted since they are not particularly relevant, in this example we will actually only use the root id. + +{{}} +graph TD; + subgraph " " + R["Root - qd3um656"] --> A["pk(A) - ykfuwzkl"] + R["Root - qd3um656"] --> B["B - ms3xjley"] + B["B - ms3xjley"] --> B_0["pk(B)"] + B["B - ms3xjley"] --> B_1["older(6)"] + end + C["C - d8jph6ax"] --> C_0["pk(C)"] + C["C - d8jph6ax"] --> C_1["after(630,000)"] + R["Root - qd3um656"] --> C["C - d8jph6ax"] +{{< /mermaid >}} + +Let's imagine that we are walking down from the root, and we want to use option #1. So we will have to select `pk(A)` + the whole `B` node. Since these nodes have an id, we can use it to refer to them and say which children +we want to use. In this case we want to use children #0 and #1 of the root, so our final policy will be: `--external_policy {"qd3um656":[0,1]}`. + +### extract\_psbt + +```text +OPTIONS: + --psbt Sets the PSBT to extract +``` + +Extracts the global transaction from a PSBT. **Note that partial signatures are ignored in this step. If you want to merge the partial signatures back into the global transaction first, please use [finalize_psbt](#finalize_psbt) first** + +### finalize\_psbt + +```text +OPTIONS: + --psbt Sets the PSBT to finalize + --assume_height Assume the blockchain has reached a specific height +``` + +Tries to finalize a PSBT by merging all the partial signatures and other elements back into the global transaction. This command fails if there are timelocks that have not yet expired, but the check can be overridden +by specifying `--assume_height` to make the wallet assume that a future height has already been reached. + +### get\_balance + +This subcommand has no extra flags, and simply returns the available balance in Satoshis. This command **should normally be called after [`sync`](#sync)**, since it only looks into the local cache to determine the list of UTXOs. + +### get\_new\_address + +This subcommand has no extra flags and returns a new address. It internally increments the derivation index and saves it in the database. + +### list\_transactions + +This subcommand has no extra flags and returns the history of transactions made or received by the wallet, with their txid, confirmation height and the amounts (in Satoshi) "sent" (meaning, the sum of the wallet's inputs spent in the transaction) and +"received" (meaning, the sum of the outputs received by the wallet). Just like [`get_balance`](#get_balance) it **should normally be called after [`sync`](#sync)**, since it only operates +on the internal cache. + +### list\_unspent + +This subcommand has no extra flags and returns the list of available UTXOs and their value in Satoshi. Just like [`get_balance`](#get_balance) it **should normally be called after [`sync`](#sync)**, since it only operates +on the internal cache. + +### policies + +This subcommand has no extra flags and returns the spending policies encoded by the descriptor in a more human-readable format. As an example, running the `policies` command on the descriptor shown earlier for the +in the explanation of the [create_tx](#create_tx) command, it will return this: + +{{% json %}} +{ + "id":"qd3um656", + "type":"THRESH", + "items":[ + { + "id":"ykfuwzkl", + "type":"SIGNATURE", + "pubkey":"...", + "satisfaction":{ + "type":"NONE" + }, + "contribution":{ + "type":"COMPLETE", + "condition":{ + + } + } + }, + { + "id":"ms3xjley", + "type":"THRESH", + "items":[ + { + "id":"xgfnp9rt", + "type":"SIGNATURE", + "pubkey":"...", + "satisfaction":{ + "type":"NONE" + }, + "contribution":{ + "type":"COMPLETE", + "condition":{ + + } + } + }, + { + "id":"5j96ludf", + "type":"RELATIVETIMELOCK", + "value":6, + "satisfaction":{ + "type":"NONE" + }, + "contribution":{ + "type":"COMPLETE", + "condition":{ + "csv":6 + } + } + } + ], + "threshold":2, + "satisfaction":{ + "type":"NONE" + }, + "contribution":{ + "type":"PARTIALCOMPLETE", + "n":2, + "m":2, + "items":[ + 0, + 1 + ], + "conditions":{ + "[0, 1]":[ + { + "csv":6 + } + ] + } + } + }, + { + "id":"d8jph6ax", + "type":"THRESH", + "items":[ + { + "id":"gdl039m6", + "type":"SIGNATURE", + "pubkey":"...", + "satisfaction":{ + "type":"NONE" + }, + "contribution":{ + "type":"COMPLETE", + "condition":{ + + } + } + }, + { + "id":"xpf2twg8", + "type":"ABSOLUTETIMELOCK", + "value":630000, + "satisfaction":{ + "type":"NONE" + }, + "contribution":{ + "type":"COMPLETE", + "condition":{ + "timelock":630000 + } + } + } + ], + "threshold":2, + "satisfaction":{ + "type":"NONE" + }, + "contribution":{ + "type":"PARTIALCOMPLETE", + "n":2, + "m":2, + "items":[ + 0, + 1 + ], + "conditions":{ + "[0, 1]":[ + { + "timelock":630000 + } + ] + } + } + } + ], + "threshold":2, + "satisfaction":{ + "type":"NONE" + }, + "contribution":{ + "type":"PARTIALCOMPLETE", + "n":3, + "m":2, + "items":[ + 0, + 1, + 2 + ], + "conditions":{ + "[0, 1]":[ + { + "csv":6 + } + ], + "[0, 2]":[ + { + "timelock":630000 + } + ], + "[1, 2]":[ + { + "csv":6, + "timelock":630000 + } + ] + } + } +} +{{% /json %}} + +This is a tree-like recursive structure, so it tends to get huge as more and more pieces are added, but it's in fact fairly simple. Let's analyze a simple node of the tree: + +```json +{ + "id":"qd3um656", + "type":"SIGNATURE", + "pubkey":"...", + "satisfaction":{ + "type":"NONE" + }, + "contribution":{ + "type":"COMPLETE", + "condition":{} + } +} +``` + +* `id` is a unique identifier to this specific node in the tree. +* `type`, as the name implies, represents the type of node. It defines what should be provided to satisfy that particular node. Generally some other data are provided to give meaning to + the type itself (like the `pubkey` field here in the example). There are basically two families of types: some of them can only be used as leaves, while some other can only be used as intermediate nodes. + + Possible leaf nodes are: + - `SIGNATURE`, requires a signature made with the specified key. Has a `pubkey` if it's a single key, a `fingerprint` if the key is an xpub, or a `pubkey_hash` if the full public key is not present in the descriptor. + - `SIGNATUREKEY`, requires a signature plus the raw public key. Again, it can have a `pubkey`, `fingerprint` or `pubkey_hash`. + - `SHA256PREIMAGE`, requires the preimage of a given `hash`. + - `HASH256PREIMAGE`, requires the preimage of a given `hash`. + - `RIPEMD160PREIMAGE`, requires the preimage of a given `hash`. + - `HASH160PREIMAGE`, requires the preimage of a given `hash`. + - `ABSOLUTETIMELOCK`, doesn't technically require anything to be satisfied, just waiting for the timelock to expire. Has a `value` field with the raw value of the timelock (can be both in blocks or time-based). + - `RELATIVETIMELOCK`, again only requires waiting for the timelock to expire. Has a `value` like `ABSOLUTETIMELOCK`. + + Possible non-leaf nodes are: + - `THRESH`, defines a threshold of policies that has to be met to satisfy the node. Has an `items` field, which is a list of policies to satisfy and a `threshold` field that defines the threshold. + - `MULTISIG`, Similar to `THRESH`, has a `keys` field, which is a list of keys represented again as either `pubkey`, `fingerprint` or `pubkey_hash` and a `threshold` field. + +* `satisfaction` is currently not implemented and will be used to provide PSBT introspection, like understanding whether or not a node is already satisfied and to which extent in a PSBT. +* `contribution` represents if so and how much, the provided descriptor can contribute to the node. + + The possible types are: + - `NONE`, which means that the descriptor cannot contribute. + - `COMPLETE`, which means that the descriptor by itself is enough to completely satisfy the node. It also adds a `condition` field which represent any potential extra condition that has to be met to + consider the node complete. An example are the timelock nodes, that are always complete *but* they have an extra `csv` or `timelock` condition. + - `PARTIAL`, which means that the descriptor can partially satisfy the descriptor. This adds a `m`, `n`, `items` that respectively represent the threshold, the number of available items to satisfy and the items + that the provided descriptor can satisfy. Also adds a `conditions` field which is an integer to list of conditions map. The key is the child index and the map are all the possibile extra conditions that + have to be satisfied if that node is used in the threshold. For instance, if you have a threshold of a SIGNATURE and a RELATIVETIMELOCK, in this order, the `conditions` field will be `1 ⇒ csv(x)`, + because the item at index 1 needs the extra csv condition. + - `PARTIALCOMPLETE`, which is basically a `PARTIAL` with the size of `items` >= `m`. It's treated as a separate entity to make the code a bit more clean and easier to implement. Like `PARTIAL`, it also has + a `m`, `n`, `items` fields but the `conditions field` is a bit different: it's a list of integers to list of conditions map. The key represents the combination that can be used to satisfy the threshold, + and the value contains all the possible conditions that also have to be satisfied. For instance, if you have a 2-of-2 threshold of a TIMELOCK and a RELATIVETIMELOCK, the `conditions` field will be `[0, 1] ⇒ + csv(x) + timelock(y)`, because if the combination of items 0 and 1 is picked, both of their conditions will have to be meet too. + +While the structure contains all of the intermediate nodes too, the root node is the most important one because defines how the descriptor can contribute to spend outputs sent to its addresses. + +For instance, looking at the root node of the previous example (with the internal `items` omitted) from a descriptor that has all the three private keys for keys A, B and C, we can clearly see that it can satisfy +the descriptor (type = `PARTIALCOMPLETE`) and the three options are `[0, 1] ⇒ csv(6)` (Option #1), `[0, 2] ⇒ timelock(630,000)` (Option #2) or `[1, 2] ⇒ csv(6) + timelock(630,000)` (Option #3). + +```json +{ + "type":"THRESH", + "items":[], + "threshold":2, + "satisfaction":{ + "type":"NONE" + }, + "contribution":{ + "type":"PARTIALCOMPLETE", + "n":3, + "m":2, + "items":[ + 0, + 1, + 2 + ], + "conditions":{ + "[0, 1]":[ + { + "csv":6 + } + ], + "[0, 2]":[ + { + "timelock":630000 + } + ], + "[1, 2]":[ + { + "csv":6, + "timelock":630000 + } + ] + } + } +} +``` + +### `public_descriptor` + +This subcommand has no extra flags and returns the "public" version of the wallet's descriptor(s). It can be used to bootstrap a watch-only instance for the wallet. + +### `repl` + +This subcommand has no extra flags and launches an interactive shell session. + +### `sign` + +```text +OPTIONS: + --psbt Sets the PSBT to sign + --assume_height Assume the blockchain has reached a specific height. This affects the transaction + finalization, if there are timelocks in the descriptor +``` + +Adds to the PSBT all the signatures it can produce with the secrets embedded in the descriptor (xprv or WIF keys). Returns the signed PSBT and, if there are enough item to satisfy the script, also the extracted raw +Bitcoin transaction. + +Optionally, the `assume_height` option can be specified to let the wallet assume the blockchain has reached a specific height. This affects the finalization of the PSBT which is done right at the end of the signing +process: the wallet tries to satisfy the spending condition of each input using the partial signatures collected. In case timelocks are present the wallet needs to know whether or not they have expired. This flag +is particularly useful for offline wallets. + +### `sync` + +This subcommand has no extra flags. It connects to the chosen Electrum server and synchronizes the list of transactions received and available UTXOs. diff --git a/content/bdk-cli/playground.md b/content/bdk-cli/playground.md new file mode 100644 index 0000000000..f135f93619 --- /dev/null +++ b/content/bdk-cli/playground.md @@ -0,0 +1,9 @@ +--- +title: "Playground" +date: 2020-05-08T15:42:22+02:00 +draft: false +weight: 6 +pre: "6. " +--- + +{{< playground >}} diff --git a/content/bdk-cli/regtest.md b/content/bdk-cli/regtest.md new file mode 100644 index 0000000000..c7ef600a4b --- /dev/null +++ b/content/bdk-cli/regtest.md @@ -0,0 +1,52 @@ +--- +title: "Regtest" +date: 2020-04-29T00:19:34+02:00 +draft: false +weight: 4 +pre: "4. " +--- + +Running the `bdk-cli` tool in regtest requires having a local Electrum server set-up. There are two main implementations, [`electrs`](https://github.com/romanz/electrs) in Rust and [`ElectrumX`](https://github.com/spesmilo/electrumx) in Python. Since the Rust toolchain is already required to +use BDK, this page will focus mostly on the former. + +Electrs can be installed by running: + +```bash +cargo install --git https://github.com/romanz/electrs --bin electrs +``` + +Just like before, this command will probably take a while to finish. + +Once it's done, assuming you have a regtest bitcoind running in background, you can launch a new terminal and run the following command to actually start electrs: + +```bash +electrs -vv --timestamp --db-dir /tmp/electrs-db --electrum-rpc-addr="127.0.0.1:50001" --network=regtest --cookie-file=$HOME/.bitcoin/regtest/.cookie +``` + +on macOS you should change the cookie-file to `$HOME/Library/Application Support/Bitcoin/regtest/.cookie`. + +This will start the Electrum server on port 50001. You can then add the `-n regtest -s localhost:50001` to the `bdk-cli` commands to switch to the local regtest. + +## Troubleshooting + +#### Stuck with "*wait until bitcoind is synced (i.e. initialblockdownload = false)*" + +Just generate a few blocks with `bitcoin-cli generatetoaddress 1
` + +## Bonus: Docker + +If you have already installed Docker on your machine, you can also use 🍣 [Nigiri CLI](https://github.com/vulpemventures/nigiri) to spin-up a complete development environment in `regtest` that includes a `bitcoin` node, an `electrs` explorer and the [`esplora`](https://github.com/blockstream/esplora) web-app to visualize blocks and transactions in the browser. + +Install 🍣 Nigiri +```bash +$ curl https://getnigiri.vulpem.com | bash +``` + +Start Docker daemon and run Nigiri box +``` +$ nigiri start +``` + +This will start electrum RPC interface on port `51401`, the REST interface on `3000` and the esplora UI on `5000` (You can visit with the browser and look for blocks, addresses and transactions) + +You can then add the `-n regtest -s localhost:51401` to the `bdk-cli` commands to switch to the local regtest. diff --git a/content/repl/_index.md b/content/repl/_index.md deleted file mode 100644 index fd9d9c762d..0000000000 --- a/content/repl/_index.md +++ /dev/null @@ -1,12 +0,0 @@ -+++ -title = "REPL" -date = 2020-04-28T17:03:00+02:00 -weight = 5 -chapter = true -pre = ' ' -+++ - -# REPL - -The [bdk](https://github.com/bitcoindevkit/bdk) repo has a very minimalistic interactive shell called `repl` that acts both as a reference implementation of a wallet and a tool to -quickly experiment with descriptors and transactions. diff --git a/content/repl/compiler.md b/content/repl/compiler.md deleted file mode 100644 index 9b717a3893..0000000000 --- a/content/repl/compiler.md +++ /dev/null @@ -1,151 +0,0 @@ ---- -title: "Compiler" -date: 2020-04-29T12:06:50+02:00 -draft: false -weight: 5 -pre: "5. " ---- - -## Introduction - -If you want to play around with more complicated spending policies, you'll start to find it harder and harder to manually create the descriptors. This is where the miniscript compiler comes in! The `bdk` library -includes a very simple compiler that can produce a descriptor given a spending policy. The syntax used to encode the spending policy is very well described [in this page](http://bitcoin.sipa.be/miniscript/), -specifically in the "Policy to Miniscript compiler". The compiler included in BDK does basically the same job, but produces descriptors for `rust-miniscript` that have some minor differences from -the ones made by the C++ implementation used in that website. - -## Installation - -To install the miniscript compiler run the following command: - -```bash -cargo install --git https://github.com/bitcoindevkit/bdk --features="compiler" --example miniscriptc -``` - -Once the command is done, you should have a `miniscriptc` command available. You can check if that's the case by running `miniscriptc --help`. - -## Usage - -In this case the interface is very simple: it accepts two arguments called "POLICY" and "TYPE", in this order. The first one, as the name implies, sets the spending policy to compile. The latter defines the type -of address that should be used to encapsulate the produced script, like a P2SH, P2WSH, etc. - -Optionally, the `--parsed_policy` flag can be enabled and it will make the compiler print the JSON "human-readable" version of the spending policy, as described in the [`policies subcommand`](/repl/interface/#policies) of the CLI. - -The `--network` flag can be used to change the network encoding of the address shown. - -{{% notice tip %}} -Keep in mind that since the compiler loads and interprets the descriptor, all the public keys specified in the policy must be valid public keys. This differs from the web tool linked above that also accepts -placeholders too. As described in the previous sections of this guide, the keys can be either `xpub`/`xprv` with or without metadata and a derivation path, WIF keys or raw hex public keys. -{{% /notice %}} - -## Example - -Let's take this policy for example: - -```bash -miniscriptc --parsed_policy and(pk(cSQPHDBwXGjVzWRqAHm6zfvQhaTuj1f2bFH58h55ghbjtFwvmeXR),or(50@pk(02e96fe52ef0e22d2f131dd425ce1893073a3c6ad20e8cac36726393dfb4856a4c),older(1000)))) sh-wsh -``` - -The compiler should print something like: - -```text -[2020-04-29T10:42:05Z INFO miniscriptc] Compiling policy: and(pk(cSQPHDBwXGjVzWRqAHm6zfvQhaTuj1f2bFH58h55ghbjtFwvmeXR),or(50@pk(02e96fe52ef0e22d2f131dd425ce1893073a3c6ad20e8cac36726393dfb4856a4c),older(1000))) -[2020-04-29T10:42:05Z INFO miniscriptc] ... Descriptor: sh(wsh(and_v(or_c(c:pk(02e96fe52ef0e22d2f131dd425ce1893073a3c6ad20e8cac36726393dfb4856a4c),v:older(1000)),c:pk(cSQPHDBwXGjVzWRqAHm6zfvQhaTuj1f2bFH58h55ghbjtFwvmeXR)))) -[2020-04-29T10:42:05Z INFO miniscriptc] ... First address: 2MsqrJuZewY3o3ADAy1Uhi5vsBqTANjH3Cf -``` - -JSON policy: - -{{% json %}} -{ - "type":"THRESH", - "items":[ - { - "type":"THRESH", - "items":[ - { - "type":"SIGNATURE", - "pubkey":"02e96fe52ef0e22d2f131dd425ce1893073a3c6ad20e8cac36726393dfb4856a4c", - "satisfaction":{ - "type":"NONE" - }, - "contribution":{ - "type":"NONE" - } - }, - { - "type":"RELATIVETIMELOCK", - "value":1000, - "satisfaction":{ - "type":"NONE" - }, - "contribution":{ - "type":"COMPLETE", - "condition":{ - "csv":1000 - } - } - } - ], - "threshold":1, - "satisfaction":{ - "type":"NONE" - }, - "contribution":{ - "type":"PARTIALCOMPLETE", - "n":2, - "m":1, - "items":[ - 1 - ], - "conditions":{ - "[1]":[ - { - "csv":1000 - } - ] - } - } - }, - { - "type":"SIGNATURE", - "pubkey":"02e96fe52ef0e22d2f131dd425ce1893073a3c6ad20e8cac36726393dfb4856a4c", - "satisfaction":{ - "type":"NONE" - }, - "contribution":{ - "type":"COMPLETE", - "condition":{ - - } - } - } - ], - "threshold":2, - "satisfaction":{ - "type":"NONE" - }, - "contribution":{ - "type":"PARTIALCOMPLETE", - "n":2, - "m":2, - "items":[ - 0, - 1 - ], - "conditions":{ - "[0, 1]":[ - { - "csv":1000 - } - ] - } - } -} -{{% /json %}} - -## Troubleshooting - -#### Nothing is printed - -This might mean that you have a `RUST_LOG` variable set to a value that suppresses the compiler's log. You can try adding `miniscriptc=info` to your `RUST_LOG` value and see if that works, or open a new clean -shell. diff --git a/content/repl/concept.md b/content/repl/concept.md deleted file mode 100644 index 9c9989f961..0000000000 --- a/content/repl/concept.md +++ /dev/null @@ -1,26 +0,0 @@ ---- -title: "Concept" -date: 2020-04-28T17:38:20+02:00 -draft: false -weight: 2 -pre: "2. " ---- - -Now, in order to better grasp some of the design choices made by BDK, it's important to understand the main concept driving the development of this project, and the goal that it's trying to -achieve. - -BDK is aiming first of all to be a **set of libraries and tools**, all meant to be very reusable and adaptable. Developers working on their own wallets or other projects that are trying to integrate -Bitcoin can pick the tools they need and piece them together to prototype and quickly ship a working product. This means that the REPL that we've just installed is designed to be a **very thin layer** over the -APIs exposed by the various components of the library, **not a full, end-user-ready Bitcoin wallet**. - -This concept leads to a few design choices that are arguably very bad for the "UX" of this wallet, but that allow developers to work more directly with the underlying library. For instance: - -* BDK has an internal database that's used to store data about received transactions, spendable UTXOs, etc. This database is stored by default in your home folder, in `~/.bdk-bitcoin`. The database - **will never** contain any data that can't be recreated purely by looking at the blockchain. Keys, descriptors, Electrum endpoints **are not stored in there**. This explains why you'll have to specify them every - time in the command line. It can be seen more like a *cache* and can be safely deleted without risking funds. -* BDK doesn't automatically "monitor" the blockchain, instead there's a `sync` command that has to be called by the user. -* When you create a transaction and then sign it, it's not automatically broadcast to the network. There's a `broadcast` command that does this. Moreover, the command doesn't accept a normal Bitcoin raw transaction, - but instead a *PSBT*. That's because internally transactions are always moved as PSBTs, and again, the `broadcast` command is just a very thin wrapper over the raw library call. - -There are probably more of these examples, but hopefully by this point you'll have more or less understood the gist of it. If you are not a developer, some parts of this will feel weird, inefficient, hard -to understand, and that's absolutely normal. Just try to survive through the pain and you'll be rewarded! diff --git a/content/repl/installation.md b/content/repl/installation.md deleted file mode 100644 index 9d0130cec1..0000000000 --- a/content/repl/installation.md +++ /dev/null @@ -1,71 +0,0 @@ ---- -title: "Installation" -date: 2020-04-28T17:11:29+02:00 -draft: false -weight: 1 -pre: "1. " ---- - -## Requirements - -The only requirement is a Linux/macOS system with a fairly recent Rust toolchain installed. Since Linux distros tend to lag behind with updates, the quickest way to install the Rust compiler and Cargo is -[rustup.rs](https://rustup.rs/). You can head there and follow their instructions, after which you can test if everything went fine by running `cargo version`, which should print something like: - -``` -cargo 1.45.0 (744bd1fbb 2020-06-15) -``` - -**At the time of writing, the project requires cargo >= 1.45.0, which is the latest stable as of June 2020. If you have an older version installed with rustup.rs, you can upgrade it with `rustup update`.** - -If you really don't want to pipe the output of `curl` into `sh`, you can also try using a [Docker image](https://hub.docker.com/_/rust) and working inside of it, but that's meant for more advanced -users and won't be covered in this guide. - -## Installing BDK `repl` - -Once Cargo is installed, you can proceed to install the interactive BDK `repl` tool directly from the GitHub repository, by running: - -```bash -cargo install --git https://github.com/bitcoindevkit/bdk --features=cli-utils,esplora --example repl -``` - -This command will probably take a while to finish, since it will fetch and compile all the dependencies and the `bdk` library itself. Once it's done, you can check if everything went fine -by running `repl --help` which should print something like this: - -```text -Magical Bitcoin Wallet 0.1.0 -Riccardo Casatta :Alekos Filini -A modern, lightweight, descriptor-based wallet - -USAGE: - repl [FLAGS] [OPTIONS] --descriptor [SUBCOMMAND] - -FLAGS: - -h, --help Prints help information - -v Sets the level of verbosity - -V, --version Prints version information - -OPTIONS: - -c, --change_descriptor Sets the descriptor to use for internal addresses - -d, --descriptor Sets the descriptor to use for the external addresses - -n, --network Sets the network [default: testnet] [possible values: testnet, regtest] - -s, --server Sets the Electrum server to use [default: tn.not.fyi:55001] - -w, --wallet Selects the wallet to use [default: main] - -SUBCOMMANDS: - broadcast Extracts the finalized transaction from a PSBT and broadcasts it to the network - create_tx Creates a new unsigned tranasaction - get_balance Returns the current wallet balance - get_new_address Generates a new external address - help Prints this message or the help of the given subcommand(s) - list_unspent Lists the available spendable UTXOs - policies Returns the available spending policies for the descriptor - repl Opens an interactive shell - sign Signs and tries to finalize a PSBT - sync Syncs with the chosen Electrum server -``` - -An example command to sync a testnet wallet looks like this: - -``` -repl --descriptor "wpkh(tprv8ZgxMBicQKsPexGYyaFwnAsCXCjmz2FaTm6LtesyyihjbQE3gRMfXqQBXKM43DvC1UgRVv1qom1qFxNMSqVAs88qx9PhgFnfGVUdiiDf6j4/0/*)" --network testnet --server tcp://testnet.aranguren.org:51001 sync -``` diff --git a/content/repl/interface.md b/content/repl/interface.md deleted file mode 100644 index 0de6b502df..0000000000 --- a/content/repl/interface.md +++ /dev/null @@ -1,524 +0,0 @@ ---- -title: "Interface" -date: 2020-04-28T18:20:28+02:00 -draft: false -weight: 3 -pre: "3. " ---- - -Remember the `repl --help` command you ran before? Let's analyze its output here to figure out the interface: - -## Flags - -```text -FLAGS: - -h, --help Prints help information - -v Sets the level of verbosity - -V, --version Prints version information -``` - -These are the optional flags that can be set with every command. The `-h` flag prints the help message, the `-V` flag only prints the version and the `-v` is actually ignored at the moment. - -### Verbosity - -If you want to increase the verbosity of the output, you should use the `RUST_LOG` environment variable. You can set it like so to see a lot more of what's going on behind the scenes, before running the `repl` -command. You only have to do this once when you open a new shell, after that you can run the `repl` command multiple times. - -```bash -export RUST_LOG="bdk=debug" -``` - -## Options - -```text -OPTIONS: - -c, --change_descriptor Sets the descriptor to use for internal addresses - -d, --descriptor Sets the descriptor to use for the external addresses - -e, --esplora Use the esplora server if given as parameter - -n, --network Sets the network [default: testnet] [possible values: testnet, regtest] - -s, --server Sets the Electrum server to use [default: - ssl://electrum.blockstream.info:60002] - -w, --wallet Selects the wallet to use [default: main] - -p, --proxy Sets the SOCKS5 proxy for the Electrum client -``` - -These are the global options that can be set. They are pretty much like the flags, but they also take a value. The only **required** one is the `--descriptor` or `-d` flag, since every wallet **must have an -associated descriptor**. - -The `--change-descriptor` flag can be used to set a different descriptor for the change addresses, sometimes called "internal" addresses in Bitcoin Core. Unfortunately there isn't -[really consensus](https://freenode.irclog.whitequark.org/bitcoin-wizards/2020-01-25#26222504;) on a nice way to encode information about the change derivation inside the standard descriptor, so we are -stuck with having two separate ones. Keep in mind though, that even if you don't specify a change descriptor, you'll still be able to create transactions - the change address will simply be generated from the -standard descriptor. - -The `--network` flag can be used to change the network. Right now only `testnet` and `regtest` are supported since the code is very much not production-ready yet. - -The `--server` flag can be used to select the Electrum server to use. By default it's connecting to Blockstream's electrum servers, which seems pretty stable. -If you are having connection issues, you can also try with one of the other servers [listed here](https://1209k.com/bitcoin-eye/ele.php?chain=tbtc) and see if you have more luck with those. -Right now both plaintext and ssl servers are supported (prefix `tcp://` or no prefix at all for tcp, prefix `ssl://` for ssl). - -The `--esplora` flag can be used to connect to an Esplora instance instead of using Electrum. It should be set to the API's "base url". For public instances of Esplora this is `https://blockstream.info/api` for mainnet -and `https://blockstream.info/testnet/api` for testnet. - -The `--proxy` flag can be optionally used to specify a SOCKS5 proxy to use when connecting to the Electrum server. Spawning a local Tor daemon and using it as a proxy will allow you to connect to `.onion` Electrum -URLs. **Keep in mind that only plaintext server are supported over a proxy** - -The `--wallet` flag can be used to select which wallet to use, if you have more than one of them. If you get a `ChecksumMismatch` error when you make some changes to your descriptor, it's because it does not -match anymore the one you've used to initialize the cache. One solution could be to switch to a new wallet name, or delete the cache directory at `~/.bdk` and start from scratch. - -## Subcommands - -| Command | Description | -| ------- | ----------- | -| [broadcast](#broadcast) | Broadcasts a transaction to the network. Takes either a raw transaction or a PSBT to extract | -| [bump_fee](#bump_fee) | Bumps the fees of an RBF transaction | -| [combine_psbt](#combine_psbt) | Combines multiple PSBTs into one | -| [create_tx](#create_tx) | Creates a new unsigned tranasaction | -| [extract_psbt](#extract_psbt) | Extracts a raw transaction from a PSBT | -| [finalize_psbt](#finalize_psbt) | Finalizes a psbt | -| [get_balance](#get_balance) | Returns the current wallet balance | -| [get_new_address](#get_new_address) | Generates a new external address | -| [list_transactions](#list_transactions) | Lists all the incoming and outgoing transactions of the wallet | -| [list_unspent](#list_unspent) | Lists the available spendable UTXOs | -| [policies](#policies) | Returns the available spending policies for the descriptor | -| [public_descriptor](#public_descriptor) | Returns the public version of the wallet's descriptor(s) | -| [repl](#repl) | Opens an interactive shell | -| [sign](#sign) | Signs and tries to finalize a PSBT | -| [sync](#sync) | Syncs with the chosen Electrum server | - -These are the main "functions" of the wallet. Most of them are pretty self explanatory, but we'll go over them quickly anyways. You can get more details about every single command by running `repl --help`. - -### broadcast - -```text -OPTIONS: - --psbt Sets the PSBT to extract and broadcast - --tx Sets the raw transaction to broadcast -``` - -Broadcasts a transaction. The transaction can be a raw hex transaction or a PSBT, in which case it also has to be "finalizable" (i.e. it should contain enough partial signatures to construct a finalized valid scriptsig/witness). - -### bump\_fee - -```text -FLAGS: - -a, --send_all Allows the wallet to reduce the amount of the only output in order to increase fees. This is - generally the expected behavior for transactions originally created with `send_all` - -OPTIONS: - -f, --fee_rate The new targeted fee rate in sat/vbyte - -t, --txid TXID of the transaction to update - --unspendable ... Marks an utxo as unspendable, in case more inputs are needed to cover the extra - fees - --utxos ... Selects which utxos *must* be added to the tx. Unconfirmed utxos cannot be used -``` - -Bumps the fee of a transaction made with RBF. The transaction to bump is specified using the `--txid` flag and the new fee rate with `--fee_rate`. - -The `--send_all` flag should be enabled if the original transaction was also made with `--send_all`. - -### combine\_psbt - -```text -OPTIONS: - --psbt ... Add one PSBT to comine. This option can be repeated multiple times, one for each PSBT -``` - -Combines multiple PSBTs by merging metadata and partial signatures. It can be used to merge multiple signed PSBTs into a single PSBT that contains every signature and is ready to be [finalized](#finalize_psbt). - -### create\_tx - -```text -FLAGS: - -a, --send_all Sends all the funds (or all the selected utxos). Requires only one addressees of value 0 - -r, --enable_rbf Enables Replace-By-Fee (BIP125) - -OPTIONS: - --external_policy Selects which policy should be used to satisfy the external descriptor - -f, --fee_rate Fee rate to use in sat/vbyte - --internal_policy Selects which policy should be used to satisfy the internal descriptor - --to ... Adds an addressee to the transaction - --unspendable ... Marks an utxo as unspendable - --utxos ... Selects which utxos *must* be spent -``` - -Creates a new unsigned PSBT. The flags allow to set a custom fee rate (the default is 1.0 sat/vbyte) with `--fee_rate` or `-f`, the list of UTXOs that should be considered unspendable with `--unspendable` (this -option can be specified multiple times) and a list of UTXOs that must be spent with `--utxos` (again, this option can also be specified multiple times). - -The `--to` option sets the receiver address of the transaction, and should contain the address and amount in Satoshi separated by a colon, like: `--to --to 2NErbQPsooXRatRJdrXDm9wKR2fRiZDT9wL:50000`. This option -can also be specified multiple times to send to multiple addresses at once. - -The `--send_all` flag can be used to send the value of all the spendable UTXOs to a single address, without creating a change output. If this flag is set, there must be only one `--to` address, and its value will -be ignored (it can be set to 0). - -The `--external_policy` and `--internal_policy` options are two advanced flags that can be used to select the spending policy that the sender intends to satisfy in this transaction. They are normally not required if there's no ambiguity, but sometimes -with complex descriptor one or both of them have to be specified, or you'll get a `SpendingPolicyRequired` error. Those flags should be set to a JSON object that maps a policy node id to the list of child indexes that -the user intends to satisfy for that node. This is probably better explained with an example: - -Let's assume our descriptor is: `sh(thresh(2,pk(A),sj:and_v(v:pk(B),n:older(6)),snj:and_v(v:pk(C),after(630000))))`. There are three conditions and we need to satisfy two of them to be able to spend. The conditions are: - -1. Sign with the key corresponding to `pk(A)` -2. Sign with the key corresponding to `pk(B)` AND wait 6 blocks -2. Sign with the key corresponding to `pk(C)` AND wait that block 630,000 is reached - -So if we write down all the possible outcomes when we combine them, we get: - -1. Sign with `pk(A)` + `pk(B)` + wait 6 blocks -2. Sign with `pk(A)` + `pk(C)` + wait block 630,000 -3. Sign with `pk(B)` + `pk(C)` + wait 6 blocks + wait block 630,000 - -In other words: - -* If we choose option #1, the final transaction will need to have the `nSequence` of its inputs set to a value greather than or equal to 6, but the `nLockTime` can stay at 0. -* If we choose option #2, the final transaction will need to have its `nLockTime` set to a value greater than or equal to 630,000, but the `nSequence` can be set to a final value. -* If we choose option #3, both the `nSequence` and `nLockTime` must be set. - -The wallet can't choose by itself which one of these combination to use, so the user has to provide this information with the `--external_policy` flag. - -Now, let's draw the condition tree to understand better how the chosen policy is represented: every node has its id shown right next to its name, like `qd3um656` for the root node. These ids can be seen by running the [policies](#policies) command. -Some ids have been omitted since they are not particularly relevant, in this example we will actually only use the root id. - -{{}} -graph TD; - subgraph " " - R["Root - qd3um656"] --> A["pk(A) - ykfuwzkl"] - R["Root - qd3um656"] --> B["B - ms3xjley"] - B["B - ms3xjley"] --> B_0["pk(B)"] - B["B - ms3xjley"] --> B_1["older(6)"] - end - C["C - d8jph6ax"] --> C_0["pk(C)"] - C["C - d8jph6ax"] --> C_1["after(630,000)"] - R["Root - qd3um656"] --> C["C - d8jph6ax"] -{{< /mermaid >}} - -Let's imagine that we are walking down from the root, and we want to use option #1. So we will have to select `pk(A)` + the whole `B` node. Since these nodes have an id, we can use it to refer to them and say which children -we want to use. In this case we want to use children #0 and #1 of the root, so our final policy will be: `--external_policy {"qd3um656":[0,1]}`. - -### extract\_psbt - -```text -OPTIONS: - --psbt Sets the PSBT to extract -``` - -Extracts the global transaction from a PSBT. **Note that partial signatures are ignored in this step. If you want to merge the partial signatures back into the global transaction first, please use [finalize_psbt](#finalize_psbt) first** - -### finalize\_psbt - -```text -OPTIONS: - --assume_height Assume the blockchain has reached a specific height - --psbt Sets the PSBT to finalize -``` - -Tries to finalize a PSBT by merging all the partial signatures and other elements back into the global transaction. This command fails if there are timelocks that have not yet expired, but the check can be overridden -by specifying `--assume_height` to make the wallet assume that a future height has already been reached. - -### get\_balance - -This subcommand has no extra flags, and simply returns the available balance in Satoshis. This command **should normally be called after [`sync`](#sync)**, since it only looks into the local cache to determine the list of UTXOs. - -### get\_new\_address - -This subcommand has no extra flags and returns a new address. It internally increments the derivation index and saves it in the database. - -### list\_transactions - -This subcommand has no extra flags and returns the history of transactions made or received by the wallet, with their txid, confirmation height and the amounts (in Satoshi) "sent" (meaning, the sum of the wallet's inputs spent in the transaction) and -"received" (meaning, the sum of the outputs received by the wallet). Just like [`get_balance`](#get_balance) it **should normally be called after [`sync`](#sync)**, since it only operates -on the internal cache. - -### list\_unspent - -This subcommand has no extra flags and returns the list of available UTXOs and their value in Satoshi. Just like [`get_balance`](#get_balance) it **should normally be called after [`sync`](#sync)**, since it only operates -on the internal cache. - -### policies - -This subcommand has no extra flags and returns the spending policies encoded by the descriptor in a more human-readable format. As an example, running the `policies` command on the descriptor shown earlier for the -in the explanation of the [create_tx](#create_tx) command, it will return this: - -{{% json %}} -{ - "id":"qd3um656", - "type":"THRESH", - "items":[ - { - "id":"ykfuwzkl", - "type":"SIGNATURE", - "pubkey":"...", - "satisfaction":{ - "type":"NONE" - }, - "contribution":{ - "type":"COMPLETE", - "condition":{ - - } - } - }, - { - "id":"ms3xjley", - "type":"THRESH", - "items":[ - { - "id":"xgfnp9rt", - "type":"SIGNATURE", - "pubkey":"...", - "satisfaction":{ - "type":"NONE" - }, - "contribution":{ - "type":"COMPLETE", - "condition":{ - - } - } - }, - { - "id":"5j96ludf", - "type":"RELATIVETIMELOCK", - "value":6, - "satisfaction":{ - "type":"NONE" - }, - "contribution":{ - "type":"COMPLETE", - "condition":{ - "csv":6 - } - } - } - ], - "threshold":2, - "satisfaction":{ - "type":"NONE" - }, - "contribution":{ - "type":"PARTIALCOMPLETE", - "n":2, - "m":2, - "items":[ - 0, - 1 - ], - "conditions":{ - "[0, 1]":[ - { - "csv":6 - } - ] - } - } - }, - { - "id":"d8jph6ax", - "type":"THRESH", - "items":[ - { - "id":"gdl039m6", - "type":"SIGNATURE", - "pubkey":"...", - "satisfaction":{ - "type":"NONE" - }, - "contribution":{ - "type":"COMPLETE", - "condition":{ - - } - } - }, - { - "id":"xpf2twg8", - "type":"ABSOLUTETIMELOCK", - "value":630000, - "satisfaction":{ - "type":"NONE" - }, - "contribution":{ - "type":"COMPLETE", - "condition":{ - "timelock":630000 - } - } - } - ], - "threshold":2, - "satisfaction":{ - "type":"NONE" - }, - "contribution":{ - "type":"PARTIALCOMPLETE", - "n":2, - "m":2, - "items":[ - 0, - 1 - ], - "conditions":{ - "[0, 1]":[ - { - "timelock":630000 - } - ] - } - } - } - ], - "threshold":2, - "satisfaction":{ - "type":"NONE" - }, - "contribution":{ - "type":"PARTIALCOMPLETE", - "n":3, - "m":2, - "items":[ - 0, - 1, - 2 - ], - "conditions":{ - "[0, 1]":[ - { - "csv":6 - } - ], - "[0, 2]":[ - { - "timelock":630000 - } - ], - "[1, 2]":[ - { - "csv":6, - "timelock":630000 - } - ] - } - } -} -{{% /json %}} - -This is a tree-like recursive structure, so it tends to get huge as more and more pieces are added, but it's in fact fairly simple. Let's analyze a simple node of the tree: - -```json -{ - "id":"qd3um656", - "type":"SIGNATURE", - "pubkey":"...", - "satisfaction":{ - "type":"NONE" - }, - "contribution":{ - "type":"COMPLETE", - "condition":{} - } -} -``` - -* `id` is a unique identifier to this specific node in the tree. -* `type`, as the name implies, represents the type of node. It defines what should be provided to satisfy that particular node. Generally some other data are provided to give meaning to - the type itself (like the `pubkey` field here in the example). There are basically two families of types: some of them can only be used as leaves, while some other can only be used as intermediate nodes. - - Possible leaf nodes are: - - `SIGNATURE`, requires a signature made with the specified key. Has a `pubkey` if it's a single key, a `fingerprint` if the key is an xpub, or a `pubkey_hash` if the full public key is not present in the descriptor. - - `SIGNATUREKEY`, requires a signature plus the raw public key. Again, it can have a `pubkey`, `fingerprint` or `pubkey_hash`. - - `SHA256PREIMAGE`, requires the preimage of a given `hash`. - - `HASH256PREIMAGE`, requires the preimage of a given `hash`. - - `RIPEMD160PREIMAGE`, requires the preimage of a given `hash`. - - `HASH160PREIMAGE`, requires the preimage of a given `hash`. - - `ABSOLUTETIMELOCK`, doesn't technically require anything to be satisfied, just waiting for the timelock to expire. Has a `value` field with the raw value of the timelock (can be both in blocks or time-based). - - `RELATIVETIMELOCK`, again only requires waiting for the timelock to expire. Has a `value` like `ABSOLUTETIMELOCK`. - - Possible non-leaf nodes are: - - `THRESH`, defines a threshold of policies that has to be met to satisfy the node. Has an `items` field, which is a list of policies to satisfy and a `threshold` field that defines the threshold. - - `MULTISIG`, Similar to `THRESH`, has a `keys` field, which is a list of keys represented again as either `pubkey`, `fingerprint` or `pubkey_hash` and a `threshold` field. - -* `satisfaction` is currently not implemented and will be used to provide PSBT introspection, like understanding whether or not a node is already satisfied and to which extent in a PSBT. -* `contribution` represents if so and how much, the provided descriptor can contribute to the node. - - The possible types are: - - `NONE`, which means that the descriptor cannot contribute. - - `COMPLETE`, which means that the descriptor by itself is enough to completely satisfy the node. It also adds a `condition` field which represent any potential extra condition that has to be met to - consider the node complete. An example are the timelock nodes, that are always complete *but* they have an extra `csv` or `timelock` condition. - - `PARTIAL`, which means that the descriptor can partially satisfy the descriptor. This adds a `m`, `n`, `items` that respectively represent the threshold, the number of available items to satisfy and the items - that the provided descriptor can satisfy. Also adds a `conditions` field which is an integer to list of conditions map. The key is the child index and the map are all the possibile extra conditions that - have to be satisfied if that node is used in the threshold. For instance, if you have a threshold of a SIGNATURE and a RELATIVETIMELOCK, in this order, the `conditions` field will be `1 ⇒ csv(x)`, - because the item at index 1 needs the extra csv condition. - - `PARTIALCOMPLETE`, which is basically a `PARTIAL` with the size of `items` >= `m`. It's treated as a separate entity to make the code a bit more clean and easier to implement. Like `PARTIAL`, it also has - a `m`, `n`, `items` fields but the `conditions field` is a bit different: it's a list of integers to list of conditions map. The key represents the combination that can be used to satisfy the threshold, - and the value contains all the possible conditions that also have to be satisfied. For instance, if you have a 2-of-2 threshold of a TIMELOCK and a RELATIVETIMELOCK, the `conditions` field will be `[0, 1] ⇒ - csv(x) + timelock(y)`, because if the combination of items 0 and 1 is picked, both of their conditions will have to be meet too. - -While the structure contains all of the intermediate nodes too, the root node is the most important one because defines how the descriptor can contribute to spend outputs sent to its addresses. - -For instance, looking at the root node of the previous example (with the internal `items` omitted) from a descriptor that has all the three private keys for keys A, B and C, we can clearly see that it can satisfy -the descriptor (type = `PARTIALCOMPLETE`) and the three options are `[0, 1] ⇒ csv(6)` (Option #1), `[0, 2] ⇒ timelock(630,000)` (Option #2) or `[1, 2] ⇒ csv(6) + timelock(630,000)` (Option #3). - -```json -{ - "type":"THRESH", - "items":[], - "threshold":2, - "satisfaction":{ - "type":"NONE" - }, - "contribution":{ - "type":"PARTIALCOMPLETE", - "n":3, - "m":2, - "items":[ - 0, - 1, - 2 - ], - "conditions":{ - "[0, 1]":[ - { - "csv":6 - } - ], - "[0, 2]":[ - { - "timelock":630000 - } - ], - "[1, 2]":[ - { - "csv":6, - "timelock":630000 - } - ] - } - } -} -``` - -### `public_descriptor` - -This subcommand has no extra flags and returns the "public" version of the wallet's descriptor(s). It can be used to bootstrap a watch-only instance for the wallet. - -### `repl` - -This subcommand has no extra flags and launches an interactive shell session. - -### `sign` - -```text -OPTIONS: - --assume_height Assume the blockchain has reached a specific height. This affects the transaction - finalization, if there are timelocks in the descriptor - --psbt Sets the PSBT to sign -``` - -Adds to the PSBT all the signatures it can produce with the secrets embedded in the descriptor (xprv or WIF keys). Returns the signed PSBT and, if there are enough item to satisfy the script, also the extracted raw -Bitcoin transaction. - -Optionally, the `assume_height` option can be specified to let the wallet assume the blockchain has reached a specific height. This affects the finalization of the PSBT which is done right at the end of the signing -process: the wallet tries to satisfy the spending condition of each input using the partial signatures collected. In case timelocks are present the wallet needs to know whether or not they have expired. This flag -is particularly useful for offline wallets. - -### `sync` - -This subcommand has no extra flags. It connects to the chosen Electrum server and synchronizes the list of transactions received and available UTXOs. diff --git a/content/repl/playground.md b/content/repl/playground.md deleted file mode 100644 index f135f93619..0000000000 --- a/content/repl/playground.md +++ /dev/null @@ -1,9 +0,0 @@ ---- -title: "Playground" -date: 2020-05-08T15:42:22+02:00 -draft: false -weight: 6 -pre: "6. " ---- - -{{< playground >}} diff --git a/content/repl/regtest.md b/content/repl/regtest.md deleted file mode 100644 index b626c9d043..0000000000 --- a/content/repl/regtest.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -title: "Regtest" -date: 2020-04-29T00:19:34+02:00 -draft: false -weight: 4 -pre: "4. " ---- - -Running the REPL in regtest requires having a local Electrum server set-up. There are two main implementations, [`electrs`](https://github.com/romanz/electrs) in Rust and [`ElectrumX`](https://github.com/spesmilo/electrumx) in Python. Since the Rust toolchain is already required to -use BDK, this page will focus mostly on the former. - -Electrs can be installed by running: - -```bash -cargo install --git https://github.com/romanz/electrs --bin electrs -``` - -Just like before, this command will probably take a while to finish. - -Once it's done, assuming you have a regtest bitcoind running in background, you can launch a new terminal and run the following command to actually start electrs: - -```bash -electrs -vv --timestamp --db-dir /tmp/electrs-db --electrum-rpc-addr="127.0.0.1:50001" --network=regtest --cookie-file=$HOME/.bitcoin/regtest/.cookie -``` - -on macOS you should change the cookie-file to `$HOME/Library/Application Support/Bitcoin/regtest/.cookie`. - -This will start the Electrum server on port 50001. You can then add the `-n regtest -s localhost:50001` the `repl` commands to switch to the local regtest. - -## Troubleshooting - -#### Stuck with "*wait until bitcoind is synced (i.e. initialblockdownload = false)*" - -Just generate a few blocks with `bitcoin-cli generatetoaddress 1
` - -## Bonus: Docker - -If you have already installed Docker on your machine, you can also use 🍣 [Nigiri CLI](https://github.com/vulpemventures/nigiri) to spin-up a complete development environment in `regtest` that includes a `bitcoin` node, an `electrs` explorer and the [`esplora`](https://github.com/blockstream/esplora) web-app to visualize blocks and transactions in the browser. - -Install 🍣 Nigiri -```bash -$ curl https://getnigiri.vulpem.com | bash -``` - -Start Docker daemon and run Nigiri box -``` -$ nigiri start -``` - -This will start electrum RPC interface on port `51401`, the REST interface on `3000` and the esplora UI on `5000` (You can visit with the browser and look for blocks, addresses and transactions) - -You can then add the `-n regtest -s localhost:51401` to the `repl` commands to switch to the local regtest. diff --git a/playground/www/index.html b/playground/www/index.html index 20a22dc8bc..6f032210de 100644 --- a/playground/www/index.html +++ b/playground/www/index.html @@ -3,4 +3,4 @@ - + diff --git a/playground/www/webpack.config.js b/playground/www/webpack.config.js index a84f692a35..26a6652bee 100644 --- a/playground/www/webpack.config.js +++ b/playground/www/webpack.config.js @@ -4,7 +4,7 @@ module.exports = { entry: "./src/bootstrap.js", output: { path: path.resolve(__dirname, "dist"), - publicPath: "/repl/playground/", + publicPath: "/bdk-cli/playground/", filename: "playground.js", } }; diff --git a/static/bdk-cli/playground/1.playground.js b/static/bdk-cli/playground/1.playground.js new file mode 100644 index 0000000000..87e47dfd57 --- /dev/null +++ b/static/bdk-cli/playground/1.playground.js @@ -0,0 +1,19 @@ +(window.webpackJsonp=window.webpackJsonp||[]).push([[1],[,,,function(t,e,o){var i,n,s;n=[o(6)],void 0===(s="function"==typeof(i=function(t){ +/** + * @license + * Copyright 2019 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +"use strict";return t.setLocale=function(e){t.Msg=t.Msg||{},Object.keys(e).forEach((function(o){t.Msg[o]=e[o]}))},t})?i.apply(e,n):i)||(t.exports=s)},function(t,e,o){var i,n,s;n=[o(5)],void 0===(s="function"==typeof(i=function(t){ +/** + * @license + * Copyright 2019 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +"use strict";return t})?i.apply(e,n):i)||(t.exports=s)},function(t,e,o){var i,n,s;n=[o(3),o(8),o(9),o(10)],void 0===(s="function"==typeof(i=function(t,e,o,i){ +/** + * @license + * Copyright 2019 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +"use strict";return t.setLocale(e),t.Blocks=t.Blocks||{},Object.keys(o).forEach((function(e){t.Blocks[e]=o[e]})),t.JavaScript=i,t})?i.apply(e,n):i)||(t.exports=s)},function(t,e,o){(function(o){var i,n,s;n=[],void 0===(s="function"==typeof(i=function(){"use strict";var t={constants:{},LINE_MODE_MULTIPLIER:40,PAGE_MODE_MULTIPLIER:125,DRAG_RADIUS:5,FLYOUT_DRAG_RADIUS:10,SNAP_RADIUS:28};return t.CONNECTING_SNAP_RADIUS=t.SNAP_RADIUS,t.CURRENT_CONNECTION_PREFERENCE=8,t.BUMP_DELAY=250,t.BUMP_RANDOMNESS=10,t.COLLAPSE_CHARS=30,t.LONGPRESS=750,t.SOUND_LIMIT=100,t.DRAG_STACK=!0,t.HSV_SATURATION=.45,t.HSV_VALUE=.65,t.SPRITE={width:96,height:124,url:"sprites.png"},t.INPUT_VALUE=1,t.OUTPUT_VALUE=2,t.NEXT_STATEMENT=3,t.PREVIOUS_STATEMENT=4,t.DUMMY_INPUT=5,t.ALIGN_LEFT=-1,t.ALIGN_CENTRE=0,t.ALIGN_RIGHT=1,t.DRAG_NONE=0,t.DRAG_STICKY=1,t.DRAG_BEGIN=1,t.DRAG_FREE=2,t.OPPOSITE_TYPE=[],t.OPPOSITE_TYPE[t.INPUT_VALUE]=t.OUTPUT_VALUE,t.OPPOSITE_TYPE[t.OUTPUT_VALUE]=t.INPUT_VALUE,t.OPPOSITE_TYPE[t.NEXT_STATEMENT]=t.PREVIOUS_STATEMENT,t.OPPOSITE_TYPE[t.PREVIOUS_STATEMENT]=t.NEXT_STATEMENT,t.TOOLBOX_AT_TOP=0,t.TOOLBOX_AT_BOTTOM=1,t.TOOLBOX_AT_LEFT=2,t.TOOLBOX_AT_RIGHT=3,t.DELETE_AREA_NONE=null,t.DELETE_AREA_TRASH=1,t.DELETE_AREA_TOOLBOX=2,t.VARIABLE_CATEGORY_NAME="VARIABLE",t.VARIABLE_DYNAMIC_CATEGORY_NAME="VARIABLE_DYNAMIC",t.PROCEDURE_CATEGORY_NAME="PROCEDURE",t.RENAME_VARIABLE_ID="RENAME_VARIABLE_ID",t.DELETE_VARIABLE_ID="DELETE_VARIABLE_ID",t.utils={},t.utils.global=function(){return"object"==typeof self?self:"object"==typeof window?window:"object"==typeof o?o:this}(),t.Msg={},t.utils.global.Blockly||(t.utils.global.Blockly={}),t.utils.global.Blockly.Msg||(t.utils.global.Blockly.Msg=t.Msg),t.utils.colour={},t.utils.colour.parse=function(e){e=String(e).toLowerCase().trim();var o=t.utils.colour.names[e];if(o)return o;if(o="#"==(o="0x"==e.substring(0,2)?"#"+e.substring(2):e)[0]?o:"#"+o,/^#[0-9a-f]{6}$/.test(o))return o;if(/^#[0-9a-f]{3}$/.test(o))return["#",o[1],o[1],o[2],o[2],o[3],o[3]].join("");var i=e.match(/^(?:rgb)?\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$/);return i&&(e=Number(i[1]),o=Number(i[2]),i=Number(i[3]),0<=e&&256>e&&0<=o&&256>o&&0<=i&&256>i)?t.utils.colour.rgbToHex(e,o,i):null},t.utils.colour.rgbToHex=function(t,e,o){return e=t<<16|e<<8|o,16>t?"#"+(16777216|e).toString(16).substr(1):"#"+e.toString(16)},t.utils.colour.hexToRgb=function(e){return(e=t.utils.colour.parse(e))?[(e=parseInt(e.substr(1),16))>>16,e>>8&255,255&e]:[0,0,0]},t.utils.colour.hsvToHex=function(e,o,i){var n=0,s=0,r=0;if(0==o)r=s=n=i;else{var a=Math.floor(e/60),l=e/60-a;e=i*(1-o);var c=i*(1-o*l);switch(o=i*(1-o*(1-l)),a){case 1:n=c,s=i,r=e;break;case 2:n=e,s=i,r=o;break;case 3:n=e,s=c,r=i;break;case 4:n=o,s=e,r=i;break;case 5:n=i,s=e,r=c;break;case 6:case 0:n=i,s=o,r=e}}return t.utils.colour.rgbToHex(Math.floor(n),Math.floor(s),Math.floor(r))},t.utils.colour.blend=function(e,o,i){return(e=t.utils.colour.parse(e))&&(o=t.utils.colour.parse(o))?(e=t.utils.colour.hexToRgb(e),o=t.utils.colour.hexToRgb(o),t.utils.colour.rgbToHex(Math.round(o[0]+i*(e[0]-o[0])),Math.round(o[1]+i*(e[1]-o[1])),Math.round(o[2]+i*(e[2]-o[2])))):null},t.utils.colour.names={aqua:"#00ffff",black:"#000000",blue:"#0000ff",fuchsia:"#ff00ff",gray:"#808080",green:"#008000",lime:"#00ff00",maroon:"#800000",navy:"#000080",olive:"#808000",purple:"#800080",red:"#ff0000",silver:"#c0c0c0",teal:"#008080",white:"#ffffff",yellow:"#ffff00"},t.utils.Coordinate=function(t,e){this.x=t,this.y=e},t.utils.Coordinate.equals=function(t,e){return t==e||!(!t||!e)&&t.x==e.x&&t.y==e.y},t.utils.Coordinate.distance=function(t,e){var o=t.x-e.x;return t=t.y-e.y,Math.sqrt(o*o+t*t)},t.utils.Coordinate.magnitude=function(t){return Math.sqrt(t.x*t.x+t.y*t.y)},t.utils.Coordinate.difference=function(e,o){return new t.utils.Coordinate(e.x-o.x,e.y-o.y)},t.utils.Coordinate.sum=function(e,o){return new t.utils.Coordinate(e.x+o.x,e.y+o.y)},t.utils.Coordinate.prototype.scale=function(t){return this.x*=t,this.y*=t,this},t.utils.Coordinate.prototype.translate=function(t,e){return this.x+=t,this.y+=e,this},t.utils.string={},t.utils.string.startsWith=function(t,e){return 0==t.lastIndexOf(e,0)},t.utils.string.shortestStringLength=function(t){return t.length?t.reduce((function(t,e){return t.lengtho&&(o=i[n].length);n=-1/0;var s=1;do{var r=n,a=e;e=[];var l=i.length/s,c=1;for(n=0;nr);return a},t.utils.string.wrapScore_=function(t,e,o){for(var i=[0],n=[],s=0;ss&&(s=l,n=a)}return n?t.utils.string.wrapMutate_(e,n,i):o},t.utils.string.wrapToText_=function(t,e){for(var o=[],i=0;i=l?(s=2,r=l,(l=e.join(""))&&i.push(l),e.length=0):"{"==l?s=3:(e.push("%",l),s=0):2==s?"0"<=l&&"9">=l?r+=l:(i.push(parseInt(r,10)),a--,s=0):3==s&&(""==l?(e.splice(0,0,"%{"),a--,s=0):"}"!=l?e.push(l):(s=e.join(""),/[A-Z]\w*/i.test(s)?(l=s.toUpperCase(),(l=t.utils.string.startsWith(l,"BKY_")?l.substring(4):null)&&l in t.Msg?"string"==typeof(s=t.Msg[l])?Array.prototype.push.apply(i,t.utils.tokenizeInterpolation_(s,o)):o?i.push(String(s)):i.push(s):i.push("%{"+s+"}")):i.push("%{"+s+"}"),s=e.length=0))}for((l=e.join(""))&&i.push(l),o=[],a=e.length=0;ai;i++)o[i]=t.utils.genUid.soup_.charAt(Math.random()*e);return o.join("")},t.utils.genUid.soup_="!#$%()*+,-./:;=?@[]^_`{|}~ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",t.utils.is3dSupported=function(){if(void 0!==t.utils.is3dSupported.cached_)return t.utils.is3dSupported.cached_;if(!t.utils.global.getComputedStyle)return!1;var e=document.createElement("p"),o="none",i={webkitTransform:"-webkit-transform",OTransform:"-o-transform",msTransform:"-ms-transform",MozTransform:"-moz-transform",transform:"transform"};for(var n in document.body.insertBefore(e,null),i)if(void 0!==e.style[n]){if(e.style[n]="translate3d(1px,1px,1px)",!(o=t.utils.global.getComputedStyle(e)))return document.body.removeChild(e),!1;o=o.getPropertyValue(i[n])}return document.body.removeChild(e),t.utils.is3dSupported.cached_="none"!==o,t.utils.is3dSupported.cached_},t.utils.runAfterPageLoad=function(t){if("object"!=typeof document)throw Error("Blockly.utils.runAfterPageLoad() requires browser document.");if("complete"==document.readyState)t();else var e=setInterval((function(){"complete"==document.readyState&&(clearInterval(e),t())}),10)},t.utils.getViewportBBox=function(){var e=t.utils.style.getViewportPageOffset();return{right:document.documentElement.clientWidth+e.x,bottom:document.documentElement.clientHeight+e.y,top:e.y,left:e.x}},t.utils.arrayRemove=function(t,e){return-1!=(e=t.indexOf(e))&&(t.splice(e,1),!0)},t.utils.getDocumentScroll=function(){var e=document.documentElement,o=window;return t.utils.userAgent.IE&&o.pageYOffset!=e.scrollTop?new t.utils.Coordinate(e.scrollLeft,e.scrollTop):new t.utils.Coordinate(o.pageXOffset||e.scrollLeft,o.pageYOffset||e.scrollTop)},t.utils.getBlockTypeCounts=function(t,e){var o=Object.create(null),i=t.getDescendants(!0);for(e&&(t=t.getNextBlock())&&(t=i.indexOf(t),i.splice(t,i.length-t)),t=0;e=i[t];t++)o[e.type]?o[e.type]++:o[e.type]=1;return o},t.utils.screenToWsCoordinates=function(e,o){var i=o.x;o=o.y;var n=e.getInjectionDiv().getBoundingClientRect();return i=new t.utils.Coordinate(i-n.left,o-n.top),o=e.getOriginOffsetInPixels(),t.utils.Coordinate.difference(i,o).scale(1/e.scale)},t.utils.parseBlockColour=function(e){var o="string"==typeof e?t.utils.replaceMessageReferences(e):e,i=Number(o);if(!isNaN(i)&&0<=i&&360>=i)return{hue:i,hex:t.utils.colour.hsvToHex(i,t.HSV_SATURATION,255*t.HSV_VALUE)};if(i=t.utils.colour.parse(o))return{hue:null,hex:i};throw i='Invalid colour: "'+o+'"',e!=o&&(i+=' (from "'+e+'")'),Error(i)},t.Events={},t.Events.group_="",t.Events.recordUndo=!0,t.Events.disabled_=0,t.Events.CREATE="create",t.Events.BLOCK_CREATE=t.Events.CREATE,t.Events.DELETE="delete",t.Events.BLOCK_DELETE=t.Events.DELETE,t.Events.CHANGE="change",t.Events.BLOCK_CHANGE=t.Events.CHANGE,t.Events.MOVE="move",t.Events.BLOCK_MOVE=t.Events.MOVE,t.Events.VAR_CREATE="var_create",t.Events.VAR_DELETE="var_delete",t.Events.VAR_RENAME="var_rename",t.Events.UI="ui",t.Events.COMMENT_CREATE="comment_create",t.Events.COMMENT_DELETE="comment_delete",t.Events.COMMENT_CHANGE="comment_change",t.Events.COMMENT_MOVE="comment_move",t.Events.FINISHED_LOADING="finished_loading",t.Events.BUMP_EVENTS=[t.Events.BLOCK_CREATE,t.Events.BLOCK_MOVE,t.Events.COMMENT_CREATE,t.Events.COMMENT_MOVE],t.Events.FIRE_QUEUE_=[],t.Events.fire=function(e){t.Events.isEnabled()&&(t.Events.FIRE_QUEUE_.length||setTimeout(t.Events.fireNow_,0),t.Events.FIRE_QUEUE_.push(e))},t.Events.fireNow_=function(){for(var e,o=t.Events.filter(t.Events.FIRE_QUEUE_,!0),i=t.Events.FIRE_QUEUE_.length=0;e=o[i];i++)if(e.workspaceId){var n=t.Workspace.getById(e.workspaceId);n&&n.fireChangeListener(e)}},t.Events.filter=function(e,o){e=e.slice(),o||e.reverse();for(var i,n=[],s=Object.create(null),r=0;i=e[r];r++)if(!i.isNull()){var a=[i.type,i.blockId,i.workspaceId].join(" "),l=s[a],c=l?l.event:null;l?i.type==t.Events.MOVE&&l.index==r-1?(c.newParentId=i.newParentId,c.newInputName=i.newInputName,c.newCoordinate=i.newCoordinate,l.index=r):i.type==t.Events.CHANGE&&i.element==c.element&&i.name==c.name?c.newValue=i.newValue:(i.type!=t.Events.UI||"click"!=i.element||"commentOpen"!=c.element&&"mutatorOpen"!=c.element&&"warningOpen"!=c.element)&&(s[a]={event:i,index:1},n.push(i)):(s[a]={event:i,index:r},n.push(i))}for(e=n.filter((function(t){return!t.isNull()})),o||e.reverse(),r=1;i=e[r];r++)i.type==t.Events.CHANGE&&"mutation"==i.element&&e.unshift(e.splice(r,1)[0]);return e},t.Events.clearPendingUndo=function(){for(var e,o=0;e=t.Events.FIRE_QUEUE_[o];o++)e.recordUndo=!1},t.Events.disable=function(){t.Events.disabled_++},t.Events.enable=function(){t.Events.disabled_--},t.Events.isEnabled=function(){return 0==t.Events.disabled_},t.Events.getGroup=function(){return t.Events.group_},t.Events.setGroup=function(e){t.Events.group_="boolean"==typeof e?e?t.utils.genUid():"":e},t.Events.getDescendantIds=function(t){var e=[];t=t.getDescendants(!1);for(var o,i=0;o=t[i];i++)e[i]=o.id;return e},t.Events.fromJson=function(e,o){switch(e.type){case t.Events.CREATE:var i=new t.Events.Create(null);break;case t.Events.DELETE:i=new t.Events.Delete(null);break;case t.Events.CHANGE:i=new t.Events.Change(null,"","","","");break;case t.Events.MOVE:i=new t.Events.Move(null);break;case t.Events.VAR_CREATE:i=new t.Events.VarCreate(null);break;case t.Events.VAR_DELETE:i=new t.Events.VarDelete(null);break;case t.Events.VAR_RENAME:i=new t.Events.VarRename(null,"");break;case t.Events.UI:i=new t.Events.Ui(null,"","","");break;case t.Events.COMMENT_CREATE:i=new t.Events.CommentCreate(null);break;case t.Events.COMMENT_CHANGE:i=new t.Events.CommentChange(null,"","");break;case t.Events.COMMENT_MOVE:i=new t.Events.CommentMove(null);break;case t.Events.COMMENT_DELETE:i=new t.Events.CommentDelete(null);break;case t.Events.FINISHED_LOADING:i=new t.Events.FinishedLoading(o);break;default:throw Error("Unknown event type.")}return i.fromJson(e),i.workspaceId=o.id,i},t.Events.disableOrphans=function(e){if((e.type==t.Events.MOVE||e.type==t.Events.CREATE)&&e.workspaceId){var o=t.Workspace.getById(e.workspaceId);if(e=o.getBlockById(e.blockId)){var i=e.getParent();if(i&&i.isEnabled())for(o=e.getDescendants(!1),e=0;i=o[e];e++)i.setEnabled(!0);else if((e.outputConnection||e.previousConnection)&&!o.isDragging())do{e.setEnabled(!1),e=e.getNextBlock()}while(e)}}},t.Events.Abstract=function(){this.workspaceId=void 0,this.group=t.Events.getGroup(),this.recordUndo=t.Events.recordUndo},t.Events.Abstract.prototype.toJson=function(){var t={type:this.type};return this.group&&(t.group=this.group),t},t.Events.Abstract.prototype.fromJson=function(t){this.group=t.group},t.Events.Abstract.prototype.isNull=function(){return!1},t.Events.Abstract.prototype.run=function(t){},t.Events.Abstract.prototype.getEventWorkspace_=function(){if(this.workspaceId)var e=t.Workspace.getById(this.workspaceId);if(!e)throw Error("Workspace is null. Event must have been generated from real Blockly events.");return e},t.utils.object={},t.utils.object.inherits=function(t,e){t.superClass_=e.prototype,t.prototype=Object.create(e.prototype),t.prototype.constructor=t},t.utils.object.mixin=function(t,e){for(var o in e)t[o]=e[o]},t.utils.object.deepMerge=function(e,o){for(var i in o)e[i]="object"==typeof o[i]?t.utils.object.deepMerge(e[i]||Object.create(null),o[i]):o[i];return e},t.utils.object.values=function(t){return Object.values?Object.values(t):Object.keys(t).map((function(e){return t[e]}))},t.Events.Ui=function(e,o,i,n){t.Events.Ui.superClass_.constructor.call(this),this.blockId=e?e.id:null,this.workspaceId=e?e.workspace.id:void 0,this.element=o,this.oldValue=i,this.newValue=n,this.recordUndo=!1},t.utils.object.inherits(t.Events.Ui,t.Events.Abstract),t.Events.Ui.prototype.type=t.Events.UI,t.Events.Ui.prototype.toJson=function(){var e=t.Events.Ui.superClass_.toJson.call(this);return e.element=this.element,void 0!==this.newValue&&(e.newValue=this.newValue),this.blockId&&(e.blockId=this.blockId),e},t.Events.Ui.prototype.fromJson=function(e){t.Events.Ui.superClass_.fromJson.call(this,e),this.element=e.element,this.newValue=e.newValue,this.blockId=e.blockId},t.utils.dom={},t.utils.dom.SVG_NS="http://www.w3.org/2000/svg",t.utils.dom.HTML_NS="http://www.w3.org/1999/xhtml",t.utils.dom.XLINK_NS="http://www.w3.org/1999/xlink",t.utils.dom.Node={ELEMENT_NODE:1,TEXT_NODE:3,COMMENT_NODE:8,DOCUMENT_POSITION_CONTAINED_BY:16},t.utils.dom.cacheWidths_=null,t.utils.dom.cacheReference_=0,t.utils.dom.canvasContext_=null,t.utils.dom.createSvgElement=function(e,o,i){for(var n in e=document.createElementNS(t.utils.dom.SVG_NS,e),o)e.setAttribute(n,o[n]);return document.body.runtimeStyle&&(e.runtimeStyle=e.currentStyle=e.style),i&&i.appendChild(e),e},t.utils.dom.addClass=function(t,e){var o=t.getAttribute("class")||"";return-1==(" "+o+" ").indexOf(" "+e+" ")&&(o&&(o+=" "),t.setAttribute("class",o+e),!0)},t.utils.dom.removeClass=function(t,e){var o=t.getAttribute("class");if(-1==(" "+o+" ").indexOf(" "+e+" "))return!1;o=o.split(/\s+/);for(var i=0;io||o>this.getChildCount())throw Error(t.Component.Error.CHILD_INDEX_OUT_OF_BOUNDS);if(this.childIndex_[e.getId()]=e,e.getParent()==this){var n=this.children_.indexOf(e);-1>>/g,e),(e=document.createElement("style")).id="blockly-common-style",i=document.createTextNode(i),e.appendChild(i),document.head.insertBefore(e,document.head.firstChild))}},t.Css.setCursor=function(t){console.warn("Deprecated call to Blockly.Css.setCursor. See https://github.com/google/blockly/issues/981 for context")},t.Css.CONTENT=[".blocklySvg {","background-color: #fff;","outline: none;","overflow: hidden;","position: absolute;","display: block;","}",".blocklyWidgetDiv {","display: none;","position: absolute;","z-index: 99999;","}",".injectionDiv {","height: 100%;","position: relative;","overflow: hidden;","touch-action: none;","}",".blocklyNonSelectable {","user-select: none;","-ms-user-select: none;","-webkit-user-select: none;","}",".blocklyWsDragSurface {","display: none;","position: absolute;","top: 0;","left: 0;","}",".blocklyWsDragSurface.blocklyOverflowVisible {","overflow: visible;","}",".blocklyBlockDragSurface {","display: none;","position: absolute;","top: 0;","left: 0;","right: 0;","bottom: 0;","overflow: visible !important;","z-index: 50;","}",".blocklyBlockCanvas.blocklyCanvasTransitioning,",".blocklyBubbleCanvas.blocklyCanvasTransitioning {","transition: transform .5s;","}",".blocklyTooltipDiv {","background-color: #ffffc7;","border: 1px solid #ddc;","box-shadow: 4px 4px 20px 1px rgba(0,0,0,.15);","color: #000;","display: none;","font-family: sans-serif;","font-size: 9pt;","opacity: .9;","padding: 2px;","position: absolute;","z-index: 100000;","}",".blocklyDropDownDiv {","position: absolute;","left: 0;","top: 0;","z-index: 1000;","display: none;","border: 1px solid;","border-color: #dadce0;","background-color: #fff;","border-radius: 2px;","padding: 4px;","box-shadow: 0px 0px 3px 1px rgba(0,0,0,.3);","}",".blocklyDropDownDiv.focused {","box-shadow: 0px 0px 6px 1px rgba(0,0,0,.3);","}",".blocklyDropDownContent {","max-height: 300px;","overflow: auto;","overflow-x: hidden;","}",".blocklyDropDownArrow {","position: absolute;","left: 0;","top: 0;","width: 16px;","height: 16px;","z-index: -1;","background-color: inherit;","border-color: inherit;","}",".blocklyDropDownButton {","display: inline-block;","float: left;","padding: 0;","margin: 4px;","border-radius: 4px;","outline: none;","border: 1px solid;","transition: box-shadow .1s;","cursor: pointer;","}",".blocklyArrowTop {","border-top: 1px solid;","border-left: 1px solid;","border-top-left-radius: 4px;","border-color: inherit;","}",".blocklyArrowBottom {","border-bottom: 1px solid;","border-right: 1px solid;","border-bottom-right-radius: 4px;","border-color: inherit;","}",".blocklyResizeSE {","cursor: se-resize;","fill: #aaa;","}",".blocklyResizeSW {","cursor: sw-resize;","fill: #aaa;","}",".blocklyResizeLine {","stroke: #515A5A;","stroke-width: 1;","}",".blocklyHighlightedConnectionPath {","fill: none;","stroke: #fc3;","stroke-width: 4px;","}",".blocklyPathLight {","fill: none;","stroke-linecap: round;","stroke-width: 1;","}",".blocklySelected>.blocklyPathLight {","display: none;","}",".blocklyDraggable {",'cursor: url("<<>>/handopen.cur"), auto;',"cursor: grab;","cursor: -webkit-grab;","}",".blocklyDragging {",'cursor: url("<<>>/handclosed.cur"), auto;',"cursor: grabbing;","cursor: -webkit-grabbing;","}",".blocklyDraggable:active {",'cursor: url("<<>>/handclosed.cur"), auto;',"cursor: grabbing;","cursor: -webkit-grabbing;","}",".blocklyBlockDragSurface .blocklyDraggable {",'cursor: url("<<>>/handclosed.cur"), auto;',"cursor: grabbing;","cursor: -webkit-grabbing;","}",".blocklyDragging.blocklyDraggingDelete {",'cursor: url("<<>>/handdelete.cur"), auto;',"}",".blocklyDragging>.blocklyPath,",".blocklyDragging>.blocklyPathLight {","fill-opacity: .8;","stroke-opacity: .8;","}",".blocklyDragging>.blocklyPathDark {","display: none;","}",".blocklyDisabled>.blocklyPath {","fill-opacity: .5;","stroke-opacity: .5;","}",".blocklyDisabled>.blocklyPathLight,",".blocklyDisabled>.blocklyPathDark {","display: none;","}",".blocklyInsertionMarker>.blocklyPath,",".blocklyInsertionMarker>.blocklyPathLight,",".blocklyInsertionMarker>.blocklyPathDark {","fill-opacity: .2;","stroke: none","}",".blocklyMultilineText {","font-family: monospace;","}",".blocklyNonEditableText>text {","pointer-events: none;","}",".blocklyFlyout {","position: absolute;","z-index: 20;","}",".blocklyText text {","cursor: default;","}",".blocklySvg text, .blocklyBlockDragSurface text {","user-select: none;","-ms-user-select: none;","-webkit-user-select: none;","cursor: inherit;","}",".blocklyHidden {","display: none;","}",".blocklyFieldDropdown:not(.blocklyHidden) {","display: block;","}",".blocklyIconGroup {","cursor: default;","}",".blocklyIconGroup:not(:hover),",".blocklyIconGroupReadonly {","opacity: .6;","}",".blocklyIconShape {","fill: #00f;","stroke: #fff;","stroke-width: 1px;","}",".blocklyIconSymbol {","fill: #fff;","}",".blocklyMinimalBody {","margin: 0;","padding: 0;","}",".blocklyHtmlInput {","border: none;","border-radius: 4px;","height: 100%;","margin: 0;","outline: none;","padding: 0;","width: 100%;","text-align: center;","display: block;","box-sizing: border-box;","}",".blocklyHtmlInput::-ms-clear {","display: none;","}",".blocklyMainBackground {","stroke-width: 1;","stroke: #c6c6c6;","}",".blocklyMutatorBackground {","fill: #fff;","stroke: #ddd;","stroke-width: 1;","}",".blocklyFlyoutBackground {","fill: #ddd;","fill-opacity: .8;","}",".blocklyMainWorkspaceScrollbar {","z-index: 20;","}",".blocklyFlyoutScrollbar {","z-index: 30;","}",".blocklyScrollbarHorizontal, .blocklyScrollbarVertical {","position: absolute;","outline: none;","}",".blocklyScrollbarBackground {","opacity: 0;","}",".blocklyScrollbarHandle {","fill: #ccc;","}",".blocklyScrollbarBackground:hover+.blocklyScrollbarHandle,",".blocklyScrollbarHandle:hover {","fill: #bbb;","}",".blocklyFlyout .blocklyScrollbarHandle {","fill: #bbb;","}",".blocklyFlyout .blocklyScrollbarBackground:hover+.blocklyScrollbarHandle,",".blocklyFlyout .blocklyScrollbarHandle:hover {","fill: #aaa;","}",".blocklyInvalidInput {","background: #faa;","}",".blocklyContextMenu {","border-radius: 4px;","max-height: 100%;","}",".blocklyDropdownMenu {","border-radius: 2px;","padding: 0 !important;","}",".blocklyWidgetDiv .blocklyDropdownMenu .goog-menuitem,",".blocklyDropDownDiv .blocklyDropdownMenu .goog-menuitem {","padding-left: 28px;","}",".blocklyWidgetDiv .blocklyDropdownMenu .goog-menuitem.goog-menuitem-rtl,",".blocklyDropDownDiv .blocklyDropdownMenu .goog-menuitem.goog-menuitem-rtl {","padding-left: 5px;","padding-right: 28px;","}",".blocklyVerticalMarker {","stroke-width: 3px;","fill: rgba(255,255,255,.5);","pointer-events: none","}",".blocklyWidgetDiv .goog-option-selected .goog-menuitem-checkbox,",".blocklyWidgetDiv .goog-option-selected .goog-menuitem-icon,",".blocklyDropDownDiv .goog-option-selected .goog-menuitem-checkbox,",".blocklyDropDownDiv .goog-option-selected .goog-menuitem-icon {","background: url(<<>>/sprites.png) no-repeat -48px -16px;","}",".blocklyWidgetDiv .goog-menu {","background: #fff;","border-color: transparent;","border-style: solid;","border-width: 1px;","cursor: default;","font: normal 13px Arial, sans-serif;","margin: 0;","outline: none;","padding: 4px 0;","position: absolute;","overflow-y: auto;","overflow-x: hidden;","max-height: 100%;","z-index: 20000;","box-shadow: 0px 0px 3px 1px rgba(0,0,0,.3);","}",".blocklyWidgetDiv .goog-menu.focused {","box-shadow: 0px 0px 6px 1px rgba(0,0,0,.3);","}",".blocklyDropDownDiv .goog-menu {","cursor: default;",'font: normal 13px "Helvetica Neue", Helvetica, sans-serif;',"outline: none;","z-index: 20000;","}",".blocklyWidgetDiv .goog-menuitem,",".blocklyDropDownDiv .goog-menuitem {","color: #000;","font: normal 13px Arial, sans-serif;","list-style: none;","margin: 0;","min-width: 7em;","border: none;","padding: 6px 15px;","white-space: nowrap;","cursor: pointer;","}",".blocklyWidgetDiv .goog-menu-nocheckbox .goog-menuitem,",".blocklyWidgetDiv .goog-menu-noicon .goog-menuitem,",".blocklyDropDownDiv .goog-menu-nocheckbox .goog-menuitem,",".blocklyDropDownDiv .goog-menu-noicon .goog-menuitem {","padding-left: 12px;","}",".blocklyWidgetDiv .goog-menuitem-content,",".blocklyDropDownDiv .goog-menuitem-content {","font-family: Arial, sans-serif;","font-size: 13px;","}",".blocklyWidgetDiv .goog-menuitem-content {","color: #000;","}",".blocklyDropDownDiv .goog-menuitem-content {","color: #000;","}",".blocklyWidgetDiv .goog-menuitem-disabled,",".blocklyDropDownDiv .goog-menuitem-disabled {","cursor: inherit;","}",".blocklyWidgetDiv .goog-menuitem-disabled .goog-menuitem-content,",".blocklyDropDownDiv .goog-menuitem-disabled .goog-menuitem-content {","color: #ccc !important;","}",".blocklyWidgetDiv .goog-menuitem-disabled .goog-menuitem-icon,",".blocklyDropDownDiv .goog-menuitem-disabled .goog-menuitem-icon {","opacity: .3;","filter: alpha(opacity=30);","}",".blocklyWidgetDiv .goog-menuitem-highlight ,",".blocklyDropDownDiv .goog-menuitem-highlight {","background-color: rgba(0,0,0,.1);","}",".blocklyWidgetDiv .goog-menuitem-checkbox,",".blocklyWidgetDiv .goog-menuitem-icon,",".blocklyDropDownDiv .goog-menuitem-checkbox,",".blocklyDropDownDiv .goog-menuitem-icon {","background-repeat: no-repeat;","height: 16px;","left: 6px;","position: absolute;","right: auto;","vertical-align: middle;","width: 16px;","}",".blocklyWidgetDiv .goog-menuitem-rtl .goog-menuitem-checkbox,",".blocklyWidgetDiv .goog-menuitem-rtl .goog-menuitem-icon,",".blocklyDropDownDiv .goog-menuitem-rtl .goog-menuitem-checkbox,",".blocklyDropDownDiv .goog-menuitem-rtl .goog-menuitem-icon {","left: auto;","right: 6px;","}",".blocklyWidgetDiv .goog-option-selected .goog-menuitem-checkbox,",".blocklyWidgetDiv .goog-option-selected .goog-menuitem-icon,",".blocklyDropDownDiv .goog-option-selected .goog-menuitem-checkbox,",".blocklyDropDownDiv .goog-option-selected .goog-menuitem-icon {","position: static;","float: left;","margin-left: -24px;","}",".blocklyWidgetDiv .goog-menuitem-rtl .goog-menuitem-checkbox,",".blocklyWidgetDiv .goog-menuitem-rtl .goog-menuitem-icon,",".blocklyDropDownDiv .goog-menuitem-rtl .goog-menuitem-checkbox,",".blocklyDropDownDiv .goog-menuitem-rtl .goog-menuitem-icon {","float: right;","margin-right: -24px;","}",".blocklyComputeCanvas {","position: absolute;","width: 0;","height: 0;","}",".blocklyNoPointerEvents {","pointer-events: none;","}"],t.utils.math={},t.utils.math.toRadians=function(t){return t*Math.PI/180},t.utils.math.toDegrees=function(t){return 180*t/Math.PI},t.utils.math.clamp=function(t,e,o){if(os.top?t.DropDownDiv.getPositionAboveMetrics_(i,n,s,r):o+r.heightdocument.documentElement.clientTop?t.DropDownDiv.getPositionAboveMetrics_(i,n,s,r):t.DropDownDiv.getPositionTopOfPageMetrics_(e,s,r)},t.DropDownDiv.getPositionBelowMetrics_=function(e,o,i,n){return{initialX:(e=t.DropDownDiv.getPositionX(e,i.left,i.right,n.width)).divX,initialY:o,finalX:e.divX,finalY:o+t.DropDownDiv.PADDING_Y,arrowX:e.arrowX,arrowY:-(t.DropDownDiv.ARROW_SIZE/2+t.DropDownDiv.BORDER_SIZE),arrowAtTop:!0,arrowVisible:!0}},t.DropDownDiv.getPositionAboveMetrics_=function(e,o,i,n){return{initialX:(e=t.DropDownDiv.getPositionX(e,i.left,i.right,n.width)).divX,initialY:o-n.height,finalX:e.divX,finalY:o-n.height-t.DropDownDiv.PADDING_Y,arrowX:e.arrowX,arrowY:n.height-2*t.DropDownDiv.BORDER_SIZE-t.DropDownDiv.ARROW_SIZE/2,arrowAtTop:!1,arrowVisible:!0}},t.DropDownDiv.getPositionTopOfPageMetrics_=function(e,o,i){return{initialX:(e=t.DropDownDiv.getPositionX(e,o.left,o.right,i.width)).divX,initialY:0,finalX:e.divX,finalY:0,arrowVisible:!1}},t.DropDownDiv.getPositionX=function(e,o,i,n){var s=e;return e=t.utils.math.clamp(o,e-n/2,i-n),s-=t.DropDownDiv.ARROW_SIZE/2,o=t.DropDownDiv.ARROW_HORIZONTAL_PADDING,{arrowX:n=t.utils.math.clamp(o,s-e,n-o-t.DropDownDiv.ARROW_SIZE),divX:e}},t.DropDownDiv.isVisible=function(){return!!t.DropDownDiv.owner_},t.DropDownDiv.hideIfOwner=function(e,o){return t.DropDownDiv.owner_===e&&(o?t.DropDownDiv.hideWithoutAnimation():t.DropDownDiv.hide(),!0)},t.DropDownDiv.hide=function(){var e=t.DropDownDiv.DIV_;e.style.transform="translate(0, 0)",e.style.opacity=0,t.DropDownDiv.animateOutTimer_=setTimeout((function(){t.DropDownDiv.hideWithoutAnimation()}),1e3*t.DropDownDiv.ANIMATION_TIME),t.DropDownDiv.onHide_&&(t.DropDownDiv.onHide_(),t.DropDownDiv.onHide_=null)},t.DropDownDiv.hideWithoutAnimation=function(){if(t.DropDownDiv.isVisible()){t.DropDownDiv.animateOutTimer_&&clearTimeout(t.DropDownDiv.animateOutTimer_);var e=t.DropDownDiv.DIV_;e.style.transform="",e.style.left="",e.style.top="",e.style.opacity=0,e.style.display="none",e.style.backgroundColor="",e.style.borderColor="",t.DropDownDiv.onHide_&&(t.DropDownDiv.onHide_(),t.DropDownDiv.onHide_=null),t.DropDownDiv.clearContent(),t.DropDownDiv.owner_=null,t.DropDownDiv.rendererClassName_&&(t.utils.dom.removeClass(e,t.DropDownDiv.rendererClassName_),t.DropDownDiv.rendererClassName_=""),t.DropDownDiv.themeClassName_&&(t.utils.dom.removeClass(e,t.DropDownDiv.themeClassName_),t.DropDownDiv.themeClassName_=""),t.getMainWorkspace().markFocused()}},t.DropDownDiv.positionInternal_=function(e,o,i,n){(e=t.DropDownDiv.getPositionMetrics_(e,o,i,n)).arrowVisible?(t.DropDownDiv.arrow_.style.display="",t.DropDownDiv.arrow_.style.transform="translate("+e.arrowX+"px,"+e.arrowY+"px) rotate(45deg)",t.DropDownDiv.arrow_.setAttribute("class",e.arrowAtTop?"blocklyDropDownArrow blocklyArrowTop":"blocklyDropDownArrow blocklyArrowBottom")):t.DropDownDiv.arrow_.style.display="none",o=Math.floor(e.initialX),i=Math.floor(e.initialY),n=Math.floor(e.finalX);var s=Math.floor(e.finalY),r=t.DropDownDiv.DIV_;return r.style.left=o+"px",r.style.top=i+"px",r.style.display="block",r.style.opacity=1,r.style.transform="translate("+(n-o)+"px,"+(s-i)+"px)",e.arrowAtTop},t.DropDownDiv.repositionForWindowResize=function(){if(t.DropDownDiv.owner_){var e=t.DropDownDiv.owner_,o=t.DropDownDiv.owner_.getSourceBlock();o=(e=t.DropDownDiv.positionToField_?t.DropDownDiv.getScaledBboxOfField_(e):t.DropDownDiv.getScaledBboxOfBlock_(o)).left+(e.right-e.left)/2,t.DropDownDiv.positionInternal_(o,e.bottom,o,e.top)}else t.DropDownDiv.hide()},t.Grid=function(t,e){this.gridPattern_=t,this.spacing_=e.spacing,this.length_=e.length,this.line2_=(this.line1_=t.firstChild)&&this.line1_.nextSibling,this.snapToGrid_=e.snap},t.Grid.prototype.scale_=1,t.Grid.prototype.dispose=function(){this.gridPattern_=null},t.Grid.prototype.shouldSnap=function(){return this.snapToGrid_},t.Grid.prototype.getSpacing=function(){return this.spacing_},t.Grid.prototype.getPatternId=function(){return this.gridPattern_.id},t.Grid.prototype.update=function(t){this.scale_=t;var e=this.spacing_*t||100;this.gridPattern_.setAttribute("width",e),this.gridPattern_.setAttribute("height",e);var o=(e=Math.floor(this.spacing_/2)+.5)-this.length_/2,i=e+this.length_/2;e*=t,o*=t,i*=t,this.setLineAttributes_(this.line1_,t,o,i,e,e),this.setLineAttributes_(this.line2_,t,e,e,o,i)},t.Grid.prototype.setLineAttributes_=function(t,e,o,i,n,s){t&&(t.setAttribute("stroke-width",e),t.setAttribute("x1",o),t.setAttribute("y1",n),t.setAttribute("x2",i),t.setAttribute("y2",s))},t.Grid.prototype.moveTo=function(e,o){this.gridPattern_.setAttribute("x",e),this.gridPattern_.setAttribute("y",o),(t.utils.userAgent.IE||t.utils.userAgent.EDGE)&&this.update(this.scale_)},t.Grid.createDom=function(e,o,i){return e=t.utils.dom.createSvgElement("pattern",{id:"blocklyGridPattern"+e,patternUnits:"userSpaceOnUse"},i),0e.indexOf(o))throw Error(o+" is not a valid modifier key.")},t.user.keyMap.createSerializedKey=function(e,o){var i="",n=t.utils.object.values(t.user.keyMap.modifierKeys);t.user.keyMap.checkModifiers_(o,n);for(var s,r=0;s=n[r];r++)-1");o.domToMutation(n)}t.Events.fire(new t.Events.Change(o,"mutation",null,i,e));break;default:console.warn("Unknown change type: "+this.element)}else console.warn("Can't change non-existent block: "+this.blockId)},t.Events.Create=function(e){e&&(t.Events.Create.superClass_.constructor.call(this,e),this.xml=e.workspace.rendered?t.Xml.blockToDomWithXY(e):t.Xml.blockToDom(e),this.ids=t.Events.getDescendantIds(e))},t.utils.object.inherits(t.Events.Create,t.Events.BlockBase),t.Events.BlockCreate=t.Events.Create,t.Events.Create.prototype.type=t.Events.CREATE,t.Events.Create.prototype.toJson=function(){var e=t.Events.Create.superClass_.toJson.call(this);return e.xml=t.Xml.domToText(this.xml),e.ids=this.ids,e},t.Events.Create.prototype.fromJson=function(e){t.Events.Create.superClass_.fromJson.call(this,e),this.xml=t.Xml.textToDom(e.xml),this.ids=e.ids},t.Events.Create.prototype.run=function(e){var o=this.getEventWorkspace_();if(e)(e=t.utils.xml.createElement("xml")).appendChild(this.xml),t.Xml.domToWorkspace(e,o);else{e=0;for(var i;i=this.ids[e];e++){var n=o.getBlockById(i);n?n.dispose(!1):i==this.blockId&&console.warn("Can't uncreate non-existent block: "+i)}}},t.Events.Delete=function(e){if(e){if(e.getParent())throw Error("Connected blocks cannot be deleted.");t.Events.Delete.superClass_.constructor.call(this,e),this.oldXml=e.workspace.rendered?t.Xml.blockToDomWithXY(e):t.Xml.blockToDom(e),this.ids=t.Events.getDescendantIds(e)}},t.utils.object.inherits(t.Events.Delete,t.Events.BlockBase),t.Events.BlockDelete=t.Events.Delete,t.Events.Delete.prototype.type=t.Events.DELETE,t.Events.Delete.prototype.toJson=function(){var e=t.Events.Delete.superClass_.toJson.call(this);return e.ids=this.ids,e},t.Events.Delete.prototype.fromJson=function(e){t.Events.Delete.superClass_.fromJson.call(this,e),this.ids=e.ids},t.Events.Delete.prototype.run=function(e){var o=this.getEventWorkspace_();if(e){e=0;for(var i;i=this.ids[e];e++){var n=o.getBlockById(i);n?n.dispose(!1):i==this.blockId&&console.warn("Can't delete non-existent block: "+i)}}else(e=t.utils.xml.createElement("xml")).appendChild(this.oldXml),t.Xml.domToWorkspace(e,o)},t.Events.Move=function(e){e&&(t.Events.Move.superClass_.constructor.call(this,e),e=this.currentLocation_(),this.oldParentId=e.parentId,this.oldInputName=e.inputName,this.oldCoordinate=e.coordinate)},t.utils.object.inherits(t.Events.Move,t.Events.BlockBase),t.Events.BlockMove=t.Events.Move,t.Events.Move.prototype.type=t.Events.MOVE,t.Events.Move.prototype.toJson=function(){var e=t.Events.Move.superClass_.toJson.call(this);return this.newParentId&&(e.newParentId=this.newParentId),this.newInputName&&(e.newInputName=this.newInputName),this.newCoordinate&&(e.newCoordinate=Math.round(this.newCoordinate.x)+","+Math.round(this.newCoordinate.y)),e},t.Events.Move.prototype.fromJson=function(e){t.Events.Move.superClass_.fromJson.call(this,e),this.newParentId=e.newParentId,this.newInputName=e.newInputName,e.newCoordinate&&(e=e.newCoordinate.split(","),this.newCoordinate=new t.utils.Coordinate(Number(e[0]),Number(e[1])))},t.Events.Move.prototype.recordNew=function(){var t=this.currentLocation_();this.newParentId=t.parentId,this.newInputName=t.inputName,this.newCoordinate=t.coordinate},t.Events.Move.prototype.currentLocation_=function(){var t=this.getEventWorkspace_().getBlockById(this.blockId),e={},o=t.getParent();return o?(e.parentId=o.id,(t=o.getInputWithBlock(t))&&(e.inputName=t.name)):e.coordinate=t.getRelativeToSurfaceXY(),e},t.Events.Move.prototype.isNull=function(){return this.oldParentId==this.newParentId&&this.oldInputName==this.newInputName&&t.utils.Coordinate.equals(this.oldCoordinate,this.newCoordinate)},t.Events.Move.prototype.run=function(e){var o=this.getEventWorkspace_(),i=o.getBlockById(this.blockId);if(i){var n=e?this.newParentId:this.oldParentId,s=e?this.newInputName:this.oldInputName;e=e?this.newCoordinate:this.oldCoordinate;var r=null;if(n&&!(r=o.getBlockById(n)))return void console.warn("Can't connect to non-existent block: "+n);if(i.getParent()&&i.unplug(),e)s=i.getRelativeToSurfaceXY(),i.moveBy(e.x-s.x,e.y-s.y);else{if(i=i.outputConnection||i.previousConnection,s){if(o=r.getInput(s))var a=o.connection}else i.type==t.PREVIOUS_STATEMENT&&(a=r.nextConnection);a?i.connect(a):console.warn("Can't connect to non-existent input: "+s)}}else console.warn("Can't move non-existent block: "+this.blockId)},t.Events.FinishedLoading=function(e){this.workspaceId=e.id,this.group=t.Events.getGroup(),this.recordUndo=!1},t.utils.object.inherits(t.Events.FinishedLoading,t.Events.Ui),t.Events.FinishedLoading.prototype.type=t.Events.FINISHED_LOADING,t.Events.FinishedLoading.prototype.toJson=function(){var t={type:this.type};return this.group&&(t.group=this.group),this.workspaceId&&(t.workspaceId=this.workspaceId),t},t.Events.FinishedLoading.prototype.fromJson=function(t){this.workspaceId=t.workspaceId,this.group=t.group},t.Events.VarBase=function(e){t.Events.VarBase.superClass_.constructor.call(this),this.varId=e.getId(),this.workspaceId=e.workspace.id},t.utils.object.inherits(t.Events.VarBase,t.Events.Abstract),t.Events.VarBase.prototype.toJson=function(){var e=t.Events.VarBase.superClass_.toJson.call(this);return e.varId=this.varId,e},t.Events.VarBase.prototype.fromJson=function(e){t.Events.VarBase.superClass_.toJson.call(this),this.varId=e.varId},t.Events.VarCreate=function(e){e&&(t.Events.VarCreate.superClass_.constructor.call(this,e),this.varType=e.type,this.varName=e.name)},t.utils.object.inherits(t.Events.VarCreate,t.Events.VarBase),t.Events.VarCreate.prototype.type=t.Events.VAR_CREATE,t.Events.VarCreate.prototype.toJson=function(){var e=t.Events.VarCreate.superClass_.toJson.call(this);return e.varType=this.varType,e.varName=this.varName,e},t.Events.VarCreate.prototype.fromJson=function(e){t.Events.VarCreate.superClass_.fromJson.call(this,e),this.varType=e.varType,this.varName=e.varName},t.Events.VarCreate.prototype.run=function(t){var e=this.getEventWorkspace_();t?e.createVariable(this.varName,this.varType,this.varId):e.deleteVariableById(this.varId)},t.Events.VarDelete=function(e){e&&(t.Events.VarDelete.superClass_.constructor.call(this,e),this.varType=e.type,this.varName=e.name)},t.utils.object.inherits(t.Events.VarDelete,t.Events.VarBase),t.Events.VarDelete.prototype.type=t.Events.VAR_DELETE,t.Events.VarDelete.prototype.toJson=function(){var e=t.Events.VarDelete.superClass_.toJson.call(this);return e.varType=this.varType,e.varName=this.varName,e},t.Events.VarDelete.prototype.fromJson=function(e){t.Events.VarDelete.superClass_.fromJson.call(this,e),this.varType=e.varType,this.varName=e.varName},t.Events.VarDelete.prototype.run=function(t){var e=this.getEventWorkspace_();t?e.deleteVariableById(this.varId):e.createVariable(this.varName,this.varType,this.varId)},t.Events.VarRename=function(e,o){e&&(t.Events.VarRename.superClass_.constructor.call(this,e),this.oldName=e.name,this.newName=o)},t.utils.object.inherits(t.Events.VarRename,t.Events.VarBase),t.Events.VarRename.prototype.type=t.Events.VAR_RENAME,t.Events.VarRename.prototype.toJson=function(){var e=t.Events.VarRename.superClass_.toJson.call(this);return e.oldName=this.oldName,e.newName=this.newName,e},t.Events.VarRename.prototype.fromJson=function(e){t.Events.VarRename.superClass_.fromJson.call(this,e),this.oldName=e.oldName,this.newName=e.newName},t.Events.VarRename.prototype.run=function(t){var e=this.getEventWorkspace_();t?e.renameVariableById(this.varId,this.newName):e.renameVariableById(this.varId,this.oldName)},t.Xml={},t.Xml.workspaceToDom=function(e,o){var i=t.utils.xml.createElement("xml"),n=t.Xml.variablesToDom(t.Variables.allUsedVarModels(e));n.hasChildNodes()&&i.appendChild(n);var s,r=e.getTopComments(!0);for(n=0;s=r[n];n++)i.appendChild(s.toXmlWithXY(o));for(e=e.getTopBlocks(!0),n=0;r=e[n];n++)i.appendChild(t.Xml.blockToDomWithXY(r,o));return i},t.Xml.variablesToDom=function(e){for(var o,i=t.utils.xml.createElement("variables"),n=0;o=e[n];n++){var s=t.utils.xml.createElement("variable");s.appendChild(t.utils.xml.createTextNode(o.name)),o.type&&s.setAttribute("type",o.type),s.id=o.getId(),i.appendChild(s)}return i},t.Xml.blockToDomWithXY=function(e,o){var i;e.workspace.RTL&&(i=e.workspace.getWidth()),o=t.Xml.blockToDom(e,o);var n=e.getRelativeToSurfaceXY();return o.setAttribute("x",Math.round(e.workspace.RTL?i-n.x:n.x)),o.setAttribute("y",Math.round(n.y)),o},t.Xml.fieldToDom_=function(e){if(e.isSerializable()){var o=t.utils.xml.createElement("field");return o.setAttribute("name",e.name||""),e.toXml(o)}return null},t.Xml.allFieldsToDom_=function(e,o){for(var i,n=0;i=e.inputList[n];n++)for(var s,r=0;s=i.fieldRow[r];r++)(s=t.Xml.fieldToDom_(s))&&o.appendChild(s)},t.Xml.blockToDom=function(e,o){var i=t.utils.xml.createElement(e.isShadow()?"shadow":"block");if(i.setAttribute("type",e.type),o||i.setAttribute("id",e.id),e.mutationToDom){var n=e.mutationToDom();n&&(n.hasChildNodes()||n.hasAttributes())&&i.appendChild(n)}if(t.Xml.allFieldsToDom_(e,i),n=e.getCommentText()){var s=e.commentModel.size,r=e.commentModel.pinned,a=t.utils.xml.createElement("comment");a.appendChild(t.utils.xml.createTextNode(n)),a.setAttribute("pinned",r),a.setAttribute("h",s.height),a.setAttribute("w",s.width),i.appendChild(a)}for(e.data&&((n=t.utils.xml.createElement("data")).appendChild(t.utils.xml.createTextNode(e.data)),i.appendChild(n)),s=0;r=e.inputList[s];s++){var l;if(a=!0,r.type!=t.DUMMY_INPUT){var c=r.connection.targetBlock();r.type==t.INPUT_VALUE?l=t.utils.xml.createElement("value"):r.type==t.NEXT_STATEMENT&&(l=t.utils.xml.createElement("statement")),!(n=r.connection.getShadowDom())||c&&c.isShadow()||l.appendChild(t.Xml.cloneShadow_(n,o)),c&&(l.appendChild(t.Xml.blockToDom(c,o)),a=!1),l.setAttribute("name",r.name),a||i.appendChild(l)}}return null!=e.inputsInline&&e.inputsInline!=e.inputsInlineDefault&&i.setAttribute("inline",e.inputsInline),e.isCollapsed()&&i.setAttribute("collapsed",!0),e.isEnabled()||i.setAttribute("disabled",!0),e.isDeletable()||e.isShadow()||i.setAttribute("deletable",!1),e.isMovable()||e.isShadow()||i.setAttribute("movable",!1),e.isEditable()||i.setAttribute("editable",!1),(s=e.getNextBlock())&&((l=t.utils.xml.createElement("next")).appendChild(t.Xml.blockToDom(s,o)),i.appendChild(l)),!(n=e.nextConnection&&e.nextConnection.getShadowDom())||s&&s.isShadow()||l.appendChild(t.Xml.cloneShadow_(n,o)),i},t.Xml.cloneShadow_=function(e,o){for(var i,n=e=e.cloneNode(!0);n;)if(o&&"shadow"==n.nodeName&&n.removeAttribute("id"),n.firstChild)n=n.firstChild;else{for(;n&&!n.nextSibling;)i=n,n=n.parentNode,i.nodeType==t.utils.dom.Node.TEXT_NODE&&""==i.data.trim()&&n.firstChild!=i&&t.utils.dom.removeNode(i);n&&(i=n,n=n.nextSibling,i.nodeType==t.utils.dom.Node.TEXT_NODE&&""==i.data.trim()&&t.utils.dom.removeNode(i))}return e},t.Xml.domToText=function(e){e=t.utils.xml.domToText(e);var o=/(<[^/](?:[^>]*[^/])?>[^<]*)\n([^<]*<\/)/;do{var i=e;e=e.replace(o,"$1 $2")}while(e!=i);return e.replace(/<(\w+)([^<]*)\/>/g,"<$1$2>")},t.Xml.domToPrettyText=function(e){e=t.Xml.domToText(e).split("<");for(var o="",i=1;i"!=n.slice(-2)&&(o+=" ")}return(e=(e=e.join("\n")).replace(/(<(\w+)\b[^>]*>[^\n]*)\n *<\/\2>/g,"$1")).replace(/^\n/,"")},t.Xml.textToDom=function(e){var o=t.utils.xml.textToDomDocument(e);if(!o||!o.documentElement||o.getElementsByTagName("parsererror").length)throw Error("textToDom was unable to parse: "+e);return o.documentElement},t.Xml.clearWorkspaceAndLoadFromXml=function(e,o){return o.setResizesEnabled(!1),o.clear(),e=t.Xml.domToWorkspace(e,o),o.setResizesEnabled(!0),e},t.Xml.domToWorkspace=function(e,o){if(e instanceof t.Workspace){var i=e;e=o,o=i,console.warn("Deprecated call to Blockly.Xml.domToWorkspace, swap the arguments.")}var n;o.RTL&&(n=o.getWidth()),i=[],t.utils.dom.startTextWidthCache();var s=t.Events.getGroup();s||t.Events.setGroup(!0),o.setResizesEnabled&&o.setResizesEnabled(!1);var r=!0;try{for(var a,l=0;a=e.childNodes[l];l++){var c=a.nodeName.toLowerCase(),h=a;if("block"==c||"shadow"==c&&!t.Events.recordUndo){var u=t.Xml.domToBlock(h,o);i.push(u.id);var p=h.hasAttribute("x")?parseInt(h.getAttribute("x"),10):10,_=h.hasAttribute("y")?parseInt(h.getAttribute("y"),10):10;isNaN(p)||isNaN(_)||u.moveBy(o.RTL?n-p:p,_),r=!1}else{if("shadow"==c)throw TypeError("Shadow block cannot be a top-level block.");if("comment"==c)o.rendered?t.WorkspaceCommentSvg?t.WorkspaceCommentSvg.fromXml(h,o,n):console.warn("Missing require for Blockly.WorkspaceCommentSvg, ignoring workspace comment."):t.WorkspaceComment?t.WorkspaceComment.fromXml(h,o):console.warn("Missing require for Blockly.WorkspaceComment, ignoring workspace comment.");else if("variables"==c){if(!r)throw Error("'variables' tag must exist once before block and shadow tag elements in the workspace XML, but it was found in another location.");t.Xml.domToVariables(h,o),r=!1}}}}finally{s||t.Events.setGroup(!1),t.utils.dom.stopTextWidthCache()}return o.setResizesEnabled&&o.setResizesEnabled(!0),t.Events.fire(new t.Events.FinishedLoading(o)),i},t.Xml.appendDomToWorkspace=function(e,o){var i;if(o.hasOwnProperty("scale")&&(i=o.getBlocksBoundingBox()),e=t.Xml.domToWorkspace(e,o),i&&i.top!=i.bottom){var n=i.bottom,s=o.RTL?i.right:i.left,r=1/0,a=-1/0,l=1/0;for(i=0;ia&&(a=c.x)}for(n=n-l+10,s=o.RTL?s-a:s-r,i=0;i document.")}else e=null;return e},t.Touch={},t.Touch.TOUCH_ENABLED="ontouchstart"in t.utils.global||!!(t.utils.global.document&&document.documentElement&&"ontouchstart"in document.documentElement)||!(!t.utils.global.navigator||!t.utils.global.navigator.maxTouchPoints&&!t.utils.global.navigator.msMaxTouchPoints),t.Touch.touchIdentifier_=null,t.Touch.TOUCH_MAP={},t.utils.global.PointerEvent?t.Touch.TOUCH_MAP={mousedown:["pointerdown"],mouseenter:["pointerenter"],mouseleave:["pointerleave"],mousemove:["pointermove"],mouseout:["pointerout"],mouseover:["pointerover"],mouseup:["pointerup","pointercancel"],touchend:["pointerup"],touchcancel:["pointercancel"]}:t.Touch.TOUCH_ENABLED&&(t.Touch.TOUCH_MAP={mousedown:["touchstart"],mousemove:["touchmove"],mouseup:["touchend","touchcancel"]}),t.longPid_=0,t.longStart=function(e,o){t.longStop_(),e.changedTouches&&1!=e.changedTouches.length||(t.longPid_=setTimeout((function(){e.changedTouches&&(e.button=2,e.clientX=e.changedTouches[0].clientX,e.clientY=e.changedTouches[0].clientY),o&&o.handleRightClick(e)}),t.LONGPRESS))},t.longStop_=function(){t.longPid_&&(clearTimeout(t.longPid_),t.longPid_=0)},t.Touch.clearTouchIdentifier=function(){t.Touch.touchIdentifier_=null},t.Touch.shouldHandleEvent=function(e){return!t.Touch.isMouseOrTouchEvent(e)||t.Touch.checkTouchIdentifier(e)},t.Touch.getTouchIdentifierFromEvent=function(t){return null!=t.pointerId?t.pointerId:t.changedTouches&&t.changedTouches[0]&&void 0!==t.changedTouches[0].identifier&&null!==t.changedTouches[0].identifier?t.changedTouches[0].identifier:"mouse"},t.Touch.checkTouchIdentifier=function(e){var o=t.Touch.getTouchIdentifierFromEvent(e);return void 0!==t.Touch.touchIdentifier_&&null!==t.Touch.touchIdentifier_?t.Touch.touchIdentifier_==o:("mousedown"==e.type||"touchstart"==e.type||"pointerdown"==e.type)&&(t.Touch.touchIdentifier_=o,!0)},t.Touch.setClientFromTouch=function(e){if(t.utils.string.startsWith(e.type,"touch")){var o=e.changedTouches[0];e.clientX=o.clientX,e.clientY=o.clientY}},t.Touch.isMouseOrTouchEvent=function(e){return t.utils.string.startsWith(e.type,"touch")||t.utils.string.startsWith(e.type,"mouse")||t.utils.string.startsWith(e.type,"pointer")},t.Touch.isTouchEvent=function(e){return t.utils.string.startsWith(e.type,"touch")||t.utils.string.startsWith(e.type,"pointer")},t.Touch.splitEventByTouches=function(t){var e=[];if(t.changedTouches)for(var o=0;o=i+this.handleLength_&&(n+=s),this.setHandlePosition(this.constrainHandle_(n)),this.onScroll_(),e.stopPropagation(),e.preventDefault()}},t.Scrollbar.prototype.onMouseDownHandle_=function(e){this.workspace_.markFocused(),this.cleanUp_(),t.utils.isRightButton(e)?e.stopPropagation():(this.startDragHandle=this.handlePosition_,this.workspace_.setupDragSurface(),this.startDragMouse_=this.horizontal_?e.clientX:e.clientY,t.Scrollbar.onMouseUpWrapper_=t.bindEventWithChecks_(document,"mouseup",this,this.onMouseUpHandle_),t.Scrollbar.onMouseMoveWrapper_=t.bindEventWithChecks_(document,"mousemove",this,this.onMouseMoveHandle_),e.stopPropagation(),e.preventDefault())},t.Scrollbar.prototype.onMouseMoveHandle_=function(t){this.setHandlePosition(this.constrainHandle_(this.startDragHandle+((this.horizontal_?t.clientX:t.clientY)-this.startDragMouse_))),this.onScroll_()},t.Scrollbar.prototype.onMouseUpHandle_=function(){this.workspace_.resetDragSurface(),t.Touch.clearTouchIdentifier(),this.cleanUp_()},t.Scrollbar.prototype.cleanUp_=function(){t.hideChaff(!0),t.Scrollbar.onMouseUpWrapper_&&(t.unbindEvent_(t.Scrollbar.onMouseUpWrapper_),t.Scrollbar.onMouseUpWrapper_=null),t.Scrollbar.onMouseMoveWrapper_&&(t.unbindEvent_(t.Scrollbar.onMouseMoveWrapper_),t.Scrollbar.onMouseMoveWrapper_=null)},t.Scrollbar.prototype.constrainHandle_=function(t){return 0>=t||isNaN(t)||this.scrollViewSize_t.Tooltip.RADIUS_OK&&t.Tooltip.hide()}else t.Tooltip.poisonedElement_!=t.Tooltip.element_&&(clearTimeout(t.Tooltip.showPid_),t.Tooltip.lastX_=e.pageX,t.Tooltip.lastY_=e.pageY,t.Tooltip.showPid_=setTimeout(t.Tooltip.show_,t.Tooltip.HOVER_MS))},t.Tooltip.dispose=function(){t.Tooltip.element_=null,t.Tooltip.poisonedElement_=null,t.Tooltip.hide()},t.Tooltip.hide=function(){t.Tooltip.visible&&(t.Tooltip.visible=!1,t.Tooltip.DIV&&(t.Tooltip.DIV.style.display="none")),t.Tooltip.showPid_&&clearTimeout(t.Tooltip.showPid_)},t.Tooltip.block=function(){t.Tooltip.hide(),t.Tooltip.blocked_=!0},t.Tooltip.unblock=function(){t.Tooltip.blocked_=!1},t.Tooltip.show_=function(){if(!t.Tooltip.blocked_&&(t.Tooltip.poisonedElement_=t.Tooltip.element_,t.Tooltip.DIV)){t.Tooltip.DIV.textContent="";for(var e=t.Tooltip.element_.tooltip;"function"==typeof e;)e=e();e=(e=t.utils.string.wrap(e,t.Tooltip.LIMIT)).split("\n");for(var o=0;oi+window.scrollY&&(s-=t.Tooltip.DIV.offsetHeight+2*t.Tooltip.OFFSET_Y),e?n=Math.max(t.Tooltip.MARGINS-window.scrollX,n):n+t.Tooltip.DIV.offsetWidth>o+window.scrollX-2*t.Tooltip.MARGINS&&(n=o-t.Tooltip.DIV.offsetWidth-2*t.Tooltip.MARGINS),t.Tooltip.DIV.style.top=s+"px",t.Tooltip.DIV.style.left=n+"px"}},t.WorkspaceDragSurfaceSvg=function(t){this.container_=t,this.createDom()},t.WorkspaceDragSurfaceSvg.prototype.SVG_=null,t.WorkspaceDragSurfaceSvg.prototype.dragGroup_=null,t.WorkspaceDragSurfaceSvg.prototype.container_=null,t.WorkspaceDragSurfaceSvg.prototype.createDom=function(){this.SVG_||(this.SVG_=t.utils.dom.createSvgElement("svg",{xmlns:t.utils.dom.SVG_NS,"xmlns:html":t.utils.dom.HTML_NS,"xmlns:xlink":t.utils.dom.XLINK_NS,version:"1.1",class:"blocklyWsDragSurface blocklyOverflowVisible"},null),this.container_.appendChild(this.SVG_))},t.WorkspaceDragSurfaceSvg.prototype.translateSurface=function(e,o){e=e.toFixed(0),o=o.toFixed(0),this.SVG_.style.display="block",t.utils.dom.setCssTransform(this.SVG_,"translate3d("+e+"px, "+o+"px, 0px)")},t.WorkspaceDragSurfaceSvg.prototype.getSurfaceTranslation=function(){return t.utils.getRelativeXY(this.SVG_)},t.WorkspaceDragSurfaceSvg.prototype.clearAndHide=function(e){if(!e)throw Error("Couldn't clear and hide the drag surface: missing new surface.");var o=this.SVG_.childNodes[0],i=this.SVG_.childNodes[1];if(!(o&&i&&t.utils.dom.hasClass(o,"blocklyBlockCanvas")&&t.utils.dom.hasClass(i,"blocklyBubbleCanvas")))throw Error("Couldn't clear and hide the drag surface. A node was missing.");if(null!=this.previousSibling_?t.utils.dom.insertAfter(o,this.previousSibling_):e.insertBefore(o,e.firstChild),t.utils.dom.insertAfter(i,o),this.SVG_.style.display="none",this.SVG_.childNodes.length)throw Error("Drag surface was not cleared.");t.utils.dom.setCssTransform(this.SVG_,""),this.previousSibling_=null},t.WorkspaceDragSurfaceSvg.prototype.setContentsAndShow=function(t,e,o,i,n,s){if(this.SVG_.childNodes.length)throw Error("Already dragging a block.");this.previousSibling_=o,t.setAttribute("transform","translate(0, 0) scale("+s+")"),e.setAttribute("transform","translate(0, 0) scale("+s+")"),this.SVG_.setAttribute("width",i),this.SVG_.setAttribute("height",n),this.SVG_.appendChild(t),this.SVG_.appendChild(e),this.SVG_.style.display="block"},t.ASTNode=function(e,o,i){if(!o)throw Error("Cannot create a node without a location.");this.type_=e,this.isConnection_=t.ASTNode.isConnectionType_(e),this.location_=o,this.processParams_(i||null)},t.ASTNode.types={FIELD:"field",BLOCK:"block",INPUT:"input",OUTPUT:"output",NEXT:"next",PREVIOUS:"previous",STACK:"stack",WORKSPACE:"workspace"},t.ASTNode.NAVIGATE_ALL_FIELDS=!1,t.ASTNode.DEFAULT_OFFSET_Y=-20,t.ASTNode.isConnectionType_=function(e){switch(e){case t.ASTNode.types.PREVIOUS:case t.ASTNode.types.NEXT:case t.ASTNode.types.INPUT:case t.ASTNode.types.OUTPUT:return!0}return!1},t.ASTNode.createFieldNode=function(e){return e?new t.ASTNode(t.ASTNode.types.FIELD,e):null},t.ASTNode.createConnectionNode=function(e){return e?e.type==t.INPUT_VALUE||e.type==t.NEXT_STATEMENT&&e.getParentInput()?t.ASTNode.createInputNode(e.getParentInput()):e.type==t.NEXT_STATEMENT?new t.ASTNode(t.ASTNode.types.NEXT,e):e.type==t.OUTPUT_VALUE?new t.ASTNode(t.ASTNode.types.OUTPUT,e):e.type==t.PREVIOUS_STATEMENT?new t.ASTNode(t.ASTNode.types.PREVIOUS,e):null:null},t.ASTNode.createInputNode=function(e){return e&&e.connection?new t.ASTNode(t.ASTNode.types.INPUT,e.connection):null},t.ASTNode.createBlockNode=function(e){return e?new t.ASTNode(t.ASTNode.types.BLOCK,e):null},t.ASTNode.createStackNode=function(e){return e?new t.ASTNode(t.ASTNode.types.STACK,e):null},t.ASTNode.createWorkspaceNode=function(e,o){return o&&e?new t.ASTNode(t.ASTNode.types.WORKSPACE,e,{wsCoordinate:o}):null},t.ASTNode.prototype.processParams_=function(t){t&&t.wsCoordinate&&(this.wsCoordinate_=t.wsCoordinate)},t.ASTNode.prototype.getLocation=function(){return this.location_},t.ASTNode.prototype.getType=function(){return this.type_},t.ASTNode.prototype.getWsCoordinate=function(){return this.wsCoordinate_},t.ASTNode.prototype.isConnection=function(){return this.isConnection_},t.ASTNode.prototype.findNextForInput_=function(){var e,o=this.location_.getParentInput(),i=o.getSourceBlock();for(o=i.inputList.indexOf(o)+1;e=i.inputList[o];o++){for(var n,s=e.fieldRow,r=0;n=s[r];r++)if(n.isClickable()||t.ASTNode.NAVIGATE_ALL_FIELDS)return t.ASTNode.createFieldNode(n);if(e.connection)return t.ASTNode.createInputNode(e)}return null},t.ASTNode.prototype.findNextForField_=function(){var e=this.location_,o=e.getParentInput(),i=e.getSourceBlock(),n=i.inputList.indexOf(o);for(e=o.fieldRow.indexOf(e)+1;o=i.inputList[n];n++){for(var s=o.fieldRow;ei)){var n=o.getSvgXY(e.getSvgRoot());e.outputConnection?(n.x+=(e.RTL?3:-3)*i,n.y+=13*i):e.previousConnection&&(n.x+=(e.RTL?-23:23)*i,n.y+=3*i),e=t.utils.dom.createSvgElement("circle",{cx:n.x,cy:n.y,r:0,fill:"none",stroke:"#888","stroke-width":10},o.getParentSvg()),t.blockAnimations.connectionUiStep_(e,new Date,i)}},t.blockAnimations.connectionUiStep_=function(e,o,i){var n=(new Date-o)/150;1e.workspace.scale)){var o=e.getHeightWidth().height;o=Math.atan(10/o)/Math.PI*180,e.RTL||(o*=-1),t.blockAnimations.disconnectUiStep_(e.getSvgRoot(),o,new Date)}},t.blockAnimations.disconnectUiStep_=function(e,o,i){var n=(new Date-i)/200;1o-t.CURRENT_CONNECTION_PREFERENCE)):!this.localConnection_&&!this.closestConnection_||(console.error("Only one of localConnection_ and closestConnection_ was set."),console.error("Returning true from shouldUpdatePreviews, but it's not clear why."),!0):!(!this.localConnection_||!this.closestConnection_)},t.InsertionMarkerManager.prototype.getCandidate_=function(t){for(var e=this.getStartRadius_(),o=null,i=null,n=0;nthis.remainingCapacityOfType(e))return!1;o+=t[e]}return!(o>this.remainingCapacity())},t.Workspace.prototype.hasBlockLimits=function(){return 1/0!=this.options.maxBlocks||!!this.options.maxInstances},t.Workspace.prototype.undo=function(e){var o=e?this.redoStack_:this.undoStack_,i=e?this.undoStack_:this.redoStack_,n=o.pop();if(n){for(var s=[n];o.length&&n.group&&n.group==o[o.length-1].group;)s.push(o.pop());for(o=0;n=s[o];o++)i.push(n);s=t.Events.filter(s,e),t.Events.recordUndo=!1;try{for(o=0;n=s[o];o++)n.run(e)}finally{t.Events.recordUndo=!0}}},t.Workspace.prototype.clearUndo=function(){this.undoStack_.length=0,this.redoStack_.length=0,t.Events.clearPendingUndo()},t.Workspace.prototype.addChangeListener=function(t){return this.listeners_.push(t),t},t.Workspace.prototype.removeChangeListener=function(e){t.utils.arrayRemove(this.listeners_,e)},t.Workspace.prototype.fireChangeListener=function(t){if(t.recordUndo)for(this.undoStack_.push(t),this.redoStack_.length=0;this.undoStack_.length>this.MAX_UNDO&&0<=this.MAX_UNDO;)this.undoStack_.shift();for(var e,o=0;e=this.listeners_[o];o++)e(t)},t.Workspace.prototype.getBlockById=function(t){return this.blockDB_[t]||null},t.Workspace.prototype.setBlockById=function(t,e){this.blockDB_[t]=e},t.Workspace.prototype.removeBlockById=function(t){delete this.blockDB_[t]},t.Workspace.prototype.getCommentById=function(t){return this.commentDB_[t]||null},t.Workspace.prototype.allInputsFilled=function(t){for(var e,o=this.getTopBlocks(!1),i=0;e=o[i];i++)if(!e.allInputsFilled(t))return!1;return!0},t.Workspace.prototype.getPotentialVariableMap=function(){return this.potentialVariableMap_},t.Workspace.prototype.createPotentialVariableMap=function(){this.potentialVariableMap_=new t.VariableMap(this)},t.Workspace.prototype.getVariableMap=function(){return this.variableMap_},t.Workspace.prototype.setVariableMap=function(t){this.variableMap_=t},t.Workspace.WorkspaceDB_=Object.create(null),t.Workspace.getById=function(e){return t.Workspace.WorkspaceDB_[e]||null},t.Workspace.getAll=function(){var e,o=[];for(e in t.Workspace.WorkspaceDB_)o.push(t.Workspace.WorkspaceDB_[e]);return o},t.Bubble=function(e,o,i,n,s,r){this.workspace_=e,this.content_=o,this.shape_=i,this.onMouseDownResizeWrapper_=this.onMouseDownBubbleWrapper_=this.moveCallback_=this.resizeCallback_=null,this.disposed=!1,i=t.Bubble.ARROW_ANGLE,this.workspace_.RTL&&(i=-i),this.arrow_radians_=t.utils.math.toRadians(i),e.getBubbleCanvas().appendChild(this.createDom_(o,!(!s||!r))),this.setAnchorLocation(n),s&&r||(s=(e=this.content_.getBBox()).width+2*t.Bubble.BORDER_WIDTH,r=e.height+2*t.Bubble.BORDER_WIDTH),this.setBubbleSize(s,r),this.positionBubble_(),this.renderArrow_(),this.rendered_=!0},t.Bubble.BORDER_WIDTH=6,t.Bubble.ARROW_THICKNESS=5,t.Bubble.ARROW_ANGLE=20,t.Bubble.ARROW_BEND=4,t.Bubble.ANCHOR_RADIUS=8,t.Bubble.onMouseUpWrapper_=null,t.Bubble.onMouseMoveWrapper_=null,t.Bubble.unbindDragEvents_=function(){t.Bubble.onMouseUpWrapper_&&(t.unbindEvent_(t.Bubble.onMouseUpWrapper_),t.Bubble.onMouseUpWrapper_=null),t.Bubble.onMouseMoveWrapper_&&(t.unbindEvent_(t.Bubble.onMouseMoveWrapper_),t.Bubble.onMouseMoveWrapper_=null)},t.Bubble.bubbleMouseUp_=function(e){t.Touch.clearTouchIdentifier(),t.Bubble.unbindDragEvents_()},t.Bubble.prototype.rendered_=!1,t.Bubble.prototype.anchorXY_=null,t.Bubble.prototype.relativeLeft_=0,t.Bubble.prototype.relativeTop_=0,t.Bubble.prototype.width_=0,t.Bubble.prototype.height_=0,t.Bubble.prototype.autoLayout_=!0,t.Bubble.prototype.createDom_=function(e,o){this.bubbleGroup_=t.utils.dom.createSvgElement("g",{},null);var i={filter:"url(#"+this.workspace_.getRenderer().getConstants().embossFilterId+")"};return t.utils.userAgent.JAVA_FX&&(i={}),i=t.utils.dom.createSvgElement("g",i,this.bubbleGroup_),this.bubbleArrow_=t.utils.dom.createSvgElement("path",{},i),this.bubbleBack_=t.utils.dom.createSvgElement("rect",{class:"blocklyDraggable",x:0,y:0,rx:t.Bubble.BORDER_WIDTH,ry:t.Bubble.BORDER_WIDTH},i),o?(this.resizeGroup_=t.utils.dom.createSvgElement("g",{class:this.workspace_.RTL?"blocklyResizeSW":"blocklyResizeSE"},this.bubbleGroup_),o=2*t.Bubble.BORDER_WIDTH,t.utils.dom.createSvgElement("polygon",{points:"0,x x,x x,0".replace(/x/g,o.toString())},this.resizeGroup_),t.utils.dom.createSvgElement("line",{class:"blocklyResizeLine",x1:o/3,y1:o-1,x2:o-1,y2:o/3},this.resizeGroup_),t.utils.dom.createSvgElement("line",{class:"blocklyResizeLine",x1:2*o/3,y1:o-1,x2:o-1,y2:2*o/3},this.resizeGroup_)):this.resizeGroup_=null,this.workspace_.options.readOnly||(this.onMouseDownBubbleWrapper_=t.bindEventWithChecks_(this.bubbleBack_,"mousedown",this,this.bubbleMouseDown_),this.resizeGroup_&&(this.onMouseDownResizeWrapper_=t.bindEventWithChecks_(this.resizeGroup_,"mousedown",this,this.resizeMouseDown_))),this.bubbleGroup_.appendChild(e),this.bubbleGroup_},t.Bubble.prototype.getSvgRoot=function(){return this.bubbleGroup_},t.Bubble.prototype.setSvgId=function(t){this.bubbleGroup_.dataset&&(this.bubbleGroup_.dataset.blockId=t)},t.Bubble.prototype.bubbleMouseDown_=function(t){var e=this.workspace_.getGesture(t);e&&e.handleBubbleStart(t,this)},t.Bubble.prototype.showContextMenu=function(t){},t.Bubble.prototype.isDeletable=function(){return!1},t.Bubble.prototype.resizeMouseDown_=function(e){this.promote(),t.Bubble.unbindDragEvents_(),t.utils.isRightButton(e)||(this.workspace_.startDrag(e,new t.utils.Coordinate(this.workspace_.RTL?-this.width_:this.width_,this.height_)),t.Bubble.onMouseUpWrapper_=t.bindEventWithChecks_(document,"mouseup",this,t.Bubble.bubbleMouseUp_),t.Bubble.onMouseMoveWrapper_=t.bindEventWithChecks_(document,"mousemove",this,this.resizeMouseMove_),t.hideChaff()),e.stopPropagation()},t.Bubble.prototype.resizeMouseMove_=function(t){this.autoLayout_=!1,t=this.workspace_.moveDrag(t),this.setBubbleSize(this.workspace_.RTL?-t.x:t.x,t.y),this.workspace_.RTL&&this.positionBubble_()},t.Bubble.prototype.registerResizeEvent=function(t){this.resizeCallback_=t},t.Bubble.prototype.registerMoveEvent=function(t){this.moveCallback_=t},t.Bubble.prototype.promote=function(){var t=this.bubbleGroup_.parentNode;return t.lastChild!==this.bubbleGroup_&&(t.appendChild(this.bubbleGroup_),!0)},t.Bubble.prototype.setAnchorLocation=function(t){this.anchorXY_=t,this.rendered_&&this.positionBubble_()},t.Bubble.prototype.layoutBubble_=function(){var t=this.workspace_.getMetrics();t.viewLeft/=this.workspace_.scale,t.viewWidth/=this.workspace_.scale,t.viewTop/=this.workspace_.scale,t.viewHeight/=this.workspace_.scale;var e=this.getOptimalRelativeLeft_(t),o=this.getOptimalRelativeTop_(t),i=this.shape_.getBBox(),n={x:e,y:-this.height_-this.workspace_.getRenderer().getConstants().MIN_BLOCK_HEIGHT},s={x:-this.width_-30,y:o};o={x:i.width,y:o};var r={x:e,y:i.height};e=i.widthe.viewWidth)return o;if(this.workspace_.RTL)var i=this.anchorXY_.x-o,n=i-this.width_,s=e.viewLeft+e.viewWidth,r=e.viewLeft+t.Scrollbar.scrollbarThickness/this.workspace_.scale;else i=(n=o+this.anchorXY_.x)+this.width_,r=e.viewLeft,s=e.viewLeft+e.viewWidth-t.Scrollbar.scrollbarThickness/this.workspace_.scale;return this.workspace_.RTL?ns&&(o=-(s-this.anchorXY_.x)):ns&&(o=s-this.anchorXY_.x-this.width_),o},t.Bubble.prototype.getOptimalRelativeTop_=function(e){var o=-this.height_/4;if(this.height_>e.viewHeight)return o;var i=this.anchorXY_.y+o,n=i+this.height_,s=e.viewTop;e=e.viewTop+e.viewHeight-t.Scrollbar.scrollbarThickness/this.workspace_.scale;var r=this.anchorXY_.y;return ie&&(o=e-r-this.height_),o},t.Bubble.prototype.positionBubble_=function(){var t=this.anchorXY_.x;t=this.workspace_.RTL?t-(this.relativeLeft_+this.width_):t+this.relativeLeft_,this.moveTo(t,this.relativeTop_+this.anchorXY_.y)},t.Bubble.prototype.moveTo=function(t,e){this.bubbleGroup_.setAttribute("transform","translate("+t+","+e+")")},t.Bubble.prototype.setDragging=function(t){!t&&this.moveCallback_&&this.moveCallback_()},t.Bubble.prototype.getBubbleSize=function(){return new t.utils.Size(this.width_,this.height_)},t.Bubble.prototype.setBubbleSize=function(e,o){var i=2*t.Bubble.BORDER_WIDTH;e=Math.max(e,i+45),o=Math.max(o,i+20),this.width_=e,this.height_=o,this.bubbleBack_.setAttribute("width",e),this.bubbleBack_.setAttribute("height",o),this.resizeGroup_&&(this.workspace_.RTL?this.resizeGroup_.setAttribute("transform","translate("+2*t.Bubble.BORDER_WIDTH+","+(o-i)+") scale(-1 1)"):this.resizeGroup_.setAttribute("transform","translate("+(e-i)+","+(o-i)+")")),this.autoLayout_&&this.layoutBubble_(),this.positionBubble_(),this.renderArrow_(),this.resizeCallback_&&this.resizeCallback_()},t.Bubble.prototype.renderArrow_=function(){var e=[],o=this.width_/2,i=this.height_/2,n=-this.relativeLeft_,s=-this.relativeTop_;if(o==n&&i==s)e.push("M "+o+","+i);else{s-=i,n-=o,this.workspace_.RTL&&(n*=-1);var r=Math.sqrt(s*s+n*n),a=Math.acos(n/r);0>s&&(a=2*Math.PI-a);var l=a+Math.PI/2;l>2*Math.PI&&(l-=2*Math.PI);var c=Math.sin(l),h=Math.cos(l),u=this.getBubbleSize();l=(u.width+u.height)/t.Bubble.ARROW_THICKNESS,l=Math.min(l,u.width,u.height)/4,n=o+(u=1-t.Bubble.ANCHOR_RADIUS/r)*n,s=i+u*s,u=o+l*h;var p=i+l*c;o-=l*h,i-=l*c,(c=a+this.arrow_radians_)>2*Math.PI&&(c-=2*Math.PI),a=Math.sin(c)*r/t.Bubble.ARROW_BEND,r=Math.cos(c)*r/t.Bubble.ARROW_BEND,e.push("M"+u+","+p),e.push("C"+(u+r)+","+(p+a)+" "+n+","+s+" "+n+","+s),e.push("C"+n+","+s+" "+(o+r)+","+(i+a)+" "+o+","+i)}e.push("z"),this.bubbleArrow_.setAttribute("d",e.join(" "))},t.Bubble.prototype.setColour=function(t){this.bubbleBack_.setAttribute("fill",t),this.bubbleArrow_.setAttribute("fill",t)},t.Bubble.prototype.dispose=function(){this.onMouseDownBubbleWrapper_&&t.unbindEvent_(this.onMouseDownBubbleWrapper_),this.onMouseDownResizeWrapper_&&t.unbindEvent_(this.onMouseDownResizeWrapper_),t.Bubble.unbindDragEvents_(),t.utils.dom.removeNode(this.bubbleGroup_),this.disposed=!0},t.Bubble.prototype.moveDuringDrag=function(t,e){t?t.translateSurface(e.x,e.y):this.moveTo(e.x,e.y),this.relativeLeft_=this.workspace_.RTL?this.anchorXY_.x-e.x-this.width_:e.x-this.anchorXY_.x,this.relativeTop_=e.y-this.anchorXY_.y,this.renderArrow_()},t.Bubble.prototype.getRelativeToSurfaceXY=function(){return new t.utils.Coordinate(this.workspace_.RTL?-this.relativeLeft_+this.anchorXY_.x-this.width_:this.anchorXY_.x+this.relativeLeft_,this.anchorXY_.y+this.relativeTop_)},t.Bubble.prototype.setAutoLayout=function(t){this.autoLayout_=t},t.Events.CommentBase=function(e){this.commentId=e.id,this.workspaceId=e.workspace.id,this.group=t.Events.getGroup(),this.recordUndo=t.Events.recordUndo},t.utils.object.inherits(t.Events.CommentBase,t.Events.Abstract),t.Events.CommentBase.prototype.toJson=function(){var e=t.Events.CommentBase.superClass_.toJson.call(this);return this.commentId&&(e.commentId=this.commentId),e},t.Events.CommentBase.prototype.fromJson=function(e){t.Events.CommentBase.superClass_.fromJson.call(this,e),this.commentId=e.commentId},t.Events.CommentChange=function(e,o,i){e&&(t.Events.CommentChange.superClass_.constructor.call(this,e),this.oldContents_=o,this.newContents_=i)},t.utils.object.inherits(t.Events.CommentChange,t.Events.CommentBase),t.Events.CommentChange.prototype.type=t.Events.COMMENT_CHANGE,t.Events.CommentChange.prototype.toJson=function(){var e=t.Events.CommentChange.superClass_.toJson.call(this);return e.newContents=this.newContents_,e},t.Events.CommentChange.prototype.fromJson=function(e){t.Events.CommentChange.superClass_.fromJson.call(this,e),this.newContents_=e.newValue},t.Events.CommentChange.prototype.isNull=function(){return this.oldContents_==this.newContents_},t.Events.CommentChange.prototype.run=function(t){var e=this.getEventWorkspace_().getCommentById(this.commentId);e?e.setContent(t?this.newContents_:this.oldContents_):console.warn("Can't change non-existent comment: "+this.commentId)},t.Events.CommentCreate=function(e){e&&(t.Events.CommentCreate.superClass_.constructor.call(this,e),this.xml=e.toXmlWithXY())},t.utils.object.inherits(t.Events.CommentCreate,t.Events.CommentBase),t.Events.CommentCreate.prototype.type=t.Events.COMMENT_CREATE,t.Events.CommentCreate.prototype.toJson=function(){var e=t.Events.CommentCreate.superClass_.toJson.call(this);return e.xml=t.Xml.domToText(this.xml),e},t.Events.CommentCreate.prototype.fromJson=function(e){t.Events.CommentCreate.superClass_.fromJson.call(this,e),this.xml=t.Xml.textToDom(e.xml)},t.Events.CommentCreate.prototype.run=function(e){t.Events.CommentCreateDeleteHelper(this,e)},t.Events.CommentCreateDeleteHelper=function(e,o){var i=e.getEventWorkspace_();o?((o=t.utils.xml.createElement("xml")).appendChild(e.xml),t.Xml.domToWorkspace(o,i)):(i=i.getCommentById(e.commentId))?i.dispose(!1,!1):console.warn("Can't uncreate non-existent comment: "+e.commentId)},t.Events.CommentDelete=function(e){e&&(t.Events.CommentDelete.superClass_.constructor.call(this,e),this.xml=e.toXmlWithXY())},t.utils.object.inherits(t.Events.CommentDelete,t.Events.CommentBase),t.Events.CommentDelete.prototype.type=t.Events.COMMENT_DELETE,t.Events.CommentDelete.prototype.toJson=function(){return t.Events.CommentDelete.superClass_.toJson.call(this)},t.Events.CommentDelete.prototype.fromJson=function(e){t.Events.CommentDelete.superClass_.fromJson.call(this,e)},t.Events.CommentDelete.prototype.run=function(e){t.Events.CommentCreateDeleteHelper(this,!e)},t.Events.CommentMove=function(e){e&&(t.Events.CommentMove.superClass_.constructor.call(this,e),this.comment_=e,this.oldCoordinate_=e.getXY(),this.newCoordinate_=null)},t.utils.object.inherits(t.Events.CommentMove,t.Events.CommentBase),t.Events.CommentMove.prototype.recordNew=function(){if(!this.comment_)throw Error("Tried to record the new position of a comment on the same event twice.");this.newCoordinate_=this.comment_.getXY(),this.comment_=null},t.Events.CommentMove.prototype.type=t.Events.COMMENT_MOVE,t.Events.CommentMove.prototype.setOldCoordinate=function(t){this.oldCoordinate_=t},t.Events.CommentMove.prototype.toJson=function(){var e=t.Events.CommentMove.superClass_.toJson.call(this);return this.newCoordinate_&&(e.newCoordinate=Math.round(this.newCoordinate_.x)+","+Math.round(this.newCoordinate_.y)),e},t.Events.CommentMove.prototype.fromJson=function(e){t.Events.CommentMove.superClass_.fromJson.call(this,e),e.newCoordinate&&(e=e.newCoordinate.split(","),this.newCoordinate_=new t.utils.Coordinate(Number(e[0]),Number(e[1])))},t.Events.CommentMove.prototype.isNull=function(){return t.utils.Coordinate.equals(this.oldCoordinate_,this.newCoordinate_)},t.Events.CommentMove.prototype.run=function(t){var e=this.getEventWorkspace_().getCommentById(this.commentId);if(e){t=t?this.newCoordinate_:this.oldCoordinate_;var o=e.getXY();e.moveBy(t.x-o.x,t.y-o.y)}else console.warn("Can't move non-existent comment: "+this.commentId)},t.BubbleDragger=function(e,o){this.draggingBubble_=e,this.workspace_=o,this.deleteArea_=null,this.wouldDeleteBubble_=!1,this.startXY_=this.draggingBubble_.getRelativeToSurfaceXY(),this.dragSurface_=t.utils.is3dSupported()&&o.getBlockDragSurface()?o.getBlockDragSurface():null},t.BubbleDragger.prototype.dispose=function(){this.dragSurface_=this.workspace_=this.draggingBubble_=null},t.BubbleDragger.prototype.startBubbleDrag=function(){t.Events.getGroup()||t.Events.setGroup(!0),this.workspace_.setResizesEnabled(!1),this.draggingBubble_.setAutoLayout(!1),this.dragSurface_&&this.moveToDragSurface_(),this.draggingBubble_.setDragging&&this.draggingBubble_.setDragging(!0);var e=this.workspace_.getToolbox();if(e){var o=this.draggingBubble_.isDeletable()?"blocklyToolboxDelete":"blocklyToolboxGrab";e.addStyle(o)}},t.BubbleDragger.prototype.dragBubble=function(e,o){o=this.pixelsToWorkspaceUnits_(o),o=t.utils.Coordinate.sum(this.startXY_,o),this.draggingBubble_.moveDuringDrag(this.dragSurface_,o),this.draggingBubble_.isDeletable()&&(this.deleteArea_=this.workspace_.isDeleteArea(e),this.updateCursorDuringBubbleDrag_())},t.BubbleDragger.prototype.maybeDeleteBubble_=function(){var t=this.workspace_.trashcan;return this.wouldDeleteBubble_?(t&&setTimeout(t.close.bind(t),100),this.fireMoveEvent_(),this.draggingBubble_.dispose(!1,!0)):t&&t.close(),this.wouldDeleteBubble_},t.BubbleDragger.prototype.updateCursorDuringBubbleDrag_=function(){this.wouldDeleteBubble_=this.deleteArea_!=t.DELETE_AREA_NONE;var e=this.workspace_.trashcan;this.wouldDeleteBubble_?(this.draggingBubble_.setDeleteStyle(!0),this.deleteArea_==t.DELETE_AREA_TRASH&&e&&e.setOpen(!0)):(this.draggingBubble_.setDeleteStyle(!1),e&&e.setOpen(!1))},t.BubbleDragger.prototype.endBubbleDrag=function(e,o){this.dragBubble(e,o),e=this.pixelsToWorkspaceUnits_(o),e=t.utils.Coordinate.sum(this.startXY_,e),this.draggingBubble_.moveTo(e.x,e.y),this.maybeDeleteBubble_()||(this.dragSurface_&&this.dragSurface_.clearAndHide(this.workspace_.getBubbleCanvas()),this.draggingBubble_.setDragging&&this.draggingBubble_.setDragging(!1),this.fireMoveEvent_()),this.workspace_.setResizesEnabled(!0),this.workspace_.getToolbox()&&(e=this.draggingBubble_.isDeletable()?"blocklyToolboxDelete":"blocklyToolboxGrab",this.workspace_.getToolbox().removeStyle(e)),t.Events.setGroup(!1)},t.BubbleDragger.prototype.fireMoveEvent_=function(){if(this.draggingBubble_.isComment){var e=new t.Events.CommentMove(this.draggingBubble_);e.setOldCoordinate(this.startXY_),e.recordNew(),t.Events.fire(e)}},t.BubbleDragger.prototype.pixelsToWorkspaceUnits_=function(e){return e=new t.utils.Coordinate(e.x/this.workspace_.scale,e.y/this.workspace_.scale),this.workspace_.isMutator&&e.scale(1/this.workspace_.options.parentWorkspace.scale),e},t.BubbleDragger.prototype.moveToDragSurface_=function(){this.draggingBubble_.moveTo(0,0),this.dragSurface_.translateSurface(this.startXY_.x,this.startXY_.y),this.dragSurface_.setBlocksAndShow(this.draggingBubble_.getSvgRoot())},t.WorkspaceDragger=function(e){this.workspace_=e,this.startScrollXY_=new t.utils.Coordinate(e.scrollX,e.scrollY)},t.WorkspaceDragger.prototype.dispose=function(){this.workspace_=null},t.WorkspaceDragger.prototype.startDrag=function(){t.selected&&t.selected.unselect(),this.workspace_.setupDragSurface()},t.WorkspaceDragger.prototype.endDrag=function(t){this.drag(t),this.workspace_.resetDragSurface()},t.WorkspaceDragger.prototype.drag=function(e){e=t.utils.Coordinate.sum(this.startScrollXY_,e),this.workspace_.scroll(e.x,e.y)},t.FlyoutDragger=function(e){t.FlyoutDragger.superClass_.constructor.call(this,e.getWorkspace()),this.scrollbar_=e.scrollbar_,this.horizontalLayout_=e.horizontalLayout_},t.utils.object.inherits(t.FlyoutDragger,t.WorkspaceDragger),t.FlyoutDragger.prototype.drag=function(e){e=t.utils.Coordinate.sum(this.startScrollXY_,e),this.horizontalLayout_?this.scrollbar_.set(-e.x):this.scrollbar_.set(-e.y)},t.Action=function(t,e){this.name=t,this.desc=e},t.navigation={},t.navigation.loggingCallback=null,t.navigation.STATE_FLYOUT=1,t.navigation.STATE_WS=2,t.navigation.STATE_TOOLBOX=3,t.navigation.WS_MOVE_DISTANCE=40,t.navigation.currentState_=t.navigation.STATE_WS,t.navigation.actionNames={PREVIOUS:"previous",NEXT:"next",IN:"in",OUT:"out",INSERT:"insert",MARK:"mark",DISCONNECT:"disconnect",TOOLBOX:"toolbox",EXIT:"exit",TOGGLE_KEYBOARD_NAV:"toggle_keyboard_nav",MOVE_WS_CURSOR_UP:"move workspace cursor up",MOVE_WS_CURSOR_DOWN:"move workspace cursor down",MOVE_WS_CURSOR_LEFT:"move workspace cursor left",MOVE_WS_CURSOR_RIGHT:"move workspace cursor right"},t.navigation.MARKER_NAME="local_marker_1",t.navigation.getMarker=function(){return t.getMainWorkspace().getMarker(t.navigation.MARKER_NAME)},t.navigation.focusToolbox_=function(){var e=t.getMainWorkspace().getToolbox();e&&(t.navigation.currentState_=t.navigation.STATE_TOOLBOX,t.navigation.resetFlyout_(!1),t.navigation.getMarker().getCurNode()||t.navigation.markAtCursor_(),e.selectFirstCategory())},t.navigation.focusFlyout_=function(){t.navigation.currentState_=t.navigation.STATE_FLYOUT;var e=t.getMainWorkspace(),o=e.getToolbox();e=o?o.flyout_:e.getFlyout(),t.navigation.getMarker().getCurNode()||t.navigation.markAtCursor_(),e&&e.getWorkspace()&&0<(e=e.getWorkspace().getTopBlocks(!0)).length&&(e=e[0],e=t.ASTNode.createStackNode(e),t.navigation.getFlyoutCursor_().setCurNode(e))},t.navigation.focusWorkspace_=function(){t.hideChaff();var e=t.getMainWorkspace(),o=e.getCursor(),i=!!e.getToolbox(),n=e.getTopBlocks(!0);t.navigation.resetFlyout_(i),t.navigation.currentState_=t.navigation.STATE_WS,0(this.flyout_?t.FLYOUT_DRAG_RADIUS:t.DRAG_RADIUS))},t.Gesture.prototype.updateIsDraggingFromFlyout_=function(){return!(!this.targetBlock_||!this.flyout_.isBlockCreatable_(this.targetBlock_)||this.flyout_.isScrollable()&&!this.flyout_.isDragTowardWorkspace(this.currentDragDeltaXY_)||(this.startWorkspace_=this.flyout_.targetWorkspace_,this.startWorkspace_.updateScreenCalculationsIfScrolled(),t.Events.getGroup()||t.Events.setGroup(!0),this.startBlock_=null,this.targetBlock_=this.flyout_.createBlock(this.targetBlock_),this.targetBlock_.select(),0))},t.Gesture.prototype.updateIsDraggingBubble_=function(){return!!this.startBubble_&&(this.isDraggingBubble_=!0,this.startDraggingBubble_(),!0)},t.Gesture.prototype.updateIsDraggingBlock_=function(){return!!this.targetBlock_&&(this.flyout_?this.isDraggingBlock_=this.updateIsDraggingFromFlyout_():this.targetBlock_.isMovable()&&(this.isDraggingBlock_=!0),!!this.isDraggingBlock_&&(this.startDraggingBlock_(),!0))},t.Gesture.prototype.updateIsDraggingWorkspace_=function(){(this.flyout_?this.flyout_.isScrollable():this.startWorkspace_&&this.startWorkspace_.isDraggable())&&(this.workspaceDragger_=this.flyout_?new t.FlyoutDragger(this.flyout_):new t.WorkspaceDragger(this.startWorkspace_),this.isDraggingWorkspace_=!0,this.workspaceDragger_.startDrag())},t.Gesture.prototype.updateIsDragging_=function(){if(this.calledUpdateIsDragging_)throw Error("updateIsDragging_ should only be called once per gesture.");this.calledUpdateIsDragging_=!0,this.updateIsDraggingBubble_()||this.updateIsDraggingBlock_()||this.updateIsDraggingWorkspace_()},t.Gesture.prototype.startDraggingBlock_=function(){this.blockDragger_=new t.BlockDragger(this.targetBlock_,this.startWorkspace_),this.blockDragger_.startBlockDrag(this.currentDragDeltaXY_,this.healStack_),this.blockDragger_.dragBlock(this.mostRecentEvent_,this.currentDragDeltaXY_)},t.Gesture.prototype.startDraggingBubble_=function(){this.bubbleDragger_=new t.BubbleDragger(this.startBubble_,this.startWorkspace_),this.bubbleDragger_.startBubbleDrag(),this.bubbleDragger_.dragBubble(this.mostRecentEvent_,this.currentDragDeltaXY_)},t.Gesture.prototype.doStart=function(e){t.utils.isTargetInput(e)?this.cancel():(this.hasStarted_=!0,t.blockAnimations.disconnectUiStop(),this.startWorkspace_.updateScreenCalculationsIfScrolled(),this.startWorkspace_.isMutator&&this.startWorkspace_.resize(),t.hideChaff(!!this.flyout_),this.startWorkspace_.markFocused(),this.mostRecentEvent_=e,t.Tooltip.block(),this.targetBlock_&&(!this.targetBlock_.isInFlyout&&e.shiftKey&&this.targetBlock_.workspace.keyboardAccessibilityMode?this.creatorWorkspace_.getCursor().setCurNode(t.navigation.getTopNode(this.targetBlock_)):this.targetBlock_.select()),t.utils.isRightButton(e)?this.handleRightClick(e):("touchstart"!=e.type.toLowerCase()&&"pointerdown"!=e.type.toLowerCase()||"mouse"==e.pointerType||t.longStart(e,this),this.mouseDownXY_=new t.utils.Coordinate(e.clientX,e.clientY),this.healStack_=e.altKey||e.ctrlKey||e.metaKey,this.bindMouseEvents(e)))},t.Gesture.prototype.bindMouseEvents=function(e){this.onMoveWrapper_=t.bindEventWithChecks_(document,"mousemove",null,this.handleMove.bind(this)),this.onUpWrapper_=t.bindEventWithChecks_(document,"mouseup",null,this.handleUp.bind(this)),e.preventDefault(),e.stopPropagation()},t.Gesture.prototype.handleMove=function(t){this.updateFromEvent_(t),this.isDraggingWorkspace_?this.workspaceDragger_.drag(this.currentDragDeltaXY_):this.isDraggingBlock_?this.blockDragger_.dragBlock(this.mostRecentEvent_,this.currentDragDeltaXY_):this.isDraggingBubble_&&this.bubbleDragger_.dragBubble(this.mostRecentEvent_,this.currentDragDeltaXY_),t.preventDefault(),t.stopPropagation()},t.Gesture.prototype.handleUp=function(e){this.updateFromEvent_(e),t.longStop_(),this.isEnding_?console.log("Trying to end a gesture recursively."):(this.isEnding_=!0,this.isDraggingBubble_?this.bubbleDragger_.endBubbleDrag(e,this.currentDragDeltaXY_):this.isDraggingBlock_?this.blockDragger_.endBlockDrag(e,this.currentDragDeltaXY_):this.isDraggingWorkspace_?this.workspaceDragger_.endDrag(this.currentDragDeltaXY_):this.isBubbleClick_()?this.doBubbleClick_():this.isFieldClick_()?this.doFieldClick_():this.isBlockClick_()?this.doBlockClick_():this.isWorkspaceClick_()&&this.doWorkspaceClick_(e),e.preventDefault(),e.stopPropagation(),this.dispose())},t.Gesture.prototype.cancel=function(){this.isEnding_||(t.longStop_(),this.isDraggingBubble_?this.bubbleDragger_.endBubbleDrag(this.mostRecentEvent_,this.currentDragDeltaXY_):this.isDraggingBlock_?this.blockDragger_.endBlockDrag(this.mostRecentEvent_,this.currentDragDeltaXY_):this.isDraggingWorkspace_&&this.workspaceDragger_.endDrag(this.currentDragDeltaXY_),this.dispose())},t.Gesture.prototype.handleRightClick=function(e){this.targetBlock_?(this.bringBlockToFront_(),t.hideChaff(!!this.flyout_),this.targetBlock_.showContextMenu(e)):this.startBubble_?this.startBubble_.showContextMenu(e):this.startWorkspace_&&!this.flyout_&&(t.hideChaff(),this.startWorkspace_.showContextMenu(e)),e.preventDefault(),e.stopPropagation(),this.dispose()},t.Gesture.prototype.handleWsStart=function(e,o){if(this.hasStarted_)throw Error("Tried to call gesture.handleWsStart, but the gesture had already been started.");this.setStartWorkspace_(o),this.mostRecentEvent_=e,this.doStart(e),this.startWorkspace_.keyboardAccessibilityMode&&t.navigation.setState(t.navigation.STATE_WS)},t.Gesture.prototype.handleFlyoutStart=function(t,e){if(this.hasStarted_)throw Error("Tried to call gesture.handleFlyoutStart, but the gesture had already been started.");this.setStartFlyout_(e),this.handleWsStart(t,e.getWorkspace())},t.Gesture.prototype.handleBlockStart=function(t,e){if(this.hasStarted_)throw Error("Tried to call gesture.handleBlockStart, but the gesture had already been started.");this.setStartBlock(e),this.mostRecentEvent_=t},t.Gesture.prototype.handleBubbleStart=function(t,e){if(this.hasStarted_)throw Error("Tried to call gesture.handleBubbleStart, but the gesture had already been started.");this.setStartBubble(e),this.mostRecentEvent_=t},t.Gesture.prototype.doBubbleClick_=function(){this.startBubble_.setFocus&&this.startBubble_.setFocus(),this.startBubble_.select&&this.startBubble_.select()},t.Gesture.prototype.doFieldClick_=function(){this.startField_.showEditor(this.mostRecentEvent_),this.bringBlockToFront_()},t.Gesture.prototype.doBlockClick_=function(){this.flyout_&&this.flyout_.autoClose?this.targetBlock_.isEnabled()&&(t.Events.getGroup()||t.Events.setGroup(!0),this.flyout_.createBlock(this.targetBlock_).scheduleSnapAndBump()):t.Events.fire(new t.Events.Ui(this.startBlock_,"click",void 0,void 0)),this.bringBlockToFront_(),t.Events.setGroup(!1)},t.Gesture.prototype.doWorkspaceClick_=function(e){var o=this.creatorWorkspace_;e.shiftKey&&o.keyboardAccessibilityMode?(e=new t.utils.Coordinate(e.clientX,e.clientY),e=t.utils.screenToWsCoordinates(o,e),e=t.ASTNode.createWorkspaceNode(o,e),o.getCursor().setCurNode(e)):t.selected&&t.selected.unselect()},t.Gesture.prototype.bringBlockToFront_=function(){this.targetBlock_&&!this.flyout_&&this.targetBlock_.bringToFront()},t.Gesture.prototype.setStartField=function(t){if(this.hasStarted_)throw Error("Tried to call gesture.setStartField, but the gesture had already been started.");this.startField_||(this.startField_=t)},t.Gesture.prototype.setStartBubble=function(t){this.startBubble_||(this.startBubble_=t)},t.Gesture.prototype.setStartBlock=function(t){this.startBlock_||this.startBubble_||(this.startBlock_=t,t.isInFlyout&&t!=t.getRootBlock()?this.setTargetBlock_(t.getRootBlock()):this.setTargetBlock_(t))},t.Gesture.prototype.setTargetBlock_=function(t){t.isShadow()?this.setTargetBlock_(t.getParent()):this.targetBlock_=t},t.Gesture.prototype.setStartWorkspace_=function(t){this.startWorkspace_||(this.startWorkspace_=t)},t.Gesture.prototype.setStartFlyout_=function(t){this.flyout_||(this.flyout_=t)},t.Gesture.prototype.isBubbleClick_=function(){return!!this.startBubble_&&!this.hasExceededDragRadius_},t.Gesture.prototype.isBlockClick_=function(){return!!this.startBlock_&&!this.hasExceededDragRadius_&&!this.isFieldClick_()},t.Gesture.prototype.isFieldClick_=function(){return!!this.startField_&&this.startField_.isClickable()&&!this.hasExceededDragRadius_&&(!this.flyout_||!this.flyout_.autoClose)},t.Gesture.prototype.isWorkspaceClick_=function(){return!(this.startBlock_||this.startBubble_||this.startField_||this.hasExceededDragRadius_)},t.Gesture.prototype.isDragging=function(){return this.isDraggingWorkspace_||this.isDraggingBlock_||this.isDraggingBubble_},t.Gesture.prototype.hasStarted=function(){return this.hasStarted_},t.Gesture.prototype.getInsertionMarkers=function(){return this.blockDragger_?this.blockDragger_.getInsertionMarkers():[]},t.Gesture.inProgress=function(){for(var e,o=t.Workspace.getAll(),i=0;e=o[i];i++)if(e.currentGesture_)return!0;return!1},t.Field=function(e,o,i){this.tooltip_=this.validator_=this.value_=null,this.size_=new t.utils.Size(0,0),this.constants_=this.mouseDownWrapper_=this.textContent_=this.textElement_=this.borderRect_=this.fieldGroup_=this.markerSvg_=this.cursorSvg_=null,i&&this.configure_(i),this.setValue(e),o&&this.setValidator(o)},t.Field.prototype.name=void 0,t.Field.prototype.disposed=!1,t.Field.prototype.maxDisplayLength=50,t.Field.prototype.sourceBlock_=null,t.Field.prototype.isDirty_=!0,t.Field.prototype.visible_=!0,t.Field.prototype.clickTarget_=null,t.Field.NBSP=" ",t.Field.prototype.EDITABLE=!0,t.Field.prototype.SERIALIZABLE=!1,t.Field.prototype.configure_=function(e){var o=e.tooltip;"string"==typeof o&&(o=t.utils.replaceMessageReferences(e.tooltip)),o&&this.setTooltip(o)},t.Field.prototype.setSourceBlock=function(t){if(this.sourceBlock_)throw Error("Field already bound to a block.");this.sourceBlock_=t},t.Field.prototype.getConstants=function(){return!this.constants_&&this.sourceBlock_&&this.sourceBlock_.workspace&&this.sourceBlock_.workspace.rendered&&(this.constants_=this.sourceBlock_.workspace.getRenderer().getConstants()),this.constants_},t.Field.prototype.getSourceBlock=function(){return this.sourceBlock_},t.Field.prototype.init=function(){this.fieldGroup_||(this.fieldGroup_=t.utils.dom.createSvgElement("g",{},null),this.isVisible()||(this.fieldGroup_.style.display="none"),this.sourceBlock_.getSvgRoot().appendChild(this.fieldGroup_),this.initView(),this.updateEditable(),this.setTooltip(this.tooltip_),this.bindEvents_(),this.initModel())},t.Field.prototype.initView=function(){this.createBorderRect_(),this.createTextElement_()},t.Field.prototype.initModel=function(){},t.Field.prototype.createBorderRect_=function(){this.borderRect_=t.utils.dom.createSvgElement("rect",{rx:this.getConstants().FIELD_BORDER_RECT_RADIUS,ry:this.getConstants().FIELD_BORDER_RECT_RADIUS,x:0,y:0,height:this.size_.height,width:this.size_.width,class:"blocklyFieldRect"},this.fieldGroup_)},t.Field.prototype.createTextElement_=function(){this.textElement_=t.utils.dom.createSvgElement("text",{class:"blocklyText"},this.fieldGroup_),this.getConstants().FIELD_TEXT_BASELINE_CENTER&&this.textElement_.setAttribute("dominant-baseline","central"),this.textContent_=document.createTextNode(""),this.textElement_.appendChild(this.textContent_)},t.Field.prototype.bindEvents_=function(){t.Tooltip.bindMouseEvents(this.getClickTarget_()),this.mouseDownWrapper_=t.bindEventWithChecks_(this.getClickTarget_(),"mousedown",this,this.onMouseDown_)},t.Field.prototype.fromXml=function(t){this.setValue(t.textContent)},t.Field.prototype.toXml=function(t){return t.textContent=this.getValue(),t},t.Field.prototype.dispose=function(){t.DropDownDiv.hideIfOwner(this),t.WidgetDiv.hideIfOwner(this),t.Tooltip.unbindMouseEvents(this.getClickTarget_()),this.mouseDownWrapper_&&t.unbindEvent_(this.mouseDownWrapper_),t.utils.dom.removeNode(this.fieldGroup_),this.disposed=!0},t.Field.prototype.updateEditable=function(){var e=this.fieldGroup_;this.EDITABLE&&e&&(this.sourceBlock_.isEditable()?(t.utils.dom.addClass(e,"blocklyEditableText"),t.utils.dom.removeClass(e,"blocklyNonEditableText"),e.style.cursor=this.CURSOR):(t.utils.dom.addClass(e,"blocklyNonEditableText"),t.utils.dom.removeClass(e,"blocklyEditableText"),e.style.cursor=""))},t.Field.prototype.isClickable=function(){return!!this.sourceBlock_&&this.sourceBlock_.isEditable()&&!!this.showEditor_&&"function"==typeof this.showEditor_},t.Field.prototype.isCurrentlyEditable=function(){return this.EDITABLE&&!!this.sourceBlock_&&this.sourceBlock_.isEditable()},t.Field.prototype.isSerializable=function(){var t=!1;return this.name&&(this.SERIALIZABLE?t=!0:this.EDITABLE&&(console.warn("Detected an editable field that was not serializable. Please define SERIALIZABLE property as true on all editable custom fields. Proceeding with serialization."),t=!0)),t},t.Field.prototype.isVisible=function(){return this.visible_},t.Field.prototype.setVisible=function(t){if(this.visible_!=t){this.visible_=t;var e=this.getSvgRoot();e&&(e.style.display=t?"block":"none")}},t.Field.prototype.setValidator=function(t){this.validator_=t},t.Field.prototype.getValidator=function(){return this.validator_},t.Field.prototype.classValidator=function(t){return t},t.Field.prototype.callValidator=function(t){var e=this.classValidator(t);if(null===e)return null;if(void 0!==e&&(t=e),e=this.getValidator()){if(null===(e=e.call(this,t)))return null;void 0!==e&&(t=e)}return t},t.Field.prototype.getSvgRoot=function(){return this.fieldGroup_},t.Field.prototype.applyColour=function(){},t.Field.prototype.render_=function(){this.textContent_&&(this.textContent_.nodeValue=this.getDisplayText_()),this.updateSize_()},t.Field.prototype.showEditor=function(t){this.isClickable()&&this.showEditor_(t)},t.Field.prototype.updateWidth=function(){console.warn("Deprecated call to updateWidth, call Blockly.Field.updateSize_ to force an update to the size of the field, or Blockly.utils.dom.getTextWidth() to check the size of the field."),this.updateSize_()},t.Field.prototype.updateSize_=function(e){var o=this.getConstants(),i=2*(e=null!=e?e:this.borderRect_?this.getConstants().FIELD_BORDER_RECT_X_PADDING:0),n=o.FIELD_TEXT_HEIGHT,s=0;this.textElement_&&(i+=s=t.utils.dom.getFastTextWidth(this.textElement_,o.FIELD_TEXT_FONTSIZE,o.FIELD_TEXT_FONTWEIGHT,o.FIELD_TEXT_FONTFAMILY)),this.borderRect_&&(n=Math.max(n,o.FIELD_BORDER_RECT_HEIGHT)),this.size_.height=n,this.size_.width=i,this.positionTextElement_(e,s),this.positionBorderRect_()},t.Field.prototype.positionTextElement_=function(t,e){if(this.textElement_){var o=this.getConstants(),i=this.size_.height/2;this.textElement_.setAttribute("x",this.sourceBlock_.RTL?this.size_.width-e-t:t),this.textElement_.setAttribute("y",o.FIELD_TEXT_BASELINE_CENTER?i:i-o.FIELD_TEXT_HEIGHT/2+o.FIELD_TEXT_BASELINE)}},t.Field.prototype.positionBorderRect_=function(){this.borderRect_&&(this.borderRect_.setAttribute("width",this.size_.width),this.borderRect_.setAttribute("height",this.size_.height),this.borderRect_.setAttribute("rx",this.getConstants().FIELD_BORDER_RECT_RADIUS),this.borderRect_.setAttribute("ry",this.getConstants().FIELD_BORDER_RECT_RADIUS))},t.Field.prototype.getSize=function(){return this.isVisible()?(this.isDirty_?(this.render_(),this.isDirty_=!1):this.visible_&&0==this.size_.width&&(console.warn("Deprecated use of setting size_.width to 0 to rerender a field. Set field.isDirty_ to true instead."),this.render_()),this.size_):new t.utils.Size(0,0)},t.Field.prototype.getScaledBBox=function(){if(this.borderRect_)e=this.borderRect_.getBoundingClientRect(),i=t.utils.style.getPageOffset(this.borderRect_),n=e.width,e=e.height;else{var e=this.sourceBlock_.getHeightWidth(),o=this.sourceBlock_.workspace.scale,i=this.getAbsoluteXY_(),n=e.width*o;e=e.height*o,t.utils.userAgent.GECKO?(i.x+=1.5*o,i.y+=1.5*o):t.utils.userAgent.EDGE||t.utils.userAgent.IE||(i.x-=.5*o,i.y-=.5*o),n+=1*o,e+=1*o}return{top:i.y,bottom:i.y+e,left:i.x,right:i.x+n}},t.Field.prototype.getDisplayText_=function(){var e=this.getText();return e?(e.length>this.maxDisplayLength&&(e=e.substring(0,this.maxDisplayLength-2)+"…"),e=e.replace(/\s/g,t.Field.NBSP),this.sourceBlock_&&this.sourceBlock_.RTL&&(e+="‏"),e):t.Field.NBSP},t.Field.prototype.getText=function(){if(this.getText_){var t=this.getText_.call(this);if(null!==t)return String(t)}return String(this.getValue())},t.Field.prototype.setText=function(t){throw Error("setText method is deprecated")},t.Field.prototype.markDirty=function(){this.isDirty_=!0,this.constants_=null},t.Field.prototype.forceRerender=function(){this.isDirty_=!0,this.sourceBlock_&&this.sourceBlock_.rendered&&(this.sourceBlock_.render(),this.sourceBlock_.bumpNeighbours(),this.updateMarkers_())},t.Field.prototype.setValue=function(e){if(null!==e){var o=this.doClassValidation_(e);if(!((e=this.processValidation_(e,o))instanceof Error)){if((o=this.getValidator())&&(o=o.call(this,e),(e=this.processValidation_(e,o))instanceof Error))return;(o=this.getValue())!==e&&(this.sourceBlock_&&t.Events.isEnabled()&&t.Events.fire(new t.Events.BlockChange(this.sourceBlock_,"field",this.name||null,o,e)),this.doValueUpdate_(e),this.isDirty_&&this.forceRerender())}}},t.Field.prototype.processValidation_=function(t,e){return null===e?(this.doValueInvalid_(t),this.isDirty_&&this.forceRerender(),Error()):(void 0!==e&&(t=e),t)},t.Field.prototype.getValue=function(){return this.value_},t.Field.prototype.doClassValidation_=function(t){return null==t?null:t=this.classValidator(t)},t.Field.prototype.doValueUpdate_=function(t){this.value_=t,this.isDirty_=!0},t.Field.prototype.doValueInvalid_=function(t){},t.Field.prototype.onMouseDown_=function(t){this.sourceBlock_&&this.sourceBlock_.workspace&&(t=this.sourceBlock_.workspace.getGesture(t))&&t.setStartField(this)},t.Field.prototype.setTooltip=function(t){var e=this.getClickTarget_();e?e.tooltip=t||""===t?t:this.sourceBlock_:this.tooltip_=t},t.Field.prototype.getClickTarget_=function(){return this.clickTarget_||this.getSvgRoot()},t.Field.prototype.getAbsoluteXY_=function(){return t.utils.style.getPageOffset(this.getClickTarget_())},t.Field.prototype.referencesVariables=function(){return!1},t.Field.prototype.getParentInput=function(){for(var t=null,e=this.sourceBlock_,o=e.inputList,i=0;ie||e>this.fieldRow.length)throw Error("index "+e+" out of bounds.");return o||""==o&&i?("string"==typeof o&&(o=new t.FieldLabel(o)),o.setSourceBlock(this.sourceBlock_),this.sourceBlock_.rendered&&o.init(),o.name=i,o.prefixField&&(e=this.insertFieldAt(e,o.prefixField)),this.fieldRow.splice(e,0,o),++e,o.suffixField&&(e=this.insertFieldAt(e,o.suffixField)),this.sourceBlock_.rendered&&(this.sourceBlock_.render(),this.sourceBlock_.bumpNeighbours()),e):e},t.Input.prototype.removeField=function(t){for(var e,o=0;e=this.fieldRow[o];o++)if(e.name===t)return e.dispose(),this.fieldRow.splice(o,1),void(this.sourceBlock_.rendered&&(this.sourceBlock_.render(),this.sourceBlock_.bumpNeighbours()));throw Error('Field "%s" not found.',t)},t.Input.prototype.isVisible=function(){return this.visible_},t.Input.prototype.setVisible=function(t){var e=[];if(this.visible_==t)return e;for(var o,i=(this.visible_=t)?"block":"none",n=0;o=this.fieldRow[n];n++)o.setVisible(t);return this.connection&&(t?e=this.connection.startTrackingAll():this.connection.stopTrackingAll(),n=this.connection.targetBlock())&&(n.getSvgRoot().style.display=i,t||(n.rendered=!1)),e},t.Input.prototype.markDirty=function(){for(var t,e=0;t=this.fieldRow[e];e++)t.markDirty()},t.Input.prototype.setCheck=function(t){if(!this.connection)throw Error("This input does not have a connection.");return this.connection.setCheck(t),this},t.Input.prototype.setAlign=function(t){return this.align=t,this.sourceBlock_.rendered&&this.sourceBlock_.render(),this},t.Input.prototype.init=function(){if(this.sourceBlock_.workspace.rendered)for(var t=0;tt&&(o=o.substring(0,t-3)+"..."),o},t.Block.prototype.appendValueInput=function(e){return this.appendInput_(t.INPUT_VALUE,e)},t.Block.prototype.appendStatementInput=function(e){return this.appendInput_(t.NEXT_STATEMENT,e)},t.Block.prototype.appendDummyInput=function(e){return this.appendInput_(t.DUMMY_INPUT,e||"")},t.Block.prototype.jsonInit=function(e){var o=e.type?'Block "'+e.type+'": ':"";if(e.output&&e.previousStatement)throw Error(o+"Must not have both an output and a previousStatement.");if(e.style&&e.style.hat&&(this.hat=e.style.hat,e.style=null),e.style&&e.colour)throw Error(o+"Must not have both a colour and a style.");e.style?this.jsonInitStyle_(e,o):this.jsonInitColour_(e,o);for(var i=0;void 0!==e["message"+i];)this.interpolate_(e["message"+i],e["args"+i]||[],e["lastDummyAlign"+i],o),i++;if(void 0!==e.inputsInline&&this.setInputsInline(e.inputsInline),void 0!==e.output&&this.setOutput(!0,e.output),void 0!==e.outputShape&&this.setOutputShape(e.outputShape),void 0!==e.previousStatement&&this.setPreviousStatement(!0,e.previousStatement),void 0!==e.nextStatement&&this.setNextStatement(!0,e.nextStatement),void 0!==e.tooltip&&(i=e.tooltip,i=t.utils.replaceMessageReferences(i),this.setTooltip(i)),void 0!==e.enableContextMenu&&(i=e.enableContextMenu,this.contextMenu=!!i),void 0!==e.helpUrl&&(i=e.helpUrl,i=t.utils.replaceMessageReferences(i),this.setHelpUrl(i)),"string"==typeof e.extensions&&(console.warn(o+"JSON attribute 'extensions' should be an array of strings. Found raw string in JSON for '"+e.type+"' block."),e.extensions=[e.extensions]),void 0!==e.mutator&&t.Extensions.apply(e.mutator,this,!0),Array.isArray(e.extensions))for(e=e.extensions,o=0;o=c||c>o.length)throw Error('Block "'+this.type+'": Message index %'+c+" out of range.");if(r[c])throw Error('Block "'+this.type+'": Message index %'+c+" duplicated.");r[c]=!0,a++,e.push(o[c-1])}else(c=c.trim())&&e.push(c)}if(a!=o.length)throw Error('Block "'+this.type+'": Message does not reference all '+o.length+" arg(s).");for(e.length&&("string"==typeof e[e.length-1]||t.utils.string.startsWith(e[e.length-1].type,"field_"))&&(l={type:"input_dummy"},i&&(l.align=i),e.push(l)),i={LEFT:t.ALIGN_LEFT,RIGHT:t.ALIGN_RIGHT,CENTRE:t.ALIGN_CENTRE,CENTER:t.ALIGN_CENTRE},o=[],l=0;l=this.inputList.length)throw RangeError("Input index "+t+" out of bounds.");if(e>this.inputList.length)throw RangeError("Reference input "+e+" out of bounds.");var o=this.inputList[t];this.inputList.splice(t,1),t--t?e-1:t}),this.highlightedIndex_)},t.Menu.prototype.highlightHelper=function(t,e){e=0>e?-1:e;var o=this.getChildCount();e=t.call(this,e,o);for(var i=0;i<=o;){var n=this.getChildAt(e);if(n&&this.canHighlightItem(n))return this.setHighlightedIndex(e),!0;i++,e=t.call(this,e,o)}return!1},t.Menu.prototype.canHighlightItem=function(t){return t.isEnabled()},t.Menu.prototype.handleMouseOver_=function(t){(t=this.getMenuItem(t.target))&&(t.isEnabled()?this.getHighlighted()!==t&&(this.unhighlightCurrent(),this.setHighlighted(t)):this.unhighlightCurrent())},t.Menu.prototype.handleClick_=function(e){var o=this.openingCoords;if(this.openingCoords=null,o&&"number"==typeof e.clientX){var i=new t.utils.Coordinate(e.clientX,e.clientY);if(1>t.utils.Coordinate.distance(o,i))return}(o=this.getMenuItem(e.target))&&o.handleClick(e)&&e.preventDefault()},t.Menu.prototype.handleMouseEnter_=function(t){this.focus()},t.Menu.prototype.handleMouseLeave_=function(t){this.getElement()&&(this.blur(),this.clearHighlighted())},t.Menu.prototype.handleKeyEvent=function(t){return!(0==this.getChildCount()||!this.handleKeyEventInternal(t)||(t.preventDefault(),t.stopPropagation(),0))},t.Menu.prototype.handleKeyEventInternal=function(e){var o=this.getHighlighted();if(o&&"function"==typeof o.handleKeyEvent&&o.handleKeyEvent(e))return!0;if(e.shiftKey||e.ctrlKey||e.metaKey||e.altKey)return!1;switch(e.keyCode){case t.utils.KeyCodes.ENTER:o&&o.performActionInternal(e);break;case t.utils.KeyCodes.UP:this.highlightPrevious();break;case t.utils.KeyCodes.DOWN:this.highlightNext();break;default:return!1}return!0},t.MenuItem=function(e,o){t.Component.call(this),this.setContentInternal(e),this.setValue(o),this.enabled_=!0},t.utils.object.inherits(t.MenuItem,t.Component),t.MenuItem.prototype.createDom=function(){var e=document.createElement("div");e.id=this.getId(),this.setElementInternal(e),e.className="goog-menuitem goog-option "+(this.enabled_?"":"goog-menuitem-disabled ")+(this.checked_?"goog-option-selected ":"")+(this.rightToLeft_?"goog-menuitem-rtl ":"");var o=this.getContentWrapperDom();e.appendChild(o);var i=this.getCheckboxDom();i&&o.appendChild(i),o.appendChild(this.getContentDom()),t.utils.aria.setRole(e,this.roleName_||(this.checkable_?t.utils.aria.Role.MENUITEMCHECKBOX:t.utils.aria.Role.MENUITEM)),t.utils.aria.setState(e,t.utils.aria.State.SELECTED,this.checkable_&&this.checked_||!1)},t.MenuItem.prototype.getCheckboxDom=function(){if(!this.checkable_)return null;var t=document.createElement("div");return t.className="goog-menuitem-checkbox",t},t.MenuItem.prototype.getContentDom=function(){var t=this.content_;return"string"==typeof t&&(t=document.createTextNode(t)),t},t.MenuItem.prototype.getContentWrapperDom=function(){var t=document.createElement("div");return t.className="goog-menuitem-content",t},t.MenuItem.prototype.setContentInternal=function(t){this.content_=t},t.MenuItem.prototype.setValue=function(t){this.value_=t},t.MenuItem.prototype.getValue=function(){return this.value_},t.MenuItem.prototype.setRole=function(t){this.roleName_=t},t.MenuItem.prototype.setCheckable=function(t){this.checkable_=t},t.MenuItem.prototype.setChecked=function(e){if(this.checkable_){this.checked_=e;var o=this.getElement();o&&this.isEnabled()&&(e?(t.utils.dom.addClass(o,"goog-option-selected"),t.utils.aria.setState(o,t.utils.aria.State.SELECTED,!0)):(t.utils.dom.removeClass(o,"goog-option-selected"),t.utils.aria.setState(o,t.utils.aria.State.SELECTED,!1)))}},t.MenuItem.prototype.setHighlighted=function(e){this.highlight_=e;var o=this.getElement();o&&this.isEnabled()&&(e?t.utils.dom.addClass(o,"goog-menuitem-highlight"):t.utils.dom.removeClass(o,"goog-menuitem-highlight"))},t.MenuItem.prototype.isEnabled=function(){return this.enabled_},t.MenuItem.prototype.setEnabled=function(e){this.enabled_=e,(e=this.getElement())&&(this.enabled_?t.utils.dom.removeClass(e,"goog-menuitem-disabled"):t.utils.dom.addClass(e,"goog-menuitem-disabled"))},t.MenuItem.prototype.handleClick=function(t){this.isEnabled()&&(this.setHighlighted(!0),this.performActionInternal())},t.MenuItem.prototype.performActionInternal=function(){this.checkable_&&this.setChecked(!this.checked_),this.actionHandler_&&this.actionHandler_.call(this.actionHandlerObj_,this)},t.MenuItem.prototype.onAction=function(t,e){this.actionHandler_=t,this.actionHandlerObj_=e},t.utils.uiMenu={},t.utils.uiMenu.getSize=function(e){e=e.getElement();var o=t.utils.style.getSize(e);return o.height=e.scrollHeight,o},t.utils.uiMenu.adjustBBoxesForRTL=function(t,e,o){e.left+=o.width,e.right+=o.width,t.left+=o.width,t.right+=o.width},t.ContextMenu={},t.ContextMenu.currentBlock=null,t.ContextMenu.eventWrapper_=null,t.ContextMenu.show=function(e,o,i){if(t.WidgetDiv.show(t.ContextMenu,i,null),o.length){var n=t.ContextMenu.populate_(o,i);t.ContextMenu.position_(n,e,i),setTimeout((function(){n.getElement().focus()}),1),t.ContextMenu.currentBlock=null}else t.ContextMenu.hide()},t.ContextMenu.populate_=function(e,o){var i=new t.Menu;i.setRightToLeft(o);for(var n,s=0;n=e[s];s++){var r=new t.MenuItem(n.text);r.setRightToLeft(o),i.addChild(r,!0),r.setEnabled(n.enabled),n.enabled&&r.onAction((function(){t.ContextMenu.hide(),this.callback()}),n)}return i},t.ContextMenu.position_=function(e,o,i){var n=t.utils.getViewportBBox();o={top:o.clientY+n.top,bottom:o.clientY+n.top,left:o.clientX+n.left,right:o.clientX+n.left},t.ContextMenu.createWidget_(e);var s=t.utils.uiMenu.getSize(e);i&&t.utils.uiMenu.adjustBBoxesForRTL(n,o,s),t.WidgetDiv.positionWithAnchor(n,o,s,i),e.getElement().focus()},t.ContextMenu.createWidget_=function(e){e.render(t.WidgetDiv.DIV);var o=e.getElement();t.utils.dom.addClass(o,"blocklyContextMenu"),t.bindEventWithChecks_(o,"contextmenu",null,t.utils.noEvent),e.focus()},t.ContextMenu.hide=function(){t.WidgetDiv.hideIfOwner(t.ContextMenu),t.ContextMenu.currentBlock=null,t.ContextMenu.eventWrapper_&&(t.unbindEvent_(t.ContextMenu.eventWrapper_),t.ContextMenu.eventWrapper_=null)},t.ContextMenu.callbackFactory=function(e,o){return function(){t.Events.disable();try{var i=t.Xml.domToBlock(o,e.workspace),n=e.getRelativeToSurfaceXY();n.x=e.RTL?n.x-t.SNAP_RADIUS:n.x+t.SNAP_RADIUS,n.y+=2*t.SNAP_RADIUS,i.moveBy(n.x,n.y)}finally{t.Events.enable()}t.Events.isEnabled()&&!i.isShadow()&&t.Events.fire(new t.Events.BlockCreate(i)),i.select()}},t.ContextMenu.blockDeleteOption=function(e){var o=e.getDescendants(!1).length,i=e.getNextBlock();return i&&(o-=i.getDescendants(!1).length),{text:1==o?t.Msg.DELETE_BLOCK:t.Msg.DELETE_X_BLOCKS.replace("%1",String(o)),enabled:!0,callback:function(){t.Events.setGroup(!0),e.dispose(!0,!0),t.Events.setGroup(!1)}}},t.ContextMenu.blockHelpOption=function(e){return{enabled:!("function"==typeof e.helpUrl?!e.helpUrl():!e.helpUrl),text:t.Msg.HELP,callback:function(){e.showHelp()}}},t.ContextMenu.blockDuplicateOption=function(e){var o=e.isDuplicatable();return{text:t.Msg.DUPLICATE_BLOCK,enabled:o,callback:function(){t.duplicate(e)}}},t.ContextMenu.blockCommentOption=function(e){var o={enabled:!t.utils.userAgent.IE};return e.getCommentIcon()?(o.text=t.Msg.REMOVE_COMMENT,o.callback=function(){e.setCommentText(null)}):(o.text=t.Msg.ADD_COMMENT,o.callback=function(){e.setCommentText("")}),o},t.ContextMenu.commentDeleteOption=function(e){return{text:t.Msg.REMOVE_COMMENT,enabled:!0,callback:function(){t.Events.setGroup(!0),e.dispose(!0,!0),t.Events.setGroup(!1)}}},t.ContextMenu.commentDuplicateOption=function(e){return{text:t.Msg.DUPLICATE_COMMENT,enabled:!0,callback:function(){t.duplicate(e)}}},t.ContextMenu.workspaceCommentOption=function(e,o){if(!t.WorkspaceCommentSvg)throw Error("Missing require for Blockly.WorkspaceCommentSvg");var i={enabled:!t.utils.userAgent.IE};return i.text=t.Msg.ADD_COMMENT,i.callback=function(){var i=new t.WorkspaceCommentSvg(e,t.Msg.WORKSPACE_COMMENT_DEFAULT_TEXT,t.WorkspaceCommentSvg.DEFAULT_SIZE,t.WorkspaceCommentSvg.DEFAULT_SIZE),n=e.getInjectionDiv().getBoundingClientRect();n=new t.utils.Coordinate(o.clientX-n.left,o.clientY-n.top);var s=e.getOriginOffsetInPixels();(n=t.utils.Coordinate.difference(n,s)).scale(1/e.scale),i.moveBy(n.x,n.y),e.rendered&&(i.initSvg(),i.render(),i.select())},i},t.RenderedConnection=function(e,o){t.RenderedConnection.superClass_.constructor.call(this,e,o),this.db_=e.workspace.connectionDBList[o],this.dbOpposite_=e.workspace.connectionDBList[t.OPPOSITE_TYPE[o]],this.offsetInBlock_=new t.utils.Coordinate(0,0),this.trackedState_=t.RenderedConnection.TrackedState.WILL_TRACK},t.utils.object.inherits(t.RenderedConnection,t.Connection),t.RenderedConnection.TrackedState={WILL_TRACK:-1,UNTRACKED:0,TRACKED:1},t.RenderedConnection.prototype.dispose=function(){t.RenderedConnection.superClass_.dispose.call(this),this.trackedState_==t.RenderedConnection.TrackedState.TRACKED&&this.db_.removeConnection(this,this.y)},t.RenderedConnection.prototype.getSourceBlock=function(){return t.RenderedConnection.superClass_.getSourceBlock.call(this)},t.RenderedConnection.prototype.targetBlock=function(){return t.RenderedConnection.superClass_.targetBlock.call(this)},t.RenderedConnection.prototype.distanceFrom=function(t){var e=this.x-t.x;return t=this.y-t.y,Math.sqrt(e*e+t*t)},t.RenderedConnection.prototype.bumpAwayFrom=function(e){if(!this.sourceBlock_.workspace.isDragging()){var o=this.sourceBlock_.getRootBlock();if(!o.isInFlyout){var i=!1;if(!o.isMovable()){if(!(o=e.getSourceBlock().getRootBlock()).isMovable())return;e=this,i=!0}var n=t.selected==o;n||o.addSelect();var s=e.x+t.SNAP_RADIUS+Math.floor(Math.random()*t.BUMP_RANDOMNESS)-this.x,r=e.y+t.SNAP_RADIUS+Math.floor(Math.random()*t.BUMP_RANDOMNESS)-this.y;i&&(r=-r),o.RTL&&(s=e.x-t.SNAP_RADIUS-Math.floor(Math.random()*t.BUMP_RANDOMNESS)-this.x),o.moveBy(s,r),n||o.removeSelect()}}},t.RenderedConnection.prototype.moveTo=function(e,o){this.trackedState_==t.RenderedConnection.TrackedState.WILL_TRACK?(this.db_.addConnection(this,o),this.trackedState_=t.RenderedConnection.TrackedState.TRACKED):this.trackedState_==t.RenderedConnection.TrackedState.TRACKED&&(this.db_.removeConnection(this,this.y),this.db_.addConnection(this,o)),this.x=e,this.y=o},t.RenderedConnection.prototype.moveBy=function(t,e){this.moveTo(this.x+t,this.y+e)},t.RenderedConnection.prototype.moveToOffset=function(t){this.moveTo(t.x+this.offsetInBlock_.x,t.y+this.offsetInBlock_.y)},t.RenderedConnection.prototype.setOffsetInBlock=function(t,e){this.offsetInBlock_.x=t,this.offsetInBlock_.y=e},t.RenderedConnection.prototype.getOffsetInBlock=function(){return this.offsetInBlock_},t.RenderedConnection.prototype.tighten=function(){var e=this.targetConnection.x-this.x,o=this.targetConnection.y-this.y;if(0!=e||0!=o){var i=this.targetBlock(),n=i.getSvgRoot();if(!n)throw Error("block is not rendered.");n=t.utils.getRelativeXY(n),i.getSvgRoot().setAttribute("transform","translate("+(n.x-e)+","+(n.y-o)+")"),i.moveConnections(-e,-o)}},t.RenderedConnection.prototype.closest=function(t,e){return this.dbOpposite_.searchForClosest(this,t,e)},t.RenderedConnection.prototype.highlight=function(){var e=this.sourceBlock_.workspace.getRenderer().getConstants(),o=e.shapeFor(this);this.type==t.INPUT_VALUE||this.type==t.OUTPUT_VALUE?(e=e.TAB_OFFSET_FROM_TOP,o=t.utils.svgPaths.moveBy(0,-e)+t.utils.svgPaths.lineOnAxis("v",e)+o.pathDown+t.utils.svgPaths.lineOnAxis("v",e)):(e=e.NOTCH_OFFSET_LEFT-e.CORNER_RADIUS,o=t.utils.svgPaths.moveBy(-e,0)+t.utils.svgPaths.lineOnAxis("h",e)+o.pathLeft+t.utils.svgPaths.lineOnAxis("h",e)),e=this.sourceBlock_.getRelativeToSurfaceXY(),t.Connection.highlightedPath_=t.utils.dom.createSvgElement("path",{class:"blocklyHighlightedConnectionPath",d:o,transform:"translate("+(this.x-e.x)+","+(this.y-e.y)+")"+(this.sourceBlock_.RTL?" scale(-1 1)":"")},this.sourceBlock_.getSvgRoot())},t.RenderedConnection.prototype.unhighlight=function(){t.utils.dom.removeNode(t.Connection.highlightedPath_),delete t.Connection.highlightedPath_},t.RenderedConnection.prototype.setTracking=function(e){e&&this.trackedState_==t.RenderedConnection.TrackedState.TRACKED||!e&&this.trackedState_==t.RenderedConnection.TrackedState.UNTRACKED||this.sourceBlock_.isInFlyout||(e?(this.db_.addConnection(this,this.y),this.trackedState_=t.RenderedConnection.TrackedState.TRACKED):(this.trackedState_==t.RenderedConnection.TrackedState.TRACKED&&this.db_.removeConnection(this,this.y),this.trackedState_=t.RenderedConnection.TrackedState.UNTRACKED))},t.RenderedConnection.prototype.stopTrackingAll=function(){if(this.setTracking(!1),this.targetConnection)for(var t=this.targetBlock().getDescendants(!1),e=0;eo)&&t.RenderedConnection.superClass_.isConnectionAllowed.call(this,e)},t.RenderedConnection.prototype.onFailedConnect=function(t){this.bumpAwayFrom(t)},t.RenderedConnection.prototype.disconnectInternal_=function(e,o){t.RenderedConnection.superClass_.disconnectInternal_.call(this,e,o),e.rendered&&e.render(),o.rendered&&(o.updateDisabled(),o.render())},t.RenderedConnection.prototype.respawnShadow_=function(){var e=this.getSourceBlock(),o=this.getShadowDom();if(e.workspace&&o&&t.Events.recordUndo){if(t.RenderedConnection.superClass_.respawnShadow_.call(this),!(o=this.targetBlock()))throw Error("Couldn't respawn the shadow block that should exist here.");o.initSvg(),o.render(!1),e.rendered&&e.render()}},t.RenderedConnection.prototype.neighbours=function(t){return this.dbOpposite_.getNeighbours(this,t)},t.RenderedConnection.prototype.connect_=function(e){t.RenderedConnection.superClass_.connect_.call(this,e);var o=this.getSourceBlock();e=e.getSourceBlock(),o.rendered&&o.updateDisabled(),e.rendered&&e.updateDisabled(),o.rendered&&e.rendered&&(this.type==t.NEXT_STATEMENT||this.type==t.PREVIOUS_STATEMENT?e.render():o.render())},t.RenderedConnection.prototype.onCheckChanged_=function(){!this.isConnected()||this.targetConnection&&this.checkType(this.targetConnection)||((this.isSuperior()?this.targetBlock():this.sourceBlock_).unplug(),this.sourceBlock_.bumpNeighbours())},t.Marker=function(){this.drawer_=this.curNode_=this.colour=null,this.type="marker"},t.Marker.prototype.setDrawer=function(t){this.drawer_=t},t.Marker.prototype.getDrawer=function(){return this.drawer_},t.Marker.prototype.getCurNode=function(){return this.curNode_},t.Marker.prototype.setCurNode=function(t){var e=this.curNode_;this.curNode_=t,this.drawer_&&this.drawer_.draw(e,this.curNode_)},t.Marker.prototype.draw=function(){this.drawer_&&this.drawer_.draw(this.curNode_,this.curNode_)},t.Marker.prototype.hide=function(){this.drawer_&&this.drawer_.hide()},t.Marker.prototype.dispose=function(){this.getDrawer()&&this.getDrawer().dispose()},t.Cursor=function(){t.Cursor.superClass_.constructor.call(this),this.type="cursor"},t.utils.object.inherits(t.Cursor,t.Marker),t.Cursor.prototype.next=function(){var e=this.getCurNode();if(!e)return null;for(e=e.next();e&&e.next()&&(e.getType()==t.ASTNode.types.NEXT||e.getType()==t.ASTNode.types.BLOCK);)e=e.next();return e&&this.setCurNode(e),e},t.Cursor.prototype.in=function(){var e=this.getCurNode();return e?(e.getType()!=t.ASTNode.types.PREVIOUS&&e.getType()!=t.ASTNode.types.OUTPUT||(e=e.next()),(e=e.in())&&this.setCurNode(e),e):null},t.Cursor.prototype.prev=function(){var e=this.getCurNode();if(!e)return null;for(e=e.prev();e&&e.prev()&&(e.getType()==t.ASTNode.types.NEXT||e.getType()==t.ASTNode.types.BLOCK);)e=e.prev();return e&&this.setCurNode(e),e},t.Cursor.prototype.out=function(){var e=this.getCurNode();return e?((e=e.out())&&e.getType()==t.ASTNode.types.BLOCK&&(e=e.prev()||e),e&&this.setCurNode(e),e):null},t.Cursor.prototype.onBlocklyAction=function(e){if(this.getCurNode()&&this.getCurNode().getType()===t.ASTNode.types.FIELD&&this.getCurNode().getLocation().onBlocklyAction(e))return!0;switch(e.name){case t.navigation.actionNames.PREVIOUS:return this.prev(),!0;case t.navigation.actionNames.OUT:return this.out(),!0;case t.navigation.actionNames.NEXT:return this.next(),!0;case t.navigation.actionNames.IN:return this.in(),!0;default:return!1}},t.BasicCursor=function(){t.BasicCursor.superClass_.constructor.call(this)},t.utils.object.inherits(t.BasicCursor,t.Cursor),t.BasicCursor.prototype.next=function(){var t=this.getCurNode();return t?((t=this.getNextNode_(t,this.validNode_))&&this.setCurNode(t),t):null},t.BasicCursor.prototype.in=function(){return this.next()},t.BasicCursor.prototype.prev=function(){var t=this.getCurNode();return t?((t=this.getPreviousNode_(t,this.validNode_))&&this.setCurNode(t),t):null},t.BasicCursor.prototype.out=function(){return this.prev()},t.BasicCursor.prototype.getNextNode_=function(t,e){if(!t)return null;var o=t.in()||t.next();return e(o)?o:o?this.getNextNode_(o,e):e(t=this.findSiblingOrParent_(t.out()))?t:t?this.getNextNode_(t,e):null},t.BasicCursor.prototype.getPreviousNode_=function(t,e){if(!t)return null;var o=t.prev();return e(o=o?this.getRightMostChild_(o):t.out())?o:o?this.getPreviousNode_(o,e):null},t.BasicCursor.prototype.validNode_=function(e){var o=!1;return(e=e&&e.getType())!=t.ASTNode.types.OUTPUT&&e!=t.ASTNode.types.INPUT&&e!=t.ASTNode.types.FIELD&&e!=t.ASTNode.types.NEXT&&e!=t.ASTNode.types.PREVIOUS&&e!=t.ASTNode.types.WORKSPACE||(o=!0),o},t.BasicCursor.prototype.findSiblingOrParent_=function(t){if(!t)return null;var e=t.next();return e||this.findSiblingOrParent_(t.out())},t.BasicCursor.prototype.getRightMostChild_=function(t){if(!t.in())return t;for(t=t.in();t.next();)t=t.next();return this.getRightMostChild_(t)},t.TabNavigateCursor=function(){t.TabNavigateCursor.superClass_.constructor.call(this)},t.utils.object.inherits(t.TabNavigateCursor,t.BasicCursor),t.TabNavigateCursor.prototype.validNode_=function(e){var o=!1,i=e&&e.getType();return e&&(e=e.getLocation(),i==t.ASTNode.types.FIELD&&e&&e.isTabNavigable()&&e.isClickable()&&(o=!0)),o},t.utils.Rect=function(t,e,o,i){this.top=t,this.bottom=e,this.left=o,this.right=i},t.utils.Rect.prototype.contains=function(t,e){return t>=this.left&&t<=this.right&&e>=this.top&&e<=this.bottom},t.BlockSvg=function(e,o,i){this.svgGroup_=t.utils.dom.createSvgElement("g",{},null),this.svgGroup_.translate_="",this.style=e.getRenderer().getConstants().getBlockStyle(null),this.pathObject=e.getRenderer().makePathObject(this.svgGroup_,this.style),this.rendered=!1,this.workspace=e,this.previousConnection=this.nextConnection=this.outputConnection=null,this.useDragSurface_=t.utils.is3dSupported()&&!!e.getBlockDragSurface();var n=this.pathObject.svgPath;n.tooltip=this,t.Tooltip.bindMouseEvents(n),t.BlockSvg.superClass_.constructor.call(this,e,o,i),this.svgGroup_.dataset&&(this.svgGroup_.dataset.id=this.id)},t.utils.object.inherits(t.BlockSvg,t.Block),t.BlockSvg.prototype.height=0,t.BlockSvg.prototype.width=0,t.BlockSvg.prototype.dragStartXY_=null,t.BlockSvg.prototype.warningTextDb_=null,t.BlockSvg.INLINE=-1,t.BlockSvg.COLLAPSED_WARNING_ID="TEMP_COLLAPSED_WARNING_",t.BlockSvg.prototype.initSvg=function(){if(!this.workspace.rendered)throw TypeError("Workspace is headless.");for(var e,o=0;e=this.inputList[o];o++)e.init();for(e=this.getIcons(),o=0;o=this.connections_.length)return-1;e=t.y;for(var i=o;0<=i&&this.connections_[i].y==e;){if(this.connections_[i]==t)return i;i--}for(;ot)){e=i;break}o=i}}return e},t.ConnectionDB.prototype.removeConnection=function(t,e){if(-1==(t=this.findIndexOfConnection_(t,e)))throw Error("Unable to find connection in connectionDB.");this.connections_.splice(t,1)},t.ConnectionDB.prototype.getNeighbours=function(t,e){function o(t){var o=n-i[t].x,r=s-i[t].y;return Math.sqrt(o*o+r*r)<=e&&l.push(i[t]),r(t=this.subscribedWorkspaces_.indexOf(t)))throw Error("Cannot unsubscribe a workspace that hasn't been subscribed.");this.subscribedWorkspaces_.splice(t,1)},t.ThemeManager.prototype.subscribe=function(t,e,o){this.componentDB_[e]||(this.componentDB_[e]=[]),this.componentDB_[e].push({element:t,propertyName:o}),e=this.theme_&&this.theme_.getComponentStyle(e),t.style[o]=e||""},t.ThemeManager.prototype.unsubscribe=function(t){if(t)for(var e,o=Object.keys(this.componentDB_),i=0;e=o[i];i++){for(var n=this.componentDB_[e],s=n.length-1;0<=s;s--)n[s].element===t&&n.splice(s,1);this.componentDB_[e].length||delete this.componentDB_[e]}},t.ThemeManager.prototype.dispose=function(){this.componentDB_=this.subscribedWorkspaces_=this.theme_=this.owner_=null},t.TouchGesture=function(e,o){t.TouchGesture.superClass_.constructor.call(this,e,o),this.isMultiTouch_=!1,this.cachedPoints_=Object.create(null),this.startDistance_=this.previousScale_=0,this.isPinchZoomEnabled_=this.onStartWrapper_=null},t.utils.object.inherits(t.TouchGesture,t.Gesture),t.TouchGesture.ZOOM_IN_MULTIPLIER=5,t.TouchGesture.ZOOM_OUT_MULTIPLIER=6,t.TouchGesture.prototype.doStart=function(e){this.isPinchZoomEnabled_=this.startWorkspace_.options.zoomOptions&&this.startWorkspace_.options.zoomOptions.pinch,t.TouchGesture.superClass_.doStart.call(this,e),!this.isEnding_&&t.Touch.isTouchEvent(e)&&this.handleTouchStart(e)},t.TouchGesture.prototype.bindMouseEvents=function(e){this.onStartWrapper_=t.bindEventWithChecks_(document,"mousedown",null,this.handleStart.bind(this),!0),this.onMoveWrapper_=t.bindEventWithChecks_(document,"mousemove",null,this.handleMove.bind(this),!0),this.onUpWrapper_=t.bindEventWithChecks_(document,"mouseup",null,this.handleUp.bind(this),!0),e.preventDefault(),e.stopPropagation()},t.TouchGesture.prototype.handleStart=function(e){!this.isDragging()&&t.Touch.isTouchEvent(e)&&(this.handleTouchStart(e),this.isMultiTouch()&&t.longStop_())},t.TouchGesture.prototype.handleMove=function(e){this.isDragging()?t.Touch.shouldHandleEvent(e)&&t.TouchGesture.superClass_.handleMove.call(this,e):this.isMultiTouch()?(t.Touch.isTouchEvent(e)&&this.handleTouchMove(e),t.longStop_()):t.TouchGesture.superClass_.handleMove.call(this,e)},t.TouchGesture.prototype.handleUp=function(e){t.Touch.isTouchEvent(e)&&!this.isDragging()&&this.handleTouchEnd(e),!this.isMultiTouch()||this.isDragging()?t.Touch.shouldHandleEvent(e)&&t.TouchGesture.superClass_.handleUp.call(this,e):(e.preventDefault(),e.stopPropagation(),this.dispose())},t.TouchGesture.prototype.isMultiTouch=function(){return this.isMultiTouch_},t.TouchGesture.prototype.dispose=function(){t.TouchGesture.superClass_.dispose.call(this),this.onStartWrapper_&&t.unbindEvent_(this.onStartWrapper_)},t.TouchGesture.prototype.handleTouchStart=function(e){var o=t.Touch.getTouchIdentifierFromEvent(e);this.cachedPoints_[o]=this.getTouchPoint(e),2==(o=Object.keys(this.cachedPoints_)).length&&(this.startDistance_=t.utils.Coordinate.distance(this.cachedPoints_[o[0]],this.cachedPoints_[o[1]]),this.isMultiTouch_=!0,e.preventDefault())},t.TouchGesture.prototype.handleTouchMove=function(e){var o=t.Touch.getTouchIdentifierFromEvent(e);this.cachedPoints_[o]=this.getTouchPoint(e),o=Object.keys(this.cachedPoints_),this.isPinchZoomEnabled_&&2===o.length?this.handlePinch_(e):t.TouchGesture.superClass_.handleMove.call(this,e)},t.TouchGesture.prototype.handlePinch_=function(e){var o=Object.keys(this.cachedPoints_);if(o=t.utils.Coordinate.distance(this.cachedPoints_[o[0]],this.cachedPoints_[o[1]])/this.startDistance_,0this.previousScale_){var i=o-this.previousScale_;i=0Object.keys(this.cachedPoints_).length&&(this.cachedPoints_=Object.create(null),this.previousScale_=0)},t.TouchGesture.prototype.getTouchPoint=function(e){return this.startWorkspace_?new t.utils.Coordinate(e.pageX?e.pageX:e.changedTouches[0].pageX,e.pageY?e.pageY:e.changedTouches[0].pageY):null},t.WorkspaceAudio=function(t){this.parentWorkspace_=t,this.SOUNDS_=Object.create(null)},t.WorkspaceAudio.prototype.lastSound_=null,t.WorkspaceAudio.prototype.dispose=function(){this.SOUNDS_=this.parentWorkspace_=null},t.WorkspaceAudio.prototype.load=function(e,o){if(e.length){try{var i=new t.utils.global.Audio}catch(t){return}for(var n,s=0;s=this.remainingCapacity()||(this.currentGesture_&&this.currentGesture_.cancel(),"comment"==t.tagName.toLowerCase()?this.pasteWorkspaceComment_(t):this.pasteBlock_(t))},t.WorkspaceSvg.prototype.pasteBlock_=function(e){t.Events.disable();try{var o=t.Xml.domToBlock(e,this),i=this.getMarker(t.navigation.MARKER_NAME).getCurNode();if(this.keyboardAccessibilityMode&&i&&i.isConnection()){var n=i.getLocation();return void t.navigation.insertBlock(o,n)}var s=parseInt(e.getAttribute("x"),10),r=parseInt(e.getAttribute("y"),10);if(!isNaN(s)&&!isNaN(r)){this.RTL&&(s=-s);do{e=!1;var a,l=this.getAllBlocks(!1);for(i=0;a=l[i];i++){var c=a.getRelativeToSurfaceXY();if(1>=Math.abs(s-c.x)&&1>=Math.abs(r-c.y)){e=!0;break}}if(!e){var h,u=o.getConnections_(!1);for(i=0;h=u[i];i++)if(h.closest(t.SNAP_RADIUS,new t.utils.Coordinate(s,r)).connection){e=!0;break}}e&&(s=this.RTL?s-t.SNAP_RADIUS:s+t.SNAP_RADIUS,r+=2*t.SNAP_RADIUS)}while(e);o.moveBy(s,r)}}finally{t.Events.enable()}t.Events.isEnabled()&&!o.isShadow()&&t.Events.fire(new t.Events.BlockCreate(o)),o.select()},t.WorkspaceSvg.prototype.pasteWorkspaceComment_=function(e){t.Events.disable();try{var o=t.WorkspaceCommentSvg.fromXml(e,this),i=parseInt(e.getAttribute("x"),10),n=parseInt(e.getAttribute("y"),10);isNaN(i)||isNaN(n)||(this.RTL&&(i=-i),o.moveBy(i+50,n+50))}finally{t.Events.enable()}t.Events.isEnabled(),o.select()},t.WorkspaceSvg.prototype.refreshToolboxSelection=function(){var t=this.isFlyout?this.targetWorkspace:this;t&&!t.currentGesture_&&t.toolbox_&&t.toolbox_.getFlyout()&&t.toolbox_.refreshSelection()},t.WorkspaceSvg.prototype.renameVariableById=function(e,o){t.WorkspaceSvg.superClass_.renameVariableById.call(this,e,o),this.refreshToolboxSelection()},t.WorkspaceSvg.prototype.deleteVariableById=function(e){t.WorkspaceSvg.superClass_.deleteVariableById.call(this,e),this.refreshToolboxSelection()},t.WorkspaceSvg.prototype.createVariable=function(e,o,i){return e=t.WorkspaceSvg.superClass_.createVariable.call(this,e,o,i),this.refreshToolboxSelection(),e},t.WorkspaceSvg.prototype.recordDeleteAreas=function(){this.deleteAreaTrash_=this.trashcan&&this.svgGroup_.parentNode?this.trashcan.getClientRect():null,this.deleteAreaToolbox_=this.flyout_?this.flyout_.getClientRect():this.toolbox_?this.toolbox_.getClientRect():null},t.WorkspaceSvg.prototype.isDeleteArea=function(e){return this.deleteAreaTrash_&&this.deleteAreaTrash_.contains(e.clientX,e.clientY)?t.DELETE_AREA_TRASH:this.deleteAreaToolbox_&&this.deleteAreaToolbox_.contains(e.clientX,e.clientY)?t.DELETE_AREA_TOOLBOX:t.DELETE_AREA_NONE},t.WorkspaceSvg.prototype.onMouseDown_=function(t){var e=this.getGesture(t);e&&e.handleWsStart(t,this)},t.WorkspaceSvg.prototype.startDrag=function(e,o){(e=t.utils.mouseToSvg(e,this.getParentSvg(),this.getInverseScreenCTM())).x/=this.scale,e.y/=this.scale,this.dragDeltaXY_=t.utils.Coordinate.difference(o,e)},t.WorkspaceSvg.prototype.moveDrag=function(e){return(e=t.utils.mouseToSvg(e,this.getParentSvg(),this.getInverseScreenCTM())).x/=this.scale,e.y/=this.scale,t.utils.Coordinate.sum(this.dragDeltaXY_,e)},t.WorkspaceSvg.prototype.isDragging=function(){return null!=this.currentGesture_&&this.currentGesture_.isDragging()},t.WorkspaceSvg.prototype.isDraggable=function(){return this.options.moveOptions&&this.options.moveOptions.drag},t.WorkspaceSvg.prototype.isContentBounded=function(){return this.options.moveOptions&&this.options.moveOptions.scrollbars||this.options.moveOptions&&this.options.moveOptions.wheel||this.options.moveOptions&&this.options.moveOptions.drag||this.options.zoomOptions&&this.options.zoomOptions.controls||this.options.zoomOptions&&this.options.zoomOptions.wheel||this.options.zoomOptions&&this.options.zoomOptions.pinch},t.WorkspaceSvg.prototype.isMovable=function(){return this.options.moveOptions&&this.options.moveOptions.scrollbars||this.options.moveOptions&&this.options.moveOptions.wheel||this.options.moveOptions&&this.options.moveOptions.drag||this.options.zoomOptions&&this.options.zoomOptions.wheel||this.options.zoomOptions&&this.options.zoomOptions.pinch},t.WorkspaceSvg.prototype.onMouseWheel_=function(e){if(t.Gesture.inProgress())e.preventDefault(),e.stopPropagation();else{var o=this.options.zoomOptions&&this.options.zoomOptions.wheel,i=this.options.moveOptions&&this.options.moveOptions.wheel;if(o||i){var n=t.utils.getScrollDeltaPixels(e);!o||!e.ctrlKey&&i?(o=this.scrollX-n.x,i=this.scrollY-n.y,e.shiftKey&&!n.x&&(o=this.scrollX-n.y,i=this.scrollY),this.scroll(o,i)):(n=-n.y/50,o=t.utils.mouseToSvg(e,this.getParentSvg(),this.getInverseScreenCTM()),this.zoom(o.x,o.y,n)),e.preventDefault()}}},t.WorkspaceSvg.prototype.getBlocksBoundingBox=function(){var e=this.getTopBlocks(!1),o=this.getTopComments(!1);if(!(e=e.concat(o)).length)return new t.utils.Rect(0,0,0,0);o=e[0].getBoundingRectangle();for(var i=1;io.bottom&&(o.bottom=n.bottom),n.lefto.right&&(o.right=n.right)}return o},t.WorkspaceSvg.prototype.cleanUp=function(){this.setResizesEnabled(!1),t.Events.setGroup(!0);for(var e,o=this.getTopBlocks(!0),i=0,n=0;e=o[n];n++)if(e.isMovable()){var s=e.getRelativeToSurfaceXY();e.moveBy(-s.x,i-s.y),e.snapToGrid(),i=e.getRelativeToSurfaceXY().y+e.getHeightWidth().height+this.renderer_.getConstants().MIN_BLOCK_HEIGHT}t.Events.setGroup(!1),this.setResizesEnabled(!0)},t.WorkspaceSvg.prototype.showContextMenu=function(e){function o(t){if(t.isDeletable())_=_.concat(t.getDescendants(!1));else{t=t.getChildren(!1);for(var e=0;e_.length?i():t.confirm(t.Msg.DELETE_ALL_BLOCKS.replace("%1",_.length),(function(t){t&&i()}))}},n.push(l),this.configureContextMenu&&this.configureContextMenu(n,e),t.ContextMenu.show(e,n,this.RTL)}},t.WorkspaceSvg.prototype.updateToolbox=function(e){if(e=t.Options.parseToolboxTree(e)){if(!this.options.languageTree)throw Error("Existing toolbox is null. Can't create new toolbox.");if(e.getElementsByTagName("category").length){if(!this.toolbox_)throw Error("Existing toolbox has no categories. Can't change mode.");this.options.languageTree=e,this.toolbox_.renderTree(e)}else{if(!this.flyout_)throw Error("Existing toolbox has categories. Can't change mode.");this.options.languageTree=e,this.flyout_.show(e.childNodes)}}else if(this.options.languageTree)throw Error("Can't nullify an existing toolbox.")},t.WorkspaceSvg.prototype.markFocused=function(){this.options.parentWorkspace?this.options.parentWorkspace.markFocused():(t.mainWorkspace=this,this.setBrowserFocus())},t.WorkspaceSvg.prototype.setBrowserFocus=function(){document.activeElement&&document.activeElement.blur();try{this.getParentSvg().focus({preventScroll:!0})}catch(t){try{this.getParentSvg().parentNode.setActive()}catch(t){this.getParentSvg().parentNode.focus({preventScroll:!0})}}},t.WorkspaceSvg.prototype.zoom=function(t,e,o){o=Math.pow(this.options.zoomOptions.scaleSpeed,o);var i=this.scale*o;if(this.scale!=i){i>this.options.zoomOptions.maxScale?o=this.options.zoomOptions.maxScale/this.scale:ithis.options.zoomOptions.maxScale?e=this.options.zoomOptions.maxScale:this.options.zoomOptions.minScale&&eo.viewBottom||o.contentLefto.viewRight){switch(i=null,e&&(i=t.Events.getGroup(),t.Events.setGroup(e.group)),e.type){case t.Events.BLOCK_CREATE:case t.Events.BLOCK_MOVE:var r=s.getBlockById(e.blockId);r&&(r=r.getRootBlock());break;case t.Events.COMMENT_CREATE:case t.Events.COMMENT_MOVE:r=s.getCommentById(e.commentId)}if(r){(n=r.getBoundingRectangle()).height=n.bottom-n.top,n.width=n.right-n.left;var a=o.viewTop,l=o.viewBottom-n.height;l=Math.max(a,l),a=t.utils.math.clamp(a,n.top,l)-n.top,l=o.viewLeft;var c=o.viewRight-n.width;o.RTL?l=Math.min(c,l):c=Math.max(l,c),o=t.utils.math.clamp(l,n.left,c)-n.left,r.moveBy(o,a)}e&&(!e.group&&r&&console.log("WARNING: Moved object in bounds but there was no event group. This may break undo."),null!==i&&t.Events.setGroup(i))}}})),t.svgResize(s),t.WidgetDiv.createDom(),t.DropDownDiv.createDom(),t.Tooltip.createDom(),s},t.init_=function(e){var o=e.options,i=e.getParentSvg();if(t.bindEventWithChecks_(i.parentNode,"contextmenu",null,(function(e){t.utils.isTargetInput(e)||e.preventDefault()})),i=t.bindEventWithChecks_(window,"resize",null,(function(){t.hideChaff(!0),t.svgResize(e)})),e.setResizeHandlerWrapper(i),t.inject.bindDocumentEvents_(),o.languageTree){i=e.getToolbox();var n=e.getFlyout(!0);i?i.init():n&&(n.init(e),n.show(o.languageTree.childNodes),n.scrollToStart())}i=t.Scrollbar.scrollbarThickness,o.hasTrashcan&&(i=e.trashcan.init(i)),o.zoomOptions&&o.zoomOptions.controls&&e.zoomControls_.init(i),o.moveOptions&&o.moveOptions.scrollbars?(e.scrollbar=new t.ScrollbarPair(e),e.scrollbar.resize()):e.setMetrics({x:.5,y:.5}),o.hasSounds&&t.inject.loadSounds_(o.pathToMedia,e)},t.inject.bindDocumentEvents_=function(){t.documentEventsBound_||(t.bindEventWithChecks_(document,"scroll",null,(function(){for(var e,o=t.Workspace.getAll(),i=0;e=o[i];i++)e.updateInverseScreenCTM&&e.updateInverseScreenCTM()})),t.bindEventWithChecks_(document,"keydown",null,t.onKeyDown),t.bindEvent_(document,"touchend",null,t.longStop_),t.bindEvent_(document,"touchcancel",null,t.longStop_),t.utils.userAgent.IPAD&&t.bindEventWithChecks_(window,"orientationchange",document,(function(){t.svgResize(t.getMainWorkspace())}))),t.documentEventsBound_=!0},t.inject.loadSounds_=function(e,o){var i=o.getAudioManager();i.load([e+"click.mp3",e+"click.wav",e+"click.ogg"],"click"),i.load([e+"disconnect.wav",e+"disconnect.mp3",e+"disconnect.ogg"],"disconnect"),i.load([e+"delete.mp3",e+"delete.ogg",e+"delete.wav"],"delete");var n=[];e=function(){for(;n.length;)t.unbindEvent_(n.pop());i.preload()},n.push(t.bindEventWithChecks_(document,"mousemove",null,e,!0)),n.push(t.bindEventWithChecks_(document,"touchstart",null,e,!0))},t.Names=function(t,e){if(this.variablePrefix_=e||"",this.reservedDict_=Object.create(null),t)for(t=t.split(","),e=0;e1'),n.appendChild(i),o.push(n)),t.Blocks.variables_get){e.sort(t.VariableModel.compareByName),i=0;for(var s;s=e[i];i++)(n=t.utils.xml.createElement("block")).setAttribute("type","variables_get"),n.setAttribute("gap",8),n.appendChild(t.Variables.generateVariableFieldDom(s)),o.push(n)}}return o},t.Variables.VAR_LETTER_OPTIONS="ijkmnopqrstuvwxyzabcdefgh",t.Variables.generateUniqueName=function(e){return t.Variables.generateUniqueNameFromOptions(t.Variables.VAR_LETTER_OPTIONS.charAt(0),e.getAllVariableNames())},t.Variables.generateUniqueNameFromOptions=function(e,o){if(!o.length)return e;for(var i=t.Variables.VAR_LETTER_OPTIONS,n="",s=i.indexOf(e);;){for(var r=!1,a=0;as?t.WidgetDiv.positionInternal_(e,0,i.height+s):t.WidgetDiv.positionInternal_(e,s,i.height)},t.WidgetDiv.calculateX_=function(t,e,o,i){return i?(e=Math.max(e.right-o.width,t.left),Math.min(e,t.right-o.width)):(e=Math.min(e.left,t.right-o.width),Math.max(e,t.left))},t.WidgetDiv.calculateY_=function(t,e,o){return e.bottom+o.height>=t.bottom?e.top-o.height:e.bottom},t.VERSION="3.20200402.1",t.mainWorkspace=null,t.selected=null,t.draggingConnections=[],t.clipboardXml_=null,t.clipboardSource_=null,t.clipboardTypeCounts_=null,t.cache3dSupported_=null,t.parentContainer=null,t.svgSize=function(t){return{width:t.cachedWidth_,height:t.cachedHeight_}},t.resizeSvgContents=function(t){t.resizeContents()},t.svgResize=function(t){for(;t.options.parentWorkspace;)t=t.options.parentWorkspace;var e=t.getParentSvg(),o=e.parentNode;if(o){var i=o.offsetWidth;o=o.offsetHeight,e.cachedWidth_!=i&&(e.setAttribute("width",i+"px"),e.cachedWidth_=i),e.cachedHeight_!=o&&(e.setAttribute("height",o+"px"),e.cachedHeight_=o),t.resize()}},t.onKeyDown=function(e){var o=t.mainWorkspace;if(o&&!(t.utils.isTargetInput(e)||o.rendered&&!o.isVisible()))if(o.options.readOnly)t.navigation.onKeyPress(e);else{var i=!1;if(e.keyCode==t.utils.KeyCodes.ESC)t.hideChaff(),t.navigation.onBlocklyAction(t.navigation.ACTION_EXIT);else{if(t.navigation.onKeyPress(e))return;if(e.keyCode==t.utils.KeyCodes.BACKSPACE||e.keyCode==t.utils.KeyCodes.DELETE){if(e.preventDefault(),t.Gesture.inProgress())return;t.selected&&t.selected.isDeletable()&&(i=!0)}else if(e.altKey||e.ctrlKey||e.metaKey){if(t.Gesture.inProgress())return;t.selected&&t.selected.isDeletable()&&t.selected.isMovable()&&(e.keyCode==t.utils.KeyCodes.C?(t.hideChaff(),t.copy_(t.selected)):e.keyCode!=t.utils.KeyCodes.X||t.selected.workspace.isFlyout||(t.copy_(t.selected),i=!0)),e.keyCode==t.utils.KeyCodes.V?t.clipboardXml_&&((e=t.clipboardSource_).isFlyout&&(e=e.targetWorkspace),t.clipboardTypeCounts_&&e.isCapacityAvailable(t.clipboardTypeCounts_)&&(t.Events.setGroup(!0),e.paste(t.clipboardXml_),t.Events.setGroup(!1))):e.keyCode==t.utils.KeyCodes.Z&&(t.hideChaff(),o.undo(e.shiftKey))}}i&&!t.selected.workspace.isFlyout&&(t.Events.setGroup(!0),t.hideChaff(),t.selected.dispose(!0,!0),t.Events.setGroup(!1))}},t.copy_=function(e){if(e.isComment)var o=e.toXmlWithXY();else{o=t.Xml.blockToDom(e,!0),t.Xml.deleteNext(o);var i=e.getRelativeToSurfaceXY();o.setAttribute("x",e.RTL?-i.x:i.x),o.setAttribute("y",i.y)}t.clipboardXml_=o,t.clipboardSource_=e.workspace,t.clipboardTypeCounts_=e.isComment?null:t.utils.getBlockTypeCounts(e,!0)},t.duplicate=function(e){var o=t.clipboardXml_,i=t.clipboardSource_;t.copy_(e),e.workspace.paste(t.clipboardXml_),t.clipboardXml_=o,t.clipboardSource_=i},t.onContextMenu_=function(e){t.utils.isTargetInput(e)||e.preventDefault()},t.hideChaff=function(e){t.Tooltip.hide(),t.WidgetDiv.hide(),t.DropDownDiv.hideWithoutAnimation(),e||((e=t.getMainWorkspace()).trashcan&&e.trashcan.flyout&&e.trashcan.flyout.hide(),(e=e.getToolbox())&&e.getFlyout()&&e.getFlyout().autoClose&&e.clearSelection())},t.getMainWorkspace=function(){return t.mainWorkspace},t.alert=function(t,e){alert(t),e&&e()},t.confirm=function(t,e){e(confirm(t))},t.prompt=function(t,e,o){o(prompt(t,e))},t.jsonInitFactory_=function(t){return function(){this.jsonInit(t)}},t.defineBlocksWithJsonArray=function(e){for(var o=0;o90-e||t>-90-e&&t<-90+e},t.HorizontalFlyout.prototype.getClientRect=function(){if(!this.svgGroup_)return null;var e=this.svgGroup_.getBoundingClientRect(),o=e.top;return this.toolboxPosition_==t.TOOLBOX_AT_TOP?new t.utils.Rect(-1e9,o+e.height,-1e9,1e9):new t.utils.Rect(o,1e9,-1e9,1e9)},t.HorizontalFlyout.prototype.reflowInternal_=function(){this.workspace_.scale=this.targetWorkspace_.scale;for(var e,o=0,i=this.workspace_.getTopBlocks(!1),n=0;e=i[n];n++)o=Math.max(o,e.getHeightWidth().height);if(o+=1.5*this.MARGIN,o*=this.workspace_.scale,o+=t.Scrollbar.scrollbarThickness,this.height_!=o){for(n=0;e=i[n];n++)e.flyoutRect_&&this.moveRectToBlock_(e.flyoutRect_,e);this.height_=o,this.position()}},t.VerticalFlyout=function(e){e.getMetrics=this.getMetrics_.bind(this),e.setMetrics=this.setMetrics_.bind(this),t.VerticalFlyout.superClass_.constructor.call(this,e),this.horizontalLayout_=!1},t.utils.object.inherits(t.VerticalFlyout,t.Flyout),t.VerticalFlyout.prototype.getMetrics_=function(){if(!this.isVisible())return null;try{var t=this.workspace_.getCanvas().getBBox()}catch(e){t={height:0,y:0,width:0,x:0}}var e=this.SCROLLBAR_PADDING,o=this.height_-2*this.SCROLLBAR_PADDING,i=this.width_;return this.RTL||(i-=this.SCROLLBAR_PADDING),{viewHeight:o,viewWidth:i,contentHeight:t.height*this.workspace_.scale+2*this.MARGIN,contentWidth:t.width*this.workspace_.scale+2*this.MARGIN,viewTop:-this.workspace_.scrollY+t.y,viewLeft:-this.workspace_.scrollX,contentTop:t.y,contentLeft:t.x,absoluteTop:e,absoluteLeft:0}},t.VerticalFlyout.prototype.setMetrics_=function(t){var e=this.getMetrics_();e&&("number"==typeof t.y&&(this.workspace_.scrollY=-e.contentHeight*t.y),this.workspace_.translate(this.workspace_.scrollX+e.absoluteLeft,this.workspace_.scrollY+e.absoluteTop))},t.VerticalFlyout.prototype.position=function(){if(this.isVisible()){var e=this.targetWorkspace_.getMetrics();e&&(this.height_=e.viewHeight,this.setBackgroundPath_(this.width_-this.CORNER_RADIUS,e.viewHeight-2*this.CORNER_RADIUS),this.positionAt_(this.width_,this.height_,this.targetWorkspace_.toolboxPosition==this.toolboxPosition_?e.toolboxWidth?this.toolboxPosition_==t.TOOLBOX_AT_LEFT?e.toolboxWidth:e.viewWidth-this.width_:this.toolboxPosition_==t.TOOLBOX_AT_LEFT?0:e.viewWidth:this.toolboxPosition_==t.TOOLBOX_AT_LEFT?0:e.viewWidth+e.absoluteLeft-this.width_,0))}},t.VerticalFlyout.prototype.setBackgroundPath_=function(e,o){var i=this.toolboxPosition_==t.TOOLBOX_AT_RIGHT,n=e+this.CORNER_RADIUS;(n=["M "+(i?n:0)+",0"]).push("h",i?-e:e),n.push("a",this.CORNER_RADIUS,this.CORNER_RADIUS,0,0,i?0:1,i?-this.CORNER_RADIUS:this.CORNER_RADIUS,this.CORNER_RADIUS),n.push("v",Math.max(0,o)),n.push("a",this.CORNER_RADIUS,this.CORNER_RADIUS,0,0,i?0:1,i?this.CORNER_RADIUS:-this.CORNER_RADIUS,this.CORNER_RADIUS),n.push("h",i?e:-e),n.push("z"),this.svgBackground_.setAttribute("d",n.join(" "))},t.VerticalFlyout.prototype.scrollToStart=function(){this.scrollbar_.set(0)},t.VerticalFlyout.prototype.wheel_=function(e){var o=t.utils.getScrollDeltaPixels(e);if(o.y){var i=this.getMetrics_();o=i.viewTop-i.contentTop+o.y,o=Math.min(o,i.contentHeight-i.viewHeight),o=Math.max(o,0),this.scrollbar_.set(o),t.WidgetDiv.hide()}e.preventDefault(),e.stopPropagation()},t.VerticalFlyout.prototype.layout_=function(t,e){this.workspace_.scale=this.targetWorkspace_.scale;for(var o,i=this.MARGIN,n=this.RTL?i:i+this.tabWidth_,s=0;o=t[s];s++)if("block"==o.type){for(var r,a=(o=o.block).getDescendants(!1),l=0;r=a[l];l++)r.isInFlyout=!0;o.render(),a=o.getSvgRoot(),l=o.getHeightWidth(),r=o.outputConnection?n-this.tabWidth_:n,o.moveBy(r,i),r=this.createRect_(o,this.RTL?r-l.width:r,i,l,s),this.addBlockListeners_(a,o,r),i+=l.height+e[s]}else"button"==o.type&&(this.initFlyoutButton_(o.button,n,i),i+=o.button.height+e[s])},t.VerticalFlyout.prototype.isDragTowardWorkspace=function(t){t=Math.atan2(t.y,t.x)/Math.PI*180;var e=this.dragAngleRange_;return t-e||t<-180+e||t>180-e},t.VerticalFlyout.prototype.getClientRect=function(){if(!this.svgGroup_)return null;var e=this.svgGroup_.getBoundingClientRect(),o=e.left;return this.toolboxPosition_==t.TOOLBOX_AT_LEFT?new t.utils.Rect(-1e9,1e9,-1e9,o+e.width):new t.utils.Rect(-1e9,1e9,o,1e9)},t.VerticalFlyout.prototype.reflowInternal_=function(){this.workspace_.scale=this.targetWorkspace_.scale;for(var e,o=0,i=this.workspace_.getTopBlocks(!1),n=0;e=i[n];n++){var s=e.getHeightWidth().width;e.outputConnection&&(s-=this.tabWidth_),o=Math.max(o,s)}for(n=0;e=this.buttons_[n];n++)o=Math.max(o,e.width);if(o+=1.5*this.MARGIN+this.tabWidth_,o*=this.workspace_.scale,o+=t.Scrollbar.scrollbarThickness,this.width_!=o){for(n=0;e=i[n];n++){if(this.RTL){s=e.getRelativeToSurfaceXY().x;var r=o/this.workspace_.scale-this.MARGIN;e.outputConnection||(r-=this.tabWidth_),e.moveBy(r-s,0)}e.flyoutRect_&&this.moveRectToBlock_(e.flyoutRect_,e)}if(this.RTL)for(n=0;e=this.buttons_[n];n++)i=e.getPosition().y,e.moveTo(o/this.workspace_.scale-e.width-this.MARGIN-this.tabWidth_,i);this.width_=o,this.position()}},t.FlyoutButton=function(e,o,i,n){this.workspace_=e,this.targetWorkspace_=o,this.text_=i.getAttribute("text"),this.position_=new t.utils.Coordinate(0,0),this.isLabel_=n,this.callbackKey_=i.getAttribute("callbackKey")||i.getAttribute("callbackkey"),this.cssClass_=i.getAttribute("web-class")||null,this.onMouseUpWrapper_=null},t.FlyoutButton.MARGIN_X=5,t.FlyoutButton.MARGIN_Y=2,t.FlyoutButton.prototype.width=0,t.FlyoutButton.prototype.height=0,t.FlyoutButton.prototype.createDom=function(){var e=this.isLabel_?"blocklyFlyoutLabel":"blocklyFlyoutButton";if(this.cssClass_&&(e+=" "+this.cssClass_),this.svgGroup_=t.utils.dom.createSvgElement("g",{class:e},this.workspace_.getCanvas()),!this.isLabel_)var o=t.utils.dom.createSvgElement("rect",{class:"blocklyFlyoutButtonShadow",rx:4,ry:4,x:1,y:1},this.svgGroup_);e=t.utils.dom.createSvgElement("rect",{class:this.isLabel_?"blocklyFlyoutLabelBackground":"blocklyFlyoutButtonBackground",rx:4,ry:4},this.svgGroup_);var i=t.utils.dom.createSvgElement("text",{class:this.isLabel_?"blocklyFlyoutLabelText":"blocklyText",x:0,y:0,"text-anchor":"middle"},this.svgGroup_),n=t.utils.replaceMessageReferences(this.text_);this.workspace_.RTL&&(n+="‏"),i.textContent=n,this.isLabel_&&(this.svgText_=i,this.workspace_.getThemeManager().subscribe(this.svgText_,"flyoutForegroundColour","fill"));var s=t.utils.style.getComputedStyle(i,"fontSize"),r=t.utils.style.getComputedStyle(i,"fontWeight"),a=t.utils.style.getComputedStyle(i,"fontFamily");return this.width=t.utils.dom.getFastTextWidthWithSizeString(i,s,r,a),n=t.utils.dom.measureFontMetrics(n,s,r,a),this.height=n.height,this.isLabel_||(this.width+=2*t.FlyoutButton.MARGIN_X,this.height+=2*t.FlyoutButton.MARGIN_Y,o.setAttribute("width",this.width),o.setAttribute("height",this.height)),e.setAttribute("width",this.width),e.setAttribute("height",this.height),i.setAttribute("x",this.width/2),i.setAttribute("y",this.height/2-n.height/2+n.baseline),this.updateTransform_(),this.onMouseUpWrapper_=t.bindEventWithChecks_(this.svgGroup_,"mouseup",this,this.onMouseUp_),this.svgGroup_},t.FlyoutButton.prototype.show=function(){this.updateTransform_(),this.svgGroup_.setAttribute("display","block")},t.FlyoutButton.prototype.updateTransform_=function(){this.svgGroup_.setAttribute("transform","translate("+this.position_.x+","+this.position_.y+")")},t.FlyoutButton.prototype.moveTo=function(t,e){this.position_.x=t,this.position_.y=e,this.updateTransform_()},t.FlyoutButton.prototype.getPosition=function(){return this.position_},t.FlyoutButton.prototype.getTargetWorkspace=function(){return this.targetWorkspace_},t.FlyoutButton.prototype.dispose=function(){this.onMouseUpWrapper_&&t.unbindEvent_(this.onMouseUpWrapper_),this.svgGroup_&&t.utils.dom.removeNode(this.svgGroup_),this.svgText_&&this.workspace_.getThemeManager().unsubscribe(this.svgText_)},t.FlyoutButton.prototype.onMouseUp_=function(t){(t=this.targetWorkspace_.getGesture(t))&&t.cancel(),this.isLabel_&&this.callbackKey_?console.warn("Labels should not have callbacks. Label text: "+this.text_):this.isLabel_||this.callbackKey_&&this.targetWorkspace_.getButtonCallback(this.callbackKey_)?this.isLabel_||this.targetWorkspace_.getButtonCallback(this.callbackKey_)(this):console.warn("Buttons should have callbacks. Button text: "+this.text_)},t.Css.register(".blocklyFlyoutButton {,fill: #888;,cursor: default;,},.blocklyFlyoutButtonShadow {,fill: #666;,},.blocklyFlyoutButton:hover {,fill: #aaa;,},.blocklyFlyoutLabel {,cursor: default;,},.blocklyFlyoutLabelBackground {,opacity: 0;,}".split(",")),t.Generator=function(t){this.name_=t,this.FUNCTION_NAME_PLACEHOLDER_REGEXP_=new RegExp(this.FUNCTION_NAME_PLACEHOLDER_,"g")},t.Generator.NAME_TYPE="generated_function",t.Generator.prototype.INFINITE_LOOP_TRAP=null,t.Generator.prototype.STATEMENT_PREFIX=null,t.Generator.prototype.STATEMENT_SUFFIX=null,t.Generator.prototype.INDENT=" ",t.Generator.prototype.COMMENT_WRAP=60,t.Generator.prototype.ORDER_OVERRIDES=[],t.Generator.prototype.workspaceToCode=function(e){e||(console.warn("No workspace specified in workspaceToCode call. Guessing."),e=t.getMainWorkspace());var o=[];this.init(e),e=e.getTopBlocks(!0);for(var i,n=0;i=e[n];n++){var s=this.blockToCode(i);Array.isArray(s)&&(s=s[0]),s&&(i.outputConnection&&(s=this.scrubNakedValue(s),this.STATEMENT_PREFIX&&!i.suppressPrefixSuffix&&(s=this.injectId(this.STATEMENT_PREFIX,i)+s),this.STATEMENT_SUFFIX&&!i.suppressPrefixSuffix&&(s+=this.injectId(this.STATEMENT_SUFFIX,i))),o.push(s))}return o=o.join("\n"),(o=(o=(o=this.finish(o)).replace(/^\s+\n/,"")).replace(/\n\s+$/,"\n")).replace(/[ \t]+\n/g,"\n")},t.Generator.prototype.prefixLines=function(t,e){return e+t.replace(/(?!\n$)\n/g,"\n"+e)},t.Generator.prototype.allNestedComments=function(t){var e=[];t=t.getDescendants(!0);for(var o=0;ot&&(t=(t=this.getParent())?t.getDepth()+1:0,this.setDepth_(t)),t},t.tree.BaseNode.prototype.setDepth_=function(t){if(t!=this.depth_){this.depth_=t;var e=this.getRowElement();if(e){var o=this.getPixelIndent_()+"px";this.rightToLeft_?e.style.paddingRight=o:e.style.paddingLeft=o}this.forEachChild((function(e){e.setDepth_(t+1)}))}},t.tree.BaseNode.prototype.contains=function(t){for(;t;){if(t==this)return!0;t=t.getParent()}return!1},t.tree.BaseNode.prototype.getChildren=function(){var t=[];return this.forEachChild((function(e){t.push(e)})),t},t.tree.BaseNode.prototype.getPreviousSibling=function(){return this.previousSibling_},t.tree.BaseNode.prototype.getNextSibling=function(){return this.nextSibling_},t.tree.BaseNode.prototype.isLastSibling=function(){return!this.nextSibling_},t.tree.BaseNode.prototype.isSelected=function(){return this.selected_},t.tree.BaseNode.prototype.select=function(){var t=this.getTree();t&&t.setSelectedItem(this)},t.tree.BaseNode.prototype.setSelected=function(e){if(this.selected_!=e){this.selected_=e,this.updateRow();var o=this.getElement();o&&(t.utils.aria.setState(o,t.utils.aria.State.SELECTED,e),e&&(e=this.getTree().getElement(),t.utils.aria.setState(e,t.utils.aria.State.ACTIVEDESCENDANT,this.getId())))}},t.tree.BaseNode.prototype.setExpanded=function(e){var o,i=e!=this.expanded_;this.expanded_=e;var n=this.getTree(),s=this.getElement();this.hasChildren()?(!e&&n&&this.contains(n.getSelectedItem())&&this.select(),s&&((o=this.getChildrenElement())&&(t.utils.style.setElementShown(o,e),t.utils.aria.setState(s,t.utils.aria.State.EXPANDED,e),e&&this.isInDocument()&&!o.hasChildNodes()&&(this.forEachChild((function(t){o.appendChild(t.toDom())})),this.forEachChild((function(t){t.enterDocument()})))),this.updateExpandIcon())):(o=this.getChildrenElement())&&t.utils.style.setElementShown(o,!1),s&&this.updateIcon_(),i&&(e?this.doNodeExpanded():this.doNodeCollapsed())},t.tree.BaseNode.prototype.doNodeExpanded=function(){},t.tree.BaseNode.prototype.doNodeCollapsed=function(){},t.tree.BaseNode.prototype.toggle=function(){this.setExpanded(!this.expanded_)},t.tree.BaseNode.prototype.toDom=function(){var t=this.expanded_&&this.hasChildren(),e=document.createElement("div");return e.style.backgroundPosition=this.getBackgroundPosition(),t||(e.style.display="none"),t&&this.forEachChild((function(t){e.appendChild(t.toDom())})),(t=document.createElement("div")).id=this.getId(),t.appendChild(this.getRowDom()),t.appendChild(e),t},t.tree.BaseNode.prototype.getPixelIndent_=function(){return Math.max(0,(this.getDepth()-1)*this.config_.indentWidth)},t.tree.BaseNode.prototype.getRowDom=function(){var t=document.createElement("div");return t.className=this.getRowClassName(),t.style["padding-"+(this.rightToLeft_?"right":"left")]=this.getPixelIndent_()+"px",t.appendChild(this.getIconDom()),t.appendChild(this.getLabelDom()),t},t.tree.BaseNode.prototype.getRowClassName=function(){var t="";return this.isSelected()&&(t=" "+(this.config_.cssSelectedRow||"")),this.config_.cssTreeRow+t},t.tree.BaseNode.prototype.getLabelDom=function(){var t=document.createElement("span");return t.className=this.config_.cssItemLabel||"",t.textContent=this.content,t},t.tree.BaseNode.prototype.getIconDom=function(){var t=document.createElement("span");return t.style.display="inline-block",t.className=this.getCalculatedIconClass(),t},t.tree.BaseNode.prototype.getCalculatedIconClass=function(){throw Error("unimplemented abstract method")},t.tree.BaseNode.prototype.getBackgroundPosition=function(){return(this.isLastSibling()?"-100":(this.getDepth()-1)*this.config_.indentWidth)+"px 0"},t.tree.BaseNode.prototype.getElement=function(){var e=t.tree.BaseNode.superClass_.getElement.call(this);return e||(e=document.getElementById(this.getId()),this.setElementInternal(e)),e},t.tree.BaseNode.prototype.getRowElement=function(){var t=this.getElement();return t?t.firstChild:null},t.tree.BaseNode.prototype.getIconElement=function(){var t=this.getRowElement();return t?t.firstChild:null},t.tree.BaseNode.prototype.getLabelElement=function(){var t=this.getRowElement();return t&&t.lastChild?t.lastChild.previousSibling:null},t.tree.BaseNode.prototype.getChildrenElement=function(){var t=this.getElement();return t?t.lastChild:null},t.tree.BaseNode.prototype.updateRow=function(){var t=this.getRowElement();t&&(t.className=this.getRowClassName())},t.tree.BaseNode.prototype.updateExpandIcon=function(){var t=this.getChildrenElement();t&&(t.style.backgroundPosition=this.getBackgroundPosition())},t.tree.BaseNode.prototype.updateIcon_=function(){this.getIconElement().className=this.getCalculatedIconClass()},t.tree.BaseNode.prototype.onMouseDown=function(t){"expand"==t.target.getAttribute("type")&&this.hasChildren()?this.isUserCollapsible_&&this.toggle():(this.select(),this.updateRow())},t.tree.BaseNode.prototype.onClick_=function(t){t.preventDefault()},t.tree.BaseNode.prototype.onKeyDown=function(e){var o=!0;switch(e.keyCode){case t.utils.KeyCodes.RIGHT:if(e.altKey)break;o=this.selectChild();break;case t.utils.KeyCodes.LEFT:if(e.altKey)break;o=this.selectParent();break;case t.utils.KeyCodes.DOWN:o=this.selectNext();break;case t.utils.KeyCodes.UP:o=this.selectPrevious();break;default:o=!1}return o&&e.preventDefault(),o},t.tree.BaseNode.prototype.selectNext=function(){var t=this.getNextShownNode();return t&&t.select(),!0},t.tree.BaseNode.prototype.selectPrevious=function(){var t=this.getPreviousShownNode();return t&&t.select(),!0},t.tree.BaseNode.prototype.selectParent=function(){if(this.hasChildren()&&this.expanded_&&this.isUserCollapsible_)this.setExpanded(!1);else{var t=this.getParent(),e=this.getTree();t&&t!=e&&t.select()}return!0},t.tree.BaseNode.prototype.selectChild=function(){return!!this.hasChildren()&&(this.expanded_?this.getChildAt(0).select():this.setExpanded(!0),!0)},t.tree.BaseNode.prototype.getLastShownDescendant=function(){return this.expanded_&&this.hasChildren()?this.getChildAt(this.getChildCount()-1).getLastShownDescendant():this},t.tree.BaseNode.prototype.getNextShownNode=function(){if(this.hasChildren()&&this.expanded_)return this.getChildAt(0);for(var t,e=this;e!=this.getTree();){if(null!=(t=e.getNextSibling()))return t;e=e.getParent()}return null},t.tree.BaseNode.prototype.getPreviousShownNode=function(){var t=this.getPreviousSibling();if(null!=t)return t.getLastShownDescendant();t=this.getParent();var e=this.getTree();return t==e||this==e?null:t},t.tree.BaseNode.prototype.setTreeInternal=function(t){this.tree!=t&&(this.tree=t,this.forEachChild((function(e){e.setTreeInternal(t)})))},t.tree.TreeNode=function(e,o,i){this.toolbox_=e,t.tree.BaseNode.call(this,o,i)},t.utils.object.inherits(t.tree.TreeNode,t.tree.BaseNode),t.tree.TreeNode.prototype.getTree=function(){if(this.tree)return this.tree;var t=this.getParent();return t&&(t=t.getTree())?(this.setTreeInternal(t),t):null},t.tree.TreeNode.prototype.getCalculatedIconClass=function(){var t=this.expanded_;if(t&&this.expandedIconClass)return this.expandedIconClass;var e=this.iconClass;if(!t&&e)return e;if(e=this.config_,this.hasChildren()){if(t&&e.cssExpandedFolderIcon)return e.cssTreeIcon+" "+e.cssExpandedFolderIcon;if(!t&&e.cssCollapsedFolderIcon)return e.cssTreeIcon+" "+e.cssCollapsedFolderIcon}else if(e.cssFileIcon)return e.cssTreeIcon+" "+e.cssFileIcon;return""},t.tree.TreeNode.prototype.onClick_=function(t){this.hasChildren()&&this.isUserCollapsible_?(this.toggle(),this.select()):this.isSelected()?this.getTree().setSelectedItem(null):this.select(),this.updateRow()},t.tree.TreeNode.prototype.onMouseDown=function(t){},t.tree.TreeNode.prototype.onKeyDown=function(e){if(this.tree.toolbox_.horizontalLayout_){var o={},i=t.utils.KeyCodes.DOWN,n=t.utils.KeyCodes.UP;o[t.utils.KeyCodes.RIGHT]=this.rightToLeft_?n:i,o[t.utils.KeyCodes.LEFT]=this.rightToLeft_?i:n,o[t.utils.KeyCodes.UP]=t.utils.KeyCodes.LEFT,o[t.utils.KeyCodes.DOWN]=t.utils.KeyCodes.RIGHT,Object.defineProperties(e,{keyCode:{value:o[e.keyCode]||e.keyCode}})}return t.tree.TreeNode.superClass_.onKeyDown.call(this,e)},t.tree.TreeNode.prototype.onSizeChanged=function(t){this.onSizeChanged_=t},t.tree.TreeNode.prototype.resizeToolbox_=function(){this.onSizeChanged_&&this.onSizeChanged_.call(this.toolbox_)},t.tree.TreeNode.prototype.doNodeExpanded=t.tree.TreeNode.prototype.resizeToolbox_,t.tree.TreeNode.prototype.doNodeCollapsed=t.tree.TreeNode.prototype.resizeToolbox_,t.tree.TreeControl=function(e,o){this.toolbox_=e,this.onKeydownWrapper_=this.onClickWrapper_=this.onBlurWrapper_=this.onFocusWrapper_=null,t.tree.BaseNode.call(this,"",o),this.selected_=this.expanded_=!0,this.selectedItem_=this},t.utils.object.inherits(t.tree.TreeControl,t.tree.BaseNode),t.tree.TreeControl.prototype.getTree=function(){return this},t.tree.TreeControl.prototype.getToolbox=function(){return this.toolbox_},t.tree.TreeControl.prototype.getDepth=function(){return 0},t.tree.TreeControl.prototype.handleFocus_=function(e){this.focused_=!0,e=this.getElement(),t.utils.dom.addClass(e,"focused"),this.selectedItem_&&this.selectedItem_.select()},t.tree.TreeControl.prototype.handleBlur_=function(e){this.focused_=!1,e=this.getElement(),t.utils.dom.removeClass(e,"focused")},t.tree.TreeControl.prototype.hasFocus=function(){return this.focused_},t.tree.TreeControl.prototype.setExpanded=function(t){this.expanded_=t},t.tree.TreeControl.prototype.getIconElement=function(){var t=this.getRowElement();return t?t.firstChild:null},t.tree.TreeControl.prototype.updateExpandIcon=function(){},t.tree.TreeControl.prototype.getRowClassName=function(){return t.tree.TreeControl.superClass_.getRowClassName.call(this)+" "+this.config_.cssHideRoot},t.tree.TreeControl.prototype.getCalculatedIconClass=function(){var t=this.expanded_;if(t&&this.expandedIconClass)return this.expandedIconClass;var e=this.iconClass;return!t&&e?e:t&&this.config_.cssExpandedRootIcon?this.config_.cssTreeIcon+" "+this.config_.cssExpandedRootIcon:""},t.tree.TreeControl.prototype.setSelectedItem=function(t){if(t!=this.selectedItem_&&(!this.onBeforeSelected_||this.onBeforeSelected_.call(this.toolbox_,t))){var e=this.getSelectedItem();this.selectedItem_&&this.selectedItem_.setSelected(!1),(this.selectedItem_=t)&&t.setSelected(!0),this.onAfterSelected_&&this.onAfterSelected_.call(this.toolbox_,e,t)}},t.tree.TreeControl.prototype.onBeforeSelected=function(t){this.onBeforeSelected_=t},t.tree.TreeControl.prototype.onAfterSelected=function(t){this.onAfterSelected_=t},t.tree.TreeControl.prototype.getSelectedItem=function(){return this.selectedItem_},t.tree.TreeControl.prototype.initAccessibility=function(){t.tree.TreeControl.superClass_.initAccessibility.call(this);var e=this.getElement();t.utils.aria.setRole(e,t.utils.aria.Role.TREE),t.utils.aria.setState(e,t.utils.aria.State.LABELLEDBY,this.getLabelElement().id)},t.tree.TreeControl.prototype.enterDocument=function(){t.tree.TreeControl.superClass_.enterDocument.call(this);var e=this.getElement();e.className=this.config_.cssRoot,e.setAttribute("hideFocus","true"),this.attachEvents_(),this.initAccessibility()},t.tree.TreeControl.prototype.exitDocument=function(){t.tree.TreeControl.superClass_.exitDocument.call(this),this.detachEvents_()},t.tree.TreeControl.prototype.attachEvents_=function(){var e=this.getElement();e.tabIndex=0,this.onFocusWrapper_=t.bindEvent_(e,"focus",this,this.handleFocus_),this.onBlurWrapper_=t.bindEvent_(e,"blur",this,this.handleBlur_),this.onClickWrapper_=t.bindEventWithChecks_(e,"click",this,this.handleMouseEvent_),this.onKeydownWrapper_=t.bindEvent_(e,"keydown",this,this.handleKeyEvent_)},t.tree.TreeControl.prototype.detachEvents_=function(){this.onFocusWrapper_&&(t.unbindEvent_(this.onFocusWrapper_),this.onFocusWrapper_=null),this.onBlurWrapper_&&(t.unbindEvent_(this.onBlurWrapper_),this.onBlurWrapper_=null),this.onClickWrapper_&&(t.unbindEvent_(this.onClickWrapper_),this.onClickWrapper_=null),this.onKeydownWrapper_&&(t.unbindEvent_(this.onKeydownWrapper_),this.onKeydownWrapper_=null)},t.tree.TreeControl.prototype.handleMouseEvent_=function(t){var e=this.getNodeFromEvent_(t);if(e)switch(t.type){case"mousedown":e.onMouseDown(t);break;case"click":e.onClick_(t)}},t.tree.TreeControl.prototype.handleKeyEvent_=function(e){var o=!1;return(o=this.selectedItem_&&this.selectedItem_.onKeyDown(e)||o)&&(t.utils.style.scrollIntoContainerView(this.selectedItem_.getElement(),this.getElement().parentNode),e.preventDefault()),o},t.tree.TreeControl.prototype.getNodeFromEvent_=function(e){for(var o=e.target;null!=o;){if(e=t.tree.BaseNode.allNodes[o.id])return e;if(o==this.getElement())break;if(o.getAttribute("role")==t.utils.aria.Role.GROUP)break;o=o.parentNode}return null},t.tree.TreeControl.prototype.createNode=function(e){return new t.tree.TreeNode(this.toolbox_,e||"",this.config_)},t.Toolbox=function(t){this.workspace_=t,this.RTL=t.options.RTL,this.horizontalLayout_=t.options.horizontalLayout,this.toolboxPosition=t.options.toolboxPosition,this.config_={indentWidth:19,cssRoot:"blocklyTreeRoot",cssHideRoot:"blocklyHidden",cssTreeRow:"blocklyTreeRow",cssItemLabel:"blocklyTreeLabel",cssTreeIcon:"blocklyTreeIcon",cssExpandedFolderIcon:"blocklyTreeIconOpen",cssFileIcon:"blocklyTreeIconNone",cssSelectedRow:"blocklyTreeSelected"},this.treeSeparatorConfig_={cssTreeRow:"blocklyTreeSeparator"},this.horizontalLayout_&&(this.config_.cssTreeRow+=t.RTL?" blocklyHorizontalTreeRtl":" blocklyHorizontalTree",this.treeSeparatorConfig_.cssTreeRow="blocklyTreeSeparatorHorizontal "+(t.RTL?"blocklyHorizontalTreeRtl":"blocklyHorizontalTree"),this.config_.cssTreeIcon=""),this.flyout_=null},t.Toolbox.prototype.width=0,t.Toolbox.prototype.height=0,t.Toolbox.prototype.selectedOption_=null,t.Toolbox.prototype.lastCategory_=null,t.Toolbox.prototype.init=function(){var e=this.workspace_,o=this.workspace_.getParentSvg();this.HtmlDiv=document.createElement("div"),this.HtmlDiv.className="blocklyToolboxDiv blocklyNonSelectable",this.HtmlDiv.setAttribute("dir",e.RTL?"RTL":"LTR"),o.parentNode.insertBefore(this.HtmlDiv,o);var i=e.getThemeManager();if(i.subscribe(this.HtmlDiv,"toolboxBackgroundColour","background-color"),i.subscribe(this.HtmlDiv,"toolboxForegroundColour","color"),t.bindEventWithChecks_(this.HtmlDiv,"mousedown",this,(function(e){t.utils.isRightButton(e)||e.target==this.HtmlDiv?t.hideChaff(!1):t.hideChaff(!0),t.Touch.clearTouchIdentifier()}),!1,!0),(i=new t.Options({parentWorkspace:e,rtl:e.RTL,oneBasedIndex:e.options.oneBasedIndex,horizontalLayout:e.horizontalLayout,renderer:e.options.renderer,rendererOverrides:e.options.rendererOverrides})).toolboxPosition=e.options.toolboxPosition,e.horizontalLayout){if(!t.HorizontalFlyout)throw Error("Missing require for Blockly.HorizontalFlyout");this.flyout_=new t.HorizontalFlyout(i)}else{if(!t.VerticalFlyout)throw Error("Missing require for Blockly.VerticalFlyout");this.flyout_=new t.VerticalFlyout(i)}if(!this.flyout_)throw Error("One of Blockly.VerticalFlyout or Blockly.Horizontal must berequired.");t.utils.dom.insertAfter(this.flyout_.createDom("svg"),o),this.flyout_.init(e),this.config_.cleardotPath=e.options.pathToMedia+"1x1.gif",this.config_.cssCollapsedFolderIcon="blocklyTreeIconClosed"+(e.RTL?"Rtl":"Ltr"),this.renderTree(e.options.languageTree)},t.Toolbox.prototype.renderTree=function(e){this.tree_&&(this.tree_.dispose(),this.lastCategory_=null);var o=new t.tree.TreeControl(this,this.config_);this.tree_=o,o.setSelectedItem(null),o.onBeforeSelected(this.handleBeforeTreeSelected_),o.onAfterSelected(this.handleAfterTreeSelected_);var i=null;if(e){if(this.tree_.blocks=[],this.hasColours_=!1,i=this.syncTrees_(e,this.tree_,this.workspace_.options.pathToMedia),this.tree_.blocks.length)throw Error("Toolbox cannot have both blocks and categories in the root level.");this.workspace_.resizeContents()}o.render(this.HtmlDiv),i&&o.setSelectedItem(i),this.addColour_(),this.position(),this.horizontalLayout_&&t.utils.aria.setState(this.tree_.getElement(),t.utils.aria.State.ORIENTATION,"horizontal")},t.Toolbox.prototype.handleBeforeTreeSelected_=function(t){if(t==this.tree_)return!1;if(this.lastCategory_&&(this.lastCategory_.getRowElement().style.backgroundColor=""),t){var e=t.hexColour||"#57e";t.getRowElement().style.backgroundColor=e,this.addColour_(t)}return!0},t.Toolbox.prototype.handleAfterTreeSelected_=function(e,o){o&&o.blocks&&o.blocks.length?(this.flyout_.show(o.blocks),this.lastCategory_!=o&&this.flyout_.scrollToStart(),this.workspace_.keyboardAccessibilityMode&&t.navigation.setState(t.navigation.STATE_TOOLBOX)):(this.flyout_.hide(),!this.workspace_.keyboardAccessibilityMode||o instanceof t.Toolbox.TreeSeparator||t.navigation.setState(t.navigation.STATE_WS)),e!=o&&e!=this&&((e=new t.Events.Ui(null,"category",e&&e.content,o&&o.content)).workspaceId=this.workspace_.id,t.Events.fire(e)),o&&(this.lastCategory_=o)},t.Toolbox.prototype.handleNodeSizeChanged_=function(){t.svgResize(this.workspace_)},t.Toolbox.prototype.onBlocklyAction=function(e){var o=this.tree_.getSelectedItem();if(!o)return!1;switch(e.name){case t.navigation.actionNames.PREVIOUS:return o.selectPrevious();case t.navigation.actionNames.OUT:return o.selectParent();case t.navigation.actionNames.NEXT:return o.selectNext();case t.navigation.actionNames.IN:return o.selectChild();default:return!1}},t.Toolbox.prototype.dispose=function(){this.flyout_.dispose(),this.tree_.dispose(),this.workspace_.getThemeManager().unsubscribe(this.HtmlDiv),t.utils.dom.removeNode(this.HtmlDiv),this.lastCategory_=null},t.Toolbox.prototype.getWidth=function(){return this.width},t.Toolbox.prototype.getHeight=function(){return this.height},t.Toolbox.prototype.getFlyout=function(){return this.flyout_},t.Toolbox.prototype.position=function(){var e=this.HtmlDiv;if(e){var o=t.svgSize(this.workspace_.getParentSvg());this.horizontalLayout_?(e.style.left="0",e.style.height="auto",e.style.width=o.width+"px",this.height=e.offsetHeight,this.toolboxPosition==t.TOOLBOX_AT_TOP?e.style.top="0":e.style.bottom="0"):(this.toolboxPosition==t.TOOLBOX_AT_RIGHT?e.style.right="0":e.style.left="0",e.style.height=o.height+"px",this.width=e.offsetWidth),this.flyout_.position()}},t.Toolbox.prototype.syncTrees_=function(e,o,i){for(var n,s=null,r=null,a=0;n=e.childNodes[a];a++)if(n.tagName)switch(n.tagName.toUpperCase()){case"CATEGORY":r=t.utils.replaceMessageReferences(n.getAttribute("name"));var l=this.tree_.createNode(r);l.onSizeChanged(this.handleNodeSizeChanged_),l.blocks=[],o.add(l);var c=n.getAttribute("custom");c?l.blocks=c:(c=this.syncTrees_(n,l,i))&&(s=c),c=n.getAttribute("categorystyle");var h=n.getAttribute("colour");h&&c?(l.hexColour="",console.warn('Toolbox category "'+r+'" can not have both a style and a colour')):c?this.setColourFromStyle_(c,l,r):this.setColour_(h,l,r),"true"==n.getAttribute("expanded")?(l.blocks.length&&(s=l),l.setExpanded(!0)):l.setExpanded(!1),r=n;break;case"SEP":if(r&&"CATEGORY"==r.tagName.toUpperCase()){o.add(new t.Toolbox.TreeSeparator(this.treeSeparatorConfig_));break}case"BLOCK":case"SHADOW":case"LABEL":case"BUTTON":o.blocks.push(n),r=n}return s},t.Toolbox.prototype.setColour_=function(e,o,i){if(null===(e=t.utils.replaceMessageReferences(e))||""===e)o.hexColour="";else{var n=Number(e);isNaN(n)?(n=t.utils.colour.parse(e))?(o.hexColour=n,this.hasColours_=!0):(o.hexColour="",console.warn('Toolbox category "'+i+'" has unrecognized colour attribute: '+e)):(o.hexColour=t.hueToHex(n),this.hasColours_=!0)}},t.Toolbox.prototype.setColourFromStyle_=function(t,e,o){e.styleName=t;var i=this.workspace_.getTheme();t&&i&&((i=i.categoryStyles[t])&&i.colour?this.setColour_(i.colour,e,o):console.warn('Style "'+t+'" must exist and contain a colour value'))},t.Toolbox.prototype.updateColourFromTheme_=function(t){if(t=t||this.tree_){t=t.getChildren(!1);for(var e,o=0;e=t[o];o++)e.styleName&&(this.setColourFromStyle_(e.styleName,e,""),this.addColour_()),this.updateColourFromTheme_(e)}},t.Toolbox.prototype.updateColourFromTheme=function(){var t=this.tree_;t&&(this.updateColourFromTheme_(t),this.updateSelectedItemColour_(t))},t.Toolbox.prototype.updateSelectedItemColour_=function(t){if(t=t.getSelectedItem()){var e=t.hexColour||"#57e";t.getRowElement().style.backgroundColor=e,this.addColour_(t)}},t.Toolbox.prototype.addColour_=function(t){t=(t||this.tree_).getChildren(!1);for(var e,o=0;e=t[o];o++){var i=e.getRowElement();if(i){var n=this.hasColours_?"8px solid "+(e.hexColour||"#ddd"):"none";this.workspace_.RTL?i.style.borderRight=n:i.style.borderLeft=n}this.addColour_(e)}},t.Toolbox.prototype.clearSelection=function(){this.tree_.setSelectedItem(null)},t.Toolbox.prototype.addStyle=function(e){t.utils.dom.addClass(this.HtmlDiv,e)},t.Toolbox.prototype.removeStyle=function(e){t.utils.dom.removeClass(this.HtmlDiv,e)},t.Toolbox.prototype.getClientRect=function(){if(!this.HtmlDiv)return null;var e=this.HtmlDiv.getBoundingClientRect(),o=e.top,i=o+e.height,n=e.left;return e=n+e.width,this.toolboxPosition==t.TOOLBOX_AT_TOP?new t.utils.Rect(-1e7,i,-1e7,1e7):this.toolboxPosition==t.TOOLBOX_AT_BOTTOM?new t.utils.Rect(o,1e7,-1e7,1e7):this.toolboxPosition==t.TOOLBOX_AT_LEFT?new t.utils.Rect(-1e7,1e7,-1e7,e):new t.utils.Rect(-1e7,1e7,n,1e7)},t.Toolbox.prototype.refreshSelection=function(){var t=this.tree_.getSelectedItem();t&&t.blocks&&this.flyout_.show(t.blocks)},t.Toolbox.prototype.selectFirstCategory=function(){this.tree_.getSelectedItem()||this.tree_.selectChild()},t.Toolbox.TreeSeparator=function(e){t.tree.TreeNode.call(this,null,"",e)},t.utils.object.inherits(t.Toolbox.TreeSeparator,t.tree.TreeNode),t.Css.register([".blocklyToolboxDelete {",'cursor: url("<<>>/handdelete.cur"), auto;',"}",".blocklyToolboxGrab {",'cursor: url("<<>>/handclosed.cur"), auto;',"cursor: grabbing;","cursor: -webkit-grabbing;","}",".blocklyToolboxDiv {","background-color: #ddd;","overflow-x: visible;","overflow-y: auto;","position: absolute;","z-index: 70;","-webkit-tap-highlight-color: transparent;","}",".blocklyTreeRoot {","padding: 4px 0;","}",".blocklyTreeRoot:focus {","outline: none;","}",".blocklyTreeRow {","height: 22px;","line-height: 22px;","margin-bottom: 3px;","padding-right: 8px;","white-space: nowrap;","}",".blocklyHorizontalTree {","float: left;","margin: 1px 5px 8px 0;","}",".blocklyHorizontalTreeRtl {","float: right;","margin: 1px 0 8px 5px;","}",'.blocklyToolboxDiv[dir="RTL"] .blocklyTreeRow {',"margin-left: 8px;","}",".blocklyTreeRow:not(.blocklyTreeSelected):hover {","background-color: rgba(255, 255, 255, 0.2);","}",".blocklyTreeSeparator {","border-bottom: solid #e5e5e5 1px;","height: 0;","margin: 5px 0;","}",".blocklyTreeSeparatorHorizontal {","border-right: solid #e5e5e5 1px;","width: 0;","padding: 5px 0;","margin: 0 5px;","}",".blocklyTreeIcon {","background-image: url(<<>>/sprites.png);","height: 16px;","vertical-align: middle;","width: 16px;","}",".blocklyTreeIconClosedLtr {","background-position: -32px -1px;","}",".blocklyTreeIconClosedRtl {","background-position: 0 -1px;","}",".blocklyTreeIconOpen {","background-position: -16px -1px;","}",".blocklyTreeSelected>.blocklyTreeIconClosedLtr {","background-position: -32px -17px;","}",".blocklyTreeSelected>.blocklyTreeIconClosedRtl {","background-position: 0 -17px;","}",".blocklyTreeSelected>.blocklyTreeIconOpen {","background-position: -16px -17px;","}",".blocklyTreeIconNone,",".blocklyTreeSelected>.blocklyTreeIconNone {","background-position: -48px -1px;","}",".blocklyTreeLabel {","cursor: default;","font-family: sans-serif;","font-size: 16px;","padding: 0 3px;","vertical-align: middle;","}",".blocklyToolboxDelete .blocklyTreeLabel {",'cursor: url("<<>>/handdelete.cur"), auto;',"}",".blocklyTreeSelected .blocklyTreeLabel {","color: #fff;","}"]),t.Trashcan=function(e){if(this.workspace_=e,this.contents_=[],this.flyout=null,!(0>=this.workspace_.options.maxTrashcanContents)){if(e=new t.Options({scrollbars:!0,parentWorkspace:this.workspace_,rtl:this.workspace_.RTL,oneBasedIndex:this.workspace_.options.oneBasedIndex,renderer:this.workspace_.options.renderer,rendererOverrides:this.workspace_.options.rendererOverrides}),this.workspace_.horizontalLayout){if(e.toolboxPosition=this.workspace_.toolboxPosition==t.TOOLBOX_AT_TOP?t.TOOLBOX_AT_BOTTOM:t.TOOLBOX_AT_TOP,!t.HorizontalFlyout)throw Error("Missing require for Blockly.HorizontalFlyout");this.flyout=new t.HorizontalFlyout(e)}else{if(e.toolboxPosition=this.workspace_.toolboxPosition==t.TOOLBOX_AT_RIGHT?t.TOOLBOX_AT_LEFT:t.TOOLBOX_AT_RIGHT,!t.VerticalFlyout)throw Error("Missing require for Blockly.VerticalFlyout");this.flyout=new t.VerticalFlyout(e)}this.workspace_.addChangeListener(this.onDelete_.bind(this))}},t.Trashcan.prototype.WIDTH_=47,t.Trashcan.prototype.BODY_HEIGHT_=44,t.Trashcan.prototype.LID_HEIGHT_=16,t.Trashcan.prototype.MARGIN_BOTTOM_=20,t.Trashcan.prototype.MARGIN_SIDE_=20,t.Trashcan.prototype.MARGIN_HOTSPOT_=10,t.Trashcan.prototype.SPRITE_LEFT_=0,t.Trashcan.prototype.SPRITE_TOP_=32,t.Trashcan.prototype.HAS_BLOCKS_LID_ANGLE_=.1,t.Trashcan.ANIMATION_LENGTH_=80,t.Trashcan.ANIMATION_FRAMES_=4,t.Trashcan.OPACITY_MIN_=.4,t.Trashcan.OPACITY_MAX_=.8,t.Trashcan.MAX_LID_ANGLE_=45,t.Trashcan.prototype.isOpen=!1,t.Trashcan.prototype.minOpenness_=0,t.Trashcan.prototype.svgGroup_=null,t.Trashcan.prototype.svgLid_=null,t.Trashcan.prototype.lidTask_=0,t.Trashcan.prototype.lidOpen_=0,t.Trashcan.prototype.left_=0,t.Trashcan.prototype.top_=0,t.Trashcan.prototype.createDom=function(){this.svgGroup_=t.utils.dom.createSvgElement("g",{class:"blocklyTrash"},null);var e=String(Math.random()).substring(2),o=t.utils.dom.createSvgElement("clipPath",{id:"blocklyTrashBodyClipPath"+e},this.svgGroup_);t.utils.dom.createSvgElement("rect",{width:this.WIDTH_,height:this.BODY_HEIGHT_,y:this.LID_HEIGHT_},o);var i=t.utils.dom.createSvgElement("image",{width:t.SPRITE.width,x:-this.SPRITE_LEFT_,height:t.SPRITE.height,y:-this.SPRITE_TOP_,"clip-path":"url(#blocklyTrashBodyClipPath"+e+")"},this.svgGroup_);return i.setAttributeNS(t.utils.dom.XLINK_NS,"xlink:href",this.workspace_.options.pathToMedia+t.SPRITE.url),o=t.utils.dom.createSvgElement("clipPath",{id:"blocklyTrashLidClipPath"+e},this.svgGroup_),t.utils.dom.createSvgElement("rect",{width:this.WIDTH_,height:this.LID_HEIGHT_},o),this.svgLid_=t.utils.dom.createSvgElement("image",{width:t.SPRITE.width,x:-this.SPRITE_LEFT_,height:t.SPRITE.height,y:-this.SPRITE_TOP_,"clip-path":"url(#blocklyTrashLidClipPath"+e+")"},this.svgGroup_),this.svgLid_.setAttributeNS(t.utils.dom.XLINK_NS,"xlink:href",this.workspace_.options.pathToMedia+t.SPRITE.url),t.bindEventWithChecks_(this.svgGroup_,"mouseup",this,this.click),t.bindEvent_(i,"mouseover",this,this.mouseOver_),t.bindEvent_(i,"mouseout",this,this.mouseOut_),this.animateLid_(),this.svgGroup_},t.Trashcan.prototype.init=function(e){return 0this.minOpenness_&&1>this.lidOpen_&&(this.lidTask_=setTimeout(this.animateLid_.bind(this),t.Trashcan.ANIMATION_LENGTH_/e))},t.Trashcan.prototype.setLidAngle_=function(e){var o=this.workspace_.toolboxPosition==t.TOOLBOX_AT_RIGHT||this.workspace_.horizontalLayout&&this.workspace_.RTL;this.svgLid_.setAttribute("transform","rotate("+(o?-e:e)+","+(o?4:this.WIDTH_-4)+","+(this.LID_HEIGHT_-2)+")")},t.Trashcan.prototype.setMinOpenness_=function(e){this.minOpenness_=e,this.isOpen||this.setLidAngle_(e*t.Trashcan.MAX_LID_ANGLE_)},t.Trashcan.prototype.close=function(){this.setOpen(!1)},t.Trashcan.prototype.click=function(){if(this.contents_.length){for(var e,o=[],i=0;e=this.contents_[i];i++)o[i]=t.Xml.textToDom(e);this.flyout.show(o)}},t.Trashcan.prototype.mouseOver_=function(){this.contents_.length&&this.setOpen(!0)},t.Trashcan.prototype.mouseOut_=function(){this.setOpen(!1)},t.Trashcan.prototype.onDelete_=function(e){if(!(0>=this.workspace_.options.maxTrashcanContents)&&e.type==t.Events.BLOCK_DELETE&&"shadow"!=e.oldXml.tagName.toLowerCase()&&(e=this.cleanBlockXML_(e.oldXml),-1==this.contents_.indexOf(e))){for(this.contents_.unshift(e);this.contents_.length>this.workspace_.options.maxTrashcanContents;)this.contents_.pop();this.setMinOpenness_(this.HAS_BLOCKS_LID_ANGLE_)}},t.Trashcan.prototype.cleanBlockXML_=function(e){for(var o=e=e.cloneNode(!0);o;){o.removeAttribute&&(o.removeAttribute("x"),o.removeAttribute("y"),o.removeAttribute("id"),o.removeAttribute("disabled"),"comment"==o.nodeName&&(o.removeAttribute("h"),o.removeAttribute("w"),o.removeAttribute("pinned")));var i=o.firstChild||o.nextSibling;if(!i)for(i=o.parentNode;i;){if(i.nextSibling){i=i.nextSibling;break}i=i.parentNode}o=i}return t.Xml.domToText(e)},t.VariablesDynamic={},t.VariablesDynamic.onCreateVariableButtonClick_String=function(e){t.Variables.createVariableButtonHandler(e.getTargetWorkspace(),void 0,"String")},t.VariablesDynamic.onCreateVariableButtonClick_Number=function(e){t.Variables.createVariableButtonHandler(e.getTargetWorkspace(),void 0,"Number")},t.VariablesDynamic.onCreateVariableButtonClick_Colour=function(e){t.Variables.createVariableButtonHandler(e.getTargetWorkspace(),void 0,"Colour")},t.VariablesDynamic.flyoutCategory=function(e){var o=[],i=document.createElement("button");return i.setAttribute("text",t.Msg.NEW_STRING_VARIABLE),i.setAttribute("callbackKey","CREATE_VARIABLE_STRING"),o.push(i),(i=document.createElement("button")).setAttribute("text",t.Msg.NEW_NUMBER_VARIABLE),i.setAttribute("callbackKey","CREATE_VARIABLE_NUMBER"),o.push(i),(i=document.createElement("button")).setAttribute("text",t.Msg.NEW_COLOUR_VARIABLE),i.setAttribute("callbackKey","CREATE_VARIABLE_COLOUR"),o.push(i),e.registerButtonCallback("CREATE_VARIABLE_STRING",t.VariablesDynamic.onCreateVariableButtonClick_String),e.registerButtonCallback("CREATE_VARIABLE_NUMBER",t.VariablesDynamic.onCreateVariableButtonClick_Number),e.registerButtonCallback("CREATE_VARIABLE_COLOUR",t.VariablesDynamic.onCreateVariableButtonClick_Colour),e=t.VariablesDynamic.flyoutCategoryBlocks(e),o.concat(e)},t.VariablesDynamic.flyoutCategoryBlocks=function(e){var o=[];if(0<(e=e.getAllVariables()).length){if(t.Blocks.variables_set_dynamic){var i=e[e.length-1],n=t.utils.xml.createElement("block");n.setAttribute("type","variables_set_dynamic"),n.setAttribute("gap",24),n.appendChild(t.Variables.generateVariableFieldDom(i)),o.push(n)}if(t.Blocks.variables_get_dynamic){e.sort(t.VariableModel.compareByName),i=0;for(var s;s=e[i];i++)(n=t.utils.xml.createElement("block")).setAttribute("type","variables_get_dynamic"),n.setAttribute("gap",8),n.appendChild(t.Variables.generateVariableFieldDom(s)),o.push(n)}}return o},t.ZoomControls=function(t){this.workspace_=t},t.ZoomControls.prototype.WIDTH_=32,t.ZoomControls.prototype.HEIGHT_=110,t.ZoomControls.prototype.MARGIN_BOTTOM_=20,t.ZoomControls.prototype.MARGIN_SIDE_=20,t.ZoomControls.prototype.svgGroup_=null,t.ZoomControls.prototype.left_=0,t.ZoomControls.prototype.top_=0,t.ZoomControls.prototype.createDom=function(){this.svgGroup_=t.utils.dom.createSvgElement("g",{},null);var e=String(Math.random()).substring(2);return this.createZoomOutSvg_(e),this.createZoomInSvg_(e),this.workspace_.isMovable()&&this.createZoomResetSvg_(e),this.svgGroup_},t.ZoomControls.prototype.init=function(t){return this.verticalSpacing_=this.MARGIN_BOTTOM_+t,this.verticalSpacing_+this.HEIGHT_},t.ZoomControls.prototype.dispose=function(){this.svgGroup_&&t.utils.dom.removeNode(this.svgGroup_)},t.ZoomControls.prototype.position=function(){if(this.verticalSpacing_){var e=this.workspace_.getMetrics();e&&(this.left_=e.toolboxPosition==t.TOOLBOX_AT_LEFT||this.workspace_.horizontalLayout&&!this.workspace_.RTL?e.viewWidth+e.absoluteLeft-this.WIDTH_-this.MARGIN_SIDE_-t.Scrollbar.scrollbarThickness:this.MARGIN_SIDE_+t.Scrollbar.scrollbarThickness,e.toolboxPosition==t.TOOLBOX_AT_BOTTOM?(this.top_=this.verticalSpacing_,this.zoomInGroup_.setAttribute("transform","translate(0, 34)"),this.zoomResetGroup_&&this.zoomResetGroup_.setAttribute("transform","translate(0, 77)")):(this.top_=e.viewHeight+e.absoluteTop-this.HEIGHT_-this.verticalSpacing_,this.zoomInGroup_.setAttribute("transform","translate(0, 43)"),this.zoomOutGroup_.setAttribute("transform","translate(0, 77)")),this.svgGroup_.setAttribute("transform","translate("+this.left_+","+this.top_+")"))}},t.ZoomControls.prototype.createZoomOutSvg_=function(e){var o=this.workspace_;this.zoomOutGroup_=t.utils.dom.createSvgElement("g",{class:"blocklyZoom"},this.svgGroup_);var i=t.utils.dom.createSvgElement("clipPath",{id:"blocklyZoomoutClipPath"+e},this.zoomOutGroup_);t.utils.dom.createSvgElement("rect",{width:32,height:32},i),(e=t.utils.dom.createSvgElement("image",{width:t.SPRITE.width,height:t.SPRITE.height,x:-64,y:-92,"clip-path":"url(#blocklyZoomoutClipPath"+e+")"},this.zoomOutGroup_)).setAttributeNS(t.utils.dom.XLINK_NS,"xlink:href",o.options.pathToMedia+t.SPRITE.url),t.bindEventWithChecks_(e,"mousedown",null,(function(e){o.markFocused(),o.zoomCenter(-1),t.Touch.clearTouchIdentifier(),e.stopPropagation(),e.preventDefault()}))},t.ZoomControls.prototype.createZoomInSvg_=function(e){var o=this.workspace_;this.zoomInGroup_=t.utils.dom.createSvgElement("g",{class:"blocklyZoom"},this.svgGroup_);var i=t.utils.dom.createSvgElement("clipPath",{id:"blocklyZoominClipPath"+e},this.zoomInGroup_);t.utils.dom.createSvgElement("rect",{width:32,height:32},i),(e=t.utils.dom.createSvgElement("image",{width:t.SPRITE.width,height:t.SPRITE.height,x:-32,y:-92,"clip-path":"url(#blocklyZoominClipPath"+e+")"},this.zoomInGroup_)).setAttributeNS(t.utils.dom.XLINK_NS,"xlink:href",o.options.pathToMedia+t.SPRITE.url),t.bindEventWithChecks_(e,"mousedown",null,(function(e){o.markFocused(),o.zoomCenter(1),t.Touch.clearTouchIdentifier(),e.stopPropagation(),e.preventDefault()}))},t.ZoomControls.prototype.createZoomResetSvg_=function(e){var o=this.workspace_;this.zoomResetGroup_=t.utils.dom.createSvgElement("g",{class:"blocklyZoom"},this.svgGroup_);var i=t.utils.dom.createSvgElement("clipPath",{id:"blocklyZoomresetClipPath"+e},this.zoomResetGroup_);t.utils.dom.createSvgElement("rect",{width:32,height:32},i),(e=t.utils.dom.createSvgElement("image",{width:t.SPRITE.width,height:t.SPRITE.height,y:-92,"clip-path":"url(#blocklyZoomresetClipPath"+e+")"},this.zoomResetGroup_)).setAttributeNS(t.utils.dom.XLINK_NS,"xlink:href",o.options.pathToMedia+t.SPRITE.url),t.bindEventWithChecks_(e,"mousedown",null,(function(e){o.markFocused(),o.setScale(o.options.zoomOptions.startScale),o.beginCanvasTransition(),o.scrollCenter(),setTimeout(o.endCanvasTransition.bind(o),500),t.Touch.clearTouchIdentifier(),e.stopPropagation(),e.preventDefault()}))},t.Css.register([".blocklyZoom>image, .blocklyZoom>svg>image {","opacity: .4;","}",".blocklyZoom>image:hover, .blocklyZoom>svg>image:hover {","opacity: .6;","}",".blocklyZoom>image:active, .blocklyZoom>svg>image:active {","opacity: .8;","}"]),t.Mutator=function(e){t.Mutator.superClass_.constructor.call(this,null),this.quarkNames_=e},t.utils.object.inherits(t.Mutator,t.Icon),t.Mutator.prototype.workspaceWidth_=0,t.Mutator.prototype.workspaceHeight_=0,t.Mutator.prototype.setBlock=function(t){this.block_=t},t.Mutator.prototype.getWorkspace=function(){return this.workspace_},t.Mutator.prototype.drawIcon_=function(e){t.utils.dom.createSvgElement("rect",{class:"blocklyIconShape",rx:"4",ry:"4",height:"16",width:"16"},e),t.utils.dom.createSvgElement("path",{class:"blocklyIconSymbol",d:"m4.203,7.296 0,1.368 -0.92,0.677 -0.11,0.41 0.9,1.559 0.41,0.11 1.043,-0.457 1.187,0.683 0.127,1.134 0.3,0.3 1.8,0 0.3,-0.299 0.127,-1.138 1.185,-0.682 1.046,0.458 0.409,-0.11 0.9,-1.559 -0.11,-0.41 -0.92,-0.677 0,-1.366 0.92,-0.677 0.11,-0.41 -0.9,-1.559 -0.409,-0.109 -1.046,0.458 -1.185,-0.682 -0.127,-1.138 -0.3,-0.299 -1.8,0 -0.3,0.3 -0.126,1.135 -1.187,0.682 -1.043,-0.457 -0.41,0.11 -0.899,1.559 0.108,0.409z"},e),t.utils.dom.createSvgElement("circle",{class:"blocklyIconShape",r:"2.7",cx:"8",cy:"8"},e)},t.Mutator.prototype.iconClick_=function(e){this.block_.isEditable()&&t.Icon.prototype.iconClick_.call(this,e)},t.Mutator.prototype.createEditor_=function(){if(this.svgDialog_=t.utils.dom.createSvgElement("svg",{x:t.Bubble.BORDER_WIDTH,y:t.Bubble.BORDER_WIDTH},null),this.quarkNames_.length)for(var e,o=t.utils.xml.createElement("xml"),i=0;e=this.quarkNames_[i];i++){var n=t.utils.xml.createElement("block");n.setAttribute("type",e),o.appendChild(n)}else o=null;return(i=new t.Options({disable:!1,parentWorkspace:this.block_.workspace,media:this.block_.workspace.options.pathToMedia,rtl:this.block_.RTL,horizontalLayout:!1,renderer:this.block_.workspace.options.renderer,rendererOverrides:this.block_.workspace.options.rendererOverrides})).toolboxPosition=this.block_.RTL?t.TOOLBOX_AT_RIGHT:t.TOOLBOX_AT_LEFT,i.languageTree=o,i.getMetrics=this.getFlyoutMetrics_.bind(this),this.workspace_=new t.WorkspaceSvg(i),this.workspace_.isMutator=!0,this.workspace_.addChangeListener(t.Events.disableOrphans),o=this.workspace_.addFlyout("g"),(i=this.workspace_.createDom("blocklyMutatorBackground")).insertBefore(o,this.workspace_.svgBlockCanvas_),this.svgDialog_.appendChild(i),this.svgDialog_},t.Mutator.prototype.updateEditable=function(){t.Mutator.superClass_.updateEditable.call(this),this.block_.isInFlyout||(this.block_.isEditable()?this.iconGroup_&&t.utils.dom.removeClass(this.iconGroup_,"blocklyIconGroupReadonly"):(this.setVisible(!1),this.iconGroup_&&t.utils.dom.addClass(this.iconGroup_,"blocklyIconGroupReadonly")))},t.Mutator.prototype.resizeBubble_=function(){var e=2*t.Bubble.BORDER_WIDTH,o=this.workspace_.getCanvas().getBBox(),i=this.block_.RTL?-o.x:o.width+o.x;o=o.height+3*e;var n=this.workspace_.getFlyout();n&&(n=n.getMetrics_(),o=Math.max(o,n.contentHeight+20)),i+=3*e,(Math.abs(this.workspaceWidth_-i)>e||Math.abs(this.workspaceHeight_-o)>e)&&(this.workspaceWidth_=i,this.workspaceHeight_=o,this.bubble_.setBubbleSize(i+e,o+e),this.svgDialog_.setAttribute("width",this.workspaceWidth_),this.svgDialog_.setAttribute("height",this.workspaceHeight_)),this.block_.RTL&&(e="translate("+this.workspaceWidth_+",0)",this.workspace_.getCanvas().setAttribute("transform",e)),this.workspace_.resize()},t.Mutator.prototype.onBubbleMove_=function(){this.workspace_&&this.workspace_.recordDeleteAreas()},t.Mutator.prototype.setVisible=function(e){if(e!=this.isVisible())if(t.Events.fire(new t.Events.Ui(this.block_,"mutatorOpen",!e,e)),e){this.bubble_=new t.Bubble(this.block_.workspace,this.createEditor_(),this.block_.pathObject.svgPath,this.iconXY_,null,null),this.bubble_.setSvgId(this.block_.id),this.bubble_.registerMoveEvent(this.onBubbleMove_.bind(this));var o=this.workspace_.options.languageTree;e=this.workspace_.getFlyout(),o&&(e.init(this.workspace_),e.show(o.childNodes)),this.rootBlock_=this.block_.decompose(this.workspace_),o=this.rootBlock_.getDescendants(!1);for(var i,n=0;i=o[n];n++)i.render();if(this.rootBlock_.setMovable(!1),this.rootBlock_.setDeletable(!1),e?(o=2*e.CORNER_RADIUS,e=e.getWidth()+o):e=o=16,this.block_.RTL&&(e=-e),this.rootBlock_.moveBy(e,o),this.block_.saveConnections){var s=this,r=this.block_;r.saveConnections(this.rootBlock_),this.sourceListener_=function(){r.saveConnections(s.rootBlock_)},this.block_.workspace.addChangeListener(this.sourceListener_)}this.resizeBubble_(),this.workspace_.addChangeListener(this.workspaceChanged_.bind(this)),this.applyColour()}else this.svgDialog_=null,this.workspace_.dispose(),this.rootBlock_=this.workspace_=null,this.bubble_.dispose(),this.bubble_=null,this.workspaceHeight_=this.workspaceWidth_=0,this.sourceListener_&&(this.block_.workspace.removeChangeListener(this.sourceListener_),this.sourceListener_=null)},t.Mutator.prototype.workspaceChanged_=function(e){if(e.type!=t.Events.UI&&(e.type!=t.Events.CHANGE||"disabled"!=e.element)){if(!this.workspace_.isDragging()){e=this.workspace_.getTopBlocks(!1);for(var o,i=0;o=e[i];i++){var n=o.getRelativeToSurfaceXY(),s=o.getHeightWidth();20>n.y+s.height&&o.moveBy(0,20-s.height-n.y)}}if(this.rootBlock_.workspace==this.workspace_){if(t.Events.setGroup(!0),e=(e=(o=this.block_).mutationToDom())&&t.Xml.domToText(e),o.compose(this.rootBlock_),o.initSvg(),o.render(),t.getMainWorkspace().keyboardAccessibilityMode&&t.navigation.moveCursorOnBlockMutation(o),e!=(i=(i=o.mutationToDom())&&t.Xml.domToText(i))){t.Events.fire(new t.Events.BlockChange(o,"mutation",null,e,i));var r=t.Events.getGroup();setTimeout((function(){t.Events.setGroup(r),o.bumpNeighbours(),t.Events.setGroup(!1)}),t.BUMP_DELAY)}this.workspace_.isDragging()||this.resizeBubble_(),t.Events.setGroup(!1)}}},t.Mutator.prototype.getFlyoutMetrics_=function(){return{viewHeight:this.workspaceHeight_,viewWidth:this.workspaceWidth_-this.workspace_.getFlyout().getWidth(),absoluteTop:0,absoluteLeft:this.workspace_.RTL?0:this.workspace_.getFlyout().getWidth()}},t.Mutator.prototype.dispose=function(){this.block_.mutator=null,t.Icon.prototype.dispose.call(this)},t.Mutator.prototype.updateBlockStyle=function(){var t=this.workspace_;if(t&&t.getAllBlocks(!1)){for(var e=t.getAllBlocks(!1),o=0;o=e&&this.sourceBlock_.outputConnection&&!o}else this.fullBlockClickTarget_=!1;this.fullBlockClickTarget_?this.clickTarget_=this.sourceBlock_.getSvgRoot():this.createBorderRect_(),this.createTextElement_()},t.FieldTextInput.prototype.doClassValidation_=function(t){return null==t?null:String(t)},t.FieldTextInput.prototype.doValueInvalid_=function(e){this.isBeingEdited_&&(this.isTextValid_=!1,e=this.value_,this.value_=this.htmlInput_.untypedDefaultValue_,this.sourceBlock_&&t.Events.isEnabled()&&t.Events.fire(new t.Events.BlockChange(this.sourceBlock_,"field",this.name||null,e,this.value_)))},t.FieldTextInput.prototype.doValueUpdate_=function(t){this.isTextValid_=!0,this.value_=t,this.isBeingEdited_||(this.isDirty_=!0)},t.FieldTextInput.prototype.applyColour=function(){this.sourceBlock_&&this.getConstants().FULL_BLOCK_FIELDS&&(this.borderRect_?this.borderRect_.setAttribute("stroke",this.sourceBlock_.style.colourTertiary):this.sourceBlock_.pathObject.svgPath.setAttribute("fill",this.getConstants().FIELD_BORDER_RECT_COLOUR))},t.FieldTextInput.prototype.render_=function(){if(t.FieldTextInput.superClass_.render_.call(this),this.isBeingEdited_){this.resizeEditor_();var e=this.htmlInput_;this.isTextValid_?(t.utils.dom.removeClass(e,"blocklyInvalidInput"),t.utils.aria.setState(e,t.utils.aria.State.INVALID,!1)):(t.utils.dom.addClass(e,"blocklyInvalidInput"),t.utils.aria.setState(e,t.utils.aria.State.INVALID,!0))}},t.FieldTextInput.prototype.setSpellcheck=function(t){t!=this.spellcheck_&&(this.spellcheck_=t,this.htmlInput_&&this.htmlInput_.setAttribute("spellcheck",this.spellcheck_))},t.FieldTextInput.prototype.showEditor_=function(e,o){this.workspace_=this.sourceBlock_.workspace,!(e=o||!1)&&(t.utils.userAgent.MOBILE||t.utils.userAgent.ANDROID||t.utils.userAgent.IPAD)?this.showPromptEditor_():this.showInlineEditor_(e)},t.FieldTextInput.prototype.showPromptEditor_=function(){var e=this;t.prompt(t.Msg.CHANGE_VALUE_TITLE,this.getText(),(function(t){e.setValue(t)}))},t.FieldTextInput.prototype.showInlineEditor_=function(e){t.WidgetDiv.show(this,this.sourceBlock_.RTL,this.widgetDispose_.bind(this)),this.htmlInput_=this.widgetCreate_(),this.isBeingEdited_=!0,e||(this.htmlInput_.focus({preventScroll:!0}),this.htmlInput_.select())},t.FieldTextInput.prototype.widgetCreate_=function(){var e=t.WidgetDiv.DIV;t.utils.dom.addClass(this.getClickTarget_(),"editing");var o=document.createElement("input");o.className="blocklyHtmlInput",o.setAttribute("spellcheck",this.spellcheck_);var i=this.workspace_.getScale(),n=this.getConstants().FIELD_TEXT_FONTSIZE*i+"pt";if(e.style.fontSize=n,o.style.fontSize=n,n=t.FieldTextInput.BORDERRADIUS*i+"px",this.fullBlockClickTarget_){n=((n=this.getScaledBBox()).bottom-n.top)/2+"px";var s=this.sourceBlock_.getParent()?this.sourceBlock_.getParent().style.colourTertiary:this.sourceBlock_.style.colourTertiary;o.style.border=1*i+"px solid "+s,e.style.borderRadius=n,e.style.transition="box-shadow 0.25s ease 0s",this.getConstants().FIELD_TEXTINPUT_BOX_SHADOW&&(e.style.boxShadow="rgba(255, 255, 255, 0.3) 0px 0px 0px "+4*i+"px")}return o.style.borderRadius=n,e.appendChild(o),o.value=o.defaultValue=this.getEditorText_(this.value_),o.untypedDefaultValue_=this.value_,o.oldValue_=null,this.resizeEditor_(),this.bindInputEvents_(o),o},t.FieldTextInput.prototype.widgetDispose_=function(){this.isBeingEdited_=!1,this.isTextValid_=!0,this.forceRerender(),this.onFinishEditing_&&this.onFinishEditing_(this.value_),this.unbindInputEvents_();var e=t.WidgetDiv.DIV.style;e.width="auto",e.height="auto",e.fontSize="",e.transition="",e.boxShadow="",this.htmlInput_=null,t.utils.dom.removeClass(this.getClickTarget_(),"editing")},t.FieldTextInput.prototype.bindInputEvents_=function(e){this.onKeyDownWrapper_=t.bindEventWithChecks_(e,"keydown",this,this.onHtmlInputKeyDown_),this.onKeyInputWrapper_=t.bindEventWithChecks_(e,"input",this,this.onHtmlInputChange_)},t.FieldTextInput.prototype.unbindInputEvents_=function(){this.onKeyDownWrapper_&&(t.unbindEvent_(this.onKeyDownWrapper_),this.onKeyDownWrapper_=null),this.onKeyInputWrapper_&&(t.unbindEvent_(this.onKeyInputWrapper_),this.onKeyInputWrapper_=null)},t.FieldTextInput.prototype.onHtmlInputKeyDown_=function(e){e.keyCode==t.utils.KeyCodes.ENTER?(t.WidgetDiv.hide(),t.DropDownDiv.hideWithoutAnimation()):e.keyCode==t.utils.KeyCodes.ESC?(this.htmlInput_.value=this.htmlInput_.defaultValue,t.WidgetDiv.hide(),t.DropDownDiv.hideWithoutAnimation()):e.keyCode==t.utils.KeyCodes.TAB&&(t.WidgetDiv.hide(),t.DropDownDiv.hideWithoutAnimation(),this.sourceBlock_.tab(this,!e.shiftKey),e.preventDefault())},t.FieldTextInput.prototype.onHtmlInputChange_=function(e){(e=this.htmlInput_.value)!==this.htmlInput_.oldValue_&&(this.htmlInput_.oldValue_=e,t.Events.setGroup(!0),e=this.getValueFromEditorText_(e),this.setValue(e),this.forceRerender(),this.resizeEditor_(),t.Events.setGroup(!1))},t.FieldTextInput.prototype.setEditorValue_=function(t){this.isDirty_=!0,this.isBeingEdited_&&(this.htmlInput_.value=this.getEditorText_(t)),this.setValue(t)},t.FieldTextInput.prototype.resizeEditor_=function(){var e=t.WidgetDiv.DIV,o=this.getScaledBBox();e.style.width=o.right-o.left+"px",e.style.height=o.bottom-o.top+"px",o=new t.utils.Coordinate(this.sourceBlock_.RTL?o.right-e.offsetWidth:o.left,o.top),e.style.left=o.x+"px",e.style.top=o.y+"px"},t.FieldTextInput.numberValidator=function(t){return console.warn("Blockly.FieldTextInput.numberValidator is deprecated. Use Blockly.FieldNumber instead."),null===t?null:(t=(t=(t=String(t)).replace(/O/gi,"0")).replace(/,/g,""),t=Number(t||0),isNaN(t)?null:String(t))},t.FieldTextInput.nonnegativeIntegerValidator=function(e){return(e=t.FieldTextInput.numberValidator(e))&&(e=String(Math.max(0,Math.floor(e)))),e},t.FieldTextInput.prototype.isTabNavigable=function(){return!0},t.FieldTextInput.prototype.getText_=function(){return this.isBeingEdited_&&this.htmlInput_?this.htmlInput_.value:null},t.FieldTextInput.prototype.getEditorText_=function(t){return String(t)},t.FieldTextInput.prototype.getValueFromEditorText_=function(t){return t},t.fieldRegistry.register("field_input",t.FieldTextInput),t.FieldAngle=function(e,o,i){this.clockwise_=t.FieldAngle.CLOCKWISE,this.offset_=t.FieldAngle.OFFSET,this.wrap_=t.FieldAngle.WRAP,this.round_=t.FieldAngle.ROUND,t.FieldAngle.superClass_.constructor.call(this,e||0,o,i),this.moveSurfaceWrapper_=this.clickSurfaceWrapper_=this.clickWrapper_=this.line_=this.gauge_=null},t.utils.object.inherits(t.FieldAngle,t.FieldTextInput),t.FieldAngle.fromJson=function(e){return new t.FieldAngle(e.angle,void 0,e)},t.FieldAngle.prototype.SERIALIZABLE=!0,t.FieldAngle.ROUND=15,t.FieldAngle.HALF=50,t.FieldAngle.CLOCKWISE=!1,t.FieldAngle.OFFSET=0,t.FieldAngle.WRAP=360,t.FieldAngle.RADIUS=t.FieldAngle.HALF-1,t.FieldAngle.prototype.configure_=function(e){switch(t.FieldAngle.superClass_.configure_.call(this,e),e.mode){case"compass":this.clockwise_=!0,this.offset_=90;break;case"protractor":this.clockwise_=!1,this.offset_=0}var o=e.clockwise;"boolean"==typeof o&&(this.clockwise_=o),null!=(o=e.offset)&&(o=Number(o),isNaN(o)||(this.offset_=o)),null!=(o=e.wrap)&&(o=Number(o),isNaN(o)||(this.wrap_=o)),null!=(e=e.round)&&(e=Number(e),isNaN(e)||(this.round_=e))},t.FieldAngle.prototype.initView=function(){t.FieldAngle.superClass_.initView.call(this),this.symbol_=t.utils.dom.createSvgElement("tspan",{},null),this.symbol_.appendChild(document.createTextNode("°")),this.textElement_.appendChild(this.symbol_)},t.FieldAngle.prototype.render_=function(){t.FieldAngle.superClass_.render_.call(this),this.updateGraph_()},t.FieldAngle.prototype.showEditor_=function(e){t.FieldAngle.superClass_.showEditor_.call(this,e,t.utils.userAgent.MOBILE||t.utils.userAgent.ANDROID||t.utils.userAgent.IPAD),e=this.dropdownCreate_(),t.DropDownDiv.getContentDiv().appendChild(e),t.DropDownDiv.setColour(this.sourceBlock_.style.colourPrimary,this.sourceBlock_.style.colourTertiary),t.DropDownDiv.showPositionedByField(this,this.dropdownDispose_.bind(this)),this.updateGraph_()},t.FieldAngle.prototype.dropdownCreate_=function(){var e=t.utils.dom.createSvgElement("svg",{xmlns:t.utils.dom.SVG_NS,"xmlns:html":t.utils.dom.HTML_NS,"xmlns:xlink":t.utils.dom.XLINK_NS,version:"1.1",height:2*t.FieldAngle.HALF+"px",width:2*t.FieldAngle.HALF+"px",style:"touch-action: none"},null),o=t.utils.dom.createSvgElement("circle",{cx:t.FieldAngle.HALF,cy:t.FieldAngle.HALF,r:t.FieldAngle.RADIUS,class:"blocklyAngleCircle"},e);this.gauge_=t.utils.dom.createSvgElement("path",{class:"blocklyAngleGauge"},e),this.line_=t.utils.dom.createSvgElement("line",{x1:t.FieldAngle.HALF,y1:t.FieldAngle.HALF,class:"blocklyAngleLine"},e);for(var i=0;360>i;i+=15)t.utils.dom.createSvgElement("line",{x1:t.FieldAngle.HALF+t.FieldAngle.RADIUS,y1:t.FieldAngle.HALF,x2:t.FieldAngle.HALF+t.FieldAngle.RADIUS-(0==i%45?10:5),y2:t.FieldAngle.HALF,class:"blocklyAngleMarks",transform:"rotate("+i+","+t.FieldAngle.HALF+","+t.FieldAngle.HALF+")"},e);return this.clickWrapper_=t.bindEventWithChecks_(e,"click",this,this.hide_),this.clickSurfaceWrapper_=t.bindEventWithChecks_(o,"click",this,this.onMouseMove_,!0,!0),this.moveSurfaceWrapper_=t.bindEventWithChecks_(o,"mousemove",this,this.onMouseMove_,!0,!0),e},t.FieldAngle.prototype.dropdownDispose_=function(){this.clickWrapper_&&(t.unbindEvent_(this.clickWrapper_),this.clickWrapper_=null),this.clickSurfaceWrapper_&&(t.unbindEvent_(this.clickSurfaceWrapper_),this.clickSurfaceWrapper_=null),this.moveSurfaceWrapper_&&(t.unbindEvent_(this.moveSurfaceWrapper_),this.moveSurfaceWrapper_=null),this.line_=this.gauge_=null},t.FieldAngle.prototype.hide_=function(){t.DropDownDiv.hideIfOwner(this),t.WidgetDiv.hide()},t.FieldAngle.prototype.onMouseMove_=function(e){var o=this.gauge_.ownerSVGElement.getBoundingClientRect(),i=e.clientX-o.left-t.FieldAngle.HALF;e=e.clientY-o.top-t.FieldAngle.HALF,o=Math.atan(-e/i),isNaN(o)||(o=t.utils.math.toDegrees(o),0>i?o+=180:0(t%=360)&&(t+=360),t>this.wrap_&&(t-=360),t},t.Css.register(".blocklyAngleCircle {,stroke: #444;,stroke-width: 1;,fill: #ddd;,fill-opacity: .8;,},.blocklyAngleMarks {,stroke: #444;,stroke-width: 1;,},.blocklyAngleGauge {,fill: #f88;,fill-opacity: .8;,pointer-events: none;,},.blocklyAngleLine {,stroke: #f00;,stroke-width: 2;,stroke-linecap: round;,pointer-events: none;,}".split(",")),t.fieldRegistry.register("field_angle",t.FieldAngle),t.FieldCheckbox=function(e,o,i){this.checkChar_=null,null==e&&(e="FALSE"),t.FieldCheckbox.superClass_.constructor.call(this,e,o,i)},t.utils.object.inherits(t.FieldCheckbox,t.Field),t.FieldCheckbox.fromJson=function(e){return new t.FieldCheckbox(e.checked,void 0,e)},t.FieldCheckbox.CHECK_CHAR="✓",t.FieldCheckbox.prototype.SERIALIZABLE=!0,t.FieldCheckbox.prototype.CURSOR="default",t.FieldCheckbox.prototype.configure_=function(e){t.FieldCheckbox.superClass_.configure_.call(this,e),e.checkCharacter&&(this.checkChar_=e.checkCharacter)},t.FieldCheckbox.prototype.initView=function(){t.FieldCheckbox.superClass_.initView.call(this),t.utils.dom.addClass(this.textElement_,"blocklyCheckbox"),this.textElement_.style.display=this.value_?"block":"none"},t.FieldCheckbox.prototype.render_=function(){this.textContent_&&(this.textContent_.nodeValue=this.getDisplayText_()),this.updateSize_(this.getConstants().FIELD_CHECKBOX_X_OFFSET)},t.FieldCheckbox.prototype.getDisplayText_=function(){return this.checkChar_||t.FieldCheckbox.CHECK_CHAR},t.FieldCheckbox.prototype.setCheckCharacter=function(t){this.checkChar_=t,this.forceRerender()},t.FieldCheckbox.prototype.showEditor_=function(){this.setValue(!this.value_)},t.FieldCheckbox.prototype.doClassValidation_=function(t){return!0===t||"TRUE"===t?"TRUE":!1===t||"FALSE"===t?"FALSE":null},t.FieldCheckbox.prototype.doValueUpdate_=function(t){this.value_=this.convertValueToBool_(t),this.textElement_&&(this.textElement_.style.display=this.value_?"block":"none")},t.FieldCheckbox.prototype.getValue=function(){return this.value_?"TRUE":"FALSE"},t.FieldCheckbox.prototype.getValueBoolean=function(){return this.value_},t.FieldCheckbox.prototype.getText=function(){return String(this.convertValueToBool_(this.value_))},t.FieldCheckbox.prototype.convertValueToBool_=function(t){return"string"==typeof t?"TRUE"==t:!!t},t.fieldRegistry.register("field_checkbox",t.FieldCheckbox),t.FieldColour=function(e,o,i){t.FieldColour.superClass_.constructor.call(this,e||t.FieldColour.COLOURS[0],o,i),this.onKeyDownWrapper_=this.onMouseLeaveWrapper_=this.onMouseEnterWrapper_=this.onMouseMoveWrapper_=this.onClickWrapper_=this.highlightedIndex_=this.picker_=null},t.utils.object.inherits(t.FieldColour,t.Field),t.FieldColour.fromJson=function(e){return new t.FieldColour(e.colour,void 0,e)},t.FieldColour.prototype.SERIALIZABLE=!0,t.FieldColour.prototype.CURSOR="default",t.FieldColour.prototype.isDirty_=!1,t.FieldColour.prototype.colours_=null,t.FieldColour.prototype.titles_=null,t.FieldColour.prototype.columns_=0,t.FieldColour.prototype.configure_=function(e){t.FieldColour.superClass_.configure_.call(this,e),e.colourOptions&&(this.colours_=e.colourOptions,this.titles_=e.colourTitles),e.columns&&(this.columns_=e.columns)},t.FieldColour.prototype.initView=function(){this.size_=new t.utils.Size(this.getConstants().FIELD_COLOUR_DEFAULT_WIDTH,this.getConstants().FIELD_COLOUR_DEFAULT_HEIGHT),this.getConstants().FIELD_COLOUR_FULL_BLOCK?this.clickTarget_=this.sourceBlock_.getSvgRoot():(this.createBorderRect_(),this.borderRect_.style.fillOpacity="1")},t.FieldColour.prototype.applyColour=function(){this.getConstants().FIELD_COLOUR_FULL_BLOCK?(this.sourceBlock_.pathObject.svgPath.setAttribute("fill",this.getValue()),this.sourceBlock_.pathObject.svgPath.setAttribute("stroke","#fff")):this.borderRect_&&(this.borderRect_.style.fill=this.getValue())},t.FieldColour.prototype.doClassValidation_=function(e){return"string"!=typeof e?null:t.utils.colour.parse(e)},t.FieldColour.prototype.doValueUpdate_=function(t){this.value_=t,this.borderRect_?this.borderRect_.style.fill=t:this.sourceBlock_&&this.sourceBlock_.rendered&&(this.sourceBlock_.pathObject.svgPath.setAttribute("fill",t),this.sourceBlock_.pathObject.svgPath.setAttribute("stroke","#fff"))},t.FieldColour.prototype.getText=function(){var t=this.value_;return/^#(.)\1(.)\2(.)\3$/.test(t)&&(t="#"+t[1]+t[3]+t[5]),t},t.FieldColour.COLOURS="#ffffff #cccccc #c0c0c0 #999999 #666666 #333333 #000000 #ffcccc #ff6666 #ff0000 #cc0000 #990000 #660000 #330000 #ffcc99 #ff9966 #ff9900 #ff6600 #cc6600 #993300 #663300 #ffff99 #ffff66 #ffcc66 #ffcc33 #cc9933 #996633 #663333 #ffffcc #ffff33 #ffff00 #ffcc00 #999900 #666600 #333300 #99ff99 #66ff99 #33ff33 #33cc00 #009900 #006600 #003300 #99ffff #33ffff #66cccc #00cccc #339999 #336666 #003333 #ccffff #66ffff #33ccff #3366ff #3333ff #000099 #000066 #ccccff #9999ff #6666cc #6633ff #6600cc #333399 #330099 #ffccff #ff99ff #cc66cc #cc33cc #993399 #663366 #330033".split(" "),t.FieldColour.TITLES=[],t.FieldColour.COLUMNS=7,t.FieldColour.prototype.setColours=function(t,e){return this.colours_=t,e&&(this.titles_=e),this},t.FieldColour.prototype.setColumns=function(t){return this.columns_=t,this},t.FieldColour.prototype.showEditor_=function(){this.picker_=this.dropdownCreate_(),t.DropDownDiv.getContentDiv().appendChild(this.picker_),t.DropDownDiv.showPositionedByField(this,this.dropdownDispose_.bind(this)),this.picker_.focus({preventScroll:!0})},t.FieldColour.prototype.onClick_=function(e){null!==(e=(e=e.target)&&e.label)&&(this.setValue(e),t.DropDownDiv.hideIfOwner(this))},t.FieldColour.prototype.onKeyDown_=function(e){var o=!1;e.keyCode===t.utils.KeyCodes.UP?(this.moveHighlightBy_(0,-1),o=!0):e.keyCode===t.utils.KeyCodes.DOWN?(this.moveHighlightBy_(0,1),o=!0):e.keyCode===t.utils.KeyCodes.LEFT?(this.moveHighlightBy_(-1,0),o=!0):e.keyCode===t.utils.KeyCodes.RIGHT?(this.moveHighlightBy_(1,0),o=!0):e.keyCode===t.utils.KeyCodes.ENTER&&((o=this.getHighlighted_())&&null!==(o=o&&o.label)&&this.setValue(o),t.DropDownDiv.hideWithoutAnimation(),o=!0),o&&e.stopPropagation()},t.FieldColour.prototype.onBlocklyAction=function(e){if(this.picker_){if(e===t.navigation.ACTION_PREVIOUS)return this.moveHighlightBy_(0,-1),!0;if(e===t.navigation.ACTION_NEXT)return this.moveHighlightBy_(0,1),!0;if(e===t.navigation.ACTION_OUT)return this.moveHighlightBy_(-1,0),!0;if(e===t.navigation.ACTION_IN)return this.moveHighlightBy_(1,0),!0}return t.FieldColour.superClass_.onBlocklyAction.call(this,e)},t.FieldColour.prototype.moveHighlightBy_=function(e,o){var i=this.colours_||t.FieldColour.COLOURS,n=this.columns_||t.FieldColour.COLUMNS,s=this.highlightedIndex_%n,r=Math.floor(this.highlightedIndex_/n);s+=e,r+=o,0>e?0>s&&0s&&(s=0):0n-1&&rn-1&&s--:0>o?0>r&&(r=0):0Math.floor(i.length/n)-1&&(r=Math.floor(i.length/n)-1),this.setHighlightedCell_(this.picker_.childNodes[r].childNodes[s],r*n+s)},t.FieldColour.prototype.onMouseMove_=function(t){var e=(t=t.target)&&Number(t.getAttribute("data-index"));null!==e&&e!==this.highlightedIndex_&&this.setHighlightedCell_(t,e)},t.FieldColour.prototype.onMouseEnter_=function(){this.picker_.focus({preventScroll:!0})},t.FieldColour.prototype.onMouseLeave_=function(){this.picker_.blur();var e=this.getHighlighted_();e&&t.utils.dom.removeClass(e,"blocklyColourHighlighted")},t.FieldColour.prototype.getHighlighted_=function(){var e=this.columns_||t.FieldColour.COLUMNS,o=this.picker_.childNodes[Math.floor(this.highlightedIndex_/e)];return o?o.childNodes[this.highlightedIndex_%e]:null},t.FieldColour.prototype.setHighlightedCell_=function(e,o){var i=this.getHighlighted_();i&&t.utils.dom.removeClass(i,"blocklyColourHighlighted"),t.utils.dom.addClass(e,"blocklyColourHighlighted"),this.highlightedIndex_=o,t.utils.aria.setState(this.picker_,t.utils.aria.State.ACTIVEDESCENDANT,e.getAttribute("id"))},t.FieldColour.prototype.dropdownCreate_=function(){var e=this.columns_||t.FieldColour.COLUMNS,o=this.colours_||t.FieldColour.COLOURS,i=this.titles_||t.FieldColour.TITLES,n=this.getValue(),s=document.createElement("table");s.className="blocklyColourTable",s.tabIndex=0,s.dir="ltr",t.utils.aria.setRole(s,t.utils.aria.Role.GRID),t.utils.aria.setState(s,t.utils.aria.State.EXPANDED,!0),t.utils.aria.setState(s,t.utils.aria.State.ROWCOUNT,Math.floor(o.length/e)),t.utils.aria.setState(s,t.utils.aria.State.COLCOUNT,e);for(var r,a=0;atr>td {","border: .5px solid #888;","box-sizing: border-box;","cursor: pointer;","display: inline-block;","height: 20px;","padding: 0;","width: 20px;","}",".blocklyColourTable>tr>td.blocklyColourHighlighted {","border-color: #eee;","box-shadow: 2px 2px 7px 2px rgba(0,0,0,.3);","position: relative;","}",".blocklyColourSelected, .blocklyColourSelected:hover {","border-color: #eee !important;","outline: 1px solid #333;","position: relative;","}"]),t.fieldRegistry.register("field_colour",t.FieldColour),t.FieldDropdown=function(e,o,i){"function"!=typeof e&&t.FieldDropdown.validateOptions_(e),this.menuGenerator_=e,this.generatedOptions_=null,this.trimOptions_(),this.selectedOption_=this.getOptions(!1)[0],t.FieldDropdown.superClass_.constructor.call(this,this.selectedOption_[1],o,i),this.svgArrow_=this.arrow_=this.imageElement_=this.menu_=this.selectedMenuItem_=null},t.utils.object.inherits(t.FieldDropdown,t.Field),t.FieldDropdown.fromJson=function(e){return new t.FieldDropdown(e.options,void 0,e)},t.FieldDropdown.prototype.SERIALIZABLE=!0,t.FieldDropdown.CHECKMARK_OVERHANG=25,t.FieldDropdown.MAX_MENU_HEIGHT_VH=.45,t.FieldDropdown.IMAGE_Y_OFFSET=5,t.FieldDropdown.IMAGE_Y_PADDING=2*t.FieldDropdown.IMAGE_Y_OFFSET,t.FieldDropdown.ARROW_CHAR=t.utils.userAgent.ANDROID?"▼":"▾",t.FieldDropdown.prototype.CURSOR="default",t.FieldDropdown.prototype.initView=function(){this.shouldAddBorderRect_()?this.createBorderRect_():this.clickTarget_=this.sourceBlock_.getSvgRoot(),this.createTextElement_(),this.imageElement_=t.utils.dom.createSvgElement("image",{},this.fieldGroup_),this.getConstants().FIELD_DROPDOWN_SVG_ARROW?this.createSVGArrow_():this.createTextArrow_(),this.borderRect_&&t.utils.dom.addClass(this.borderRect_,"blocklyDropdownRect")},t.FieldDropdown.prototype.shouldAddBorderRect_=function(){return!this.getConstants().FIELD_DROPDOWN_NO_BORDER_RECT_SHADOW||this.getConstants().FIELD_DROPDOWN_NO_BORDER_RECT_SHADOW&&!this.sourceBlock_.isShadow()},t.FieldDropdown.prototype.createTextArrow_=function(){this.arrow_=t.utils.dom.createSvgElement("tspan",{},this.textElement_),this.arrow_.appendChild(document.createTextNode(this.sourceBlock_.RTL?t.FieldDropdown.ARROW_CHAR+" ":" "+t.FieldDropdown.ARROW_CHAR)),this.sourceBlock_.RTL?this.textElement_.insertBefore(this.arrow_,this.textContent_):this.textElement_.appendChild(this.arrow_)},t.FieldDropdown.prototype.createSVGArrow_=function(){this.svgArrow_=t.utils.dom.createSvgElement("image",{height:this.getConstants().FIELD_DROPDOWN_SVG_ARROW_SIZE+"px",width:this.getConstants().FIELD_DROPDOWN_SVG_ARROW_SIZE+"px"},this.fieldGroup_),this.svgArrow_.setAttributeNS(t.utils.dom.XLINK_NS,"xlink:href",this.getConstants().FIELD_DROPDOWN_SVG_ARROW_DATAURI)},t.FieldDropdown.prototype.showEditor_=function(e){if(this.menu_=this.dropdownCreate_(),this.menu_.openingCoords=e&&"number"==typeof e.clientX?new t.utils.Coordinate(e.clientX,e.clientY):null,this.menu_.render(t.DropDownDiv.getContentDiv()),t.utils.dom.addClass(this.menu_.getElement(),"blocklyDropdownMenu"),this.getConstants().FIELD_DROPDOWN_COLOURED_DIV){e=this.sourceBlock_.isShadow()?this.sourceBlock_.getParent().getColour():this.sourceBlock_.getColour();var o=this.sourceBlock_.isShadow()?this.sourceBlock_.getParent().style.colourTertiary:this.sourceBlock_.style.colourTertiary;t.DropDownDiv.setColour(e,o)}t.DropDownDiv.showPositionedByField(this,this.dropdownDispose_.bind(this)),this.menu_.focus(),this.selectedMenuItem_&&t.utils.style.scrollIntoContainerView(this.selectedMenuItem_.getElement(),this.menu_.getElement()),this.applyColour()},t.FieldDropdown.prototype.dropdownCreate_=function(){var e=new t.Menu;e.setRightToLeft(this.sourceBlock_.RTL),e.setRole(t.utils.aria.Role.LISTBOX);var o=this.getOptions(!1);this.selectedMenuItem_=null;for(var i=0;ie.length)){for(o=[],i=0;i=i||0>=o)throw Error("Height and width values of an image field must be greater than 0.");this.flipRtl_=!1,this.altText_="",t.FieldImage.superClass_.constructor.call(this,e||"",null,a),a||(this.flipRtl_=!!r,this.altText_=t.utils.replaceMessageReferences(n)||""),this.size_=new t.utils.Size(o,i+t.FieldImage.Y_PADDING),this.imageHeight_=i,this.clickHandler_=null,"function"==typeof s&&(this.clickHandler_=s),this.imageElement_=null},t.utils.object.inherits(t.FieldImage,t.Field),t.FieldImage.fromJson=function(e){return new t.FieldImage(e.src,e.width,e.height,void 0,void 0,void 0,e)},t.FieldImage.Y_PADDING=1,t.FieldImage.prototype.EDITABLE=!1,t.FieldImage.prototype.isDirty_=!1,t.FieldImage.prototype.configure_=function(e){t.FieldImage.superClass_.configure_.call(this,e),this.flipRtl_=!!e.flipRtl,this.altText_=t.utils.replaceMessageReferences(e.alt)||""},t.FieldImage.prototype.initView=function(){this.imageElement_=t.utils.dom.createSvgElement("image",{height:this.imageHeight_+"px",width:this.size_.width+"px",alt:this.altText_},this.fieldGroup_),this.imageElement_.setAttributeNS(t.utils.dom.XLINK_NS,"xlink:href",this.value_),this.clickHandler_&&(this.imageElement_.style.cursor="pointer")},t.FieldImage.prototype.updateSize_=function(){},t.FieldImage.prototype.doClassValidation_=function(t){return"string"!=typeof t?null:t},t.FieldImage.prototype.doValueUpdate_=function(e){this.value_=e,this.imageElement_&&this.imageElement_.setAttributeNS(t.utils.dom.XLINK_NS,"xlink:href",String(this.value_))},t.FieldImage.prototype.getFlipRtl=function(){return this.flipRtl_},t.FieldImage.prototype.setAlt=function(t){t!=this.altText_&&(this.altText_=t||"",this.imageElement_&&this.imageElement_.setAttribute("alt",this.altText_))},t.FieldImage.prototype.showEditor_=function(){this.clickHandler_&&this.clickHandler_(this)},t.FieldImage.prototype.setOnClickHandler=function(t){this.clickHandler_=t},t.FieldImage.prototype.getText_=function(){return this.altText_},t.fieldRegistry.register("field_image",t.FieldImage),t.FieldMultilineInput=function(e,o,i){null==e&&(e=""),t.FieldMultilineInput.superClass_.constructor.call(this,e,o,i),this.textGroup_=null},t.utils.object.inherits(t.FieldMultilineInput,t.FieldTextInput),t.FieldMultilineInput.fromJson=function(e){var o=t.utils.replaceMessageReferences(e.text);return new t.FieldMultilineInput(o,void 0,e)},t.FieldMultilineInput.prototype.initView=function(){this.createBorderRect_(),this.textGroup_=t.utils.dom.createSvgElement("g",{class:"blocklyEditableText"},this.fieldGroup_)},t.FieldMultilineInput.prototype.getDisplayText_=function(){var e=this.value_;if(!e)return t.Field.NBSP;var o=e.split("\n");e="";for(var i=0;ithis.maxDisplayLength&&(n=n.substring(0,this.maxDisplayLength-4)+"..."),e+=n=n.replace(/\s/g,t.Field.NBSP),i!==o.length-1&&(e+="\n")}return this.sourceBlock_.RTL&&(e+="‏"),e},t.FieldMultilineInput.prototype.render_=function(){for(var e;e=this.textGroup_.firstChild;)this.textGroup_.removeChild(e);e=this.getDisplayText_().split("\n");for(var o=0,i=0;io&&(o=s),i+=this.getConstants().FIELD_TEXT_HEIGHT+(0this.max_&&t.utils.aria.setState(e,t.utils.aria.State.VALUEMAX,this.max_),e},t.fieldRegistry.register("field_number",t.FieldNumber),t.FieldVariable=function(e,o,i,n,s){this.menuGenerator_=t.FieldVariable.dropdownCreate,this.defaultVariableName=e||"",this.size_=new t.utils.Size(0,0),s&&this.configure_(s),o&&this.setValidator(o),s||this.setTypes_(i,n)},t.utils.object.inherits(t.FieldVariable,t.FieldDropdown),t.FieldVariable.fromJson=function(e){var o=t.utils.replaceMessageReferences(e.variable);return new t.FieldVariable(o,void 0,void 0,void 0,e)},t.FieldVariable.prototype.workspace_=null,t.FieldVariable.prototype.SERIALIZABLE=!0,t.FieldVariable.prototype.configure_=function(e){t.FieldVariable.superClass_.configure_.call(this,e),this.setTypes_(e.variableTypes,e.defaultType)},t.FieldVariable.prototype.initModel=function(){if(!this.variable_){var e=t.Variables.getOrCreateVariablePackage(this.sourceBlock_.workspace,null,this.defaultVariableName,this.defaultType_);this.doValueUpdate_(e.getId())}},t.FieldVariable.prototype.shouldAddBorderRect_=function(){return t.FieldVariable.superClass_.shouldAddBorderRect_.call(this)&&(!this.getConstants().FIELD_DROPDOWN_NO_BORDER_RECT_SHADOW||"variables_get"!=this.sourceBlock_.type)},t.FieldVariable.prototype.fromXml=function(e){var o=e.getAttribute("id"),i=e.textContent,n=e.getAttribute("variabletype")||e.getAttribute("variableType")||"";if(o=t.Variables.getOrCreateVariablePackage(this.sourceBlock_.workspace,o,i,n),null!=n&&n!==o.type)throw Error("Serialized variable type with id '"+o.getId()+"' had type "+o.type+", and does not match variable field that references it: "+t.Xml.domToText(e)+".");this.setValue(o.getId())},t.FieldVariable.prototype.toXml=function(t){return this.initModel(),t.id=this.variable_.getId(),t.textContent=this.variable_.name,this.variable_.type&&t.setAttribute("variabletype",this.variable_.type),t},t.FieldVariable.prototype.setSourceBlock=function(e){if(e.isShadow())throw Error("Variable fields are not allowed to exist on shadow blocks.");t.FieldVariable.superClass_.setSourceBlock.call(this,e)},t.FieldVariable.prototype.getValue=function(){return this.variable_?this.variable_.getId():null},t.FieldVariable.prototype.getText=function(){return this.variable_?this.variable_.name:""},t.FieldVariable.prototype.getVariable=function(){return this.variable_},t.FieldVariable.prototype.getValidator=function(){return this.variable_?this.validator_:null},t.FieldVariable.prototype.doClassValidation_=function(e){if(null===e)return null;var o=t.Variables.getVariable(this.sourceBlock_.workspace,e);return o?(o=o.type,this.typeIsAllowed_(o)?e:(console.warn("Variable type doesn't match this field! Type was "+o),null)):(console.warn("Variable id doesn't point to a real variable! ID was "+e),null)},t.FieldVariable.prototype.doValueUpdate_=function(e){this.variable_=t.Variables.getVariable(this.sourceBlock_.workspace,e),t.FieldVariable.superClass_.doValueUpdate_.call(this,e)},t.FieldVariable.prototype.typeIsAllowed_=function(t){var e=this.getVariableTypes_();if(!e)return!0;for(var o=0;orect,",t+" .blocklyEditableText>rect {","fill: "+this.FIELD_BORDER_RECT_COLOUR+";","fill-opacity: .6;","stroke: none;","}",t+" .blocklyNonEditableText>text,",t+" .blocklyEditableText>text {","fill: #000;","}",t+" .blocklyFlyoutLabelText {","fill: #000;","}",t+" .blocklyText.blocklyBubbleText {","fill: #000;","}",t+" .blocklyEditableText:not(.editing):hover>rect {","stroke: #fff;","stroke-width: 2;","}",t+" .blocklyHtmlInput {","font-family: "+this.FIELD_TEXT_FONTFAMILY+";","font-weight: "+this.FIELD_TEXT_FONTWEIGHT+";","}",t+" .blocklySelected>.blocklyPath {","stroke: #fc3;","stroke-width: 3px;","}",t+" .blocklyHighlightedConnectionPath {","stroke: #fc3;","}",t+" .blocklyReplaceable .blocklyPath {","fill-opacity: .5;","}",t+" .blocklyReplaceable .blocklyPathLight,",t+" .blocklyReplaceable .blocklyPathDark {","display: none;","}",t+" .blocklyInsertionMarker>.blocklyPath {","fill-opacity: "+this.INSERTION_MARKER_OPACITY+";","stroke: none","}"]},t.blockRendering.MarkerSvg=function(t,e,o){this.workspace_=t,this.marker_=o,this.parent_=null,this.constants_=e,this.currentMarkerSvg=null,t=this.isCursor()?this.constants_.CURSOR_COLOUR:this.constants_.MARKER_COLOUR,this.colour_=o.colour||t},t.blockRendering.MarkerSvg.CURSOR_CLASS="blocklyCursor",t.blockRendering.MarkerSvg.MARKER_CLASS="blocklyMarker",t.blockRendering.MarkerSvg.HEIGHT_MULTIPLIER=.75,t.blockRendering.MarkerSvg.prototype.getSvgRoot=function(){return this.svgGroup_},t.blockRendering.MarkerSvg.prototype.isCursor=function(){return"cursor"==this.marker_.type},t.blockRendering.MarkerSvg.prototype.createDom=function(){var e=this.isCursor()?t.blockRendering.MarkerSvg.CURSOR_CLASS:t.blockRendering.MarkerSvg.MARKER_CLASS;return this.svgGroup_=t.utils.dom.createSvgElement("g",{class:e},null),this.createDomInternal_(),this.applyColour_(),this.svgGroup_},t.blockRendering.MarkerSvg.prototype.setParent_=function(t){this.isCursor()?(this.parent_&&this.parent_.setCursorSvg(null),t.setCursorSvg(this.getSvgRoot())):(this.parent_&&this.parent_.setMarkerSvg(null),t.setMarkerSvg(this.getSvgRoot())),this.parent_=t},t.blockRendering.MarkerSvg.prototype.showWithBlockPrevOutput_=function(e){if(e){var o=e.width,i=e.height,n=i*t.blockRendering.MarkerSvg.HEIGHT_MULTIPLIER,s=this.constants_.CURSOR_BLOCK_PADDING;if(e.previousConnection){var r=this.constants_.shapeFor(e.previousConnection);this.positionPrevious_(o,s,n,r)}else e.outputConnection?(r=this.constants_.shapeFor(e.outputConnection),this.positionOutput_(o,i,r)):this.positionBlock_(o,s,n);this.setParent_(e),this.showCurrent_()}},t.blockRendering.MarkerSvg.prototype.showWithCoordinates_=function(t){var e=t.getWsCoordinate();t=e.x,e=e.y,this.workspace_.RTL&&(t-=this.constants_.CURSOR_WS_WIDTH),this.positionLine_(t,e,this.constants_.CURSOR_WS_WIDTH),this.setParent_(this.workspace_),this.showCurrent_()},t.blockRendering.MarkerSvg.prototype.showWithField_=function(t){var e=(t=t.getLocation()).getSize().width,o=t.getSize().height;this.positionRect_(0,0,e,o),this.setParent_(t),this.showCurrent_()},t.blockRendering.MarkerSvg.prototype.showWithInput_=function(t){var e=(t=t.getLocation()).getSourceBlock();this.positionInput_(t),this.setParent_(e),this.showCurrent_()},t.blockRendering.MarkerSvg.prototype.showWithNext_=function(t){var e=t.getLocation();t=e.getSourceBlock();var o=0;e=e.getOffsetInBlock().y;var i=t.getHeightWidth().width;this.workspace_.RTL&&(o=-i),this.positionLine_(o,e,i),this.setParent_(t),this.showCurrent_()},t.blockRendering.MarkerSvg.prototype.showWithStack_=function(t){var e=(t=t.getLocation()).getHeightWidth(),o=e.width+this.constants_.CURSOR_STACK_PADDING;e=e.height+this.constants_.CURSOR_STACK_PADDING;var i=-this.constants_.CURSOR_STACK_PADDING/2,n=-this.constants_.CURSOR_STACK_PADDING/2,s=i;this.workspace_.RTL&&(s=-(o+i)),this.positionRect_(s,n,o,e),this.setParent_(t),this.showCurrent_()},t.blockRendering.MarkerSvg.prototype.showCurrent_=function(){this.hide(),this.currentMarkerSvg.style.display=""},t.blockRendering.MarkerSvg.prototype.positionBlock_=function(e,o,i){e=t.utils.svgPaths.moveBy(-o,i)+t.utils.svgPaths.lineOnAxis("V",-o)+t.utils.svgPaths.lineOnAxis("H",e+2*o)+t.utils.svgPaths.lineOnAxis("V",i),this.markerBlock_.setAttribute("d",e),this.workspace_.RTL&&this.flipRtl_(this.markerBlock_),this.currentMarkerSvg=this.markerBlock_},t.blockRendering.MarkerSvg.prototype.positionInput_=function(e){var o=e.getOffsetInBlock().x,i=e.getOffsetInBlock().y;e=t.utils.svgPaths.moveTo(0,0)+this.constants_.shapeFor(e).pathDown,this.markerInput_.setAttribute("d",e),this.markerInput_.setAttribute("transform","translate("+o+","+i+")"+(this.workspace_.RTL?" scale(-1 1)":"")),this.currentMarkerSvg=this.markerInput_},t.blockRendering.MarkerSvg.prototype.positionLine_=function(t,e,o){this.markerSvgLine_.setAttribute("x",t),this.markerSvgLine_.setAttribute("y",e),this.markerSvgLine_.setAttribute("width",o),this.currentMarkerSvg=this.markerSvgLine_},t.blockRendering.MarkerSvg.prototype.positionOutput_=function(e,o,i){e=t.utils.svgPaths.moveBy(e,0)+t.utils.svgPaths.lineOnAxis("h",-(e-i.width))+t.utils.svgPaths.lineOnAxis("v",this.constants_.TAB_OFFSET_FROM_TOP)+i.pathDown+t.utils.svgPaths.lineOnAxis("V",o)+t.utils.svgPaths.lineOnAxis("H",e),this.markerBlock_.setAttribute("d",e),this.workspace_.RTL&&this.flipRtl_(this.markerBlock_),this.currentMarkerSvg=this.markerBlock_},t.blockRendering.MarkerSvg.prototype.positionPrevious_=function(e,o,i,n){e=t.utils.svgPaths.moveBy(-o,i)+t.utils.svgPaths.lineOnAxis("V",-o)+t.utils.svgPaths.lineOnAxis("H",this.constants_.NOTCH_OFFSET_LEFT)+n.pathLeft+t.utils.svgPaths.lineOnAxis("H",e+2*o)+t.utils.svgPaths.lineOnAxis("V",i),this.markerBlock_.setAttribute("d",e),this.workspace_.RTL&&this.flipRtl_(this.markerBlock_),this.currentMarkerSvg=this.markerBlock_},t.blockRendering.MarkerSvg.prototype.positionRect_=function(t,e,o,i){this.markerSvgRect_.setAttribute("x",t),this.markerSvgRect_.setAttribute("y",e),this.markerSvgRect_.setAttribute("width",o),this.markerSvgRect_.setAttribute("height",i),this.currentMarkerSvg=this.markerSvgRect_},t.blockRendering.MarkerSvg.prototype.flipRtl_=function(t){t.setAttribute("transform","scale(-1 1)")},t.blockRendering.MarkerSvg.prototype.hide=function(){this.markerSvgLine_.style.display="none",this.markerSvgRect_.style.display="none",this.markerInput_.style.display="none",this.markerBlock_.style.display="none"},t.blockRendering.MarkerSvg.prototype.draw=function(t,e){if(e){this.constants_=this.workspace_.getRenderer().getConstants();var o=this.isCursor()?this.constants_.CURSOR_COLOUR:this.constants_.MARKER_COLOUR;this.colour_=this.marker_.colour||o,this.applyColour_(),this.showAtLocation_(e),this.firemarkerEvent_(t,e),void 0!==(t=this.currentMarkerSvg.childNodes[0])&&t.beginElement&&t.beginElement()}else this.hide()},t.blockRendering.MarkerSvg.prototype.showAtLocation_=function(e){e.getType()==t.ASTNode.types.BLOCK?(e=e.getLocation(),this.showWithBlockPrevOutput_(e)):e.getType()==t.ASTNode.types.OUTPUT?(e=e.getLocation().getSourceBlock(),this.showWithBlockPrevOutput_(e)):e.getLocation().type==t.INPUT_VALUE?this.showWithInput_(e):e.getLocation().type==t.NEXT_STATEMENT?this.showWithNext_(e):e.getType()==t.ASTNode.types.PREVIOUS?(e=e.getLocation().getSourceBlock(),this.showWithBlockPrevOutput_(e)):e.getType()==t.ASTNode.types.FIELD?this.showWithField_(e):e.getType()==t.ASTNode.types.WORKSPACE?this.showWithCoordinates_(e):e.getType()==t.ASTNode.types.STACK&&this.showWithStack_(e)},t.blockRendering.MarkerSvg.prototype.firemarkerEvent_=function(e,o){var i=o.getSourceBlock(),n=this.isCursor()?"cursorMove":"markerMove";e=new t.Events.Ui(i,n,e,o),o.getType()==t.ASTNode.types.WORKSPACE&&(e.workspaceId=o.getLocation().id),t.Events.fire(e)},t.blockRendering.MarkerSvg.prototype.getBlinkProperties_=function(){return{attributeType:"XML",attributeName:"fill",dur:"1s",values:this.colour_+";transparent;transparent;",repeatCount:"indefinite"}},t.blockRendering.MarkerSvg.prototype.createDomInternal_=function(){if(this.markerSvg_=t.utils.dom.createSvgElement("g",{width:this.constants_.CURSOR_WS_WIDTH,height:this.constants_.WS_CURSOR_HEIGHT},this.svgGroup_),this.markerSvgLine_=t.utils.dom.createSvgElement("rect",{width:this.constants_.CURSOR_WS_WIDTH,height:this.constants_.WS_CURSOR_HEIGHT,style:"display: none"},this.markerSvg_),this.markerSvgRect_=t.utils.dom.createSvgElement("rect",{class:"blocklyVerticalMarker",rx:10,ry:10,style:"display: none"},this.markerSvg_),this.markerInput_=t.utils.dom.createSvgElement("path",{transform:"",style:"display: none"},this.markerSvg_),this.markerBlock_=t.utils.dom.createSvgElement("path",{transform:"",style:"display: none",fill:"none","stroke-width":this.constants_.CURSOR_STROKE_WIDTH},this.markerSvg_),this.isCursor()){var e=this.getBlinkProperties_();t.utils.dom.createSvgElement("animate",e,this.markerSvgLine_),t.utils.dom.createSvgElement("animate",e,this.markerInput_),e.attributeName="stroke",t.utils.dom.createSvgElement("animate",e,this.markerBlock_)}return this.markerSvg_},t.blockRendering.MarkerSvg.prototype.applyColour_=function(){if(this.markerSvgLine_.setAttribute("fill",this.colour_),this.markerSvgRect_.setAttribute("stroke",this.colour_),this.markerInput_.setAttribute("fill",this.colour_),this.markerBlock_.setAttribute("stroke",this.colour_),this.isCursor()){var t=this.colour_+";transparent;transparent;";this.markerSvgLine_.firstChild.setAttribute("values",t),this.markerInput_.firstChild.setAttribute("values",t),this.markerBlock_.firstChild.setAttribute("values",t)}},t.blockRendering.MarkerSvg.prototype.dispose=function(){this.svgGroup_&&t.utils.dom.removeNode(this.svgGroup_)},t.blockRendering.Types={NONE:0,FIELD:1,HAT:2,ICON:4,SPACER:8,BETWEEN_ROW_SPACER:16,IN_ROW_SPACER:32,EXTERNAL_VALUE_INPUT:64,INPUT:128,INLINE_INPUT:256,STATEMENT_INPUT:512,CONNECTION:1024,PREVIOUS_CONNECTION:2048,NEXT_CONNECTION:4096,OUTPUT_CONNECTION:8192,CORNER:16384,LEFT_SQUARE_CORNER:32768,LEFT_ROUND_CORNER:65536,RIGHT_SQUARE_CORNER:131072,RIGHT_ROUND_CORNER:262144,JAGGED_EDGE:524288,ROW:1048576,TOP_ROW:2097152,BOTTOM_ROW:4194304,INPUT_ROW:8388608},t.blockRendering.Types.LEFT_CORNER=t.blockRendering.Types.LEFT_SQUARE_CORNER|t.blockRendering.Types.LEFT_ROUND_CORNER,t.blockRendering.Types.RIGHT_CORNER=t.blockRendering.Types.RIGHT_SQUARE_CORNER|t.blockRendering.Types.RIGHT_ROUND_CORNER,t.blockRendering.Types.nextTypeValue_=16777216,t.blockRendering.Types.getType=function(e){return t.blockRendering.Types.hasOwnProperty(e)||(t.blockRendering.Types[e]=t.blockRendering.Types.nextTypeValue_,t.blockRendering.Types.nextTypeValue_<<=1),t.blockRendering.Types[e]},t.blockRendering.Types.isField=function(e){return e.type&t.blockRendering.Types.FIELD},t.blockRendering.Types.isHat=function(e){return e.type&t.blockRendering.Types.HAT},t.blockRendering.Types.isIcon=function(e){return e.type&t.blockRendering.Types.ICON},t.blockRendering.Types.isSpacer=function(e){return e.type&t.blockRendering.Types.SPACER},t.blockRendering.Types.isInRowSpacer=function(e){return e.type&t.blockRendering.Types.IN_ROW_SPACER},t.blockRendering.Types.isInput=function(e){return e.type&t.blockRendering.Types.INPUT},t.blockRendering.Types.isExternalInput=function(e){return e.type&t.blockRendering.Types.EXTERNAL_VALUE_INPUT},t.blockRendering.Types.isInlineInput=function(e){return e.type&t.blockRendering.Types.INLINE_INPUT},t.blockRendering.Types.isStatementInput=function(e){return e.type&t.blockRendering.Types.STATEMENT_INPUT},t.blockRendering.Types.isPreviousConnection=function(e){return e.type&t.blockRendering.Types.PREVIOUS_CONNECTION},t.blockRendering.Types.isNextConnection=function(e){return e.type&t.blockRendering.Types.NEXT_CONNECTION},t.blockRendering.Types.isPreviousOrNextConnection=function(e){return e.type&(t.blockRendering.Types.PREVIOUS_CONNECTION|t.blockRendering.Types.NEXT_CONNECTION)},t.blockRendering.Types.isLeftRoundedCorner=function(e){return e.type&t.blockRendering.Types.LEFT_ROUND_CORNER},t.blockRendering.Types.isRightRoundedCorner=function(e){return e.type&t.blockRendering.Types.RIGHT_ROUND_CORNER},t.blockRendering.Types.isLeftSquareCorner=function(e){return e.type&t.blockRendering.Types.LEFT_SQUARE_CORNER},t.blockRendering.Types.isRightSquareCorner=function(e){return e.type&t.blockRendering.Types.RIGHT_SQUARE_CORNER},t.blockRendering.Types.isCorner=function(e){return e.type&t.blockRendering.Types.CORNER},t.blockRendering.Types.isJaggedEdge=function(e){return e.type&t.blockRendering.Types.JAGGED_EDGE},t.blockRendering.Types.isRow=function(e){return e.type&t.blockRendering.Types.ROW},t.blockRendering.Types.isBetweenRowSpacer=function(e){return e.type&t.blockRendering.Types.BETWEEN_ROW_SPACER},t.blockRendering.Types.isTopRow=function(e){return e.type&t.blockRendering.Types.TOP_ROW},t.blockRendering.Types.isBottomRow=function(e){return e.type&t.blockRendering.Types.BOTTOM_ROW},t.blockRendering.Types.isTopOrBottomRow=function(e){return e.type&(t.blockRendering.Types.TOP_ROW|t.blockRendering.Types.BOTTOM_ROW)},t.blockRendering.Types.isInputRow=function(e){return e.type&t.blockRendering.Types.INPUT_ROW},t.blockRendering.Measurable=function(e){this.height=this.width=0,this.type=t.blockRendering.Types.NONE,this.centerline=this.xPos=0,this.constants_=e,this.notchOffset=this.constants_.NOTCH_OFFSET_LEFT},t.blockRendering.Connection=function(e,o){t.blockRendering.Connection.superClass_.constructor.call(this,e),this.connectionModel=o,this.shape=this.constants_.shapeFor(o),this.isDynamicShape=!!this.shape.isDynamic,this.type|=t.blockRendering.Types.CONNECTION},t.utils.object.inherits(t.blockRendering.Connection,t.blockRendering.Measurable),t.blockRendering.OutputConnection=function(e,o){t.blockRendering.OutputConnection.superClass_.constructor.call(this,e,o),this.type|=t.blockRendering.Types.OUTPUT_CONNECTION,this.height=this.isDynamicShape?0:this.shape.height,this.startX=this.width=this.isDynamicShape?0:this.shape.width,this.connectionOffsetY=this.constants_.TAB_OFFSET_FROM_TOP,this.connectionOffsetX=0},t.utils.object.inherits(t.blockRendering.OutputConnection,t.blockRendering.Connection),t.blockRendering.PreviousConnection=function(e,o){t.blockRendering.PreviousConnection.superClass_.constructor.call(this,e,o),this.type|=t.blockRendering.Types.PREVIOUS_CONNECTION,this.height=this.shape.height,this.width=this.shape.width},t.utils.object.inherits(t.blockRendering.PreviousConnection,t.blockRendering.Connection),t.blockRendering.NextConnection=function(e,o){t.blockRendering.NextConnection.superClass_.constructor.call(this,e,o),this.type|=t.blockRendering.Types.NEXT_CONNECTION,this.height=this.shape.height,this.width=this.shape.width},t.utils.object.inherits(t.blockRendering.NextConnection,t.blockRendering.Connection),t.blockRendering.InputConnection=function(e,o){t.blockRendering.InputConnection.superClass_.constructor.call(this,e,o.connection),this.type|=t.blockRendering.Types.INPUT,this.input=o,this.align=o.align,(this.connectedBlock=o.connection&&o.connection.targetBlock()?o.connection.targetBlock():null)?(e=this.connectedBlock.getHeightWidth(),this.connectedBlockWidth=e.width,this.connectedBlockHeight=e.height):this.connectedBlockHeight=this.connectedBlockWidth=0,this.connectionOffsetY=this.connectionOffsetX=0},t.utils.object.inherits(t.blockRendering.InputConnection,t.blockRendering.Connection),t.blockRendering.InlineInput=function(e,o){t.blockRendering.InlineInput.superClass_.constructor.call(this,e,o),this.type|=t.blockRendering.Types.INLINE_INPUT,this.connectedBlock?(this.width=this.connectedBlockWidth,this.height=this.connectedBlockHeight):(this.height=this.constants_.EMPTY_INLINE_INPUT_HEIGHT,this.width=this.constants_.EMPTY_INLINE_INPUT_PADDING),this.connectionHeight=this.isDynamicShape?this.shape.height(this.height):this.shape.height,this.connectionWidth=this.isDynamicShape?this.shape.width(this.height):this.shape.width,this.connectedBlock||(this.width+=this.connectionWidth*(this.isDynamicShape?2:1)),this.connectionOffsetY=this.isDynamicShape?this.shape.connectionOffsetY(this.connectionHeight):this.constants_.TAB_OFFSET_FROM_TOP,this.connectionOffsetX=this.isDynamicShape?this.shape.connectionOffsetX(this.connectionWidth):0},t.utils.object.inherits(t.blockRendering.InlineInput,t.blockRendering.InputConnection),t.blockRendering.StatementInput=function(e,o){t.blockRendering.StatementInput.superClass_.constructor.call(this,e,o),this.type|=t.blockRendering.Types.STATEMENT_INPUT,this.height=this.connectedBlock?this.connectedBlockHeight+this.constants_.STATEMENT_BOTTOM_SPACER:this.constants_.EMPTY_STATEMENT_INPUT_HEIGHT,this.width=this.constants_.STATEMENT_INPUT_NOTCH_OFFSET+this.shape.width},t.utils.object.inherits(t.blockRendering.StatementInput,t.blockRendering.InputConnection),t.blockRendering.ExternalValueInput=function(e,o){t.blockRendering.ExternalValueInput.superClass_.constructor.call(this,e,o),this.type|=t.blockRendering.Types.EXTERNAL_VALUE_INPUT,this.height=this.connectedBlock?this.connectedBlockHeight-this.constants_.TAB_OFFSET_FROM_TOP-this.constants_.MEDIUM_PADDING:this.shape.height,this.width=this.shape.width+this.constants_.EXTERNAL_VALUE_INPUT_PADDING,this.connectionOffsetY=this.constants_.TAB_OFFSET_FROM_TOP,this.connectionHeight=this.shape.height,this.connectionWidth=this.shape.width},t.utils.object.inherits(t.blockRendering.ExternalValueInput,t.blockRendering.InputConnection),t.blockRendering.Icon=function(e,o){t.blockRendering.Icon.superClass_.constructor.call(this,e),this.icon=o,this.isVisible=o.isVisible(),this.type|=t.blockRendering.Types.ICON,e=o.getCorrectedSize(),this.height=e.height,this.width=e.width},t.utils.object.inherits(t.blockRendering.Icon,t.blockRendering.Measurable),t.blockRendering.JaggedEdge=function(e){t.blockRendering.JaggedEdge.superClass_.constructor.call(this,e),this.type|=t.blockRendering.Types.JAGGED_EDGE,this.height=this.constants_.JAGGED_TEETH.height,this.width=this.constants_.JAGGED_TEETH.width},t.utils.object.inherits(t.blockRendering.JaggedEdge,t.blockRendering.Measurable),t.blockRendering.Field=function(e,o,i){t.blockRendering.Field.superClass_.constructor.call(this,e),this.field=o,this.isEditable=o.EDITABLE,this.flipRtl=o.getFlipRtl(),this.type|=t.blockRendering.Types.FIELD,e=this.field.getSize(),this.height=e.height,this.width=e.width,this.parentInput=i},t.utils.object.inherits(t.blockRendering.Field,t.blockRendering.Measurable),t.blockRendering.Hat=function(e){t.blockRendering.Hat.superClass_.constructor.call(this,e),this.type|=t.blockRendering.Types.HAT,this.height=this.constants_.START_HAT.height,this.width=this.constants_.START_HAT.width,this.ascenderHeight=this.height},t.utils.object.inherits(t.blockRendering.Hat,t.blockRendering.Measurable),t.blockRendering.SquareCorner=function(e,o){t.blockRendering.SquareCorner.superClass_.constructor.call(this,e),this.type=(o&&"left"!=o?t.blockRendering.Types.RIGHT_SQUARE_CORNER:t.blockRendering.Types.LEFT_SQUARE_CORNER)|t.blockRendering.Types.CORNER,this.width=this.height=this.constants_.NO_PADDING},t.utils.object.inherits(t.blockRendering.SquareCorner,t.blockRendering.Measurable),t.blockRendering.RoundCorner=function(e,o){t.blockRendering.RoundCorner.superClass_.constructor.call(this,e),this.type=(o&&"left"!=o?t.blockRendering.Types.RIGHT_ROUND_CORNER:t.blockRendering.Types.LEFT_ROUND_CORNER)|t.blockRendering.Types.CORNER,this.width=this.constants_.CORNER_RADIUS,this.height=this.constants_.CORNER_RADIUS/2},t.utils.object.inherits(t.blockRendering.RoundCorner,t.blockRendering.Measurable),t.blockRendering.InRowSpacer=function(e,o){t.blockRendering.InRowSpacer.superClass_.constructor.call(this,e),this.type=this.type|t.blockRendering.Types.SPACER|t.blockRendering.Types.IN_ROW_SPACER,this.width=o,this.height=this.constants_.SPACER_DEFAULT_HEIGHT},t.utils.object.inherits(t.blockRendering.InRowSpacer,t.blockRendering.Measurable),t.blockRendering.Row=function(e){this.type=t.blockRendering.Types.ROW,this.elements=[],this.xPos=this.yPos=this.widthWithConnectedBlocks=this.minWidth=this.minHeight=this.width=this.height=0,this.hasJaggedEdge=this.hasDummyInput=this.hasInlineInput=this.hasStatement=this.hasExternalInput=!1,this.constants_=e,this.notchOffset=this.constants_.NOTCH_OFFSET_LEFT,this.align=null},t.blockRendering.Row.prototype.measure=function(){throw Error("Unexpected attempt to measure a base Row.")},t.blockRendering.Row.prototype.getLastInput=function(){for(var e,o=this.elements.length-1;e=this.elements[o];o--)if(t.blockRendering.Types.isInput(e))return e;return null},t.blockRendering.Row.prototype.startsWithElemSpacer=function(){return!0},t.blockRendering.Row.prototype.endsWithElemSpacer=function(){return!0},t.blockRendering.Row.prototype.getFirstSpacer=function(){for(var e,o=0;e=this.elements[o];o++)if(t.blockRendering.Types.isSpacer(e))return e;return null},t.blockRendering.Row.prototype.getLastSpacer=function(){for(var e,o=this.elements.length-1;e=this.elements[o];o--)if(t.blockRendering.Types.isSpacer(e))return e;return null},t.blockRendering.TopRow=function(e){t.blockRendering.TopRow.superClass_.constructor.call(this,e),this.type|=t.blockRendering.Types.TOP_ROW,this.ascenderHeight=this.capline=0,this.hasPreviousConnection=!1,this.connection=null},t.utils.object.inherits(t.blockRendering.TopRow,t.blockRendering.Row),t.blockRendering.TopRow.prototype.hasLeftSquareCorner=function(t){var e=(t.hat?"cap"===t.hat:this.constants_.ADD_START_HATS)&&!t.outputConnection&&!t.previousConnection,o=t.getPreviousBlock();return!!t.outputConnection||e||!!o&&o.getNextBlock()==t},t.blockRendering.TopRow.prototype.hasRightSquareCorner=function(t){return!0},t.blockRendering.TopRow.prototype.measure=function(){for(var e,o=0,i=0,n=0,s=0;e=this.elements[s];s++)i+=e.width,t.blockRendering.Types.isSpacer(e)||(t.blockRendering.Types.isHat(e)?n=Math.max(n,e.ascenderHeight):o=Math.max(o,e.height));this.width=Math.max(this.minWidth,i),this.height=Math.max(this.minHeight,o)+n,this.capline=this.ascenderHeight=n,this.widthWithConnectedBlocks=this.width},t.blockRendering.TopRow.prototype.startsWithElemSpacer=function(){return!1},t.blockRendering.TopRow.prototype.endsWithElemSpacer=function(){return!1},t.blockRendering.BottomRow=function(e){t.blockRendering.BottomRow.superClass_.constructor.call(this,e),this.type|=t.blockRendering.Types.BOTTOM_ROW,this.hasNextConnection=!1,this.connection=null,this.baseline=this.descenderHeight=0},t.utils.object.inherits(t.blockRendering.BottomRow,t.blockRendering.Row),t.blockRendering.BottomRow.prototype.hasLeftSquareCorner=function(t){return!!t.outputConnection||!!t.getNextBlock()},t.blockRendering.BottomRow.prototype.hasRightSquareCorner=function(t){return!0},t.blockRendering.BottomRow.prototype.measure=function(){for(var e,o=0,i=0,n=0,s=0;e=this.elements[s];s++)i+=e.width,t.blockRendering.Types.isSpacer(e)||(t.blockRendering.Types.isNextConnection(e)?n=Math.max(n,e.height):o=Math.max(o,e.height));this.width=Math.max(this.minWidth,i),this.height=Math.max(this.minHeight,o)+n,this.descenderHeight=n,this.widthWithConnectedBlocks=this.width},t.blockRendering.BottomRow.prototype.startsWithElemSpacer=function(){return!1},t.blockRendering.BottomRow.prototype.endsWithElemSpacer=function(){return!1},t.blockRendering.SpacerRow=function(e,o,i){t.blockRendering.SpacerRow.superClass_.constructor.call(this,e),this.type=this.type|t.blockRendering.Types.SPACER|t.blockRendering.Types.BETWEEN_ROW_SPACER,this.width=i,this.height=o,this.followsStatement=!1,this.widthWithConnectedBlocks=0,this.elements=[new t.blockRendering.InRowSpacer(this.constants_,i)]},t.utils.object.inherits(t.blockRendering.SpacerRow,t.blockRendering.Row),t.blockRendering.SpacerRow.prototype.measure=function(){},t.blockRendering.InputRow=function(e){t.blockRendering.InputRow.superClass_.constructor.call(this,e),this.type|=t.blockRendering.Types.INPUT_ROW,this.connectedBlockWidths=0},t.utils.object.inherits(t.blockRendering.InputRow,t.blockRendering.Row),t.blockRendering.InputRow.prototype.measure=function(){this.width=this.minWidth,this.height=this.minHeight;for(var e,o=0,i=0;e=this.elements[i];i++)this.width+=e.width,t.blockRendering.Types.isInput(e)&&(t.blockRendering.Types.isStatementInput(e)?o+=e.connectedBlockWidth:t.blockRendering.Types.isExternalInput(e)&&0!=e.connectedBlockWidth&&(o+=e.connectedBlockWidth-e.connectionWidth)),t.blockRendering.Types.isSpacer(e)||(this.height=Math.max(this.height,e.height));this.connectedBlockWidths=o,this.widthWithConnectedBlocks=this.width+o},t.blockRendering.InputRow.prototype.endsWithElemSpacer=function(){return!this.hasExternalInput&&!this.hasStatement},t.blockRendering.RenderInfo=function(e,o){this.block_=o,this.renderer_=e,this.constants_=this.renderer_.getConstants(),this.outputConnection=o.outputConnection?new t.blockRendering.OutputConnection(this.constants_,o.outputConnection):null,this.isInline=o.getInputsInline()&&!o.isCollapsed(),this.isCollapsed=o.isCollapsed(),this.isInsertionMarker=o.isInsertionMarker(),this.RTL=o.RTL,this.statementEdge=this.width=this.widthWithChildren=this.height=0,this.rows=[],this.inputRows=[],this.hiddenIcons=[],this.topRow=new t.blockRendering.TopRow(this.constants_),this.bottomRow=new t.blockRendering.BottomRow(this.constants_),this.startY=this.startX=0},t.blockRendering.RenderInfo.prototype.getRenderer=function(){return this.renderer_},t.blockRendering.RenderInfo.prototype.measure=function(){this.createRows_(),this.addElemSpacing_(),this.addRowSpacing_(),this.computeBounds_(),this.alignRowElements_(),this.finalize_()},t.blockRendering.RenderInfo.prototype.createRows_=function(){this.populateTopRow_(),this.rows.push(this.topRow);var e=new t.blockRendering.InputRow(this.constants_);this.inputRows.push(e);var o=this.block_.getIcons();if(o.length)for(var i,n=0;i=o[n];n++){var s=new t.blockRendering.Icon(this.constants_,i);this.isCollapsed&&i.collapseHidden?this.hiddenIcons.push(s):e.elements.push(s)}for(i=null,n=0;o=this.block_.inputList[n];n++)if(o.isVisible()){for(this.shouldStartNewRow_(o,i)&&(this.rows.push(e),e=new t.blockRendering.InputRow(this.constants_),this.inputRows.push(e)),i=0;s=o.fieldRow[i];i++)e.elements.push(new t.blockRendering.Field(this.constants_,s,o));this.addInput_(o,e),i=o}this.isCollapsed&&(e.hasJaggedEdge=!0,e.elements.push(new t.blockRendering.JaggedEdge(this.constants_))),(e.elements.length||e.hasDummyInput)&&this.rows.push(e),this.populateBottomRow_(),this.rows.push(this.bottomRow)},t.blockRendering.RenderInfo.prototype.populateTopRow_=function(){var e=!!this.block_.previousConnection,o=(this.block_.hat?"cap"===this.block_.hat:this.constants_.ADD_START_HATS)&&!this.outputConnection&&!e;this.topRow.hasLeftSquareCorner(this.block_)?this.topRow.elements.push(new t.blockRendering.SquareCorner(this.constants_)):this.topRow.elements.push(new t.blockRendering.RoundCorner(this.constants_)),o?(e=new t.blockRendering.Hat(this.constants_),this.topRow.elements.push(e),this.topRow.capline=e.ascenderHeight):e&&(this.topRow.hasPreviousConnection=!0,this.topRow.connection=new t.blockRendering.PreviousConnection(this.constants_,this.block_.previousConnection),this.topRow.elements.push(this.topRow.connection)),this.block_.inputList.length&&this.block_.inputList[0].type==t.NEXT_STATEMENT&&!this.block_.isCollapsed()?this.topRow.minHeight=this.constants_.TOP_ROW_PRECEDES_STATEMENT_MIN_HEIGHT:this.topRow.minHeight=this.constants_.TOP_ROW_MIN_HEIGHT,this.topRow.hasRightSquareCorner(this.block_)?this.topRow.elements.push(new t.blockRendering.SquareCorner(this.constants_,"right")):this.topRow.elements.push(new t.blockRendering.RoundCorner(this.constants_,"right"))},t.blockRendering.RenderInfo.prototype.populateBottomRow_=function(){this.bottomRow.hasNextConnection=!!this.block_.nextConnection,this.bottomRow.minHeight=this.block_.inputList.length&&this.block_.inputList[this.block_.inputList.length-1].type==t.NEXT_STATEMENT?this.constants_.BOTTOM_ROW_AFTER_STATEMENT_MIN_HEIGHT:this.constants_.BOTTOM_ROW_MIN_HEIGHT,this.bottomRow.hasLeftSquareCorner(this.block_)?this.bottomRow.elements.push(new t.blockRendering.SquareCorner(this.constants_)):this.bottomRow.elements.push(new t.blockRendering.RoundCorner(this.constants_)),this.bottomRow.hasNextConnection&&(this.bottomRow.connection=new t.blockRendering.NextConnection(this.constants_,this.block_.nextConnection),this.bottomRow.elements.push(this.bottomRow.connection)),this.bottomRow.hasRightSquareCorner(this.block_)?this.bottomRow.elements.push(new t.blockRendering.SquareCorner(this.constants_,"right")):this.bottomRow.elements.push(new t.blockRendering.RoundCorner(this.constants_,"right"))},t.blockRendering.RenderInfo.prototype.addInput_=function(e,o){this.isInline&&e.type==t.INPUT_VALUE?(o.elements.push(new t.blockRendering.InlineInput(this.constants_,e)),o.hasInlineInput=!0):e.type==t.NEXT_STATEMENT?(o.elements.push(new t.blockRendering.StatementInput(this.constants_,e)),o.hasStatement=!0):e.type==t.INPUT_VALUE?(o.elements.push(new t.blockRendering.ExternalValueInput(this.constants_,e)),o.hasExternalInput=!0):e.type==t.DUMMY_INPUT&&(o.minHeight=Math.max(o.minHeight,e.getSourceBlock()&&e.getSourceBlock().isShadow()?this.constants_.DUMMY_INPUT_SHADOW_MIN_HEIGHT:this.constants_.DUMMY_INPUT_MIN_HEIGHT),o.hasDummyInput=!0),null==o.align&&(o.align=e.align)},t.blockRendering.RenderInfo.prototype.shouldStartNewRow_=function(e,o){return!(!o||e.type!=t.NEXT_STATEMENT&&o.type!=t.NEXT_STATEMENT&&(e.type!=t.INPUT_VALUE&&e.type!=t.DUMMY_INPUT||this.isInline))},t.blockRendering.RenderInfo.prototype.addElemSpacing_=function(){for(var e,o=0;e=this.rows[o];o++){var i=e.elements;if(e.elements=[],e.startsWithElemSpacer()&&e.elements.push(new t.blockRendering.InRowSpacer(this.constants_,this.getInRowSpacing_(null,i[0]))),i.length){for(var n=0;n.blocklyPathLight,",e+" .blocklyInsertionMarker>.blocklyPathDark {","fill-opacity: "+this.INSERTION_MARKER_OPACITY+";","stroke: none","}"])},t.geras.Highlighter=function(t){this.info_=t,this.inlineSteps_=this.steps_="",this.RTL_=this.info_.RTL,t=t.getRenderer(),this.constants_=t.getConstants(),this.highlightConstants_=t.getHighlightConstants(),this.highlightOffset_=this.highlightConstants_.OFFSET,this.outsideCornerPaths_=this.highlightConstants_.OUTSIDE_CORNER,this.insideCornerPaths_=this.highlightConstants_.INSIDE_CORNER,this.puzzleTabPaths_=this.highlightConstants_.PUZZLE_TAB,this.notchPaths_=this.highlightConstants_.NOTCH,this.startPaths_=this.highlightConstants_.START_HAT,this.jaggedTeethPaths_=this.highlightConstants_.JAGGED_TEETH},t.geras.Highlighter.prototype.getPath=function(){return this.steps_+"\n"+this.inlineSteps_},t.geras.Highlighter.prototype.drawTopCorner=function(e){this.steps_+=t.utils.svgPaths.moveBy(e.xPos,this.info_.startY);for(var o,i=0;o=e.elements[i];i++)t.blockRendering.Types.isLeftSquareCorner(o)?this.steps_+=this.highlightConstants_.START_POINT:t.blockRendering.Types.isLeftRoundedCorner(o)?this.steps_+=this.outsideCornerPaths_.topLeft(this.RTL_):t.blockRendering.Types.isPreviousConnection(o)?this.steps_+=this.notchPaths_.pathLeft:t.blockRendering.Types.isHat(o)?this.steps_+=this.startPaths_.path(this.RTL_):t.blockRendering.Types.isSpacer(o)&&0!=o.width&&(this.steps_+=t.utils.svgPaths.lineOnAxis("H",o.xPos+o.width-this.highlightOffset_));this.steps_+=t.utils.svgPaths.lineOnAxis("H",e.xPos+e.width-this.highlightOffset_)},t.geras.Highlighter.prototype.drawJaggedEdge_=function(e){this.info_.RTL&&(this.steps_+=this.jaggedTeethPaths_.pathLeft+t.utils.svgPaths.lineOnAxis("v",e.height-this.jaggedTeethPaths_.height-this.highlightOffset_))},t.geras.Highlighter.prototype.drawValueInput=function(e){var o=e.getLastInput();if(this.RTL_){var i=e.height-o.connectionHeight;this.steps_+=t.utils.svgPaths.moveTo(o.xPos+o.width-this.highlightOffset_,e.yPos)+this.puzzleTabPaths_.pathDown(this.RTL_)+t.utils.svgPaths.lineOnAxis("v",i)}else this.steps_+=t.utils.svgPaths.moveTo(o.xPos+o.width,e.yPos)+this.puzzleTabPaths_.pathDown(this.RTL_)},t.geras.Highlighter.prototype.drawStatementInput=function(e){var o=e.getLastInput();if(this.RTL_){var i=e.height-2*this.insideCornerPaths_.height;this.steps_+=t.utils.svgPaths.moveTo(o.xPos,e.yPos)+this.insideCornerPaths_.pathTop(this.RTL_)+t.utils.svgPaths.lineOnAxis("v",i)+this.insideCornerPaths_.pathBottom(this.RTL_)+t.utils.svgPaths.lineTo(e.width-o.xPos-this.insideCornerPaths_.width,0)}else this.steps_+=t.utils.svgPaths.moveTo(o.xPos,e.yPos+e.height)+this.insideCornerPaths_.pathBottom(this.RTL_)+t.utils.svgPaths.lineTo(e.width-o.xPos-this.insideCornerPaths_.width,0)},t.geras.Highlighter.prototype.drawRightSideRow=function(e){var o=e.xPos+e.width-this.highlightOffset_;e.followsStatement&&(this.steps_+=t.utils.svgPaths.lineOnAxis("H",o)),this.RTL_&&(this.steps_+=t.utils.svgPaths.lineOnAxis("H",o),e.height>this.highlightOffset_&&(this.steps_+=t.utils.svgPaths.lineOnAxis("V",e.yPos+e.height-this.highlightOffset_)))},t.geras.Highlighter.prototype.drawBottomRow=function(e){if(this.RTL_)this.steps_+=t.utils.svgPaths.lineOnAxis("V",e.baseline-this.highlightOffset_);else{var o=this.info_.bottomRow.elements[0];t.blockRendering.Types.isLeftSquareCorner(o)?this.steps_+=t.utils.svgPaths.moveTo(e.xPos+this.highlightOffset_,e.baseline-this.highlightOffset_):t.blockRendering.Types.isLeftRoundedCorner(o)&&(this.steps_+=t.utils.svgPaths.moveTo(e.xPos,e.baseline),this.steps_+=this.outsideCornerPaths_.bottomLeft())}},t.geras.Highlighter.prototype.drawLeft=function(){var e=this.info_.outputConnection;e&&(e=e.connectionOffsetY+e.height,this.RTL_?this.steps_+=t.utils.svgPaths.moveTo(this.info_.startX,e):(this.steps_+=t.utils.svgPaths.moveTo(this.info_.startX+this.highlightOffset_,this.info_.bottomRow.baseline-this.highlightOffset_),this.steps_+=t.utils.svgPaths.lineOnAxis("V",e)),this.steps_+=this.puzzleTabPaths_.pathUp(this.RTL_)),this.RTL_||(e=this.info_.topRow,t.blockRendering.Types.isLeftRoundedCorner(e.elements[0])?this.steps_+=t.utils.svgPaths.lineOnAxis("V",this.outsideCornerPaths_.height):this.steps_+=t.utils.svgPaths.lineOnAxis("V",e.capline+this.highlightOffset_))},t.geras.Highlighter.prototype.drawInlineInput=function(e){var o=this.highlightOffset_,i=e.xPos+e.connectionWidth,n=e.centerline-e.height/2,s=e.width-e.connectionWidth,r=n+o;this.RTL_?(n=e.connectionOffsetY-o,e=e.height-(e.connectionOffsetY+e.connectionHeight)+o,this.inlineSteps_+=t.utils.svgPaths.moveTo(i-o,r)+t.utils.svgPaths.lineOnAxis("v",n)+this.puzzleTabPaths_.pathDown(this.RTL_)+t.utils.svgPaths.lineOnAxis("v",e)+t.utils.svgPaths.lineOnAxis("h",s)):this.inlineSteps_+=t.utils.svgPaths.moveTo(e.xPos+e.width+o,r)+t.utils.svgPaths.lineOnAxis("v",e.height)+t.utils.svgPaths.lineOnAxis("h",-s)+t.utils.svgPaths.moveTo(i,n+e.connectionOffsetY)+this.puzzleTabPaths_.pathDown(this.RTL_)},t.geras.InlineInput=function(e,o){t.geras.InlineInput.superClass_.constructor.call(this,e,o),this.connectedBlock&&(this.width+=this.constants_.DARK_PATH_OFFSET,this.height+=this.constants_.DARK_PATH_OFFSET)},t.utils.object.inherits(t.geras.InlineInput,t.blockRendering.InlineInput),t.geras.StatementInput=function(e,o){t.geras.StatementInput.superClass_.constructor.call(this,e,o),this.connectedBlock&&(this.height+=this.constants_.DARK_PATH_OFFSET)},t.utils.object.inherits(t.geras.StatementInput,t.blockRendering.StatementInput),t.geras.RenderInfo=function(e,o){t.geras.RenderInfo.superClass_.constructor.call(this,e,o)},t.utils.object.inherits(t.geras.RenderInfo,t.blockRendering.RenderInfo),t.geras.RenderInfo.prototype.getRenderer=function(){return this.renderer_},t.geras.RenderInfo.prototype.populateBottomRow_=function(){t.geras.RenderInfo.superClass_.populateBottomRow_.call(this),this.block_.inputList.length&&this.block_.inputList[this.block_.inputList.length-1].type==t.NEXT_STATEMENT||(this.bottomRow.minHeight=this.constants_.MEDIUM_PADDING-this.constants_.DARK_PATH_OFFSET)},t.geras.RenderInfo.prototype.addInput_=function(e,o){this.isInline&&e.type==t.INPUT_VALUE?(o.elements.push(new t.geras.InlineInput(this.constants_,e)),o.hasInlineInput=!0):e.type==t.NEXT_STATEMENT?(o.elements.push(new t.geras.StatementInput(this.constants_,e)),o.hasStatement=!0):e.type==t.INPUT_VALUE?(o.elements.push(new t.blockRendering.ExternalValueInput(this.constants_,e)),o.hasExternalInput=!0):e.type==t.DUMMY_INPUT&&(o.minHeight=Math.max(o.minHeight,this.constants_.DUMMY_INPUT_MIN_HEIGHT),o.hasDummyInput=!0),this.isInline||null!=o.align||(o.align=e.align)},t.geras.RenderInfo.prototype.addElemSpacing_=function(){for(var e,o=!1,i=0;e=this.rows[i];i++)e.hasExternalInput&&(o=!0);for(i=0;e=this.rows[i];i++){var n=e.elements;if(e.elements=[],e.startsWithElemSpacer()&&e.elements.push(new t.blockRendering.InRowSpacer(this.constants_,this.getInRowSpacing_(null,n[0]))),n.length){for(var s=0;so?o:s,n=n?-1:1,e=(i?-1:1)*e/2,t.utils.svgPaths.lineTo(-n*s,e)+t.utils.svgPaths.lineTo(n*s,e)}var o=this.MAX_DYNAMIC_CONNECTION_SHAPE_WIDTH;return{type:this.SHAPES.HEXAGONAL,isDynamic:!0,width:function(t){return(t/=2)>o?o:t},height:function(t){return t},connectionOffsetY:function(t){return t/2},connectionOffsetX:function(t){return-t},pathDown:function(t){return e(t,!1,!1)},pathUp:function(t){return e(t,!0,!1)},pathRightDown:function(t){return e(t,!1,!0)},pathRightUp:function(t){return e(t,!1,!0)}}},t.zelos.ConstantProvider.prototype.makeRounded=function(){function e(e,o,n){var s=e>i?e-i:0;return e=(e>i?i:e)/2,t.utils.svgPaths.arc("a","0 0,1",e,t.utils.svgPaths.point((o?-1:1)*e,(o?-1:1)*e))+t.utils.svgPaths.lineOnAxis("v",(n?1:-1)*s)+t.utils.svgPaths.arc("a","0 0,1",e,t.utils.svgPaths.point((o?1:-1)*e,(o?-1:1)*e))}var o=this.MAX_DYNAMIC_CONNECTION_SHAPE_WIDTH,i=2*o;return{type:this.SHAPES.ROUND,isDynamic:!0,width:function(t){return(t/=2)>o?o:t},height:function(t){return t},connectionOffsetY:function(t){return t/2},connectionOffsetX:function(t){return-t},pathDown:function(t){return e(t,!1,!1)},pathUp:function(t){return e(t,!0,!1)},pathRightDown:function(t){return e(t,!1,!0)},pathRightUp:function(t){return e(t,!1,!0)}}},t.zelos.ConstantProvider.prototype.makeSquared=function(){function e(e,i,n){return e-=2*o,t.utils.svgPaths.arc("a","0 0,1",o,t.utils.svgPaths.point((i?-1:1)*o,(i?-1:1)*o))+t.utils.svgPaths.lineOnAxis("v",(n?1:-1)*e)+t.utils.svgPaths.arc("a","0 0,1",o,t.utils.svgPaths.point((i?1:-1)*o,(i?-1:1)*o))}var o=this.CORNER_RADIUS;return{type:this.SHAPES.SQUARE,isDynamic:!0,width:function(t){return o},height:function(t){return t},connectionOffsetY:function(t){return t/2},connectionOffsetX:function(t){return-t},pathDown:function(t){return e(t,!1,!1)},pathUp:function(t){return e(t,!0,!1)},pathRightDown:function(t){return e(t,!1,!0)},pathRightUp:function(t){return e(t,!1,!0)}}},t.zelos.ConstantProvider.prototype.shapeFor=function(e){var o=e.getCheck();switch(!o&&e.targetConnection&&(o=e.targetConnection.getCheck()),e.type){case t.INPUT_VALUE:case t.OUTPUT_VALUE:if(null!=(e=e.getSourceBlock().getOutputShape()))switch(e){case this.SHAPES.HEXAGONAL:return this.HEXAGONAL;case this.SHAPES.ROUND:return this.ROUNDED;case this.SHAPES.SQUARE:return this.SQUARED}return o&&-1!=o.indexOf("Boolean")?this.HEXAGONAL:(o&&-1!=o.indexOf("Number")||o&&o.indexOf("String"),this.ROUNDED);case t.PREVIOUS_STATEMENT:case t.NEXT_STATEMENT:return this.NOTCH;default:throw Error("Unknown type")}},t.zelos.ConstantProvider.prototype.makeNotch=function(){function e(e){return t.utils.svgPaths.curve("c",[t.utils.svgPaths.point(e*s/2,0),t.utils.svgPaths.point(e*s*3/4,a/2),t.utils.svgPaths.point(e*s,a)])+t.utils.svgPaths.line([t.utils.svgPaths.point(e*s,r)])+t.utils.svgPaths.curve("c",[t.utils.svgPaths.point(e*s/4,a/2),t.utils.svgPaths.point(e*s/2,a),t.utils.svgPaths.point(e*s,a)])+t.utils.svgPaths.lineOnAxis("h",e*n)+t.utils.svgPaths.curve("c",[t.utils.svgPaths.point(e*s/2,0),t.utils.svgPaths.point(e*s*3/4,-a/2),t.utils.svgPaths.point(e*s,-a)])+t.utils.svgPaths.line([t.utils.svgPaths.point(e*s,-r)])+t.utils.svgPaths.curve("c",[t.utils.svgPaths.point(e*s/4,-a/2),t.utils.svgPaths.point(e*s/2,-a),t.utils.svgPaths.point(e*s,-a)])}var o=this.NOTCH_WIDTH,i=this.NOTCH_HEIGHT,n=o/3,s=n/3,r=i/2,a=r/2,l=e(1),c=e(-1);return{type:this.SHAPES.NOTCH,width:o,height:i,pathLeft:l,pathRight:c}},t.zelos.ConstantProvider.prototype.makeInsideCorners=function(){var e=this.CORNER_RADIUS,o=t.utils.svgPaths.arc("a","0 0,0",e,t.utils.svgPaths.point(-e,e)),i=t.utils.svgPaths.arc("a","0 0,1",e,t.utils.svgPaths.point(-e,e));return{width:e,height:e,pathTop:o,pathBottom:t.utils.svgPaths.arc("a","0 0,0",e,t.utils.svgPaths.point(e,e)),rightWidth:e,rightHeight:e,pathTopRight:i,pathBottomRight:t.utils.svgPaths.arc("a","0 0,1",e,t.utils.svgPaths.point(e,e))}},t.zelos.ConstantProvider.prototype.generateSecondaryColour_=function(e){return t.utils.colour.blend("#000",e,.15)||e},t.zelos.ConstantProvider.prototype.generateTertiaryColour_=function(e){return t.utils.colour.blend("#000",e,.25)||e},t.zelos.ConstantProvider.prototype.createDom=function(e,o,i){t.zelos.ConstantProvider.superClass_.createDom.call(this,e,o,i),e=t.utils.dom.createSvgElement("defs",{},e),o=t.utils.dom.createSvgElement("filter",{id:"blocklySelectedGlowFilter"+this.randomIdentifier,height:"160%",width:"180%",y:"-30%",x:"-40%"},e),t.utils.dom.createSvgElement("feGaussianBlur",{in:"SourceGraphic",stdDeviation:this.SELECTED_GLOW_SIZE},o),i=t.utils.dom.createSvgElement("feComponentTransfer",{result:"outBlur"},o),t.utils.dom.createSvgElement("feFuncA",{type:"table",tableValues:"0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"},i),t.utils.dom.createSvgElement("feFlood",{"flood-color":this.SELECTED_GLOW_COLOUR,"flood-opacity":1,result:"outColor"},o),t.utils.dom.createSvgElement("feComposite",{in:"outColor",in2:"outBlur",operator:"in",result:"outGlow"},o),this.selectedGlowFilterId=o.id,this.selectedGlowFilter_=o,e=t.utils.dom.createSvgElement("filter",{id:"blocklyReplacementGlowFilter"+this.randomIdentifier,height:"160%",width:"180%",y:"-30%",x:"-40%"},e),t.utils.dom.createSvgElement("feGaussianBlur",{in:"SourceGraphic",stdDeviation:this.REPLACEMENT_GLOW_SIZE},e),o=t.utils.dom.createSvgElement("feComponentTransfer",{result:"outBlur"},e),t.utils.dom.createSvgElement("feFuncA",{type:"table",tableValues:"0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"},o),t.utils.dom.createSvgElement("feFlood",{"flood-color":this.REPLACEMENT_GLOW_COLOUR,"flood-opacity":1,result:"outColor"},e),t.utils.dom.createSvgElement("feComposite",{in:"outColor",in2:"outBlur",operator:"in",result:"outGlow"},e),t.utils.dom.createSvgElement("feComposite",{in:"SourceGraphic",in2:"outGlow",operator:"over"},e),this.replacementGlowFilterId=e.id,this.replacementGlowFilter_=e},t.zelos.ConstantProvider.prototype.getCSS_=function(t){return[t+" .blocklyText, ",t+" .blocklyFlyoutLabelText {","font-family: "+this.FIELD_TEXT_FONTFAMILY+";","font-size: "+this.FIELD_TEXT_FONTSIZE+"pt;","font-weight: "+this.FIELD_TEXT_FONTWEIGHT+";","}",t+" .blocklyText {","fill: #fff;","}",t+" .blocklyNonEditableText>rect:not(.blocklyDropdownRect),",t+" .blocklyEditableText>rect:not(.blocklyDropdownRect) {","fill: "+this.FIELD_BORDER_RECT_COLOUR+";","}",t+" .blocklyNonEditableText>text,",t+" .blocklyEditableText>text,",t+" .blocklyNonEditableText>g>text,",t+" .blocklyEditableText>g>text {","fill: #575E75;","}",t+" .blocklyFlyoutLabelText {","fill: #575E75;","}",t+" .blocklyText.blocklyBubbleText {","fill: #575E75;","}",t+" .blocklyDraggable:not(.blocklyDisabled)"," .blocklyEditableText:not(.editing):hover>rect ,",t+" .blocklyDraggable:not(.blocklyDisabled)"," .blocklyEditableText:not(.editing):hover>.blocklyPath {","stroke: #fff;","stroke-width: 2;","}",t+" .blocklyHtmlInput {","font-family: "+this.FIELD_TEXT_FONTFAMILY+";","font-weight: "+this.FIELD_TEXT_FONTWEIGHT+";","color: #575E75;","}",t+" .blocklyDropdownText {","fill: #fff !important;","}",t+".blocklyWidgetDiv .goog-menuitem,",t+".blocklyDropDownDiv .goog-menuitem {","font-family: "+this.FIELD_TEXT_FONTFAMILY+";","}",t+".blocklyDropDownDiv .goog-menuitem-content {","color: #fff;","}",t+" .blocklyHighlightedConnectionPath {","stroke: "+this.SELECTED_GLOW_COLOUR+";","}",t+" .blocklyDisabled > .blocklyOutlinePath {","fill: url(#blocklyDisabledPattern"+this.randomIdentifier+")","}",t+" .blocklyInsertionMarker>.blocklyPath {","fill-opacity: "+this.INSERTION_MARKER_OPACITY+";","stroke: none","}"]},t.zelos.TopRow=function(e){t.zelos.TopRow.superClass_.constructor.call(this,e)},t.utils.object.inherits(t.zelos.TopRow,t.blockRendering.TopRow),t.zelos.TopRow.prototype.endsWithElemSpacer=function(){return!1},t.zelos.TopRow.prototype.hasLeftSquareCorner=function(t){var e=(t.hat?"cap"===t.hat:this.constants_.ADD_START_HATS)&&!t.outputConnection&&!t.previousConnection;return!!t.outputConnection||e},t.zelos.TopRow.prototype.hasRightSquareCorner=function(t){return!!t.outputConnection&&!t.statementInputCount&&!t.nextConnection},t.zelos.BottomRow=function(e){t.zelos.BottomRow.superClass_.constructor.call(this,e)},t.utils.object.inherits(t.zelos.BottomRow,t.blockRendering.BottomRow),t.zelos.BottomRow.prototype.endsWithElemSpacer=function(){return!1},t.zelos.BottomRow.prototype.hasLeftSquareCorner=function(t){return!!t.outputConnection},t.zelos.BottomRow.prototype.hasRightSquareCorner=function(t){return!!t.outputConnection&&!t.statementInputCount&&!t.nextConnection},t.zelos.RightConnectionShape=function(e){t.zelos.RightConnectionShape.superClass_.constructor.call(this,e),this.type|=t.blockRendering.Types.getType("RIGHT_CONNECTION"),this.width=this.height=0},t.utils.object.inherits(t.zelos.RightConnectionShape,t.blockRendering.Measurable),t.zelos.StatementInput=function(e,o){if(t.zelos.StatementInput.superClass_.constructor.call(this,e,o),this.connectedBlock){for(e=this.connectedBlock;e.getNextBlock();)e=e.getNextBlock();e.nextConnection||(this.height=this.connectedBlockHeight,this.connectedBottomNextConnection=!0)}},t.utils.object.inherits(t.zelos.StatementInput,t.blockRendering.StatementInput),t.zelos.RenderInfo=function(e,o){t.zelos.RenderInfo.superClass_.constructor.call(this,e,o),this.topRow=new t.zelos.TopRow(this.constants_),this.bottomRow=new t.zelos.BottomRow(this.constants_),this.isInline=!0,this.isMultiRow=!o.getInputsInline()||o.isCollapsed(),this.hasStatementInput=0=this.rows.length-1?!!this.bottomRow.hasNextConnection:!!r.precedesStatement,t.blockRendering.Types.isInputRow(s)&&s.hasStatement)s.measure(),o=s.width-s.getLastInput().width+e;else if(n&&(2==i||r)&&t.blockRendering.Types.isInputRow(s)&&!s.hasStatement){r=s.xPos,n=null;for(var a,l=0;a=s.elements[l];l++)t.blockRendering.Types.isSpacer(a)&&(n=a),!(n&&(t.blockRendering.Types.isField(a)||t.blockRendering.Types.isInput(a))&&ri?i:this.height/2)*(1-Math.sin(Math.acos((i-this.constants_.SMALL_PADDING)/i)));default:return 0}if(t.blockRendering.Types.isInlineInput(e)){var s=e.connectedBlock;return e=s?s.pathObject.outputShapeType:e.shape.type,s&&s.outputConnection&&(s.statementInputCount||s.nextConnection)||i==n.SHAPES.HEXAGONAL&&i!=e?0:o-this.constants_.SHAPE_IN_SHAPE_PADDING[i][e]}return t.blockRendering.Types.isField(e)?i==n.SHAPES.ROUND&&e.field instanceof t.FieldTextInput?o-2.75*n.GRID_UNIT:o-this.constants_.SHAPE_IN_SHAPE_PADDING[i][0]:t.blockRendering.Types.isIcon(e)?this.constants_.SMALL_PADDING:0},t.zelos.RenderInfo.prototype.finalizeVerticalAlignment_=function(){if(!this.outputConnection)for(var e=2;e=this.rows.length-1?!!this.bottomRow.hasNextConnection:!!n.precedesStatement;if(s?this.topRow.hasPreviousConnection:o.followsStatement){var a=3==i.elements.length&&(i.elements[1].field instanceof t.FieldLabel||i.elements[1].field instanceof t.FieldImage);if(!s&&a)o.height-=this.constants_.SMALL_PADDING,n.height-=this.constants_.SMALL_PADDING,i.height-=this.constants_.MEDIUM_PADDING;else if(s||r){if(r){for(s=!1,r=0;a=i.elements[r];r++)if(t.blockRendering.Types.isInlineInput(a)&&a.connectedBlock&&!a.connectedBlock.isShadow()&&40<=a.connectedBlock.getHeightWidth().height){s=!0;break}s&&(o.height-=this.constants_.SMALL_PADDING,n.height-=this.constants_.SMALL_PADDING)}}else o.height+=this.constants_.SMALL_PADDING}}},t.zelos.RenderInfo.prototype.finalize_=function(){this.finalizeOutputConnection_(),this.finalizeHorizontalAlignment_(),this.finalizeVerticalAlignment_(),t.zelos.RenderInfo.superClass_.finalize_.call(this),this.rightSide&&(this.widthWithChildren+=this.rightSide.width)},t.zelos.Drawer=function(e,o){t.zelos.Drawer.superClass_.constructor.call(this,e,o)},t.utils.object.inherits(t.zelos.Drawer,t.blockRendering.Drawer),t.zelos.Drawer.prototype.draw=function(){var e=this.block_.pathObject;e.beginDrawing(),this.hideHiddenIcons_(),this.drawOutline_(),this.drawInternals_(),e.setPath(this.outlinePath_+"\n"+this.inlinePath_),this.info_.RTL&&e.flipRTL(),t.blockRendering.useDebugger&&this.block_.renderingDebugger.drawDebug(this.block_,this.info_),this.recordSizeOnBlock_(),this.info_.outputConnection&&(e.outputShapeType=this.info_.outputConnection.shape.type),e.endDrawing()},t.zelos.Drawer.prototype.drawOutline_=function(){this.info_.outputConnection&&this.info_.outputConnection.isDynamicShape&&!this.info_.hasStatementInput&&!this.info_.bottomRow.hasNextConnection?(this.drawFlatTop_(),this.drawRightDynamicConnection_(),this.drawFlatBottom_(),this.drawLeftDynamicConnection_()):t.zelos.Drawer.superClass_.drawOutline_.call(this)},t.zelos.Drawer.prototype.drawLeft_=function(){this.info_.outputConnection&&this.info_.outputConnection.isDynamicShape?this.drawLeftDynamicConnection_():t.zelos.Drawer.superClass_.drawLeft_.call(this)},t.zelos.Drawer.prototype.drawRightSideRow_=function(e){if(!(0>=e.height))if(e.precedesStatement||e.followsStatement){var o=this.constants_.INSIDE_CORNERS.rightHeight;o=e.height-(e.precedesStatement?o:0),this.outlinePath_+=(e.followsStatement?this.constants_.INSIDE_CORNERS.pathBottomRight:"")+(0","GT"],["‏≥","GTE"]]},{type:"input_value",name:"B"}],inputsInline:!0,output:"Boolean",style:"logic_blocks",helpUrl:"%{BKY_LOGIC_COMPARE_HELPURL}",extensions:["logic_compare","logic_op_tooltip"]},{type:"logic_operation",message0:"%1 %2 %3",args0:[{type:"input_value",name:"A",check:"Boolean"},{type:"field_dropdown",name:"OP",options:[["%{BKY_LOGIC_OPERATION_AND}","AND"],["%{BKY_LOGIC_OPERATION_OR}","OR"]]},{type:"input_value",name:"B",check:"Boolean"}],inputsInline:!0,output:"Boolean",style:"logic_blocks",helpUrl:"%{BKY_LOGIC_OPERATION_HELPURL}",extensions:["logic_op_tooltip"]},{type:"logic_negate",message0:"%{BKY_LOGIC_NEGATE_TITLE}",args0:[{type:"input_value",name:"BOOL",check:"Boolean"}],output:"Boolean",style:"logic_blocks",tooltip:"%{BKY_LOGIC_NEGATE_TOOLTIP}",helpUrl:"%{BKY_LOGIC_NEGATE_HELPURL}"},{type:"logic_null",message0:"%{BKY_LOGIC_NULL}",output:null,style:"logic_blocks",tooltip:"%{BKY_LOGIC_NULL_TOOLTIP}",helpUrl:"%{BKY_LOGIC_NULL_HELPURL}"},{type:"logic_ternary",message0:"%{BKY_LOGIC_TERNARY_CONDITION} %1",args0:[{type:"input_value",name:"IF",check:"Boolean"}],message1:"%{BKY_LOGIC_TERNARY_IF_TRUE} %1",args1:[{type:"input_value",name:"THEN"}],message2:"%{BKY_LOGIC_TERNARY_IF_FALSE} %1",args2:[{type:"input_value",name:"ELSE"}],output:null,style:"logic_blocks",tooltip:"%{BKY_LOGIC_TERNARY_TOOLTIP}",helpUrl:"%{BKY_LOGIC_TERNARY_HELPURL}",extensions:["logic_ternary"]}]),t.defineBlocksWithJsonArray([{type:"controls_if_if",message0:"%{BKY_CONTROLS_IF_IF_TITLE_IF}",nextStatement:null,enableContextMenu:!1,style:"logic_blocks",tooltip:"%{BKY_CONTROLS_IF_IF_TOOLTIP}"},{type:"controls_if_elseif",message0:"%{BKY_CONTROLS_IF_ELSEIF_TITLE_ELSEIF}",previousStatement:null,nextStatement:null,enableContextMenu:!1,style:"logic_blocks",tooltip:"%{BKY_CONTROLS_IF_ELSEIF_TOOLTIP}"},{type:"controls_if_else",message0:"%{BKY_CONTROLS_IF_ELSE_TITLE_ELSE}",previousStatement:null,enableContextMenu:!1,style:"logic_blocks",tooltip:"%{BKY_CONTROLS_IF_ELSE_TOOLTIP}"}]),t.Constants.Logic.TOOLTIPS_BY_OP={EQ:"%{BKY_LOGIC_COMPARE_TOOLTIP_EQ}",NEQ:"%{BKY_LOGIC_COMPARE_TOOLTIP_NEQ}",LT:"%{BKY_LOGIC_COMPARE_TOOLTIP_LT}",LTE:"%{BKY_LOGIC_COMPARE_TOOLTIP_LTE}",GT:"%{BKY_LOGIC_COMPARE_TOOLTIP_GT}",GTE:"%{BKY_LOGIC_COMPARE_TOOLTIP_GTE}",AND:"%{BKY_LOGIC_OPERATION_TOOLTIP_AND}",OR:"%{BKY_LOGIC_OPERATION_TOOLTIP_OR}"},t.Extensions.register("logic_op_tooltip",t.Extensions.buildTooltipForDropdown("OP",t.Constants.Logic.TOOLTIPS_BY_OP)),t.Constants.Logic.CONTROLS_IF_MUTATOR_MIXIN={elseifCount_:0,elseCount_:0,suppressPrefixSuffix:!0,mutationToDom:function(){if(!this.elseifCount_&&!this.elseCount_)return null;var e=t.utils.xml.createElement("mutation");return this.elseifCount_&&e.setAttribute("elseif",this.elseifCount_),this.elseCount_&&e.setAttribute("else",1),e},domToMutation:function(t){this.elseifCount_=parseInt(t.getAttribute("elseif"),10)||0,this.elseCount_=parseInt(t.getAttribute("else"),10)||0,this.rebuildShape_()},decompose:function(t){var e=t.newBlock("controls_if_if");e.initSvg();for(var o=e.nextConnection,i=1;i<=this.elseifCount_;i++){var n=t.newBlock("controls_if_elseif");n.initSvg(),o.connect(n.previousConnection),o=n.nextConnection}return this.elseCount_&&((t=t.newBlock("controls_if_else")).initSvg(),o.connect(t.previousConnection)),e},compose:function(t){t=t.nextConnection.targetBlock(),this.elseCount_=this.elseifCount_=0;for(var e=[null],o=[null],i=null;t;){switch(t.type){case"controls_if_elseif":this.elseifCount_++,e.push(t.valueConnection_),o.push(t.statementConnection_);break;case"controls_if_else":this.elseCount_++,i=t.statementConnection_;break;default:throw TypeError("Unknown block type: "+t.type)}t=t.nextConnection&&t.nextConnection.targetBlock()}this.updateShape_(),this.reconnectChildBlocks_(e,o,i)},saveConnections:function(t){t=t.nextConnection.targetBlock();for(var e=1;t;){switch(t.type){case"controls_if_elseif":var o=this.getInput("IF"+e),i=this.getInput("DO"+e);t.valueConnection_=o&&o.connection.targetConnection,t.statementConnection_=i&&i.connection.targetConnection,e++;break;case"controls_if_else":i=this.getInput("ELSE"),t.statementConnection_=i&&i.connection.targetConnection;break;default:throw TypeError("Unknown block type: "+t.type)}t=t.nextConnection&&t.nextConnection.targetBlock()}},rebuildShape_:function(){var t=[null],e=[null],o=null;this.getInput("ELSE")&&(o=this.getInput("ELSE").connection.targetConnection);for(var i=1;this.getInput("IF"+i);){var n=this.getInput("IF"+i),s=this.getInput("DO"+i);t.push(n.connection.targetConnection),e.push(s.connection.targetConnection),i++}this.updateShape_(),this.reconnectChildBlocks_(t,e,o)},updateShape_:function(){this.getInput("ELSE")&&this.removeInput("ELSE");for(var e=1;this.getInput("IF"+e);)this.removeInput("IF"+e),this.removeInput("DO"+e),e++;for(e=1;e<=this.elseifCount_;e++)this.appendValueInput("IF"+e).setCheck("Boolean").appendField(t.Msg.CONTROLS_IF_MSG_ELSEIF),this.appendStatementInput("DO"+e).appendField(t.Msg.CONTROLS_IF_MSG_THEN);this.elseCount_&&this.appendStatementInput("ELSE").appendField(t.Msg.CONTROLS_IF_MSG_ELSE)},reconnectChildBlocks_:function(e,o,i){for(var n=1;n<=this.elseifCount_;n++)t.Mutator.reconnect(e[n],this,"IF"+n),t.Mutator.reconnect(o[n],this,"DO"+n);t.Mutator.reconnect(i,this,"ELSE")}},t.Extensions.registerMutator("controls_if_mutator",t.Constants.Logic.CONTROLS_IF_MUTATOR_MIXIN,null,["controls_if_elseif","controls_if_else"]),t.Constants.Logic.CONTROLS_IF_TOOLTIP_EXTENSION=function(){this.setTooltip(function(){return this.elseifCount_||this.elseCount_?!this.elseifCount_&&this.elseCount_?t.Msg.CONTROLS_IF_TOOLTIP_2:this.elseifCount_&&!this.elseCount_?t.Msg.CONTROLS_IF_TOOLTIP_3:this.elseifCount_&&this.elseCount_?t.Msg.CONTROLS_IF_TOOLTIP_4:"":t.Msg.CONTROLS_IF_TOOLTIP_1}.bind(this))},t.Extensions.register("controls_if_tooltip",t.Constants.Logic.CONTROLS_IF_TOOLTIP_EXTENSION),t.Constants.Logic.LOGIC_COMPARE_ONCHANGE_MIXIN={onchange:function(e){this.prevBlocks_||(this.prevBlocks_=[null,null]);var o=this.getInputTargetBlock("A"),i=this.getInputTargetBlock("B");o&&i&&!o.outputConnection.checkType(i.outputConnection)&&(t.Events.setGroup(e.group),(e=this.prevBlocks_[0])!==o&&(o.unplug(),!e||e.isDisposed()||e.isShadow()||this.getInput("A").connection.connect(e.outputConnection)),(o=this.prevBlocks_[1])!==i&&(i.unplug(),!o||o.isDisposed()||o.isShadow()||this.getInput("B").connection.connect(o.outputConnection)),this.bumpNeighbours(),t.Events.setGroup(!1)),this.prevBlocks_[0]=this.getInputTargetBlock("A"),this.prevBlocks_[1]=this.getInputTargetBlock("B")}},t.Constants.Logic.LOGIC_COMPARE_EXTENSION=function(){this.mixin(t.Constants.Logic.LOGIC_COMPARE_ONCHANGE_MIXIN)},t.Extensions.register("logic_compare",t.Constants.Logic.LOGIC_COMPARE_EXTENSION),t.Constants.Logic.LOGIC_TERNARY_ONCHANGE_MIXIN={prevParentConnection_:null,onchange:function(e){var o=this.getInputTargetBlock("THEN"),i=this.getInputTargetBlock("ELSE"),n=this.outputConnection.targetConnection;if((o||i)&&n)for(var s=0;2>s;s++){var r=1==s?o:i;r&&!r.outputConnection.checkType(n)&&(t.Events.setGroup(e.group),n===this.prevParentConnection_?(this.unplug(),n.getSourceBlock().bumpNeighbours()):(r.unplug(),r.bumpNeighbours()),t.Events.setGroup(!1))}this.prevParentConnection_=n}},t.Extensions.registerMixin("logic_ternary",t.Constants.Logic.LOGIC_TERNARY_ONCHANGE_MIXIN),t.Blocks.loops={},t.Constants.Loops={},t.Constants.Loops.HUE=120,t.defineBlocksWithJsonArray([{type:"controls_repeat_ext",message0:"%{BKY_CONTROLS_REPEAT_TITLE}",args0:[{type:"input_value",name:"TIMES",check:"Number"}],message1:"%{BKY_CONTROLS_REPEAT_INPUT_DO} %1",args1:[{type:"input_statement",name:"DO"}],previousStatement:null,nextStatement:null,style:"loop_blocks",tooltip:"%{BKY_CONTROLS_REPEAT_TOOLTIP}",helpUrl:"%{BKY_CONTROLS_REPEAT_HELPURL}"},{type:"controls_repeat",message0:"%{BKY_CONTROLS_REPEAT_TITLE}",args0:[{type:"field_number",name:"TIMES",value:10,min:0,precision:1}],message1:"%{BKY_CONTROLS_REPEAT_INPUT_DO} %1",args1:[{type:"input_statement",name:"DO"}],previousStatement:null,nextStatement:null,style:"loop_blocks",tooltip:"%{BKY_CONTROLS_REPEAT_TOOLTIP}",helpUrl:"%{BKY_CONTROLS_REPEAT_HELPURL}"},{type:"controls_whileUntil",message0:"%1 %2",args0:[{type:"field_dropdown",name:"MODE",options:[["%{BKY_CONTROLS_WHILEUNTIL_OPERATOR_WHILE}","WHILE"],["%{BKY_CONTROLS_WHILEUNTIL_OPERATOR_UNTIL}","UNTIL"]]},{type:"input_value",name:"BOOL",check:"Boolean"}],message1:"%{BKY_CONTROLS_REPEAT_INPUT_DO} %1",args1:[{type:"input_statement",name:"DO"}],previousStatement:null,nextStatement:null,style:"loop_blocks",helpUrl:"%{BKY_CONTROLS_WHILEUNTIL_HELPURL}",extensions:["controls_whileUntil_tooltip"]},{type:"controls_for",message0:"%{BKY_CONTROLS_FOR_TITLE}",args0:[{type:"field_variable",name:"VAR",variable:null},{type:"input_value",name:"FROM",check:"Number",align:"RIGHT"},{type:"input_value",name:"TO",check:"Number",align:"RIGHT"},{type:"input_value",name:"BY",check:"Number",align:"RIGHT"}],message1:"%{BKY_CONTROLS_REPEAT_INPUT_DO} %1",args1:[{type:"input_statement",name:"DO"}],inputsInline:!0,previousStatement:null,nextStatement:null,style:"loop_blocks",helpUrl:"%{BKY_CONTROLS_FOR_HELPURL}",extensions:["contextMenu_newGetVariableBlock","controls_for_tooltip"]},{type:"controls_forEach",message0:"%{BKY_CONTROLS_FOREACH_TITLE}",args0:[{type:"field_variable",name:"VAR",variable:null},{type:"input_value",name:"LIST",check:"Array"}],message1:"%{BKY_CONTROLS_REPEAT_INPUT_DO} %1",args1:[{type:"input_statement",name:"DO"}],previousStatement:null,nextStatement:null,style:"loop_blocks",helpUrl:"%{BKY_CONTROLS_FOREACH_HELPURL}",extensions:["contextMenu_newGetVariableBlock","controls_forEach_tooltip"]},{type:"controls_flow_statements",message0:"%1",args0:[{type:"field_dropdown",name:"FLOW",options:[["%{BKY_CONTROLS_FLOW_STATEMENTS_OPERATOR_BREAK}","BREAK"],["%{BKY_CONTROLS_FLOW_STATEMENTS_OPERATOR_CONTINUE}","CONTINUE"]]}],previousStatement:null,style:"loop_blocks",helpUrl:"%{BKY_CONTROLS_FLOW_STATEMENTS_HELPURL}",extensions:["controls_flow_tooltip","controls_flow_in_loop_check"]}]),t.Constants.Loops.WHILE_UNTIL_TOOLTIPS={WHILE:"%{BKY_CONTROLS_WHILEUNTIL_TOOLTIP_WHILE}",UNTIL:"%{BKY_CONTROLS_WHILEUNTIL_TOOLTIP_UNTIL}"},t.Extensions.register("controls_whileUntil_tooltip",t.Extensions.buildTooltipForDropdown("MODE",t.Constants.Loops.WHILE_UNTIL_TOOLTIPS)),t.Constants.Loops.BREAK_CONTINUE_TOOLTIPS={BREAK:"%{BKY_CONTROLS_FLOW_STATEMENTS_TOOLTIP_BREAK}",CONTINUE:"%{BKY_CONTROLS_FLOW_STATEMENTS_TOOLTIP_CONTINUE}"},t.Extensions.register("controls_flow_tooltip",t.Extensions.buildTooltipForDropdown("FLOW",t.Constants.Loops.BREAK_CONTINUE_TOOLTIPS)),t.Constants.Loops.CUSTOM_CONTEXT_MENU_CREATE_VARIABLES_GET_MIXIN={customContextMenu:function(e){if(!this.isInFlyout){var o=this.getField("VAR").getVariable(),i=o.name;if(!this.isCollapsed()&&null!=i){var n={enabled:!0};n.text=t.Msg.VARIABLES_SET_CREATE_GET.replace("%1",i),o=t.Variables.generateVariableFieldDom(o),(i=t.utils.xml.createElement("block")).setAttribute("type","variables_get"),i.appendChild(o),n.callback=t.ContextMenu.callbackFactory(this,i),e.push(n)}}}},t.Extensions.registerMixin("contextMenu_newGetVariableBlock",t.Constants.Loops.CUSTOM_CONTEXT_MENU_CREATE_VARIABLES_GET_MIXIN),t.Extensions.register("controls_for_tooltip",t.Extensions.buildTooltipWithFieldText("%{BKY_CONTROLS_FOR_TOOLTIP}","VAR")),t.Extensions.register("controls_forEach_tooltip",t.Extensions.buildTooltipWithFieldText("%{BKY_CONTROLS_FOREACH_TOOLTIP}","VAR")),t.Constants.Loops.CONTROL_FLOW_IN_LOOP_CHECK_MIXIN={LOOP_TYPES:["controls_repeat","controls_repeat_ext","controls_forEach","controls_for","controls_whileUntil"],suppressPrefixSuffix:!0,getSurroundLoop:function(e){do{if(-1!=t.Constants.Loops.CONTROL_FLOW_IN_LOOP_CHECK_MIXIN.LOOP_TYPES.indexOf(e.type))return e;e=e.getSurroundParent()}while(e);return null},onchange:function(e){if(this.workspace.isDragging&&!this.workspace.isDragging()&&e.type==t.Events.BLOCK_MOVE&&e.blockId==this.id){var o=t.Constants.Loops.CONTROL_FLOW_IN_LOOP_CHECK_MIXIN.getSurroundLoop(this);if(this.setWarningText(o?null:t.Msg.CONTROLS_FLOW_STATEMENTS_WARNING),!this.isInFlyout){var i=t.Events.getGroup();t.Events.setGroup(e.group),this.setEnabled(o),t.Events.setGroup(i)}}}},t.Extensions.registerMixin("controls_flow_in_loop_check",t.Constants.Loops.CONTROL_FLOW_IN_LOOP_CHECK_MIXIN),t.Blocks.math={},t.Constants.Math={},t.Constants.Math.HUE=230,t.defineBlocksWithJsonArray([{type:"math_number",message0:"%1",args0:[{type:"field_number",name:"NUM",value:0}],output:"Number",helpUrl:"%{BKY_MATH_NUMBER_HELPURL}",style:"math_blocks",tooltip:"%{BKY_MATH_NUMBER_TOOLTIP}",extensions:["parent_tooltip_when_inline"]},{type:"math_arithmetic",message0:"%1 %2 %3",args0:[{type:"input_value",name:"A",check:"Number"},{type:"field_dropdown",name:"OP",options:[["%{BKY_MATH_ADDITION_SYMBOL}","ADD"],["%{BKY_MATH_SUBTRACTION_SYMBOL}","MINUS"],["%{BKY_MATH_MULTIPLICATION_SYMBOL}","MULTIPLY"],["%{BKY_MATH_DIVISION_SYMBOL}","DIVIDE"],["%{BKY_MATH_POWER_SYMBOL}","POWER"]]},{type:"input_value",name:"B",check:"Number"}],inputsInline:!0,output:"Number",style:"math_blocks",helpUrl:"%{BKY_MATH_ARITHMETIC_HELPURL}",extensions:["math_op_tooltip"]},{type:"math_single",message0:"%1 %2",args0:[{type:"field_dropdown",name:"OP",options:[["%{BKY_MATH_SINGLE_OP_ROOT}","ROOT"],["%{BKY_MATH_SINGLE_OP_ABSOLUTE}","ABS"],["-","NEG"],["ln","LN"],["log10","LOG10"],["e^","EXP"],["10^","POW10"]]},{type:"input_value",name:"NUM",check:"Number"}],output:"Number",style:"math_blocks",helpUrl:"%{BKY_MATH_SINGLE_HELPURL}",extensions:["math_op_tooltip"]},{type:"math_trig",message0:"%1 %2",args0:[{type:"field_dropdown",name:"OP",options:[["%{BKY_MATH_TRIG_SIN}","SIN"],["%{BKY_MATH_TRIG_COS}","COS"],["%{BKY_MATH_TRIG_TAN}","TAN"],["%{BKY_MATH_TRIG_ASIN}","ASIN"],["%{BKY_MATH_TRIG_ACOS}","ACOS"],["%{BKY_MATH_TRIG_ATAN}","ATAN"]]},{type:"input_value",name:"NUM",check:"Number"}],output:"Number",style:"math_blocks",helpUrl:"%{BKY_MATH_TRIG_HELPURL}",extensions:["math_op_tooltip"]},{type:"math_constant",message0:"%1",args0:[{type:"field_dropdown",name:"CONSTANT",options:[["π","PI"],["e","E"],["φ","GOLDEN_RATIO"],["sqrt(2)","SQRT2"],["sqrt(½)","SQRT1_2"],["∞","INFINITY"]]}],output:"Number",style:"math_blocks",tooltip:"%{BKY_MATH_CONSTANT_TOOLTIP}",helpUrl:"%{BKY_MATH_CONSTANT_HELPURL}"},{type:"math_number_property",message0:"%1 %2",args0:[{type:"input_value",name:"NUMBER_TO_CHECK",check:"Number"},{type:"field_dropdown",name:"PROPERTY",options:[["%{BKY_MATH_IS_EVEN}","EVEN"],["%{BKY_MATH_IS_ODD}","ODD"],["%{BKY_MATH_IS_PRIME}","PRIME"],["%{BKY_MATH_IS_WHOLE}","WHOLE"],["%{BKY_MATH_IS_POSITIVE}","POSITIVE"],["%{BKY_MATH_IS_NEGATIVE}","NEGATIVE"],["%{BKY_MATH_IS_DIVISIBLE_BY}","DIVISIBLE_BY"]]}],inputsInline:!0,output:"Boolean",style:"math_blocks",tooltip:"%{BKY_MATH_IS_TOOLTIP}",mutator:"math_is_divisibleby_mutator"},{type:"math_change",message0:"%{BKY_MATH_CHANGE_TITLE}",args0:[{type:"field_variable",name:"VAR",variable:"%{BKY_MATH_CHANGE_TITLE_ITEM}"},{type:"input_value",name:"DELTA",check:"Number"}],previousStatement:null,nextStatement:null,style:"variable_blocks",helpUrl:"%{BKY_MATH_CHANGE_HELPURL}",extensions:["math_change_tooltip"]},{type:"math_round",message0:"%1 %2",args0:[{type:"field_dropdown",name:"OP",options:[["%{BKY_MATH_ROUND_OPERATOR_ROUND}","ROUND"],["%{BKY_MATH_ROUND_OPERATOR_ROUNDUP}","ROUNDUP"],["%{BKY_MATH_ROUND_OPERATOR_ROUNDDOWN}","ROUNDDOWN"]]},{type:"input_value",name:"NUM",check:"Number"}],output:"Number",style:"math_blocks",helpUrl:"%{BKY_MATH_ROUND_HELPURL}",tooltip:"%{BKY_MATH_ROUND_TOOLTIP}"},{type:"math_on_list",message0:"%1 %2",args0:[{type:"field_dropdown",name:"OP",options:[["%{BKY_MATH_ONLIST_OPERATOR_SUM}","SUM"],["%{BKY_MATH_ONLIST_OPERATOR_MIN}","MIN"],["%{BKY_MATH_ONLIST_OPERATOR_MAX}","MAX"],["%{BKY_MATH_ONLIST_OPERATOR_AVERAGE}","AVERAGE"],["%{BKY_MATH_ONLIST_OPERATOR_MEDIAN}","MEDIAN"],["%{BKY_MATH_ONLIST_OPERATOR_MODE}","MODE"],["%{BKY_MATH_ONLIST_OPERATOR_STD_DEV}","STD_DEV"],["%{BKY_MATH_ONLIST_OPERATOR_RANDOM}","RANDOM"]]},{type:"input_value",name:"LIST",check:"Array"}],output:"Number",style:"math_blocks",helpUrl:"%{BKY_MATH_ONLIST_HELPURL}",mutator:"math_modes_of_list_mutator",extensions:["math_op_tooltip"]},{type:"math_modulo",message0:"%{BKY_MATH_MODULO_TITLE}",args0:[{type:"input_value",name:"DIVIDEND",check:"Number"},{type:"input_value",name:"DIVISOR",check:"Number"}],inputsInline:!0,output:"Number",style:"math_blocks",tooltip:"%{BKY_MATH_MODULO_TOOLTIP}",helpUrl:"%{BKY_MATH_MODULO_HELPURL}"},{type:"math_constrain",message0:"%{BKY_MATH_CONSTRAIN_TITLE}",args0:[{type:"input_value",name:"VALUE",check:"Number"},{type:"input_value",name:"LOW",check:"Number"},{type:"input_value",name:"HIGH",check:"Number"}],inputsInline:!0,output:"Number",style:"math_blocks",tooltip:"%{BKY_MATH_CONSTRAIN_TOOLTIP}",helpUrl:"%{BKY_MATH_CONSTRAIN_HELPURL}"},{type:"math_random_int",message0:"%{BKY_MATH_RANDOM_INT_TITLE}",args0:[{type:"input_value",name:"FROM",check:"Number"},{type:"input_value",name:"TO",check:"Number"}],inputsInline:!0,output:"Number",style:"math_blocks",tooltip:"%{BKY_MATH_RANDOM_INT_TOOLTIP}",helpUrl:"%{BKY_MATH_RANDOM_INT_HELPURL}"},{type:"math_random_float",message0:"%{BKY_MATH_RANDOM_FLOAT_TITLE_RANDOM}",output:"Number",style:"math_blocks",tooltip:"%{BKY_MATH_RANDOM_FLOAT_TOOLTIP}",helpUrl:"%{BKY_MATH_RANDOM_FLOAT_HELPURL}"},{type:"math_atan2",message0:"%{BKY_MATH_ATAN2_TITLE}",args0:[{type:"input_value",name:"X",check:"Number"},{type:"input_value",name:"Y",check:"Number"}],inputsInline:!0,output:"Number",style:"math_blocks",tooltip:"%{BKY_MATH_ATAN2_TOOLTIP}",helpUrl:"%{BKY_MATH_ATAN2_HELPURL}"}]),t.Constants.Math.TOOLTIPS_BY_OP={ADD:"%{BKY_MATH_ARITHMETIC_TOOLTIP_ADD}",MINUS:"%{BKY_MATH_ARITHMETIC_TOOLTIP_MINUS}",MULTIPLY:"%{BKY_MATH_ARITHMETIC_TOOLTIP_MULTIPLY}",DIVIDE:"%{BKY_MATH_ARITHMETIC_TOOLTIP_DIVIDE}",POWER:"%{BKY_MATH_ARITHMETIC_TOOLTIP_POWER}",ROOT:"%{BKY_MATH_SINGLE_TOOLTIP_ROOT}",ABS:"%{BKY_MATH_SINGLE_TOOLTIP_ABS}",NEG:"%{BKY_MATH_SINGLE_TOOLTIP_NEG}",LN:"%{BKY_MATH_SINGLE_TOOLTIP_LN}",LOG10:"%{BKY_MATH_SINGLE_TOOLTIP_LOG10}",EXP:"%{BKY_MATH_SINGLE_TOOLTIP_EXP}",POW10:"%{BKY_MATH_SINGLE_TOOLTIP_POW10}",SIN:"%{BKY_MATH_TRIG_TOOLTIP_SIN}",COS:"%{BKY_MATH_TRIG_TOOLTIP_COS}",TAN:"%{BKY_MATH_TRIG_TOOLTIP_TAN}",ASIN:"%{BKY_MATH_TRIG_TOOLTIP_ASIN}",ACOS:"%{BKY_MATH_TRIG_TOOLTIP_ACOS}",ATAN:"%{BKY_MATH_TRIG_TOOLTIP_ATAN}",SUM:"%{BKY_MATH_ONLIST_TOOLTIP_SUM}",MIN:"%{BKY_MATH_ONLIST_TOOLTIP_MIN}",MAX:"%{BKY_MATH_ONLIST_TOOLTIP_MAX}",AVERAGE:"%{BKY_MATH_ONLIST_TOOLTIP_AVERAGE}",MEDIAN:"%{BKY_MATH_ONLIST_TOOLTIP_MEDIAN}",MODE:"%{BKY_MATH_ONLIST_TOOLTIP_MODE}",STD_DEV:"%{BKY_MATH_ONLIST_TOOLTIP_STD_DEV}",RANDOM:"%{BKY_MATH_ONLIST_TOOLTIP_RANDOM}"},t.Extensions.register("math_op_tooltip",t.Extensions.buildTooltipForDropdown("OP",t.Constants.Math.TOOLTIPS_BY_OP)),t.Constants.Math.IS_DIVISIBLEBY_MUTATOR_MIXIN={mutationToDom:function(){var e=t.utils.xml.createElement("mutation"),o="DIVISIBLE_BY"==this.getFieldValue("PROPERTY");return e.setAttribute("divisor_input",o),e},domToMutation:function(t){t="true"==t.getAttribute("divisor_input"),this.updateShape_(t)},updateShape_:function(t){var e=this.getInput("DIVISOR");t?e||this.appendValueInput("DIVISOR").setCheck("Number"):e&&this.removeInput("DIVISOR")}},t.Constants.Math.IS_DIVISIBLE_MUTATOR_EXTENSION=function(){this.getField("PROPERTY").setValidator((function(t){t="DIVISIBLE_BY"==t,this.getSourceBlock().updateShape_(t)}))},t.Extensions.registerMutator("math_is_divisibleby_mutator",t.Constants.Math.IS_DIVISIBLEBY_MUTATOR_MIXIN,t.Constants.Math.IS_DIVISIBLE_MUTATOR_EXTENSION),t.Extensions.register("math_change_tooltip",t.Extensions.buildTooltipWithFieldText("%{BKY_MATH_CHANGE_TOOLTIP}","VAR")),t.Constants.Math.LIST_MODES_MUTATOR_MIXIN={updateType_:function(t){"MODE"==t?this.outputConnection.setCheck("Array"):this.outputConnection.setCheck("Number")},mutationToDom:function(){var e=t.utils.xml.createElement("mutation");return e.setAttribute("op",this.getFieldValue("OP")),e},domToMutation:function(t){this.updateType_(t.getAttribute("op"))}},t.Constants.Math.LIST_MODES_MUTATOR_EXTENSION=function(){this.getField("OP").setValidator(function(t){this.updateType_(t)}.bind(this))},t.Extensions.registerMutator("math_modes_of_list_mutator",t.Constants.Math.LIST_MODES_MUTATOR_MIXIN,t.Constants.Math.LIST_MODES_MUTATOR_EXTENSION),t.Blocks.procedures={},t.Blocks.procedures_defnoreturn={init:function(){var e=new t.FieldTextInput("",t.Procedures.rename);e.setSpellcheck(!1),this.appendDummyInput().appendField(t.Msg.PROCEDURES_DEFNORETURN_TITLE).appendField(e,"NAME").appendField("","PARAMS"),this.setMutator(new t.Mutator(["procedures_mutatorarg"])),(this.workspace.options.comments||this.workspace.options.parentWorkspace&&this.workspace.options.parentWorkspace.options.comments)&&t.Msg.PROCEDURES_DEFNORETURN_COMMENT&&this.setCommentText(t.Msg.PROCEDURES_DEFNORETURN_COMMENT),this.setStyle("procedure_blocks"),this.setTooltip(t.Msg.PROCEDURES_DEFNORETURN_TOOLTIP),this.setHelpUrl(t.Msg.PROCEDURES_DEFNORETURN_HELPURL),this.arguments_=[],this.argumentVarModels_=[],this.setStatements_(!0),this.statementConnection_=null},setStatements_:function(e){this.hasStatements_!==e&&(e?(this.appendStatementInput("STACK").appendField(t.Msg.PROCEDURES_DEFNORETURN_DO),this.getInput("RETURN")&&this.moveInputBefore("STACK","RETURN")):this.removeInput("STACK",!0),this.hasStatements_=e)},updateParams_:function(){var e="";this.arguments_.length&&(e=t.Msg.PROCEDURES_BEFORE_PARAMS+" "+this.arguments_.join(", ")),t.Events.disable();try{this.setFieldValue(e,"PARAMS")}finally{t.Events.enable()}},mutationToDom:function(e){var o=t.utils.xml.createElement("mutation");e&&o.setAttribute("name",this.getFieldValue("NAME"));for(var i=0;ii?t.JavaScript.valueToCode(e,o,t.JavaScript.ORDER_SUBTRACTION)||r:n?t.JavaScript.valueToCode(e,o,t.JavaScript.ORDER_UNARY_NEGATION)||r:t.JavaScript.valueToCode(e,o,s)||r,t.isNumber(e))e=Number(e)+i,n&&(e=-e);else{if(0i&&(e=e+" - "+-i,a=t.JavaScript.ORDER_SUBTRACTION);n&&(e=i?"-("+e+")":"-"+e,a=t.JavaScript.ORDER_UNARY_NEGATION),a=Math.floor(a),s=Math.floor(s),a&&s>=a&&(e="("+e+")")}return e},t.JavaScript.colour={},t.JavaScript.colour_picker=function(e){return[t.JavaScript.quote_(e.getFieldValue("COLOUR")),t.JavaScript.ORDER_ATOMIC]},t.JavaScript.colour_random=function(e){return[t.JavaScript.provideFunction_("colourRandom",["function "+t.JavaScript.FUNCTION_NAME_PLACEHOLDER_+"() {"," var num = Math.floor(Math.random() * Math.pow(2, 24));"," return '#' + ('00000' + num.toString(16)).substr(-6);","}"])+"()",t.JavaScript.ORDER_FUNCTION_CALL]},t.JavaScript.colour_rgb=function(e){var o=t.JavaScript.valueToCode(e,"RED",t.JavaScript.ORDER_COMMA)||0,i=t.JavaScript.valueToCode(e,"GREEN",t.JavaScript.ORDER_COMMA)||0;return e=t.JavaScript.valueToCode(e,"BLUE",t.JavaScript.ORDER_COMMA)||0,[t.JavaScript.provideFunction_("colourRgb",["function "+t.JavaScript.FUNCTION_NAME_PLACEHOLDER_+"(r, g, b) {"," r = Math.max(Math.min(Number(r), 100), 0) * 2.55;"," g = Math.max(Math.min(Number(g), 100), 0) * 2.55;"," b = Math.max(Math.min(Number(b), 100), 0) * 2.55;"," r = ('0' + (Math.round(r) || 0).toString(16)).slice(-2);"," g = ('0' + (Math.round(g) || 0).toString(16)).slice(-2);"," b = ('0' + (Math.round(b) || 0).toString(16)).slice(-2);"," return '#' + r + g + b;","}"])+"("+o+", "+i+", "+e+")",t.JavaScript.ORDER_FUNCTION_CALL]},t.JavaScript.colour_blend=function(e){var o=t.JavaScript.valueToCode(e,"COLOUR1",t.JavaScript.ORDER_COMMA)||"'#000000'",i=t.JavaScript.valueToCode(e,"COLOUR2",t.JavaScript.ORDER_COMMA)||"'#000000'";return e=t.JavaScript.valueToCode(e,"RATIO",t.JavaScript.ORDER_COMMA)||.5,[t.JavaScript.provideFunction_("colourBlend",["function "+t.JavaScript.FUNCTION_NAME_PLACEHOLDER_+"(c1, c2, ratio) {"," ratio = Math.max(Math.min(Number(ratio), 1), 0);"," var r1 = parseInt(c1.substring(1, 3), 16);"," var g1 = parseInt(c1.substring(3, 5), 16);"," var b1 = parseInt(c1.substring(5, 7), 16);"," var r2 = parseInt(c2.substring(1, 3), 16);"," var g2 = parseInt(c2.substring(3, 5), 16);"," var b2 = parseInt(c2.substring(5, 7), 16);"," var r = Math.round(r1 * (1 - ratio) + r2 * ratio);"," var g = Math.round(g1 * (1 - ratio) + g2 * ratio);"," var b = Math.round(b1 * (1 - ratio) + b2 * ratio);"," r = ('0' + (r || 0).toString(16)).slice(-2);"," g = ('0' + (g || 0).toString(16)).slice(-2);"," b = ('0' + (b || 0).toString(16)).slice(-2);"," return '#' + r + g + b;","}"])+"("+o+", "+i+", "+e+")",t.JavaScript.ORDER_FUNCTION_CALL]},t.JavaScript.lists={},t.JavaScript.lists_create_empty=function(e){return["[]",t.JavaScript.ORDER_ATOMIC]},t.JavaScript.lists_create_with=function(e){for(var o=Array(e.itemCount_),i=0;i b.toString() ? 1 : -1; },",' "IGNORE_CASE": function(a, b) {'," return a.toString().toLowerCase() > b.toString().toLowerCase() ? 1 : -1; },"," };"," var compare = compareFuncs[type];"," return function(a, b) { return compare(a, b) * direction; }","}"])+'("'+e+'", '+i+"))",t.JavaScript.ORDER_FUNCTION_CALL]},t.JavaScript.lists_split=function(e){var o=t.JavaScript.valueToCode(e,"INPUT",t.JavaScript.ORDER_MEMBER),i=t.JavaScript.valueToCode(e,"DELIM",t.JavaScript.ORDER_NONE)||"''";if("SPLIT"==(e=e.getFieldValue("MODE")))o||(o="''"),e="split";else{if("JOIN"!=e)throw Error("Unknown mode: "+e);o||(o="[]"),e="join"}return[o+"."+e+"("+i+")",t.JavaScript.ORDER_FUNCTION_CALL]},t.JavaScript.lists_reverse=function(e){return[(t.JavaScript.valueToCode(e,"LIST",t.JavaScript.ORDER_FUNCTION_CALL)||"[]")+".slice().reverse()",t.JavaScript.ORDER_FUNCTION_CALL]},t.JavaScript.logic={},t.JavaScript.controls_if=function(e){var o=0,i="";t.JavaScript.STATEMENT_PREFIX&&(i+=t.JavaScript.injectId(t.JavaScript.STATEMENT_PREFIX,e));do{var n=t.JavaScript.valueToCode(e,"IF"+o,t.JavaScript.ORDER_NONE)||"false",s=t.JavaScript.statementToCode(e,"DO"+o);t.JavaScript.STATEMENT_SUFFIX&&(s=t.JavaScript.prefixLines(t.JavaScript.injectId(t.JavaScript.STATEMENT_SUFFIX,e),t.JavaScript.INDENT)+s),i+=(0",GTE:">="}[e.getFieldValue("OP")],i="=="==o||"!="==o?t.JavaScript.ORDER_EQUALITY:t.JavaScript.ORDER_RELATIONAL;return[(t.JavaScript.valueToCode(e,"A",i)||"0")+" "+o+" "+(e=t.JavaScript.valueToCode(e,"B",i)||"0"),i]},t.JavaScript.logic_operation=function(e){var o="AND"==e.getFieldValue("OP")?"&&":"||",i="&&"==o?t.JavaScript.ORDER_LOGICAL_AND:t.JavaScript.ORDER_LOGICAL_OR,n=t.JavaScript.valueToCode(e,"A",i);if(e=t.JavaScript.valueToCode(e,"B",i),n||e){var s="&&"==o?"true":"false";n||(n=s),e||(e=s)}else e=n="false";return[n+" "+o+" "+e,i]},t.JavaScript.logic_negate=function(e){var o=t.JavaScript.ORDER_LOGICAL_NOT;return["!"+(t.JavaScript.valueToCode(e,"BOOL",o)||"true"),o]},t.JavaScript.logic_boolean=function(e){return["TRUE"==e.getFieldValue("BOOL")?"true":"false",t.JavaScript.ORDER_ATOMIC]},t.JavaScript.logic_null=function(e){return["null",t.JavaScript.ORDER_ATOMIC]},t.JavaScript.logic_ternary=function(e){return[(t.JavaScript.valueToCode(e,"IF",t.JavaScript.ORDER_CONDITIONAL)||"false")+" ? "+(t.JavaScript.valueToCode(e,"THEN",t.JavaScript.ORDER_CONDITIONAL)||"null")+" : "+(e=t.JavaScript.valueToCode(e,"ELSE",t.JavaScript.ORDER_CONDITIONAL)||"null"),t.JavaScript.ORDER_CONDITIONAL]},t.JavaScript.loops={},t.JavaScript.controls_repeat_ext=function(e){var o=e.getField("TIMES")?String(Number(e.getFieldValue("TIMES"))):t.JavaScript.valueToCode(e,"TIMES",t.JavaScript.ORDER_ASSIGNMENT)||"0",i=t.JavaScript.statementToCode(e,"DO");i=t.JavaScript.addLoopTrap(i,e),e="";var n=t.JavaScript.variableDB_.getDistinctName("count",t.VARIABLE_CATEGORY_NAME),s=o;return o.match(/^\w+$/)||t.isNumber(o)||(e+="var "+(s=t.JavaScript.variableDB_.getDistinctName("repeat_end",t.VARIABLE_CATEGORY_NAME))+" = "+o+";\n"),e+"for (var "+n+" = 0; "+n+" < "+s+"; "+n+"++) {\n"+i+"}\n"},t.JavaScript.controls_repeat=t.JavaScript.controls_repeat_ext,t.JavaScript.controls_whileUntil=function(e){var o="UNTIL"==e.getFieldValue("MODE"),i=t.JavaScript.valueToCode(e,"BOOL",o?t.JavaScript.ORDER_LOGICAL_NOT:t.JavaScript.ORDER_NONE)||"false",n=t.JavaScript.statementToCode(e,"DO");return o&&(i="!"+i),"while ("+i+") {\n"+(n=t.JavaScript.addLoopTrap(n,e))+"}\n"},t.JavaScript.controls_for=function(e){var o=t.JavaScript.variableDB_.getName(e.getFieldValue("VAR"),t.VARIABLE_CATEGORY_NAME),i=t.JavaScript.valueToCode(e,"FROM",t.JavaScript.ORDER_ASSIGNMENT)||"0",n=t.JavaScript.valueToCode(e,"TO",t.JavaScript.ORDER_ASSIGNMENT)||"0",s=t.JavaScript.valueToCode(e,"BY",t.JavaScript.ORDER_ASSIGNMENT)||"1",r=t.JavaScript.statementToCode(e,"DO");if(r=t.JavaScript.addLoopTrap(r,e),t.isNumber(i)&&t.isNumber(n)&&t.isNumber(s)){var a=Number(i)<=Number(n);e="for ("+o+" = "+i+"; "+o+(a?" <= ":" >= ")+n+"; "+o,e=(1==(o=Math.abs(Number(s)))?e+(a?"++":"--"):e+(a?" += ":" -= ")+o)+") {\n"+r+"}\n"}else e="",a=i,i.match(/^\w+$/)||t.isNumber(i)||(e+="var "+(a=t.JavaScript.variableDB_.getDistinctName(o+"_start",t.VARIABLE_CATEGORY_NAME))+" = "+i+";\n"),i=n,n.match(/^\w+$/)||t.isNumber(n)||(e+="var "+(i=t.JavaScript.variableDB_.getDistinctName(o+"_end",t.VARIABLE_CATEGORY_NAME))+" = "+n+";\n"),e+="var "+(n=t.JavaScript.variableDB_.getDistinctName(o+"_inc",t.VARIABLE_CATEGORY_NAME))+" = ",e=(e=t.isNumber(s)?e+(Math.abs(s)+";\n"):e+"Math.abs("+s+");\n")+"if ("+a+" > "+i+") {\n"+(t.JavaScript.INDENT+n)+" = -"+n+";\n",e+="}\n",e+="for ("+o+" = "+a+"; "+n+" >= 0 ? "+o+" <= "+i+" : "+o+" >= "+i+"; "+o+" += "+n+") {\n"+r+"}\n";return e},t.JavaScript.controls_forEach=function(e){var o=t.JavaScript.variableDB_.getName(e.getFieldValue("VAR"),t.VARIABLE_CATEGORY_NAME),i=t.JavaScript.valueToCode(e,"LIST",t.JavaScript.ORDER_ASSIGNMENT)||"[]",n=t.JavaScript.statementToCode(e,"DO");n=t.JavaScript.addLoopTrap(n,e),e="";var s=i;return i.match(/^\w+$/)||(e+="var "+(s=t.JavaScript.variableDB_.getDistinctName(o+"_list",t.VARIABLE_CATEGORY_NAME))+" = "+i+";\n"),e+"for (var "+(i=t.JavaScript.variableDB_.getDistinctName(o+"_index",t.VARIABLE_CATEGORY_NAME))+" in "+s+") {\n"+(n=t.JavaScript.INDENT+o+" = "+s+"["+i+"];\n"+n)+"}\n"},t.JavaScript.controls_flow_statements=function(e){var o="";if(t.JavaScript.STATEMENT_PREFIX&&(o+=t.JavaScript.injectId(t.JavaScript.STATEMENT_PREFIX,e)),t.JavaScript.STATEMENT_SUFFIX&&(o+=t.JavaScript.injectId(t.JavaScript.STATEMENT_SUFFIX,e)),t.JavaScript.STATEMENT_PREFIX){var i=t.Constants.Loops.CONTROL_FLOW_IN_LOOP_CHECK_MIXIN.getSurroundLoop(e);i&&!i.suppressPrefixSuffix&&(o+=t.JavaScript.injectId(t.JavaScript.STATEMENT_PREFIX,i))}switch(e.getFieldValue("FLOW")){case"BREAK":return o+"break;\n";case"CONTINUE":return o+"continue;\n"}throw Error("Unknown flow statement.")},t.JavaScript.math={},t.JavaScript.math_number=function(e){return[e=Number(e.getFieldValue("NUM")),0<=e?t.JavaScript.ORDER_ATOMIC:t.JavaScript.ORDER_UNARY_NEGATION]},t.JavaScript.math_arithmetic=function(e){var o={ADD:[" + ",t.JavaScript.ORDER_ADDITION],MINUS:[" - ",t.JavaScript.ORDER_SUBTRACTION],MULTIPLY:[" * ",t.JavaScript.ORDER_MULTIPLICATION],DIVIDE:[" / ",t.JavaScript.ORDER_DIVISION],POWER:[null,t.JavaScript.ORDER_COMMA]}[e.getFieldValue("OP")],i=o[0];o=o[1];var n=t.JavaScript.valueToCode(e,"A",o)||"0";return e=t.JavaScript.valueToCode(e,"B",o)||"0",i?[n+i+e,o]:["Math.pow("+n+", "+e+")",t.JavaScript.ORDER_FUNCTION_CALL]},t.JavaScript.math_single=function(e){var o=e.getFieldValue("OP");if("NEG"==o)return"-"==(e=t.JavaScript.valueToCode(e,"NUM",t.JavaScript.ORDER_UNARY_NEGATION)||"0")[0]&&(e=" "+e),["-"+e,t.JavaScript.ORDER_UNARY_NEGATION];switch(e="SIN"==o||"COS"==o||"TAN"==o?t.JavaScript.valueToCode(e,"NUM",t.JavaScript.ORDER_DIVISION)||"0":t.JavaScript.valueToCode(e,"NUM",t.JavaScript.ORDER_NONE)||"0",o){case"ABS":var i="Math.abs("+e+")";break;case"ROOT":i="Math.sqrt("+e+")";break;case"LN":i="Math.log("+e+")";break;case"EXP":i="Math.exp("+e+")";break;case"POW10":i="Math.pow(10,"+e+")";break;case"ROUND":i="Math.round("+e+")";break;case"ROUNDUP":i="Math.ceil("+e+")";break;case"ROUNDDOWN":i="Math.floor("+e+")";break;case"SIN":i="Math.sin("+e+" / 180 * Math.PI)";break;case"COS":i="Math.cos("+e+" / 180 * Math.PI)";break;case"TAN":i="Math.tan("+e+" / 180 * Math.PI)"}if(i)return[i,t.JavaScript.ORDER_FUNCTION_CALL];switch(o){case"LOG10":i="Math.log("+e+") / Math.log(10)";break;case"ASIN":i="Math.asin("+e+") / Math.PI * 180";break;case"ACOS":i="Math.acos("+e+") / Math.PI * 180";break;case"ATAN":i="Math.atan("+e+") / Math.PI * 180";break;default:throw Error("Unknown math operator: "+o)}return[i,t.JavaScript.ORDER_DIVISION]},t.JavaScript.math_constant=function(e){return{PI:["Math.PI",t.JavaScript.ORDER_MEMBER],E:["Math.E",t.JavaScript.ORDER_MEMBER],GOLDEN_RATIO:["(1 + Math.sqrt(5)) / 2",t.JavaScript.ORDER_DIVISION],SQRT2:["Math.SQRT2",t.JavaScript.ORDER_MEMBER],SQRT1_2:["Math.SQRT1_2",t.JavaScript.ORDER_MEMBER],INFINITY:["Infinity",t.JavaScript.ORDER_ATOMIC]}[e.getFieldValue("CONSTANT")]},t.JavaScript.math_number_property=function(e){var o=t.JavaScript.valueToCode(e,"NUMBER_TO_CHECK",t.JavaScript.ORDER_MODULUS)||"0",i=e.getFieldValue("PROPERTY");if("PRIME"==i)return[t.JavaScript.provideFunction_("mathIsPrime",["function "+t.JavaScript.FUNCTION_NAME_PLACEHOLDER_+"(n) {"," // https://en.wikipedia.org/wiki/Primality_test#Naive_methods"," if (n == 2 || n == 3) {"," return true;"," }"," // False if n is NaN, negative, is 1, or not whole."," // And false if n is divisible by 2 or 3."," if (isNaN(n) || n <= 1 || n % 1 != 0 || n % 2 == 0 || n % 3 == 0) {"," return false;"," }"," // Check all the numbers of form 6k +/- 1, up to sqrt(n)."," for (var x = 6; x <= Math.sqrt(n) + 1; x += 6) {"," if (n % (x - 1) == 0 || n % (x + 1) == 0) {"," return false;"," }"," }"," return true;","}"])+"("+o+")",t.JavaScript.ORDER_FUNCTION_CALL];switch(i){case"EVEN":var n=o+" % 2 == 0";break;case"ODD":n=o+" % 2 == 1";break;case"WHOLE":n=o+" % 1 == 0";break;case"POSITIVE":n=o+" > 0";break;case"NEGATIVE":n=o+" < 0";break;case"DIVISIBLE_BY":n=o+" % "+(e=t.JavaScript.valueToCode(e,"DIVISOR",t.JavaScript.ORDER_MODULUS)||"0")+" == 0"}return[n,t.JavaScript.ORDER_EQUALITY]},t.JavaScript.math_change=function(e){var o=t.JavaScript.valueToCode(e,"DELTA",t.JavaScript.ORDER_ADDITION)||"0";return(e=t.JavaScript.variableDB_.getName(e.getFieldValue("VAR"),t.VARIABLE_CATEGORY_NAME))+" = (typeof "+e+" == 'number' ? "+e+" : 0) + "+o+";\n"},t.JavaScript.math_round=t.JavaScript.math_single,t.JavaScript.math_trig=t.JavaScript.math_single,t.JavaScript.math_on_list=function(e){var o=e.getFieldValue("OP");switch(o){case"SUM":e=t.JavaScript.valueToCode(e,"LIST",t.JavaScript.ORDER_MEMBER)||"[]",e+=".reduce(function(x, y) {return x + y;})";break;case"MIN":e="Math.min.apply(null, "+(e=t.JavaScript.valueToCode(e,"LIST",t.JavaScript.ORDER_COMMA)||"[]")+")";break;case"MAX":e="Math.max.apply(null, "+(e=t.JavaScript.valueToCode(e,"LIST",t.JavaScript.ORDER_COMMA)||"[]")+")";break;case"AVERAGE":e=(o=t.JavaScript.provideFunction_("mathMean",["function "+t.JavaScript.FUNCTION_NAME_PLACEHOLDER_+"(myList) {"," return myList.reduce(function(x, y) {return x + y;}) / myList.length;","}"]))+"("+(e=t.JavaScript.valueToCode(e,"LIST",t.JavaScript.ORDER_NONE)||"[]")+")";break;case"MEDIAN":e=(o=t.JavaScript.provideFunction_("mathMedian",["function "+t.JavaScript.FUNCTION_NAME_PLACEHOLDER_+"(myList) {"," var localList = myList.filter(function (x) {return typeof x == 'number';});"," if (!localList.length) return null;"," localList.sort(function(a, b) {return b - a;});"," if (localList.length % 2 == 0) {"," return (localList[localList.length / 2 - 1] + localList[localList.length / 2]) / 2;"," } else {"," return localList[(localList.length - 1) / 2];"," }","}"]))+"("+(e=t.JavaScript.valueToCode(e,"LIST",t.JavaScript.ORDER_NONE)||"[]")+")";break;case"MODE":e=(o=t.JavaScript.provideFunction_("mathModes",["function "+t.JavaScript.FUNCTION_NAME_PLACEHOLDER_+"(values) {"," var modes = [];"," var counts = [];"," var maxCount = 0;"," for (var i = 0; i < values.length; i++) {"," var value = values[i];"," var found = false;"," var thisCount;"," for (var j = 0; j < counts.length; j++) {"," if (counts[j][0] === value) {"," thisCount = ++counts[j][1];"," found = true;"," break;"," }"," }"," if (!found) {"," counts.push([value, 1]);"," thisCount = 1;"," }"," maxCount = Math.max(thisCount, maxCount);"," }"," for (var j = 0; j < counts.length; j++) {"," if (counts[j][1] == maxCount) {"," modes.push(counts[j][0]);"," }"," }"," return modes;","}"]))+"("+(e=t.JavaScript.valueToCode(e,"LIST",t.JavaScript.ORDER_NONE)||"[]")+")";break;case"STD_DEV":e=(o=t.JavaScript.provideFunction_("mathStandardDeviation",["function "+t.JavaScript.FUNCTION_NAME_PLACEHOLDER_+"(numbers) {"," var n = numbers.length;"," if (!n) return null;"," var mean = numbers.reduce(function(x, y) {return x + y;}) / n;"," var variance = 0;"," for (var j = 0; j < n; j++) {"," variance += Math.pow(numbers[j] - mean, 2);"," }"," variance = variance / n;"," return Math.sqrt(variance);","}"]))+"("+(e=t.JavaScript.valueToCode(e,"LIST",t.JavaScript.ORDER_NONE)||"[]")+")";break;case"RANDOM":e=(o=t.JavaScript.provideFunction_("mathRandomList",["function "+t.JavaScript.FUNCTION_NAME_PLACEHOLDER_+"(list) {"," var x = Math.floor(Math.random() * list.length);"," return list[x];","}"]))+"("+(e=t.JavaScript.valueToCode(e,"LIST",t.JavaScript.ORDER_NONE)||"[]")+")";break;default:throw Error("Unknown operator: "+o)}return[e,t.JavaScript.ORDER_FUNCTION_CALL]},t.JavaScript.math_modulo=function(e){return[(t.JavaScript.valueToCode(e,"DIVIDEND",t.JavaScript.ORDER_MODULUS)||"0")+" % "+(e=t.JavaScript.valueToCode(e,"DIVISOR",t.JavaScript.ORDER_MODULUS)||"0"),t.JavaScript.ORDER_MODULUS]},t.JavaScript.math_constrain=function(e){return["Math.min(Math.max("+(t.JavaScript.valueToCode(e,"VALUE",t.JavaScript.ORDER_COMMA)||"0")+", "+(t.JavaScript.valueToCode(e,"LOW",t.JavaScript.ORDER_COMMA)||"0")+"), "+(e=t.JavaScript.valueToCode(e,"HIGH",t.JavaScript.ORDER_COMMA)||"Infinity")+")",t.JavaScript.ORDER_FUNCTION_CALL]},t.JavaScript.math_random_int=function(e){var o=t.JavaScript.valueToCode(e,"FROM",t.JavaScript.ORDER_COMMA)||"0";return e=t.JavaScript.valueToCode(e,"TO",t.JavaScript.ORDER_COMMA)||"0",[t.JavaScript.provideFunction_("mathRandomInt",["function "+t.JavaScript.FUNCTION_NAME_PLACEHOLDER_+"(a, b) {"," if (a > b) {"," // Swap a and b to ensure a is smaller."," var c = a;"," a = b;"," b = c;"," }"," return Math.floor(Math.random() * (b - a + 1) + a);","}"])+"("+o+", "+e+")",t.JavaScript.ORDER_FUNCTION_CALL]},t.JavaScript.math_random_float=function(e){return["Math.random()",t.JavaScript.ORDER_FUNCTION_CALL]},t.JavaScript.math_atan2=function(e){var o=t.JavaScript.valueToCode(e,"X",t.JavaScript.ORDER_COMMA)||"0";return["Math.atan2("+(t.JavaScript.valueToCode(e,"Y",t.JavaScript.ORDER_COMMA)||"0")+", "+o+") / Math.PI * 180",t.JavaScript.ORDER_DIVISION]},t.JavaScript.procedures={},t.JavaScript.procedures_defreturn=function(e){var o=t.JavaScript.variableDB_.getName(e.getFieldValue("NAME"),t.PROCEDURE_CATEGORY_NAME),i="";t.JavaScript.STATEMENT_PREFIX&&(i+=t.JavaScript.injectId(t.JavaScript.STATEMENT_PREFIX,e)),t.JavaScript.STATEMENT_SUFFIX&&(i+=t.JavaScript.injectId(t.JavaScript.STATEMENT_SUFFIX,e)),i&&(i=t.JavaScript.prefixLines(i,t.JavaScript.INDENT));var n="";t.JavaScript.INFINITE_LOOP_TRAP&&(n=t.JavaScript.prefixLines(t.JavaScript.injectId(t.JavaScript.INFINITE_LOOP_TRAP,e),t.JavaScript.INDENT));var s=t.JavaScript.statementToCode(e,"STACK"),r=t.JavaScript.valueToCode(e,"RETURN",t.JavaScript.ORDER_NONE)||"",a="";s&&r&&(a=i),r&&(r=t.JavaScript.INDENT+"return "+r+";\n");for(var l=[],c=0;c\n \n \n \n 1\n 1\n \n \n 1\n \n \n 1\n \n \n \n \n 1\n \n \n Alias\n name\n \n \n Existing Key\n tpub, WIF, hex...\n \n \n \n \n \n \n Alias\n Alice\n \n \n \n \n 1\n 1\n \n \n \n \n Alias\n Alice\n \n \n \n \n \n \n \n \n Alias\n Bob\n \n \n \n \n \n \n 99\n 1\n \n \n \n \n Alias\n KeyLikely\n \n \n \n \n \n \n \n \n Alias\n Likely\n \n \n \n \n \n \n \n \n \n \n Alias\n User\n \n \n \n \n \n \n 99\n 1\n \n \n \n \n Alias\n Service\n \n \n \n \n \n \n 12960\n \n \n \n \n \n \n 3\n \n \n \n \n \n \n Alias\n Alice\n \n \n \n \n \n \n \n \n \n \n Alias\n Bob\n \n \n \n \n \n \n \n \n \n \n Alias\n Carol\n \n \n \n \n \n \n \n \n 12960\n \n \n \n \n \n \n \n \n \n \n \n \n',collapse:!0,comments:!0,disable:!0,maxBlocks:1/0,trashcan:!0,horizontalLayout:!0,toolboxPosition:"start",css:!0,media:"https://blockly-demo.appspot.com/static/media/",rtl:!1,scrollbars:!0,sounds:!0,oneBasedIndex:!0,grid:{spacing:20,length:1,colour:"#888",snap:!0}};r.a.Blocks.pk={init:function(){this.appendValueInput("pk").setCheck("key").appendField("Key"),this.setPreviousStatement(!0,"policy"),this.setColour(260),this.setTooltip("Requires a signature with a given public key"),this.setHelpUrl("")}},r.a.Blocks.begin={init:function(){this.appendDummyInput().appendField("Begin"),this.setNextStatement(!0,"policy"),this.setColour(160),this.setTooltip("Sets the beginning of the policy"),this.setHelpUrl("")}},r.a.Blocks.existing_key={init:function(){this.appendDummyInput().appendField(new r.a.FieldLabelSerializable("Existing Key"),"NAME").appendField(new r.a.FieldTextInput("tpub, WIF, hex..."),"key"),this.setOutput(!0,"key"),this.setColour(120),this.setTooltip("Sets the value of a key to an existing WIF key, xpub or hex public key"),this.setHelpUrl("")}},r.a.Blocks.alias_key={init:function(){this.appendDummyInput().appendField(new r.a.FieldLabelSerializable("Alias"),"label").appendField(new r.a.FieldTextInput("name"),"name"),this.setOutput(!0,"key"),this.setColour(120),this.setTooltip("Sets the value of a key to an alias"),this.setHelpUrl("")}},r.a.Blocks.thresh={init:function(){this.appendDummyInput().appendField("Threshold").appendField(new r.a.FieldNumber(1,1,1/0,1),"Threshold"),this.appendStatementInput("A").setCheck("thresh").appendField("Policies"),this.setPreviousStatement(!0,"policy"),this.setColour(230),this.setTooltip("Creates a threshold element (m-of-n), where the 'm' field is manually set and 'n' is implied by the number of sub-policies added. Requies all of its children to be wrapped in the 'Entry' block"),this.setHelpUrl("")}},r.a.Blocks.older={init:function(){this.appendDummyInput().appendField("Older").appendField(new r.a.FieldNumber(1,1,1/0,1),"NAME"),this.setPreviousStatement(!0,"policy"),this.setColour(20),this.setTooltip("Requires waiting a number of blocks from the confirmation height of a UTXO before it becomes spendable"),this.setHelpUrl("")}},r.a.Blocks.after={init:function(){this.appendDummyInput().appendField("After").appendField(new r.a.FieldNumber(1,1,1/0,1),"NAME"),this.setPreviousStatement(!0,"policy"),this.setColour(20),this.setTooltip("Requires the blockchain to reach a specific block height before the UTXO becomes spendable"),this.setHelpUrl("")}},r.a.Blocks.adapter={init:function(){this.appendStatementInput("NAME").setCheck("policy").appendField("Entry"),this.setPreviousStatement(!0,"thresh"),this.setNextStatement(!0,"thresh"),this.setColour(290),this.setTooltip("Adapter used to stack policies into 'Threshold' blocks"),this.setHelpUrl("")}},r.a.Blocks.and={init:function(){this.appendStatementInput("A").setCheck("policy"),this.appendDummyInput().appendField("AND"),this.appendStatementInput("B").setCheck("policy"),this.setPreviousStatement(!0,"policy"),this.setColour(230),this.setTooltip("Requires both sub-policies to be satisfied"),this.setHelpUrl("")}},r.a.Blocks.or={init:function(){this.appendStatementInput("A").setCheck("policy").appendField("Weight").appendField(new r.a.FieldNumber(1,1),"A_weight"),this.appendDummyInput().appendField("OR"),this.appendStatementInput("B").setCheck("policy").appendField("Weight").appendField(new r.a.FieldNumber(1,1),"B_weight"),this.setPreviousStatement(!0,"policy"),this.setColour(230),this.setTooltip("Requires either one of the two sub-policies to be satisfied. Weights can be used to indicate the relative probability of each sub-policy"),this.setHelpUrl("")}},r.a.JavaScript.begin=function(e){return""},r.a.JavaScript.pk=function(e){if(!e.getParent())return"";var n=r.a.JavaScript.valueToCode(e,"pk",r.a.JavaScript.ORDER_ATOMIC);return""==n&&(n="()"),"pk"+n},r.a.JavaScript.existing_key=function(e){return e.getParent()?[e.getFieldValue("key"),r.a.JavaScript.ORDER_NONE]:["",r.a.JavaScript.ORDER_NONE]},r.a.JavaScript.alias_key=function(e){return e.getParent()?[e.getFieldValue("name"),r.a.JavaScript.ORDER_NONE]:["",r.a.JavaScript.ORDER_NONE]},r.a.JavaScript.thresh=function(e){return"thresh("+e.getFieldValue("Threshold")+","+r.a.JavaScript.statementToCode(e,"A")+")"},r.a.JavaScript.older=function(e){return e.getParent()?"older("+e.getFieldValue("NAME")+")":""},r.a.JavaScript.after=function(e){return e.getParent()?"after("+e.getFieldValue("NAME")+")":""},r.a.JavaScript.adapter=function(e){return e.getParent()?r.a.JavaScript.statementToCode(e,"NAME")+(e.getNextBlock()?",":""):""},r.a.JavaScript.and=function(e){return e.getParent()?"and("+r.a.JavaScript.statementToCode(e,"A")+","+r.a.JavaScript.statementToCode(e,"B")+")":""},r.a.JavaScript.or=function(e){if(!e.getParent())return"";var n=e.getFieldValue("A_weight");"1"==n?n="":n+="@";var t=r.a.JavaScript.statementToCode(e,"A"),i=e.getFieldValue("B_weight");return"1"==i?i="":i+="@","or("+n+t+","+i+r.a.JavaScript.statementToCode(e,"B")+")"};var o=r.a.inject(e,i);o.addChangeListener((function(e){t.value=r.a.JavaScript.workspaceToCode(o)})),o.addChangeListener(r.a.Events.disableOrphans),setTimeout(()=>{if(l.restoreBlocks(),0==o.getTopBlocks().length){var e=o.newBlock("begin");e.setDeletable(!1),e.setEditable(!1),e.moveBy(20,20),e.initSvg(),e.render()}const n=document.createElement("span");n.innerHTML='',n.style.float="right",n.style["margin-right"]="10px";let t=!1;n.onclick=function(){t?document.exitFullscreen():document.getElementById("blocklyDiv").requestFullscreen(),t=!t},document.getElementsByClassName("blocklyToolboxDiv")[0].appendChild(n)},0),l.backupOnUnload()}("blocklyDiv","policy");let e=null;document.getElementById("stdin").disabled=!0;const n=document.getElementById("start_button"),t=document.getElementById("stop_button"),o=document.getElementById("start_message");n.disabled=!1,t.disabled=!0;const a=document.getElementById("descriptor"),u=document.getElementById("change_descriptor");n.onclick=r=>{0!=a.value.length&&(r.preventDefault(),async function(e,n){const t=document.getElementById("stdout"),o=document.getElementById("stdin");o.disabled=!1;const r=[];let a=0;const l=await new i.a("testnet",e,n,"https://blockstream.info/testnet/api"),u=e=>{if("clear"!=e)return o.disabled=!0,t.innerHTML.length>0&&(t.innerHTML+="\n"),t.innerHTML+=`> ${e}\n`,a=r.push(e),l.run(e).then(e=>{e&&(t.innerHTML+=`${e}\n`)}).catch(e=>t.innerHTML+=`${e}\n`).finally(()=>{o.disabled=!1,t.scrollTop=t.scrollHeight-t.clientHeight});t.innerHTML=""};return o.onkeydown=e=>{if("Enter"==e.key){if(0==o.value.length)return;u(o.value),o.value="",e.preventDefault()}else"ArrowUp"==e.key?a>0&&(o.value=r[--a]):"ArrowDown"==e.key&&a0?u.value:null).then(i=>{n.disabled=!0,a.disabled=!0,u.disabled=!0,o.innerHTML="Wallet created, running `sync`...",i.run("sync").then(()=>o.innerHTML="Ready!"),e=i,t.disabled=!1}).catch(e=>o.innerHTML=`${e}`))},t.onclick=i=>{null!=e&&(i.preventDefault(),e.free(),o.innerHTML="Wallet instance destroyed",n.disabled=!1,t.disabled=!0,a.disabled=!1,u.disabled=!1)};const c=document.getElementById("policy"),s=document.getElementById("compiler_script_type"),d=document.getElementById("compiler_output");document.getElementById("compile_button").onclick=e=>{if(0==c.value.length)return;e.preventDefault();const n=!e.target.form.elements.namedItem("alias").length;let t=e.target.form.elements.namedItem("alias"),o=e.target.form.elements.namedItem("type"),r=e.target.form.elements.namedItem("extra");n?(t=[t],o=[o],r=[r]):(t=Array.from(t),o=Array.from(o),r=Array.from(r));const a={};t.forEach(e=>{const n=o.filter(n=>n.attributes["data-index"].value==e.attributes["data-index"].value)[0].value,t=r.filter(n=>n.attributes["data-index"].value==e.attributes["data-index"].value)[0].value,i=e.value;a[i]={type:n,extra:t}}),Object(i.nb)(c.value,JSON.stringify(a),s.value).then(e=>d.innerHTML=e).catch(e=>d.innerHTML=`${e}`)}}()},12:function(e,n,t){"use strict";var i=t.w[e.i];e.exports=i;t(2);i.n()},2:function(e,n,t){"use strict";(function(e){t.d(n,"ob",(function(){return w})),t.d(n,"nb",(function(){return _})),t.d(n,"a",(function(){return S})),t.d(n,"jb",(function(){return E})),t.d(n,"Y",(function(){return R})),t.d(n,"lb",(function(){return x})),t.d(n,"A",(function(){return B})),t.d(n,"Q",(function(){return I})),t.d(n,"l",(function(){return F})),t.d(n,"gb",(function(){return q})),t.d(n,"N",(function(){return C})),t.d(n,"L",(function(){return N})),t.d(n,"i",(function(){return M})),t.d(n,"x",(function(){return D})),t.d(n,"fb",(function(){return O})),t.d(n,"o",(function(){return H})),t.d(n,"p",(function(){return J})),t.d(n,"K",(function(){return L})),t.d(n,"R",(function(){return P})),t.d(n,"n",(function(){return U})),t.d(n,"ib",(function(){return X})),t.d(n,"j",(function(){return j})),t.d(n,"m",(function(){return W})),t.d(n,"s",(function(){return V})),t.d(n,"w",(function(){return $})),t.d(n,"Z",(function(){return K})),t.d(n,"G",(function(){return z})),t.d(n,"t",(function(){return Q})),t.d(n,"W",(function(){return G})),t.d(n,"S",(function(){return Y})),t.d(n,"r",(function(){return Z})),t.d(n,"e",(function(){return ee})),t.d(n,"T",(function(){return ne})),t.d(n,"F",(function(){return te})),t.d(n,"z",(function(){return ie})),t.d(n,"d",(function(){return oe})),t.d(n,"c",(function(){return re})),t.d(n,"B",(function(){return ae})),t.d(n,"b",(function(){return le})),t.d(n,"ab",(function(){return ue})),t.d(n,"db",(function(){return ce})),t.d(n,"eb",(function(){return se})),t.d(n,"I",(function(){return de})),t.d(n,"k",(function(){return fe})),t.d(n,"X",(function(){return pe})),t.d(n,"u",(function(){return me})),t.d(n,"g",(function(){return be})),t.d(n,"h",(function(){return he})),t.d(n,"H",(function(){return ke})),t.d(n,"J",(function(){return ye})),t.d(n,"y",(function(){return ge})),t.d(n,"D",(function(){return ve})),t.d(n,"M",(function(){return we})),t.d(n,"V",(function(){return _e})),t.d(n,"U",(function(){return Te})),t.d(n,"f",(function(){return Ae})),t.d(n,"E",(function(){return Se})),t.d(n,"C",(function(){return Ee})),t.d(n,"P",(function(){return Re})),t.d(n,"v",(function(){return xe})),t.d(n,"q",(function(){return Be})),t.d(n,"O",(function(){return Ie})),t.d(n,"kb",(function(){return Fe})),t.d(n,"cb",(function(){return qe})),t.d(n,"mb",(function(){return Ce})),t.d(n,"hb",(function(){return Ne})),t.d(n,"bb",(function(){return Me}));var i=t(12);const o=new Array(32).fill(void 0);function r(e){return o[e]}o.push(void 0,null,!0,!1);let a=o.length;function l(e){const n=r(e);return function(e){e<36||(o[e]=a,a=e)}(e),n}let u=new("undefined"==typeof TextDecoder?(0,e.require)("util").TextDecoder:TextDecoder)("utf-8",{ignoreBOM:!0,fatal:!0});u.decode();let c=null;function s(){return null!==c&&c.buffer===i.j.buffer||(c=new Uint8Array(i.j.buffer)),c}function d(e,n){return u.decode(s().subarray(e,e+n))}function f(e){a===o.length&&o.push(o.length+1);const n=a;return a=o[n],o[n]=e,n}let p=0;let m=new("undefined"==typeof TextEncoder?(0,e.require)("util").TextEncoder:TextEncoder)("utf-8");const b="function"==typeof m.encodeInto?function(e,n){return m.encodeInto(e,n)}:function(e,n){const t=m.encode(e);return n.set(t),{read:e.length,written:t.length}};function h(e,n,t){if(void 0===t){const t=m.encode(e),i=n(t.length);return s().subarray(i,i+t.length).set(t),p=t.length,i}let i=e.length,o=n(i);const r=s();let a=0;for(;a127)break;r[o+a]=n}if(a!==i){0!==a&&(e=e.slice(a)),o=t(o,i,i=a+3*e.length);const n=s().subarray(o+a,o+i);a+=b(e,n).written}return p=a,o}let k=null;function y(){return null!==k&&k.buffer===i.j.buffer||(k=new Int32Array(i.j.buffer)),k}function g(e){return null==e}function v(e,n,t){i.g(e,n,f(t))}function w(){i.i()}function _(e,n,t){var o=h(e,i.e,i.f),r=p,a=h(n,i.e,i.f),u=p,c=h(t,i.e,i.f),s=p;return l(i.h(o,r,a,u,c,s))}function T(e){return function(){try{return e.apply(this,arguments)}catch(e){i.b(f(e))}}}function A(e,n){return s().subarray(e/1,e/1+n)}class S{static __wrap(e){const n=Object.create(S.prototype);return n.ptr=e,n}free(){const e=this.ptr;this.ptr=0,i.a(e)}constructor(e,n,t,o){var r=h(e,i.e,i.f),a=p,u=h(n,i.e,i.f),c=p,s=g(t)?0:h(t,i.e,i.f),d=p,f=h(o,i.e,i.f),m=p;return l(i.k(r,a,u,c,s,d,f,m))}run(e){var n=h(e,i.e,i.f),t=p;return l(i.l(this.ptr,n,t))}}const E=function(e){l(e)},R=function(e){return f(S.__wrap(e))},x=function(e,n){return f(d(e,n))},B=function(){return f(new Error)},I=function(e,n){var t=h(r(n).stack,i.e,i.f),o=p;y()[e/4+1]=o,y()[e/4+0]=t},F=function(e,n){try{console.error(d(e,n))}finally{i.d(e,n)}},q=function(e,n){const t=r(n);var o=h(JSON.stringify(void 0===t?null:t),i.e,i.f),a=p;y()[e/4+1]=a,y()[e/4+0]=o},C=T((function(){return f(self.self)})),N=function(e,n,t){return f(r(e).require(d(n,t)))},M=function(e){return f(r(e).crypto)},D=function(e){return f(r(e).msCrypto)},O=function(e){return void 0===r(e)},H=function(e){return f(r(e).getRandomValues)},J=function(e,n,t){r(e).getRandomValues(A(n,t))},L=function(e,n,t){r(e).randomFillSync(A(n,t))},P=function(){return f(e)},U=function(e){return f(fetch(r(e)))},X=function(e){return f(r(e))},j=function(e){console.debug(r(e))},W=function(e){console.error(r(e))},V=function(e){console.info(r(e))},$=function(e){console.log(r(e))},K=function(e){console.warn(r(e))},z=T((function(e,n){return f(new Blob(r(e),r(n)))})),Q=function(e){return r(e)instanceof Response},G=function(e,n){var t=h(r(n).url,i.e,i.f),o=p;y()[e/4+1]=o,y()[e/4+0]=t},Y=function(e){return r(e).status},Z=function(e){return f(r(e).headers)},ee=T((function(e){return f(r(e).arrayBuffer())})),ne=T((function(e){return f(r(e).text())})),te=T((function(e,n,t){return f(new Request(d(e,n),r(t)))})),ie=T((function(){return f(new FormData)})),oe=T((function(e,n,t,i){r(e).append(d(n,t),r(i))})),re=T((function(e,n,t,i,o,a){r(e).append(d(n,t),r(i),d(o,a))})),ae=T((function(){return f(new Headers)})),le=T((function(e,n,t,i,o){r(e).append(d(n,t),d(i,o))})),ue=function(e){const n=l(e).original;if(1==n.cnt--)return n.a=0,!0;return!1},ce=function(e){return"function"==typeof r(e)},se=function(e){const n=r(e);return"object"==typeof n&&null!==n},de=function(e){return f(r(e).next)},fe=function(e){return r(e).done},pe=function(e){return f(r(e).value)},me=function(){return f(Symbol.iterator)},be=T((function(e,n){return f(r(e).call(r(n)))})),he=T((function(e,n,t){return f(r(e).call(r(n),r(t)))})),ke=T((function(e){return f(r(e).next())})),ye=function(){return Date.now()},ge=function(){return f(new Object)},ve=function(e,n){try{var t={a:e,b:n},o=new Promise((e,n)=>{const o=t.a;t.a=0;try{return function(e,n,t,o){i.m(e,n,f(t),f(o))}(o,t.b,e,n)}finally{t.a=o}});return f(o)}finally{t.a=t.b=0}},we=function(e){return f(Promise.resolve(r(e)))},_e=function(e,n){return f(r(e).then(r(n)))},Te=function(e,n,t){return f(r(e).then(r(n),r(t)))},Ae=function(e){return f(r(e).buffer)},Se=function(e,n,t){return f(new Uint8Array(r(e),n>>>0,t>>>0))},Ee=function(e){return f(new Uint8Array(r(e)))},Re=function(e,n,t){r(e).set(r(n),t>>>0)},xe=function(e){return r(e).length},Be=T((function(e,n){return f(Reflect.get(r(e),r(n)))})),Ie=T((function(e,n,t){return Reflect.set(r(e),r(n),r(t))})),Fe=function(e,n){const t=r(n);var o="string"==typeof t?t:void 0,a=g(o)?0:h(o,i.e,i.f),l=p;y()[e/4+1]=l,y()[e/4+0]=a},qe=function(e,n){var t=h(function e(n){const t=typeof n;if("number"==t||"boolean"==t||null==n)return""+n;if("string"==t)return`"${n}"`;if("symbol"==t){const e=n.description;return null==e?"Symbol":`Symbol(${e})`}if("function"==t){const e=n.name;return"string"==typeof e&&e.length>0?`Function(${e})`:"Function"}if(Array.isArray(n)){const t=n.length;let i="[";t>0&&(i+=e(n[0]));for(let o=1;o1))return toString.call(n);if(o=i[1],"Object"==o)try{return"Object("+JSON.stringify(n)+")"}catch(e){return"Object"}return n instanceof Error?`${n.name}: ${n.message}\n${n.stack}`:o}(r(n)),i.e,i.f),o=p;y()[e/4+1]=o,y()[e/4+0]=t},Ce=function(e,n){throw new Error(d(e,n))},Ne=function(){return f(i.j)},Me=function(e,n,t){return f(function(e,n,t,o){const r={a:e,b:n,cnt:1,dtor:t},a=(...e)=>{r.cnt++;const n=r.a;r.a=0;try{return o(n,r.b,...e)}finally{0==--r.cnt?i.c.get(r.dtor)(n,r.b):r.a=n}};return a.original=r,a}(e,n,1080,v))}}).call(this,t(11)(e))}}]); \ No newline at end of file diff --git a/static/bdk-cli/playground/25cafba91a92f4b8098c.module.wasm b/static/bdk-cli/playground/25cafba91a92f4b8098c.module.wasm new file mode 100644 index 0000000000..cdcd1360e7 Binary files /dev/null and b/static/bdk-cli/playground/25cafba91a92f4b8098c.module.wasm differ diff --git a/static/bdk-cli/playground/playground.js b/static/bdk-cli/playground/playground.js new file mode 100644 index 0000000000..ab260a4b2b --- /dev/null +++ b/static/bdk-cli/playground/playground.js @@ -0,0 +1 @@ +!function(e){function n(n){for(var t,o,_=n[0],u=n[1],c=0,f=[];c<_.length;c++)o=_[c],Object.prototype.hasOwnProperty.call(r,o)&&r[o]&&f.push(r[o][0]),r[o]=0;for(t in u)Object.prototype.hasOwnProperty.call(u,t)&&(e[t]=u[t]);for(b&&b(n);f.length;)f.shift()()}var t={},r={0:0};var o={};var _={12:function(){return{"./bdk_playground_bg.js":{__wbindgen_object_drop_ref:function(e){return t[2].exports.jb(e)},__wbg_walletwrapper_new:function(e){return t[2].exports.Y(e)},__wbindgen_string_new:function(e,n){return t[2].exports.lb(e,n)},__wbg_new_59cb74e423758ede:function(){return t[2].exports.A()},__wbg_stack_558ba5917b466edd:function(e,n){return t[2].exports.Q(e,n)},__wbg_error_4bb6c2a97407129a:function(e,n){return t[2].exports.l(e,n)},__wbindgen_json_serialize:function(e,n){return t[2].exports.gb(e,n)},__wbg_self_1c83eb4471d9eb9b:function(){return t[2].exports.N()},__wbg_require_5b2b5b594d809d9f:function(e,n,r){return t[2].exports.L(e,n,r)},__wbg_crypto_c12f14e810edcaa2:function(e){return t[2].exports.i(e)},__wbg_msCrypto_679be765111ba775:function(e){return t[2].exports.x(e)},__wbindgen_is_undefined:function(e){return t[2].exports.fb(e)},__wbg_getRandomValues_05a60bf171bfc2be:function(e){return t[2].exports.o(e)},__wbg_getRandomValues_3ac1b33c90b52596:function(e,n,r){return t[2].exports.p(e,n,r)},__wbg_randomFillSync_6f956029658662ec:function(e,n,r){return t[2].exports.K(e,n,r)},__wbg_static_accessor_MODULE_abf5ae284bffdf45:function(){return t[2].exports.R()},__wbg_fetch_f5b2195afedb6a6b:function(e){return t[2].exports.n(e)},__wbindgen_object_clone_ref:function(e){return t[2].exports.ib(e)},__wbg_debug_b443de592faba09f:function(e){return t[2].exports.j(e)},__wbg_error_7f083efc6bc6752c:function(e){return t[2].exports.m(e)},__wbg_info_6d4a86f0fd590270:function(e){return t[2].exports.s(e)},__wbg_log_3bafd82835c6de6d:function(e){return t[2].exports.w(e)},__wbg_warn_d05e82888b7fad05:function(e){return t[2].exports.Z(e)},__wbg_newwithu8arraysequenceandoptions_ae6479c676bebdcf:function(e,n){return t[2].exports.G(e,n)},__wbg_instanceof_Response_328c03967a8e8902:function(e){return t[2].exports.t(e)},__wbg_url_67bbdafba8ff6e85:function(e,n){return t[2].exports.W(e,n)},__wbg_status_eb6dbb31556c329f:function(e){return t[2].exports.S(e)},__wbg_headers_c736e1fe38752cff:function(e){return t[2].exports.r(e)},__wbg_arrayBuffer_dc33ab7b8cdf0d63:function(e){return t[2].exports.e(e)},__wbg_text_966d07536ca6ccdc:function(e){return t[2].exports.T(e)},__wbg_newwithstrandinit_d1de1bfcd175e38a:function(e,n,r){return t[2].exports.F(e,n,r)},__wbg_new_43d9cb1835f877ad:function(){return t[2].exports.z()},__wbg_append_f76809690e4b2f3a:function(e,n,r,o){return t[2].exports.d(e,n,r,o)},__wbg_append_eaa42b75460769af:function(e,n,r,o,_,u){return t[2].exports.c(e,n,r,o,_,u)},__wbg_new_8469604d5504c189:function(){return t[2].exports.B()},__wbg_append_cc6fe0273163a31b:function(e,n,r,o,_){return t[2].exports.b(e,n,r,o,_)},__wbindgen_cb_drop:function(e){return t[2].exports.ab(e)},__wbindgen_is_function:function(e){return t[2].exports.db(e)},__wbindgen_is_object:function(e){return t[2].exports.eb(e)},__wbg_next_edda7e0003e5daf9:function(e){return t[2].exports.I(e)},__wbg_done_037d0a173aef1834:function(e){return t[2].exports.k(e)},__wbg_value_e60bbfb7d52af62f:function(e){return t[2].exports.X(e)},__wbg_iterator_09191f8878ea9877:function(){return t[2].exports.u()},__wbg_call_8e95613cc6524977:function(e,n){return t[2].exports.g(e,n)},__wbg_call_d713ea0274dfc6d2:function(e,n,r){return t[2].exports.h(e,n,r)},__wbg_next_2966fa909601a075:function(e){return t[2].exports.H(e)},__wbg_now_4de5b53a19e45567:function(){return t[2].exports.J()},__wbg_new_3e06d4f36713e4cb:function(){return t[2].exports.y()},__wbg_new_d0c63652ab4d825c:function(e,n){return t[2].exports.D(e,n)},__wbg_resolve_2529512c3bb73938:function(e){return t[2].exports.M(e)},__wbg_then_4a7a614abbbe6d81:function(e,n){return t[2].exports.V(e,n)},__wbg_then_3b7ac098cfda2fa5:function(e,n,r){return t[2].exports.U(e,n,r)},__wbg_buffer_49131c283a06686f:function(e){return t[2].exports.f(e)},__wbg_newwithbyteoffsetandlength_c0f38401daad5a22:function(e,n,r){return t[2].exports.E(e,n,r)},__wbg_new_9b295d24cf1d706f:function(e){return t[2].exports.C(e)},__wbg_set_3bb960a9975f3cd2:function(e,n,r){return t[2].exports.P(e,n,r)},__wbg_length_2b13641a9d906653:function(e){return t[2].exports.v(e)},__wbg_get_0e3f2950cdf758ae:function(e,n){return t[2].exports.q(e,n)},__wbg_set_304f2ec1a3ab3b79:function(e,n,r){return t[2].exports.O(e,n,r)},__wbindgen_string_get:function(e,n){return t[2].exports.kb(e,n)},__wbindgen_debug_string:function(e,n){return t[2].exports.cb(e,n)},__wbindgen_throw:function(e,n){return t[2].exports.mb(e,n)},__wbindgen_memory:function(){return t[2].exports.hb()},__wbindgen_closure_wrapper7033:function(e,n,r){return t[2].exports.bb(e,n,r)}}}}};function u(n){if(t[n])return t[n].exports;var r=t[n]={i:n,l:!1,exports:{}};return e[n].call(r.exports,r,r.exports,u),r.l=!0,r.exports}u.e=function(e){var n=[],t=r[e];if(0!==t)if(t)n.push(t[2]);else{var c=new Promise((function(n,o){t=r[e]=[n,o]}));n.push(t[2]=c);var f,i=document.createElement("script");i.charset="utf-8",i.timeout=120,u.nc&&i.setAttribute("nonce",u.nc),i.src=function(e){return u.p+""+e+".playground.js"}(e);var b=new Error;f=function(n){i.onerror=i.onload=null,clearTimeout(a);var t=r[e];if(0!==t){if(t){var o=n&&("load"===n.type?"missing":n.type),_=n&&n.target&&n.target.src;b.message="Loading chunk "+e+" failed.\n("+o+": "+_+")",b.name="ChunkLoadError",b.type=o,b.request=_,t[1](b)}r[e]=void 0}};var a=setTimeout((function(){f({type:"timeout",target:i})}),12e4);i.onerror=i.onload=f,document.head.appendChild(i)}return({2:[12]}[e]||[]).forEach((function(e){var t=o[e];if(t)n.push(t);else{var r,c=_[e](),f=fetch(u.p+""+{12:"25cafba91a92f4b8098c"}[e]+".module.wasm");if(c instanceof Promise&&"function"==typeof WebAssembly.compileStreaming)r=Promise.all([WebAssembly.compileStreaming(f),c]).then((function(e){return WebAssembly.instantiate(e[0],e[1])}));else if("function"==typeof WebAssembly.instantiateStreaming)r=WebAssembly.instantiateStreaming(f,c);else{r=f.then((function(e){return e.arrayBuffer()})).then((function(e){return WebAssembly.instantiate(e,c)}))}n.push(o[e]=r.then((function(n){return u.w[e]=(n.instance||n).exports})))}})),Promise.all(n)},u.m=e,u.c=t,u.d=function(e,n,t){u.o(e,n)||Object.defineProperty(e,n,{enumerable:!0,get:t})},u.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},u.t=function(e,n){if(1&n&&(e=u(e)),8&n)return e;if(4&n&&"object"==typeof e&&e&&e.__esModule)return e;var t=Object.create(null);if(u.r(t),Object.defineProperty(t,"default",{enumerable:!0,value:e}),2&n&&"string"!=typeof e)for(var r in e)u.d(t,r,function(n){return e[n]}.bind(null,r));return t},u.n=function(e){var n=e&&e.__esModule?function(){return e.default}:function(){return e};return u.d(n,"a",n),n},u.o=function(e,n){return Object.prototype.hasOwnProperty.call(e,n)},u.p="/bdk-cli/playground/",u.oe=function(e){throw console.error(e),e},u.w={};var c=window.webpackJsonp=window.webpackJsonp||[],f=c.push.bind(c);c.push=n,c=c.slice();for(var i=0;iconsole.error("Error importing `index.js`:",e))}]); \ No newline at end of file diff --git a/static/repl/playground/1.playground.js b/static/repl/playground/1.playground.js deleted file mode 100644 index 87e47dfd57..0000000000 --- a/static/repl/playground/1.playground.js +++ /dev/null @@ -1,19 +0,0 @@ -(window.webpackJsonp=window.webpackJsonp||[]).push([[1],[,,,function(t,e,o){var i,n,s;n=[o(6)],void 0===(s="function"==typeof(i=function(t){ -/** - * @license - * Copyright 2019 Google LLC - * SPDX-License-Identifier: Apache-2.0 - */ -"use strict";return t.setLocale=function(e){t.Msg=t.Msg||{},Object.keys(e).forEach((function(o){t.Msg[o]=e[o]}))},t})?i.apply(e,n):i)||(t.exports=s)},function(t,e,o){var i,n,s;n=[o(5)],void 0===(s="function"==typeof(i=function(t){ -/** - * @license - * Copyright 2019 Google LLC - * SPDX-License-Identifier: Apache-2.0 - */ -"use strict";return t})?i.apply(e,n):i)||(t.exports=s)},function(t,e,o){var i,n,s;n=[o(3),o(8),o(9),o(10)],void 0===(s="function"==typeof(i=function(t,e,o,i){ -/** - * @license - * Copyright 2019 Google LLC - * SPDX-License-Identifier: Apache-2.0 - */ -"use strict";return t.setLocale(e),t.Blocks=t.Blocks||{},Object.keys(o).forEach((function(e){t.Blocks[e]=o[e]})),t.JavaScript=i,t})?i.apply(e,n):i)||(t.exports=s)},function(t,e,o){(function(o){var i,n,s;n=[],void 0===(s="function"==typeof(i=function(){"use strict";var t={constants:{},LINE_MODE_MULTIPLIER:40,PAGE_MODE_MULTIPLIER:125,DRAG_RADIUS:5,FLYOUT_DRAG_RADIUS:10,SNAP_RADIUS:28};return t.CONNECTING_SNAP_RADIUS=t.SNAP_RADIUS,t.CURRENT_CONNECTION_PREFERENCE=8,t.BUMP_DELAY=250,t.BUMP_RANDOMNESS=10,t.COLLAPSE_CHARS=30,t.LONGPRESS=750,t.SOUND_LIMIT=100,t.DRAG_STACK=!0,t.HSV_SATURATION=.45,t.HSV_VALUE=.65,t.SPRITE={width:96,height:124,url:"sprites.png"},t.INPUT_VALUE=1,t.OUTPUT_VALUE=2,t.NEXT_STATEMENT=3,t.PREVIOUS_STATEMENT=4,t.DUMMY_INPUT=5,t.ALIGN_LEFT=-1,t.ALIGN_CENTRE=0,t.ALIGN_RIGHT=1,t.DRAG_NONE=0,t.DRAG_STICKY=1,t.DRAG_BEGIN=1,t.DRAG_FREE=2,t.OPPOSITE_TYPE=[],t.OPPOSITE_TYPE[t.INPUT_VALUE]=t.OUTPUT_VALUE,t.OPPOSITE_TYPE[t.OUTPUT_VALUE]=t.INPUT_VALUE,t.OPPOSITE_TYPE[t.NEXT_STATEMENT]=t.PREVIOUS_STATEMENT,t.OPPOSITE_TYPE[t.PREVIOUS_STATEMENT]=t.NEXT_STATEMENT,t.TOOLBOX_AT_TOP=0,t.TOOLBOX_AT_BOTTOM=1,t.TOOLBOX_AT_LEFT=2,t.TOOLBOX_AT_RIGHT=3,t.DELETE_AREA_NONE=null,t.DELETE_AREA_TRASH=1,t.DELETE_AREA_TOOLBOX=2,t.VARIABLE_CATEGORY_NAME="VARIABLE",t.VARIABLE_DYNAMIC_CATEGORY_NAME="VARIABLE_DYNAMIC",t.PROCEDURE_CATEGORY_NAME="PROCEDURE",t.RENAME_VARIABLE_ID="RENAME_VARIABLE_ID",t.DELETE_VARIABLE_ID="DELETE_VARIABLE_ID",t.utils={},t.utils.global=function(){return"object"==typeof self?self:"object"==typeof window?window:"object"==typeof o?o:this}(),t.Msg={},t.utils.global.Blockly||(t.utils.global.Blockly={}),t.utils.global.Blockly.Msg||(t.utils.global.Blockly.Msg=t.Msg),t.utils.colour={},t.utils.colour.parse=function(e){e=String(e).toLowerCase().trim();var o=t.utils.colour.names[e];if(o)return o;if(o="#"==(o="0x"==e.substring(0,2)?"#"+e.substring(2):e)[0]?o:"#"+o,/^#[0-9a-f]{6}$/.test(o))return o;if(/^#[0-9a-f]{3}$/.test(o))return["#",o[1],o[1],o[2],o[2],o[3],o[3]].join("");var i=e.match(/^(?:rgb)?\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$/);return i&&(e=Number(i[1]),o=Number(i[2]),i=Number(i[3]),0<=e&&256>e&&0<=o&&256>o&&0<=i&&256>i)?t.utils.colour.rgbToHex(e,o,i):null},t.utils.colour.rgbToHex=function(t,e,o){return e=t<<16|e<<8|o,16>t?"#"+(16777216|e).toString(16).substr(1):"#"+e.toString(16)},t.utils.colour.hexToRgb=function(e){return(e=t.utils.colour.parse(e))?[(e=parseInt(e.substr(1),16))>>16,e>>8&255,255&e]:[0,0,0]},t.utils.colour.hsvToHex=function(e,o,i){var n=0,s=0,r=0;if(0==o)r=s=n=i;else{var a=Math.floor(e/60),l=e/60-a;e=i*(1-o);var c=i*(1-o*l);switch(o=i*(1-o*(1-l)),a){case 1:n=c,s=i,r=e;break;case 2:n=e,s=i,r=o;break;case 3:n=e,s=c,r=i;break;case 4:n=o,s=e,r=i;break;case 5:n=i,s=e,r=c;break;case 6:case 0:n=i,s=o,r=e}}return t.utils.colour.rgbToHex(Math.floor(n),Math.floor(s),Math.floor(r))},t.utils.colour.blend=function(e,o,i){return(e=t.utils.colour.parse(e))&&(o=t.utils.colour.parse(o))?(e=t.utils.colour.hexToRgb(e),o=t.utils.colour.hexToRgb(o),t.utils.colour.rgbToHex(Math.round(o[0]+i*(e[0]-o[0])),Math.round(o[1]+i*(e[1]-o[1])),Math.round(o[2]+i*(e[2]-o[2])))):null},t.utils.colour.names={aqua:"#00ffff",black:"#000000",blue:"#0000ff",fuchsia:"#ff00ff",gray:"#808080",green:"#008000",lime:"#00ff00",maroon:"#800000",navy:"#000080",olive:"#808000",purple:"#800080",red:"#ff0000",silver:"#c0c0c0",teal:"#008080",white:"#ffffff",yellow:"#ffff00"},t.utils.Coordinate=function(t,e){this.x=t,this.y=e},t.utils.Coordinate.equals=function(t,e){return t==e||!(!t||!e)&&t.x==e.x&&t.y==e.y},t.utils.Coordinate.distance=function(t,e){var o=t.x-e.x;return t=t.y-e.y,Math.sqrt(o*o+t*t)},t.utils.Coordinate.magnitude=function(t){return Math.sqrt(t.x*t.x+t.y*t.y)},t.utils.Coordinate.difference=function(e,o){return new t.utils.Coordinate(e.x-o.x,e.y-o.y)},t.utils.Coordinate.sum=function(e,o){return new t.utils.Coordinate(e.x+o.x,e.y+o.y)},t.utils.Coordinate.prototype.scale=function(t){return this.x*=t,this.y*=t,this},t.utils.Coordinate.prototype.translate=function(t,e){return this.x+=t,this.y+=e,this},t.utils.string={},t.utils.string.startsWith=function(t,e){return 0==t.lastIndexOf(e,0)},t.utils.string.shortestStringLength=function(t){return t.length?t.reduce((function(t,e){return t.lengtho&&(o=i[n].length);n=-1/0;var s=1;do{var r=n,a=e;e=[];var l=i.length/s,c=1;for(n=0;nr);return a},t.utils.string.wrapScore_=function(t,e,o){for(var i=[0],n=[],s=0;ss&&(s=l,n=a)}return n?t.utils.string.wrapMutate_(e,n,i):o},t.utils.string.wrapToText_=function(t,e){for(var o=[],i=0;i=l?(s=2,r=l,(l=e.join(""))&&i.push(l),e.length=0):"{"==l?s=3:(e.push("%",l),s=0):2==s?"0"<=l&&"9">=l?r+=l:(i.push(parseInt(r,10)),a--,s=0):3==s&&(""==l?(e.splice(0,0,"%{"),a--,s=0):"}"!=l?e.push(l):(s=e.join(""),/[A-Z]\w*/i.test(s)?(l=s.toUpperCase(),(l=t.utils.string.startsWith(l,"BKY_")?l.substring(4):null)&&l in t.Msg?"string"==typeof(s=t.Msg[l])?Array.prototype.push.apply(i,t.utils.tokenizeInterpolation_(s,o)):o?i.push(String(s)):i.push(s):i.push("%{"+s+"}")):i.push("%{"+s+"}"),s=e.length=0))}for((l=e.join(""))&&i.push(l),o=[],a=e.length=0;ai;i++)o[i]=t.utils.genUid.soup_.charAt(Math.random()*e);return o.join("")},t.utils.genUid.soup_="!#$%()*+,-./:;=?@[]^_`{|}~ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",t.utils.is3dSupported=function(){if(void 0!==t.utils.is3dSupported.cached_)return t.utils.is3dSupported.cached_;if(!t.utils.global.getComputedStyle)return!1;var e=document.createElement("p"),o="none",i={webkitTransform:"-webkit-transform",OTransform:"-o-transform",msTransform:"-ms-transform",MozTransform:"-moz-transform",transform:"transform"};for(var n in document.body.insertBefore(e,null),i)if(void 0!==e.style[n]){if(e.style[n]="translate3d(1px,1px,1px)",!(o=t.utils.global.getComputedStyle(e)))return document.body.removeChild(e),!1;o=o.getPropertyValue(i[n])}return document.body.removeChild(e),t.utils.is3dSupported.cached_="none"!==o,t.utils.is3dSupported.cached_},t.utils.runAfterPageLoad=function(t){if("object"!=typeof document)throw Error("Blockly.utils.runAfterPageLoad() requires browser document.");if("complete"==document.readyState)t();else var e=setInterval((function(){"complete"==document.readyState&&(clearInterval(e),t())}),10)},t.utils.getViewportBBox=function(){var e=t.utils.style.getViewportPageOffset();return{right:document.documentElement.clientWidth+e.x,bottom:document.documentElement.clientHeight+e.y,top:e.y,left:e.x}},t.utils.arrayRemove=function(t,e){return-1!=(e=t.indexOf(e))&&(t.splice(e,1),!0)},t.utils.getDocumentScroll=function(){var e=document.documentElement,o=window;return t.utils.userAgent.IE&&o.pageYOffset!=e.scrollTop?new t.utils.Coordinate(e.scrollLeft,e.scrollTop):new t.utils.Coordinate(o.pageXOffset||e.scrollLeft,o.pageYOffset||e.scrollTop)},t.utils.getBlockTypeCounts=function(t,e){var o=Object.create(null),i=t.getDescendants(!0);for(e&&(t=t.getNextBlock())&&(t=i.indexOf(t),i.splice(t,i.length-t)),t=0;e=i[t];t++)o[e.type]?o[e.type]++:o[e.type]=1;return o},t.utils.screenToWsCoordinates=function(e,o){var i=o.x;o=o.y;var n=e.getInjectionDiv().getBoundingClientRect();return i=new t.utils.Coordinate(i-n.left,o-n.top),o=e.getOriginOffsetInPixels(),t.utils.Coordinate.difference(i,o).scale(1/e.scale)},t.utils.parseBlockColour=function(e){var o="string"==typeof e?t.utils.replaceMessageReferences(e):e,i=Number(o);if(!isNaN(i)&&0<=i&&360>=i)return{hue:i,hex:t.utils.colour.hsvToHex(i,t.HSV_SATURATION,255*t.HSV_VALUE)};if(i=t.utils.colour.parse(o))return{hue:null,hex:i};throw i='Invalid colour: "'+o+'"',e!=o&&(i+=' (from "'+e+'")'),Error(i)},t.Events={},t.Events.group_="",t.Events.recordUndo=!0,t.Events.disabled_=0,t.Events.CREATE="create",t.Events.BLOCK_CREATE=t.Events.CREATE,t.Events.DELETE="delete",t.Events.BLOCK_DELETE=t.Events.DELETE,t.Events.CHANGE="change",t.Events.BLOCK_CHANGE=t.Events.CHANGE,t.Events.MOVE="move",t.Events.BLOCK_MOVE=t.Events.MOVE,t.Events.VAR_CREATE="var_create",t.Events.VAR_DELETE="var_delete",t.Events.VAR_RENAME="var_rename",t.Events.UI="ui",t.Events.COMMENT_CREATE="comment_create",t.Events.COMMENT_DELETE="comment_delete",t.Events.COMMENT_CHANGE="comment_change",t.Events.COMMENT_MOVE="comment_move",t.Events.FINISHED_LOADING="finished_loading",t.Events.BUMP_EVENTS=[t.Events.BLOCK_CREATE,t.Events.BLOCK_MOVE,t.Events.COMMENT_CREATE,t.Events.COMMENT_MOVE],t.Events.FIRE_QUEUE_=[],t.Events.fire=function(e){t.Events.isEnabled()&&(t.Events.FIRE_QUEUE_.length||setTimeout(t.Events.fireNow_,0),t.Events.FIRE_QUEUE_.push(e))},t.Events.fireNow_=function(){for(var e,o=t.Events.filter(t.Events.FIRE_QUEUE_,!0),i=t.Events.FIRE_QUEUE_.length=0;e=o[i];i++)if(e.workspaceId){var n=t.Workspace.getById(e.workspaceId);n&&n.fireChangeListener(e)}},t.Events.filter=function(e,o){e=e.slice(),o||e.reverse();for(var i,n=[],s=Object.create(null),r=0;i=e[r];r++)if(!i.isNull()){var a=[i.type,i.blockId,i.workspaceId].join(" "),l=s[a],c=l?l.event:null;l?i.type==t.Events.MOVE&&l.index==r-1?(c.newParentId=i.newParentId,c.newInputName=i.newInputName,c.newCoordinate=i.newCoordinate,l.index=r):i.type==t.Events.CHANGE&&i.element==c.element&&i.name==c.name?c.newValue=i.newValue:(i.type!=t.Events.UI||"click"!=i.element||"commentOpen"!=c.element&&"mutatorOpen"!=c.element&&"warningOpen"!=c.element)&&(s[a]={event:i,index:1},n.push(i)):(s[a]={event:i,index:r},n.push(i))}for(e=n.filter((function(t){return!t.isNull()})),o||e.reverse(),r=1;i=e[r];r++)i.type==t.Events.CHANGE&&"mutation"==i.element&&e.unshift(e.splice(r,1)[0]);return e},t.Events.clearPendingUndo=function(){for(var e,o=0;e=t.Events.FIRE_QUEUE_[o];o++)e.recordUndo=!1},t.Events.disable=function(){t.Events.disabled_++},t.Events.enable=function(){t.Events.disabled_--},t.Events.isEnabled=function(){return 0==t.Events.disabled_},t.Events.getGroup=function(){return t.Events.group_},t.Events.setGroup=function(e){t.Events.group_="boolean"==typeof e?e?t.utils.genUid():"":e},t.Events.getDescendantIds=function(t){var e=[];t=t.getDescendants(!1);for(var o,i=0;o=t[i];i++)e[i]=o.id;return e},t.Events.fromJson=function(e,o){switch(e.type){case t.Events.CREATE:var i=new t.Events.Create(null);break;case t.Events.DELETE:i=new t.Events.Delete(null);break;case t.Events.CHANGE:i=new t.Events.Change(null,"","","","");break;case t.Events.MOVE:i=new t.Events.Move(null);break;case t.Events.VAR_CREATE:i=new t.Events.VarCreate(null);break;case t.Events.VAR_DELETE:i=new t.Events.VarDelete(null);break;case t.Events.VAR_RENAME:i=new t.Events.VarRename(null,"");break;case t.Events.UI:i=new t.Events.Ui(null,"","","");break;case t.Events.COMMENT_CREATE:i=new t.Events.CommentCreate(null);break;case t.Events.COMMENT_CHANGE:i=new t.Events.CommentChange(null,"","");break;case t.Events.COMMENT_MOVE:i=new t.Events.CommentMove(null);break;case t.Events.COMMENT_DELETE:i=new t.Events.CommentDelete(null);break;case t.Events.FINISHED_LOADING:i=new t.Events.FinishedLoading(o);break;default:throw Error("Unknown event type.")}return i.fromJson(e),i.workspaceId=o.id,i},t.Events.disableOrphans=function(e){if((e.type==t.Events.MOVE||e.type==t.Events.CREATE)&&e.workspaceId){var o=t.Workspace.getById(e.workspaceId);if(e=o.getBlockById(e.blockId)){var i=e.getParent();if(i&&i.isEnabled())for(o=e.getDescendants(!1),e=0;i=o[e];e++)i.setEnabled(!0);else if((e.outputConnection||e.previousConnection)&&!o.isDragging())do{e.setEnabled(!1),e=e.getNextBlock()}while(e)}}},t.Events.Abstract=function(){this.workspaceId=void 0,this.group=t.Events.getGroup(),this.recordUndo=t.Events.recordUndo},t.Events.Abstract.prototype.toJson=function(){var t={type:this.type};return this.group&&(t.group=this.group),t},t.Events.Abstract.prototype.fromJson=function(t){this.group=t.group},t.Events.Abstract.prototype.isNull=function(){return!1},t.Events.Abstract.prototype.run=function(t){},t.Events.Abstract.prototype.getEventWorkspace_=function(){if(this.workspaceId)var e=t.Workspace.getById(this.workspaceId);if(!e)throw Error("Workspace is null. Event must have been generated from real Blockly events.");return e},t.utils.object={},t.utils.object.inherits=function(t,e){t.superClass_=e.prototype,t.prototype=Object.create(e.prototype),t.prototype.constructor=t},t.utils.object.mixin=function(t,e){for(var o in e)t[o]=e[o]},t.utils.object.deepMerge=function(e,o){for(var i in o)e[i]="object"==typeof o[i]?t.utils.object.deepMerge(e[i]||Object.create(null),o[i]):o[i];return e},t.utils.object.values=function(t){return Object.values?Object.values(t):Object.keys(t).map((function(e){return t[e]}))},t.Events.Ui=function(e,o,i,n){t.Events.Ui.superClass_.constructor.call(this),this.blockId=e?e.id:null,this.workspaceId=e?e.workspace.id:void 0,this.element=o,this.oldValue=i,this.newValue=n,this.recordUndo=!1},t.utils.object.inherits(t.Events.Ui,t.Events.Abstract),t.Events.Ui.prototype.type=t.Events.UI,t.Events.Ui.prototype.toJson=function(){var e=t.Events.Ui.superClass_.toJson.call(this);return e.element=this.element,void 0!==this.newValue&&(e.newValue=this.newValue),this.blockId&&(e.blockId=this.blockId),e},t.Events.Ui.prototype.fromJson=function(e){t.Events.Ui.superClass_.fromJson.call(this,e),this.element=e.element,this.newValue=e.newValue,this.blockId=e.blockId},t.utils.dom={},t.utils.dom.SVG_NS="http://www.w3.org/2000/svg",t.utils.dom.HTML_NS="http://www.w3.org/1999/xhtml",t.utils.dom.XLINK_NS="http://www.w3.org/1999/xlink",t.utils.dom.Node={ELEMENT_NODE:1,TEXT_NODE:3,COMMENT_NODE:8,DOCUMENT_POSITION_CONTAINED_BY:16},t.utils.dom.cacheWidths_=null,t.utils.dom.cacheReference_=0,t.utils.dom.canvasContext_=null,t.utils.dom.createSvgElement=function(e,o,i){for(var n in e=document.createElementNS(t.utils.dom.SVG_NS,e),o)e.setAttribute(n,o[n]);return document.body.runtimeStyle&&(e.runtimeStyle=e.currentStyle=e.style),i&&i.appendChild(e),e},t.utils.dom.addClass=function(t,e){var o=t.getAttribute("class")||"";return-1==(" "+o+" ").indexOf(" "+e+" ")&&(o&&(o+=" "),t.setAttribute("class",o+e),!0)},t.utils.dom.removeClass=function(t,e){var o=t.getAttribute("class");if(-1==(" "+o+" ").indexOf(" "+e+" "))return!1;o=o.split(/\s+/);for(var i=0;io||o>this.getChildCount())throw Error(t.Component.Error.CHILD_INDEX_OUT_OF_BOUNDS);if(this.childIndex_[e.getId()]=e,e.getParent()==this){var n=this.children_.indexOf(e);-1>>/g,e),(e=document.createElement("style")).id="blockly-common-style",i=document.createTextNode(i),e.appendChild(i),document.head.insertBefore(e,document.head.firstChild))}},t.Css.setCursor=function(t){console.warn("Deprecated call to Blockly.Css.setCursor. See https://github.com/google/blockly/issues/981 for context")},t.Css.CONTENT=[".blocklySvg {","background-color: #fff;","outline: none;","overflow: hidden;","position: absolute;","display: block;","}",".blocklyWidgetDiv {","display: none;","position: absolute;","z-index: 99999;","}",".injectionDiv {","height: 100%;","position: relative;","overflow: hidden;","touch-action: none;","}",".blocklyNonSelectable {","user-select: none;","-ms-user-select: none;","-webkit-user-select: none;","}",".blocklyWsDragSurface {","display: none;","position: absolute;","top: 0;","left: 0;","}",".blocklyWsDragSurface.blocklyOverflowVisible {","overflow: visible;","}",".blocklyBlockDragSurface {","display: none;","position: absolute;","top: 0;","left: 0;","right: 0;","bottom: 0;","overflow: visible !important;","z-index: 50;","}",".blocklyBlockCanvas.blocklyCanvasTransitioning,",".blocklyBubbleCanvas.blocklyCanvasTransitioning {","transition: transform .5s;","}",".blocklyTooltipDiv {","background-color: #ffffc7;","border: 1px solid #ddc;","box-shadow: 4px 4px 20px 1px rgba(0,0,0,.15);","color: #000;","display: none;","font-family: sans-serif;","font-size: 9pt;","opacity: .9;","padding: 2px;","position: absolute;","z-index: 100000;","}",".blocklyDropDownDiv {","position: absolute;","left: 0;","top: 0;","z-index: 1000;","display: none;","border: 1px solid;","border-color: #dadce0;","background-color: #fff;","border-radius: 2px;","padding: 4px;","box-shadow: 0px 0px 3px 1px rgba(0,0,0,.3);","}",".blocklyDropDownDiv.focused {","box-shadow: 0px 0px 6px 1px rgba(0,0,0,.3);","}",".blocklyDropDownContent {","max-height: 300px;","overflow: auto;","overflow-x: hidden;","}",".blocklyDropDownArrow {","position: absolute;","left: 0;","top: 0;","width: 16px;","height: 16px;","z-index: -1;","background-color: inherit;","border-color: inherit;","}",".blocklyDropDownButton {","display: inline-block;","float: left;","padding: 0;","margin: 4px;","border-radius: 4px;","outline: none;","border: 1px solid;","transition: box-shadow .1s;","cursor: pointer;","}",".blocklyArrowTop {","border-top: 1px solid;","border-left: 1px solid;","border-top-left-radius: 4px;","border-color: inherit;","}",".blocklyArrowBottom {","border-bottom: 1px solid;","border-right: 1px solid;","border-bottom-right-radius: 4px;","border-color: inherit;","}",".blocklyResizeSE {","cursor: se-resize;","fill: #aaa;","}",".blocklyResizeSW {","cursor: sw-resize;","fill: #aaa;","}",".blocklyResizeLine {","stroke: #515A5A;","stroke-width: 1;","}",".blocklyHighlightedConnectionPath {","fill: none;","stroke: #fc3;","stroke-width: 4px;","}",".blocklyPathLight {","fill: none;","stroke-linecap: round;","stroke-width: 1;","}",".blocklySelected>.blocklyPathLight {","display: none;","}",".blocklyDraggable {",'cursor: url("<<>>/handopen.cur"), auto;',"cursor: grab;","cursor: -webkit-grab;","}",".blocklyDragging {",'cursor: url("<<>>/handclosed.cur"), auto;',"cursor: grabbing;","cursor: -webkit-grabbing;","}",".blocklyDraggable:active {",'cursor: url("<<>>/handclosed.cur"), auto;',"cursor: grabbing;","cursor: -webkit-grabbing;","}",".blocklyBlockDragSurface .blocklyDraggable {",'cursor: url("<<>>/handclosed.cur"), auto;',"cursor: grabbing;","cursor: -webkit-grabbing;","}",".blocklyDragging.blocklyDraggingDelete {",'cursor: url("<<>>/handdelete.cur"), auto;',"}",".blocklyDragging>.blocklyPath,",".blocklyDragging>.blocklyPathLight {","fill-opacity: .8;","stroke-opacity: .8;","}",".blocklyDragging>.blocklyPathDark {","display: none;","}",".blocklyDisabled>.blocklyPath {","fill-opacity: .5;","stroke-opacity: .5;","}",".blocklyDisabled>.blocklyPathLight,",".blocklyDisabled>.blocklyPathDark {","display: none;","}",".blocklyInsertionMarker>.blocklyPath,",".blocklyInsertionMarker>.blocklyPathLight,",".blocklyInsertionMarker>.blocklyPathDark {","fill-opacity: .2;","stroke: none","}",".blocklyMultilineText {","font-family: monospace;","}",".blocklyNonEditableText>text {","pointer-events: none;","}",".blocklyFlyout {","position: absolute;","z-index: 20;","}",".blocklyText text {","cursor: default;","}",".blocklySvg text, .blocklyBlockDragSurface text {","user-select: none;","-ms-user-select: none;","-webkit-user-select: none;","cursor: inherit;","}",".blocklyHidden {","display: none;","}",".blocklyFieldDropdown:not(.blocklyHidden) {","display: block;","}",".blocklyIconGroup {","cursor: default;","}",".blocklyIconGroup:not(:hover),",".blocklyIconGroupReadonly {","opacity: .6;","}",".blocklyIconShape {","fill: #00f;","stroke: #fff;","stroke-width: 1px;","}",".blocklyIconSymbol {","fill: #fff;","}",".blocklyMinimalBody {","margin: 0;","padding: 0;","}",".blocklyHtmlInput {","border: none;","border-radius: 4px;","height: 100%;","margin: 0;","outline: none;","padding: 0;","width: 100%;","text-align: center;","display: block;","box-sizing: border-box;","}",".blocklyHtmlInput::-ms-clear {","display: none;","}",".blocklyMainBackground {","stroke-width: 1;","stroke: #c6c6c6;","}",".blocklyMutatorBackground {","fill: #fff;","stroke: #ddd;","stroke-width: 1;","}",".blocklyFlyoutBackground {","fill: #ddd;","fill-opacity: .8;","}",".blocklyMainWorkspaceScrollbar {","z-index: 20;","}",".blocklyFlyoutScrollbar {","z-index: 30;","}",".blocklyScrollbarHorizontal, .blocklyScrollbarVertical {","position: absolute;","outline: none;","}",".blocklyScrollbarBackground {","opacity: 0;","}",".blocklyScrollbarHandle {","fill: #ccc;","}",".blocklyScrollbarBackground:hover+.blocklyScrollbarHandle,",".blocklyScrollbarHandle:hover {","fill: #bbb;","}",".blocklyFlyout .blocklyScrollbarHandle {","fill: #bbb;","}",".blocklyFlyout .blocklyScrollbarBackground:hover+.blocklyScrollbarHandle,",".blocklyFlyout .blocklyScrollbarHandle:hover {","fill: #aaa;","}",".blocklyInvalidInput {","background: #faa;","}",".blocklyContextMenu {","border-radius: 4px;","max-height: 100%;","}",".blocklyDropdownMenu {","border-radius: 2px;","padding: 0 !important;","}",".blocklyWidgetDiv .blocklyDropdownMenu .goog-menuitem,",".blocklyDropDownDiv .blocklyDropdownMenu .goog-menuitem {","padding-left: 28px;","}",".blocklyWidgetDiv .blocklyDropdownMenu .goog-menuitem.goog-menuitem-rtl,",".blocklyDropDownDiv .blocklyDropdownMenu .goog-menuitem.goog-menuitem-rtl {","padding-left: 5px;","padding-right: 28px;","}",".blocklyVerticalMarker {","stroke-width: 3px;","fill: rgba(255,255,255,.5);","pointer-events: none","}",".blocklyWidgetDiv .goog-option-selected .goog-menuitem-checkbox,",".blocklyWidgetDiv .goog-option-selected .goog-menuitem-icon,",".blocklyDropDownDiv .goog-option-selected .goog-menuitem-checkbox,",".blocklyDropDownDiv .goog-option-selected .goog-menuitem-icon {","background: url(<<>>/sprites.png) no-repeat -48px -16px;","}",".blocklyWidgetDiv .goog-menu {","background: #fff;","border-color: transparent;","border-style: solid;","border-width: 1px;","cursor: default;","font: normal 13px Arial, sans-serif;","margin: 0;","outline: none;","padding: 4px 0;","position: absolute;","overflow-y: auto;","overflow-x: hidden;","max-height: 100%;","z-index: 20000;","box-shadow: 0px 0px 3px 1px rgba(0,0,0,.3);","}",".blocklyWidgetDiv .goog-menu.focused {","box-shadow: 0px 0px 6px 1px rgba(0,0,0,.3);","}",".blocklyDropDownDiv .goog-menu {","cursor: default;",'font: normal 13px "Helvetica Neue", Helvetica, sans-serif;',"outline: none;","z-index: 20000;","}",".blocklyWidgetDiv .goog-menuitem,",".blocklyDropDownDiv .goog-menuitem {","color: #000;","font: normal 13px Arial, sans-serif;","list-style: none;","margin: 0;","min-width: 7em;","border: none;","padding: 6px 15px;","white-space: nowrap;","cursor: pointer;","}",".blocklyWidgetDiv .goog-menu-nocheckbox .goog-menuitem,",".blocklyWidgetDiv .goog-menu-noicon .goog-menuitem,",".blocklyDropDownDiv .goog-menu-nocheckbox .goog-menuitem,",".blocklyDropDownDiv .goog-menu-noicon .goog-menuitem {","padding-left: 12px;","}",".blocklyWidgetDiv .goog-menuitem-content,",".blocklyDropDownDiv .goog-menuitem-content {","font-family: Arial, sans-serif;","font-size: 13px;","}",".blocklyWidgetDiv .goog-menuitem-content {","color: #000;","}",".blocklyDropDownDiv .goog-menuitem-content {","color: #000;","}",".blocklyWidgetDiv .goog-menuitem-disabled,",".blocklyDropDownDiv .goog-menuitem-disabled {","cursor: inherit;","}",".blocklyWidgetDiv .goog-menuitem-disabled .goog-menuitem-content,",".blocklyDropDownDiv .goog-menuitem-disabled .goog-menuitem-content {","color: #ccc !important;","}",".blocklyWidgetDiv .goog-menuitem-disabled .goog-menuitem-icon,",".blocklyDropDownDiv .goog-menuitem-disabled .goog-menuitem-icon {","opacity: .3;","filter: alpha(opacity=30);","}",".blocklyWidgetDiv .goog-menuitem-highlight ,",".blocklyDropDownDiv .goog-menuitem-highlight {","background-color: rgba(0,0,0,.1);","}",".blocklyWidgetDiv .goog-menuitem-checkbox,",".blocklyWidgetDiv .goog-menuitem-icon,",".blocklyDropDownDiv .goog-menuitem-checkbox,",".blocklyDropDownDiv .goog-menuitem-icon {","background-repeat: no-repeat;","height: 16px;","left: 6px;","position: absolute;","right: auto;","vertical-align: middle;","width: 16px;","}",".blocklyWidgetDiv .goog-menuitem-rtl .goog-menuitem-checkbox,",".blocklyWidgetDiv .goog-menuitem-rtl .goog-menuitem-icon,",".blocklyDropDownDiv .goog-menuitem-rtl .goog-menuitem-checkbox,",".blocklyDropDownDiv .goog-menuitem-rtl .goog-menuitem-icon {","left: auto;","right: 6px;","}",".blocklyWidgetDiv .goog-option-selected .goog-menuitem-checkbox,",".blocklyWidgetDiv .goog-option-selected .goog-menuitem-icon,",".blocklyDropDownDiv .goog-option-selected .goog-menuitem-checkbox,",".blocklyDropDownDiv .goog-option-selected .goog-menuitem-icon {","position: static;","float: left;","margin-left: -24px;","}",".blocklyWidgetDiv .goog-menuitem-rtl .goog-menuitem-checkbox,",".blocklyWidgetDiv .goog-menuitem-rtl .goog-menuitem-icon,",".blocklyDropDownDiv .goog-menuitem-rtl .goog-menuitem-checkbox,",".blocklyDropDownDiv .goog-menuitem-rtl .goog-menuitem-icon {","float: right;","margin-right: -24px;","}",".blocklyComputeCanvas {","position: absolute;","width: 0;","height: 0;","}",".blocklyNoPointerEvents {","pointer-events: none;","}"],t.utils.math={},t.utils.math.toRadians=function(t){return t*Math.PI/180},t.utils.math.toDegrees=function(t){return 180*t/Math.PI},t.utils.math.clamp=function(t,e,o){if(os.top?t.DropDownDiv.getPositionAboveMetrics_(i,n,s,r):o+r.heightdocument.documentElement.clientTop?t.DropDownDiv.getPositionAboveMetrics_(i,n,s,r):t.DropDownDiv.getPositionTopOfPageMetrics_(e,s,r)},t.DropDownDiv.getPositionBelowMetrics_=function(e,o,i,n){return{initialX:(e=t.DropDownDiv.getPositionX(e,i.left,i.right,n.width)).divX,initialY:o,finalX:e.divX,finalY:o+t.DropDownDiv.PADDING_Y,arrowX:e.arrowX,arrowY:-(t.DropDownDiv.ARROW_SIZE/2+t.DropDownDiv.BORDER_SIZE),arrowAtTop:!0,arrowVisible:!0}},t.DropDownDiv.getPositionAboveMetrics_=function(e,o,i,n){return{initialX:(e=t.DropDownDiv.getPositionX(e,i.left,i.right,n.width)).divX,initialY:o-n.height,finalX:e.divX,finalY:o-n.height-t.DropDownDiv.PADDING_Y,arrowX:e.arrowX,arrowY:n.height-2*t.DropDownDiv.BORDER_SIZE-t.DropDownDiv.ARROW_SIZE/2,arrowAtTop:!1,arrowVisible:!0}},t.DropDownDiv.getPositionTopOfPageMetrics_=function(e,o,i){return{initialX:(e=t.DropDownDiv.getPositionX(e,o.left,o.right,i.width)).divX,initialY:0,finalX:e.divX,finalY:0,arrowVisible:!1}},t.DropDownDiv.getPositionX=function(e,o,i,n){var s=e;return e=t.utils.math.clamp(o,e-n/2,i-n),s-=t.DropDownDiv.ARROW_SIZE/2,o=t.DropDownDiv.ARROW_HORIZONTAL_PADDING,{arrowX:n=t.utils.math.clamp(o,s-e,n-o-t.DropDownDiv.ARROW_SIZE),divX:e}},t.DropDownDiv.isVisible=function(){return!!t.DropDownDiv.owner_},t.DropDownDiv.hideIfOwner=function(e,o){return t.DropDownDiv.owner_===e&&(o?t.DropDownDiv.hideWithoutAnimation():t.DropDownDiv.hide(),!0)},t.DropDownDiv.hide=function(){var e=t.DropDownDiv.DIV_;e.style.transform="translate(0, 0)",e.style.opacity=0,t.DropDownDiv.animateOutTimer_=setTimeout((function(){t.DropDownDiv.hideWithoutAnimation()}),1e3*t.DropDownDiv.ANIMATION_TIME),t.DropDownDiv.onHide_&&(t.DropDownDiv.onHide_(),t.DropDownDiv.onHide_=null)},t.DropDownDiv.hideWithoutAnimation=function(){if(t.DropDownDiv.isVisible()){t.DropDownDiv.animateOutTimer_&&clearTimeout(t.DropDownDiv.animateOutTimer_);var e=t.DropDownDiv.DIV_;e.style.transform="",e.style.left="",e.style.top="",e.style.opacity=0,e.style.display="none",e.style.backgroundColor="",e.style.borderColor="",t.DropDownDiv.onHide_&&(t.DropDownDiv.onHide_(),t.DropDownDiv.onHide_=null),t.DropDownDiv.clearContent(),t.DropDownDiv.owner_=null,t.DropDownDiv.rendererClassName_&&(t.utils.dom.removeClass(e,t.DropDownDiv.rendererClassName_),t.DropDownDiv.rendererClassName_=""),t.DropDownDiv.themeClassName_&&(t.utils.dom.removeClass(e,t.DropDownDiv.themeClassName_),t.DropDownDiv.themeClassName_=""),t.getMainWorkspace().markFocused()}},t.DropDownDiv.positionInternal_=function(e,o,i,n){(e=t.DropDownDiv.getPositionMetrics_(e,o,i,n)).arrowVisible?(t.DropDownDiv.arrow_.style.display="",t.DropDownDiv.arrow_.style.transform="translate("+e.arrowX+"px,"+e.arrowY+"px) rotate(45deg)",t.DropDownDiv.arrow_.setAttribute("class",e.arrowAtTop?"blocklyDropDownArrow blocklyArrowTop":"blocklyDropDownArrow blocklyArrowBottom")):t.DropDownDiv.arrow_.style.display="none",o=Math.floor(e.initialX),i=Math.floor(e.initialY),n=Math.floor(e.finalX);var s=Math.floor(e.finalY),r=t.DropDownDiv.DIV_;return r.style.left=o+"px",r.style.top=i+"px",r.style.display="block",r.style.opacity=1,r.style.transform="translate("+(n-o)+"px,"+(s-i)+"px)",e.arrowAtTop},t.DropDownDiv.repositionForWindowResize=function(){if(t.DropDownDiv.owner_){var e=t.DropDownDiv.owner_,o=t.DropDownDiv.owner_.getSourceBlock();o=(e=t.DropDownDiv.positionToField_?t.DropDownDiv.getScaledBboxOfField_(e):t.DropDownDiv.getScaledBboxOfBlock_(o)).left+(e.right-e.left)/2,t.DropDownDiv.positionInternal_(o,e.bottom,o,e.top)}else t.DropDownDiv.hide()},t.Grid=function(t,e){this.gridPattern_=t,this.spacing_=e.spacing,this.length_=e.length,this.line2_=(this.line1_=t.firstChild)&&this.line1_.nextSibling,this.snapToGrid_=e.snap},t.Grid.prototype.scale_=1,t.Grid.prototype.dispose=function(){this.gridPattern_=null},t.Grid.prototype.shouldSnap=function(){return this.snapToGrid_},t.Grid.prototype.getSpacing=function(){return this.spacing_},t.Grid.prototype.getPatternId=function(){return this.gridPattern_.id},t.Grid.prototype.update=function(t){this.scale_=t;var e=this.spacing_*t||100;this.gridPattern_.setAttribute("width",e),this.gridPattern_.setAttribute("height",e);var o=(e=Math.floor(this.spacing_/2)+.5)-this.length_/2,i=e+this.length_/2;e*=t,o*=t,i*=t,this.setLineAttributes_(this.line1_,t,o,i,e,e),this.setLineAttributes_(this.line2_,t,e,e,o,i)},t.Grid.prototype.setLineAttributes_=function(t,e,o,i,n,s){t&&(t.setAttribute("stroke-width",e),t.setAttribute("x1",o),t.setAttribute("y1",n),t.setAttribute("x2",i),t.setAttribute("y2",s))},t.Grid.prototype.moveTo=function(e,o){this.gridPattern_.setAttribute("x",e),this.gridPattern_.setAttribute("y",o),(t.utils.userAgent.IE||t.utils.userAgent.EDGE)&&this.update(this.scale_)},t.Grid.createDom=function(e,o,i){return e=t.utils.dom.createSvgElement("pattern",{id:"blocklyGridPattern"+e,patternUnits:"userSpaceOnUse"},i),0e.indexOf(o))throw Error(o+" is not a valid modifier key.")},t.user.keyMap.createSerializedKey=function(e,o){var i="",n=t.utils.object.values(t.user.keyMap.modifierKeys);t.user.keyMap.checkModifiers_(o,n);for(var s,r=0;s=n[r];r++)-1");o.domToMutation(n)}t.Events.fire(new t.Events.Change(o,"mutation",null,i,e));break;default:console.warn("Unknown change type: "+this.element)}else console.warn("Can't change non-existent block: "+this.blockId)},t.Events.Create=function(e){e&&(t.Events.Create.superClass_.constructor.call(this,e),this.xml=e.workspace.rendered?t.Xml.blockToDomWithXY(e):t.Xml.blockToDom(e),this.ids=t.Events.getDescendantIds(e))},t.utils.object.inherits(t.Events.Create,t.Events.BlockBase),t.Events.BlockCreate=t.Events.Create,t.Events.Create.prototype.type=t.Events.CREATE,t.Events.Create.prototype.toJson=function(){var e=t.Events.Create.superClass_.toJson.call(this);return e.xml=t.Xml.domToText(this.xml),e.ids=this.ids,e},t.Events.Create.prototype.fromJson=function(e){t.Events.Create.superClass_.fromJson.call(this,e),this.xml=t.Xml.textToDom(e.xml),this.ids=e.ids},t.Events.Create.prototype.run=function(e){var o=this.getEventWorkspace_();if(e)(e=t.utils.xml.createElement("xml")).appendChild(this.xml),t.Xml.domToWorkspace(e,o);else{e=0;for(var i;i=this.ids[e];e++){var n=o.getBlockById(i);n?n.dispose(!1):i==this.blockId&&console.warn("Can't uncreate non-existent block: "+i)}}},t.Events.Delete=function(e){if(e){if(e.getParent())throw Error("Connected blocks cannot be deleted.");t.Events.Delete.superClass_.constructor.call(this,e),this.oldXml=e.workspace.rendered?t.Xml.blockToDomWithXY(e):t.Xml.blockToDom(e),this.ids=t.Events.getDescendantIds(e)}},t.utils.object.inherits(t.Events.Delete,t.Events.BlockBase),t.Events.BlockDelete=t.Events.Delete,t.Events.Delete.prototype.type=t.Events.DELETE,t.Events.Delete.prototype.toJson=function(){var e=t.Events.Delete.superClass_.toJson.call(this);return e.ids=this.ids,e},t.Events.Delete.prototype.fromJson=function(e){t.Events.Delete.superClass_.fromJson.call(this,e),this.ids=e.ids},t.Events.Delete.prototype.run=function(e){var o=this.getEventWorkspace_();if(e){e=0;for(var i;i=this.ids[e];e++){var n=o.getBlockById(i);n?n.dispose(!1):i==this.blockId&&console.warn("Can't delete non-existent block: "+i)}}else(e=t.utils.xml.createElement("xml")).appendChild(this.oldXml),t.Xml.domToWorkspace(e,o)},t.Events.Move=function(e){e&&(t.Events.Move.superClass_.constructor.call(this,e),e=this.currentLocation_(),this.oldParentId=e.parentId,this.oldInputName=e.inputName,this.oldCoordinate=e.coordinate)},t.utils.object.inherits(t.Events.Move,t.Events.BlockBase),t.Events.BlockMove=t.Events.Move,t.Events.Move.prototype.type=t.Events.MOVE,t.Events.Move.prototype.toJson=function(){var e=t.Events.Move.superClass_.toJson.call(this);return this.newParentId&&(e.newParentId=this.newParentId),this.newInputName&&(e.newInputName=this.newInputName),this.newCoordinate&&(e.newCoordinate=Math.round(this.newCoordinate.x)+","+Math.round(this.newCoordinate.y)),e},t.Events.Move.prototype.fromJson=function(e){t.Events.Move.superClass_.fromJson.call(this,e),this.newParentId=e.newParentId,this.newInputName=e.newInputName,e.newCoordinate&&(e=e.newCoordinate.split(","),this.newCoordinate=new t.utils.Coordinate(Number(e[0]),Number(e[1])))},t.Events.Move.prototype.recordNew=function(){var t=this.currentLocation_();this.newParentId=t.parentId,this.newInputName=t.inputName,this.newCoordinate=t.coordinate},t.Events.Move.prototype.currentLocation_=function(){var t=this.getEventWorkspace_().getBlockById(this.blockId),e={},o=t.getParent();return o?(e.parentId=o.id,(t=o.getInputWithBlock(t))&&(e.inputName=t.name)):e.coordinate=t.getRelativeToSurfaceXY(),e},t.Events.Move.prototype.isNull=function(){return this.oldParentId==this.newParentId&&this.oldInputName==this.newInputName&&t.utils.Coordinate.equals(this.oldCoordinate,this.newCoordinate)},t.Events.Move.prototype.run=function(e){var o=this.getEventWorkspace_(),i=o.getBlockById(this.blockId);if(i){var n=e?this.newParentId:this.oldParentId,s=e?this.newInputName:this.oldInputName;e=e?this.newCoordinate:this.oldCoordinate;var r=null;if(n&&!(r=o.getBlockById(n)))return void console.warn("Can't connect to non-existent block: "+n);if(i.getParent()&&i.unplug(),e)s=i.getRelativeToSurfaceXY(),i.moveBy(e.x-s.x,e.y-s.y);else{if(i=i.outputConnection||i.previousConnection,s){if(o=r.getInput(s))var a=o.connection}else i.type==t.PREVIOUS_STATEMENT&&(a=r.nextConnection);a?i.connect(a):console.warn("Can't connect to non-existent input: "+s)}}else console.warn("Can't move non-existent block: "+this.blockId)},t.Events.FinishedLoading=function(e){this.workspaceId=e.id,this.group=t.Events.getGroup(),this.recordUndo=!1},t.utils.object.inherits(t.Events.FinishedLoading,t.Events.Ui),t.Events.FinishedLoading.prototype.type=t.Events.FINISHED_LOADING,t.Events.FinishedLoading.prototype.toJson=function(){var t={type:this.type};return this.group&&(t.group=this.group),this.workspaceId&&(t.workspaceId=this.workspaceId),t},t.Events.FinishedLoading.prototype.fromJson=function(t){this.workspaceId=t.workspaceId,this.group=t.group},t.Events.VarBase=function(e){t.Events.VarBase.superClass_.constructor.call(this),this.varId=e.getId(),this.workspaceId=e.workspace.id},t.utils.object.inherits(t.Events.VarBase,t.Events.Abstract),t.Events.VarBase.prototype.toJson=function(){var e=t.Events.VarBase.superClass_.toJson.call(this);return e.varId=this.varId,e},t.Events.VarBase.prototype.fromJson=function(e){t.Events.VarBase.superClass_.toJson.call(this),this.varId=e.varId},t.Events.VarCreate=function(e){e&&(t.Events.VarCreate.superClass_.constructor.call(this,e),this.varType=e.type,this.varName=e.name)},t.utils.object.inherits(t.Events.VarCreate,t.Events.VarBase),t.Events.VarCreate.prototype.type=t.Events.VAR_CREATE,t.Events.VarCreate.prototype.toJson=function(){var e=t.Events.VarCreate.superClass_.toJson.call(this);return e.varType=this.varType,e.varName=this.varName,e},t.Events.VarCreate.prototype.fromJson=function(e){t.Events.VarCreate.superClass_.fromJson.call(this,e),this.varType=e.varType,this.varName=e.varName},t.Events.VarCreate.prototype.run=function(t){var e=this.getEventWorkspace_();t?e.createVariable(this.varName,this.varType,this.varId):e.deleteVariableById(this.varId)},t.Events.VarDelete=function(e){e&&(t.Events.VarDelete.superClass_.constructor.call(this,e),this.varType=e.type,this.varName=e.name)},t.utils.object.inherits(t.Events.VarDelete,t.Events.VarBase),t.Events.VarDelete.prototype.type=t.Events.VAR_DELETE,t.Events.VarDelete.prototype.toJson=function(){var e=t.Events.VarDelete.superClass_.toJson.call(this);return e.varType=this.varType,e.varName=this.varName,e},t.Events.VarDelete.prototype.fromJson=function(e){t.Events.VarDelete.superClass_.fromJson.call(this,e),this.varType=e.varType,this.varName=e.varName},t.Events.VarDelete.prototype.run=function(t){var e=this.getEventWorkspace_();t?e.deleteVariableById(this.varId):e.createVariable(this.varName,this.varType,this.varId)},t.Events.VarRename=function(e,o){e&&(t.Events.VarRename.superClass_.constructor.call(this,e),this.oldName=e.name,this.newName=o)},t.utils.object.inherits(t.Events.VarRename,t.Events.VarBase),t.Events.VarRename.prototype.type=t.Events.VAR_RENAME,t.Events.VarRename.prototype.toJson=function(){var e=t.Events.VarRename.superClass_.toJson.call(this);return e.oldName=this.oldName,e.newName=this.newName,e},t.Events.VarRename.prototype.fromJson=function(e){t.Events.VarRename.superClass_.fromJson.call(this,e),this.oldName=e.oldName,this.newName=e.newName},t.Events.VarRename.prototype.run=function(t){var e=this.getEventWorkspace_();t?e.renameVariableById(this.varId,this.newName):e.renameVariableById(this.varId,this.oldName)},t.Xml={},t.Xml.workspaceToDom=function(e,o){var i=t.utils.xml.createElement("xml"),n=t.Xml.variablesToDom(t.Variables.allUsedVarModels(e));n.hasChildNodes()&&i.appendChild(n);var s,r=e.getTopComments(!0);for(n=0;s=r[n];n++)i.appendChild(s.toXmlWithXY(o));for(e=e.getTopBlocks(!0),n=0;r=e[n];n++)i.appendChild(t.Xml.blockToDomWithXY(r,o));return i},t.Xml.variablesToDom=function(e){for(var o,i=t.utils.xml.createElement("variables"),n=0;o=e[n];n++){var s=t.utils.xml.createElement("variable");s.appendChild(t.utils.xml.createTextNode(o.name)),o.type&&s.setAttribute("type",o.type),s.id=o.getId(),i.appendChild(s)}return i},t.Xml.blockToDomWithXY=function(e,o){var i;e.workspace.RTL&&(i=e.workspace.getWidth()),o=t.Xml.blockToDom(e,o);var n=e.getRelativeToSurfaceXY();return o.setAttribute("x",Math.round(e.workspace.RTL?i-n.x:n.x)),o.setAttribute("y",Math.round(n.y)),o},t.Xml.fieldToDom_=function(e){if(e.isSerializable()){var o=t.utils.xml.createElement("field");return o.setAttribute("name",e.name||""),e.toXml(o)}return null},t.Xml.allFieldsToDom_=function(e,o){for(var i,n=0;i=e.inputList[n];n++)for(var s,r=0;s=i.fieldRow[r];r++)(s=t.Xml.fieldToDom_(s))&&o.appendChild(s)},t.Xml.blockToDom=function(e,o){var i=t.utils.xml.createElement(e.isShadow()?"shadow":"block");if(i.setAttribute("type",e.type),o||i.setAttribute("id",e.id),e.mutationToDom){var n=e.mutationToDom();n&&(n.hasChildNodes()||n.hasAttributes())&&i.appendChild(n)}if(t.Xml.allFieldsToDom_(e,i),n=e.getCommentText()){var s=e.commentModel.size,r=e.commentModel.pinned,a=t.utils.xml.createElement("comment");a.appendChild(t.utils.xml.createTextNode(n)),a.setAttribute("pinned",r),a.setAttribute("h",s.height),a.setAttribute("w",s.width),i.appendChild(a)}for(e.data&&((n=t.utils.xml.createElement("data")).appendChild(t.utils.xml.createTextNode(e.data)),i.appendChild(n)),s=0;r=e.inputList[s];s++){var l;if(a=!0,r.type!=t.DUMMY_INPUT){var c=r.connection.targetBlock();r.type==t.INPUT_VALUE?l=t.utils.xml.createElement("value"):r.type==t.NEXT_STATEMENT&&(l=t.utils.xml.createElement("statement")),!(n=r.connection.getShadowDom())||c&&c.isShadow()||l.appendChild(t.Xml.cloneShadow_(n,o)),c&&(l.appendChild(t.Xml.blockToDom(c,o)),a=!1),l.setAttribute("name",r.name),a||i.appendChild(l)}}return null!=e.inputsInline&&e.inputsInline!=e.inputsInlineDefault&&i.setAttribute("inline",e.inputsInline),e.isCollapsed()&&i.setAttribute("collapsed",!0),e.isEnabled()||i.setAttribute("disabled",!0),e.isDeletable()||e.isShadow()||i.setAttribute("deletable",!1),e.isMovable()||e.isShadow()||i.setAttribute("movable",!1),e.isEditable()||i.setAttribute("editable",!1),(s=e.getNextBlock())&&((l=t.utils.xml.createElement("next")).appendChild(t.Xml.blockToDom(s,o)),i.appendChild(l)),!(n=e.nextConnection&&e.nextConnection.getShadowDom())||s&&s.isShadow()||l.appendChild(t.Xml.cloneShadow_(n,o)),i},t.Xml.cloneShadow_=function(e,o){for(var i,n=e=e.cloneNode(!0);n;)if(o&&"shadow"==n.nodeName&&n.removeAttribute("id"),n.firstChild)n=n.firstChild;else{for(;n&&!n.nextSibling;)i=n,n=n.parentNode,i.nodeType==t.utils.dom.Node.TEXT_NODE&&""==i.data.trim()&&n.firstChild!=i&&t.utils.dom.removeNode(i);n&&(i=n,n=n.nextSibling,i.nodeType==t.utils.dom.Node.TEXT_NODE&&""==i.data.trim()&&t.utils.dom.removeNode(i))}return e},t.Xml.domToText=function(e){e=t.utils.xml.domToText(e);var o=/(<[^/](?:[^>]*[^/])?>[^<]*)\n([^<]*<\/)/;do{var i=e;e=e.replace(o,"$1 $2")}while(e!=i);return e.replace(/<(\w+)([^<]*)\/>/g,"<$1$2>")},t.Xml.domToPrettyText=function(e){e=t.Xml.domToText(e).split("<");for(var o="",i=1;i"!=n.slice(-2)&&(o+=" ")}return(e=(e=e.join("\n")).replace(/(<(\w+)\b[^>]*>[^\n]*)\n *<\/\2>/g,"$1")).replace(/^\n/,"")},t.Xml.textToDom=function(e){var o=t.utils.xml.textToDomDocument(e);if(!o||!o.documentElement||o.getElementsByTagName("parsererror").length)throw Error("textToDom was unable to parse: "+e);return o.documentElement},t.Xml.clearWorkspaceAndLoadFromXml=function(e,o){return o.setResizesEnabled(!1),o.clear(),e=t.Xml.domToWorkspace(e,o),o.setResizesEnabled(!0),e},t.Xml.domToWorkspace=function(e,o){if(e instanceof t.Workspace){var i=e;e=o,o=i,console.warn("Deprecated call to Blockly.Xml.domToWorkspace, swap the arguments.")}var n;o.RTL&&(n=o.getWidth()),i=[],t.utils.dom.startTextWidthCache();var s=t.Events.getGroup();s||t.Events.setGroup(!0),o.setResizesEnabled&&o.setResizesEnabled(!1);var r=!0;try{for(var a,l=0;a=e.childNodes[l];l++){var c=a.nodeName.toLowerCase(),h=a;if("block"==c||"shadow"==c&&!t.Events.recordUndo){var u=t.Xml.domToBlock(h,o);i.push(u.id);var p=h.hasAttribute("x")?parseInt(h.getAttribute("x"),10):10,_=h.hasAttribute("y")?parseInt(h.getAttribute("y"),10):10;isNaN(p)||isNaN(_)||u.moveBy(o.RTL?n-p:p,_),r=!1}else{if("shadow"==c)throw TypeError("Shadow block cannot be a top-level block.");if("comment"==c)o.rendered?t.WorkspaceCommentSvg?t.WorkspaceCommentSvg.fromXml(h,o,n):console.warn("Missing require for Blockly.WorkspaceCommentSvg, ignoring workspace comment."):t.WorkspaceComment?t.WorkspaceComment.fromXml(h,o):console.warn("Missing require for Blockly.WorkspaceComment, ignoring workspace comment.");else if("variables"==c){if(!r)throw Error("'variables' tag must exist once before block and shadow tag elements in the workspace XML, but it was found in another location.");t.Xml.domToVariables(h,o),r=!1}}}}finally{s||t.Events.setGroup(!1),t.utils.dom.stopTextWidthCache()}return o.setResizesEnabled&&o.setResizesEnabled(!0),t.Events.fire(new t.Events.FinishedLoading(o)),i},t.Xml.appendDomToWorkspace=function(e,o){var i;if(o.hasOwnProperty("scale")&&(i=o.getBlocksBoundingBox()),e=t.Xml.domToWorkspace(e,o),i&&i.top!=i.bottom){var n=i.bottom,s=o.RTL?i.right:i.left,r=1/0,a=-1/0,l=1/0;for(i=0;ia&&(a=c.x)}for(n=n-l+10,s=o.RTL?s-a:s-r,i=0;i document.")}else e=null;return e},t.Touch={},t.Touch.TOUCH_ENABLED="ontouchstart"in t.utils.global||!!(t.utils.global.document&&document.documentElement&&"ontouchstart"in document.documentElement)||!(!t.utils.global.navigator||!t.utils.global.navigator.maxTouchPoints&&!t.utils.global.navigator.msMaxTouchPoints),t.Touch.touchIdentifier_=null,t.Touch.TOUCH_MAP={},t.utils.global.PointerEvent?t.Touch.TOUCH_MAP={mousedown:["pointerdown"],mouseenter:["pointerenter"],mouseleave:["pointerleave"],mousemove:["pointermove"],mouseout:["pointerout"],mouseover:["pointerover"],mouseup:["pointerup","pointercancel"],touchend:["pointerup"],touchcancel:["pointercancel"]}:t.Touch.TOUCH_ENABLED&&(t.Touch.TOUCH_MAP={mousedown:["touchstart"],mousemove:["touchmove"],mouseup:["touchend","touchcancel"]}),t.longPid_=0,t.longStart=function(e,o){t.longStop_(),e.changedTouches&&1!=e.changedTouches.length||(t.longPid_=setTimeout((function(){e.changedTouches&&(e.button=2,e.clientX=e.changedTouches[0].clientX,e.clientY=e.changedTouches[0].clientY),o&&o.handleRightClick(e)}),t.LONGPRESS))},t.longStop_=function(){t.longPid_&&(clearTimeout(t.longPid_),t.longPid_=0)},t.Touch.clearTouchIdentifier=function(){t.Touch.touchIdentifier_=null},t.Touch.shouldHandleEvent=function(e){return!t.Touch.isMouseOrTouchEvent(e)||t.Touch.checkTouchIdentifier(e)},t.Touch.getTouchIdentifierFromEvent=function(t){return null!=t.pointerId?t.pointerId:t.changedTouches&&t.changedTouches[0]&&void 0!==t.changedTouches[0].identifier&&null!==t.changedTouches[0].identifier?t.changedTouches[0].identifier:"mouse"},t.Touch.checkTouchIdentifier=function(e){var o=t.Touch.getTouchIdentifierFromEvent(e);return void 0!==t.Touch.touchIdentifier_&&null!==t.Touch.touchIdentifier_?t.Touch.touchIdentifier_==o:("mousedown"==e.type||"touchstart"==e.type||"pointerdown"==e.type)&&(t.Touch.touchIdentifier_=o,!0)},t.Touch.setClientFromTouch=function(e){if(t.utils.string.startsWith(e.type,"touch")){var o=e.changedTouches[0];e.clientX=o.clientX,e.clientY=o.clientY}},t.Touch.isMouseOrTouchEvent=function(e){return t.utils.string.startsWith(e.type,"touch")||t.utils.string.startsWith(e.type,"mouse")||t.utils.string.startsWith(e.type,"pointer")},t.Touch.isTouchEvent=function(e){return t.utils.string.startsWith(e.type,"touch")||t.utils.string.startsWith(e.type,"pointer")},t.Touch.splitEventByTouches=function(t){var e=[];if(t.changedTouches)for(var o=0;o=i+this.handleLength_&&(n+=s),this.setHandlePosition(this.constrainHandle_(n)),this.onScroll_(),e.stopPropagation(),e.preventDefault()}},t.Scrollbar.prototype.onMouseDownHandle_=function(e){this.workspace_.markFocused(),this.cleanUp_(),t.utils.isRightButton(e)?e.stopPropagation():(this.startDragHandle=this.handlePosition_,this.workspace_.setupDragSurface(),this.startDragMouse_=this.horizontal_?e.clientX:e.clientY,t.Scrollbar.onMouseUpWrapper_=t.bindEventWithChecks_(document,"mouseup",this,this.onMouseUpHandle_),t.Scrollbar.onMouseMoveWrapper_=t.bindEventWithChecks_(document,"mousemove",this,this.onMouseMoveHandle_),e.stopPropagation(),e.preventDefault())},t.Scrollbar.prototype.onMouseMoveHandle_=function(t){this.setHandlePosition(this.constrainHandle_(this.startDragHandle+((this.horizontal_?t.clientX:t.clientY)-this.startDragMouse_))),this.onScroll_()},t.Scrollbar.prototype.onMouseUpHandle_=function(){this.workspace_.resetDragSurface(),t.Touch.clearTouchIdentifier(),this.cleanUp_()},t.Scrollbar.prototype.cleanUp_=function(){t.hideChaff(!0),t.Scrollbar.onMouseUpWrapper_&&(t.unbindEvent_(t.Scrollbar.onMouseUpWrapper_),t.Scrollbar.onMouseUpWrapper_=null),t.Scrollbar.onMouseMoveWrapper_&&(t.unbindEvent_(t.Scrollbar.onMouseMoveWrapper_),t.Scrollbar.onMouseMoveWrapper_=null)},t.Scrollbar.prototype.constrainHandle_=function(t){return 0>=t||isNaN(t)||this.scrollViewSize_t.Tooltip.RADIUS_OK&&t.Tooltip.hide()}else t.Tooltip.poisonedElement_!=t.Tooltip.element_&&(clearTimeout(t.Tooltip.showPid_),t.Tooltip.lastX_=e.pageX,t.Tooltip.lastY_=e.pageY,t.Tooltip.showPid_=setTimeout(t.Tooltip.show_,t.Tooltip.HOVER_MS))},t.Tooltip.dispose=function(){t.Tooltip.element_=null,t.Tooltip.poisonedElement_=null,t.Tooltip.hide()},t.Tooltip.hide=function(){t.Tooltip.visible&&(t.Tooltip.visible=!1,t.Tooltip.DIV&&(t.Tooltip.DIV.style.display="none")),t.Tooltip.showPid_&&clearTimeout(t.Tooltip.showPid_)},t.Tooltip.block=function(){t.Tooltip.hide(),t.Tooltip.blocked_=!0},t.Tooltip.unblock=function(){t.Tooltip.blocked_=!1},t.Tooltip.show_=function(){if(!t.Tooltip.blocked_&&(t.Tooltip.poisonedElement_=t.Tooltip.element_,t.Tooltip.DIV)){t.Tooltip.DIV.textContent="";for(var e=t.Tooltip.element_.tooltip;"function"==typeof e;)e=e();e=(e=t.utils.string.wrap(e,t.Tooltip.LIMIT)).split("\n");for(var o=0;oi+window.scrollY&&(s-=t.Tooltip.DIV.offsetHeight+2*t.Tooltip.OFFSET_Y),e?n=Math.max(t.Tooltip.MARGINS-window.scrollX,n):n+t.Tooltip.DIV.offsetWidth>o+window.scrollX-2*t.Tooltip.MARGINS&&(n=o-t.Tooltip.DIV.offsetWidth-2*t.Tooltip.MARGINS),t.Tooltip.DIV.style.top=s+"px",t.Tooltip.DIV.style.left=n+"px"}},t.WorkspaceDragSurfaceSvg=function(t){this.container_=t,this.createDom()},t.WorkspaceDragSurfaceSvg.prototype.SVG_=null,t.WorkspaceDragSurfaceSvg.prototype.dragGroup_=null,t.WorkspaceDragSurfaceSvg.prototype.container_=null,t.WorkspaceDragSurfaceSvg.prototype.createDom=function(){this.SVG_||(this.SVG_=t.utils.dom.createSvgElement("svg",{xmlns:t.utils.dom.SVG_NS,"xmlns:html":t.utils.dom.HTML_NS,"xmlns:xlink":t.utils.dom.XLINK_NS,version:"1.1",class:"blocklyWsDragSurface blocklyOverflowVisible"},null),this.container_.appendChild(this.SVG_))},t.WorkspaceDragSurfaceSvg.prototype.translateSurface=function(e,o){e=e.toFixed(0),o=o.toFixed(0),this.SVG_.style.display="block",t.utils.dom.setCssTransform(this.SVG_,"translate3d("+e+"px, "+o+"px, 0px)")},t.WorkspaceDragSurfaceSvg.prototype.getSurfaceTranslation=function(){return t.utils.getRelativeXY(this.SVG_)},t.WorkspaceDragSurfaceSvg.prototype.clearAndHide=function(e){if(!e)throw Error("Couldn't clear and hide the drag surface: missing new surface.");var o=this.SVG_.childNodes[0],i=this.SVG_.childNodes[1];if(!(o&&i&&t.utils.dom.hasClass(o,"blocklyBlockCanvas")&&t.utils.dom.hasClass(i,"blocklyBubbleCanvas")))throw Error("Couldn't clear and hide the drag surface. A node was missing.");if(null!=this.previousSibling_?t.utils.dom.insertAfter(o,this.previousSibling_):e.insertBefore(o,e.firstChild),t.utils.dom.insertAfter(i,o),this.SVG_.style.display="none",this.SVG_.childNodes.length)throw Error("Drag surface was not cleared.");t.utils.dom.setCssTransform(this.SVG_,""),this.previousSibling_=null},t.WorkspaceDragSurfaceSvg.prototype.setContentsAndShow=function(t,e,o,i,n,s){if(this.SVG_.childNodes.length)throw Error("Already dragging a block.");this.previousSibling_=o,t.setAttribute("transform","translate(0, 0) scale("+s+")"),e.setAttribute("transform","translate(0, 0) scale("+s+")"),this.SVG_.setAttribute("width",i),this.SVG_.setAttribute("height",n),this.SVG_.appendChild(t),this.SVG_.appendChild(e),this.SVG_.style.display="block"},t.ASTNode=function(e,o,i){if(!o)throw Error("Cannot create a node without a location.");this.type_=e,this.isConnection_=t.ASTNode.isConnectionType_(e),this.location_=o,this.processParams_(i||null)},t.ASTNode.types={FIELD:"field",BLOCK:"block",INPUT:"input",OUTPUT:"output",NEXT:"next",PREVIOUS:"previous",STACK:"stack",WORKSPACE:"workspace"},t.ASTNode.NAVIGATE_ALL_FIELDS=!1,t.ASTNode.DEFAULT_OFFSET_Y=-20,t.ASTNode.isConnectionType_=function(e){switch(e){case t.ASTNode.types.PREVIOUS:case t.ASTNode.types.NEXT:case t.ASTNode.types.INPUT:case t.ASTNode.types.OUTPUT:return!0}return!1},t.ASTNode.createFieldNode=function(e){return e?new t.ASTNode(t.ASTNode.types.FIELD,e):null},t.ASTNode.createConnectionNode=function(e){return e?e.type==t.INPUT_VALUE||e.type==t.NEXT_STATEMENT&&e.getParentInput()?t.ASTNode.createInputNode(e.getParentInput()):e.type==t.NEXT_STATEMENT?new t.ASTNode(t.ASTNode.types.NEXT,e):e.type==t.OUTPUT_VALUE?new t.ASTNode(t.ASTNode.types.OUTPUT,e):e.type==t.PREVIOUS_STATEMENT?new t.ASTNode(t.ASTNode.types.PREVIOUS,e):null:null},t.ASTNode.createInputNode=function(e){return e&&e.connection?new t.ASTNode(t.ASTNode.types.INPUT,e.connection):null},t.ASTNode.createBlockNode=function(e){return e?new t.ASTNode(t.ASTNode.types.BLOCK,e):null},t.ASTNode.createStackNode=function(e){return e?new t.ASTNode(t.ASTNode.types.STACK,e):null},t.ASTNode.createWorkspaceNode=function(e,o){return o&&e?new t.ASTNode(t.ASTNode.types.WORKSPACE,e,{wsCoordinate:o}):null},t.ASTNode.prototype.processParams_=function(t){t&&t.wsCoordinate&&(this.wsCoordinate_=t.wsCoordinate)},t.ASTNode.prototype.getLocation=function(){return this.location_},t.ASTNode.prototype.getType=function(){return this.type_},t.ASTNode.prototype.getWsCoordinate=function(){return this.wsCoordinate_},t.ASTNode.prototype.isConnection=function(){return this.isConnection_},t.ASTNode.prototype.findNextForInput_=function(){var e,o=this.location_.getParentInput(),i=o.getSourceBlock();for(o=i.inputList.indexOf(o)+1;e=i.inputList[o];o++){for(var n,s=e.fieldRow,r=0;n=s[r];r++)if(n.isClickable()||t.ASTNode.NAVIGATE_ALL_FIELDS)return t.ASTNode.createFieldNode(n);if(e.connection)return t.ASTNode.createInputNode(e)}return null},t.ASTNode.prototype.findNextForField_=function(){var e=this.location_,o=e.getParentInput(),i=e.getSourceBlock(),n=i.inputList.indexOf(o);for(e=o.fieldRow.indexOf(e)+1;o=i.inputList[n];n++){for(var s=o.fieldRow;ei)){var n=o.getSvgXY(e.getSvgRoot());e.outputConnection?(n.x+=(e.RTL?3:-3)*i,n.y+=13*i):e.previousConnection&&(n.x+=(e.RTL?-23:23)*i,n.y+=3*i),e=t.utils.dom.createSvgElement("circle",{cx:n.x,cy:n.y,r:0,fill:"none",stroke:"#888","stroke-width":10},o.getParentSvg()),t.blockAnimations.connectionUiStep_(e,new Date,i)}},t.blockAnimations.connectionUiStep_=function(e,o,i){var n=(new Date-o)/150;1e.workspace.scale)){var o=e.getHeightWidth().height;o=Math.atan(10/o)/Math.PI*180,e.RTL||(o*=-1),t.blockAnimations.disconnectUiStep_(e.getSvgRoot(),o,new Date)}},t.blockAnimations.disconnectUiStep_=function(e,o,i){var n=(new Date-i)/200;1o-t.CURRENT_CONNECTION_PREFERENCE)):!this.localConnection_&&!this.closestConnection_||(console.error("Only one of localConnection_ and closestConnection_ was set."),console.error("Returning true from shouldUpdatePreviews, but it's not clear why."),!0):!(!this.localConnection_||!this.closestConnection_)},t.InsertionMarkerManager.prototype.getCandidate_=function(t){for(var e=this.getStartRadius_(),o=null,i=null,n=0;nthis.remainingCapacityOfType(e))return!1;o+=t[e]}return!(o>this.remainingCapacity())},t.Workspace.prototype.hasBlockLimits=function(){return 1/0!=this.options.maxBlocks||!!this.options.maxInstances},t.Workspace.prototype.undo=function(e){var o=e?this.redoStack_:this.undoStack_,i=e?this.undoStack_:this.redoStack_,n=o.pop();if(n){for(var s=[n];o.length&&n.group&&n.group==o[o.length-1].group;)s.push(o.pop());for(o=0;n=s[o];o++)i.push(n);s=t.Events.filter(s,e),t.Events.recordUndo=!1;try{for(o=0;n=s[o];o++)n.run(e)}finally{t.Events.recordUndo=!0}}},t.Workspace.prototype.clearUndo=function(){this.undoStack_.length=0,this.redoStack_.length=0,t.Events.clearPendingUndo()},t.Workspace.prototype.addChangeListener=function(t){return this.listeners_.push(t),t},t.Workspace.prototype.removeChangeListener=function(e){t.utils.arrayRemove(this.listeners_,e)},t.Workspace.prototype.fireChangeListener=function(t){if(t.recordUndo)for(this.undoStack_.push(t),this.redoStack_.length=0;this.undoStack_.length>this.MAX_UNDO&&0<=this.MAX_UNDO;)this.undoStack_.shift();for(var e,o=0;e=this.listeners_[o];o++)e(t)},t.Workspace.prototype.getBlockById=function(t){return this.blockDB_[t]||null},t.Workspace.prototype.setBlockById=function(t,e){this.blockDB_[t]=e},t.Workspace.prototype.removeBlockById=function(t){delete this.blockDB_[t]},t.Workspace.prototype.getCommentById=function(t){return this.commentDB_[t]||null},t.Workspace.prototype.allInputsFilled=function(t){for(var e,o=this.getTopBlocks(!1),i=0;e=o[i];i++)if(!e.allInputsFilled(t))return!1;return!0},t.Workspace.prototype.getPotentialVariableMap=function(){return this.potentialVariableMap_},t.Workspace.prototype.createPotentialVariableMap=function(){this.potentialVariableMap_=new t.VariableMap(this)},t.Workspace.prototype.getVariableMap=function(){return this.variableMap_},t.Workspace.prototype.setVariableMap=function(t){this.variableMap_=t},t.Workspace.WorkspaceDB_=Object.create(null),t.Workspace.getById=function(e){return t.Workspace.WorkspaceDB_[e]||null},t.Workspace.getAll=function(){var e,o=[];for(e in t.Workspace.WorkspaceDB_)o.push(t.Workspace.WorkspaceDB_[e]);return o},t.Bubble=function(e,o,i,n,s,r){this.workspace_=e,this.content_=o,this.shape_=i,this.onMouseDownResizeWrapper_=this.onMouseDownBubbleWrapper_=this.moveCallback_=this.resizeCallback_=null,this.disposed=!1,i=t.Bubble.ARROW_ANGLE,this.workspace_.RTL&&(i=-i),this.arrow_radians_=t.utils.math.toRadians(i),e.getBubbleCanvas().appendChild(this.createDom_(o,!(!s||!r))),this.setAnchorLocation(n),s&&r||(s=(e=this.content_.getBBox()).width+2*t.Bubble.BORDER_WIDTH,r=e.height+2*t.Bubble.BORDER_WIDTH),this.setBubbleSize(s,r),this.positionBubble_(),this.renderArrow_(),this.rendered_=!0},t.Bubble.BORDER_WIDTH=6,t.Bubble.ARROW_THICKNESS=5,t.Bubble.ARROW_ANGLE=20,t.Bubble.ARROW_BEND=4,t.Bubble.ANCHOR_RADIUS=8,t.Bubble.onMouseUpWrapper_=null,t.Bubble.onMouseMoveWrapper_=null,t.Bubble.unbindDragEvents_=function(){t.Bubble.onMouseUpWrapper_&&(t.unbindEvent_(t.Bubble.onMouseUpWrapper_),t.Bubble.onMouseUpWrapper_=null),t.Bubble.onMouseMoveWrapper_&&(t.unbindEvent_(t.Bubble.onMouseMoveWrapper_),t.Bubble.onMouseMoveWrapper_=null)},t.Bubble.bubbleMouseUp_=function(e){t.Touch.clearTouchIdentifier(),t.Bubble.unbindDragEvents_()},t.Bubble.prototype.rendered_=!1,t.Bubble.prototype.anchorXY_=null,t.Bubble.prototype.relativeLeft_=0,t.Bubble.prototype.relativeTop_=0,t.Bubble.prototype.width_=0,t.Bubble.prototype.height_=0,t.Bubble.prototype.autoLayout_=!0,t.Bubble.prototype.createDom_=function(e,o){this.bubbleGroup_=t.utils.dom.createSvgElement("g",{},null);var i={filter:"url(#"+this.workspace_.getRenderer().getConstants().embossFilterId+")"};return t.utils.userAgent.JAVA_FX&&(i={}),i=t.utils.dom.createSvgElement("g",i,this.bubbleGroup_),this.bubbleArrow_=t.utils.dom.createSvgElement("path",{},i),this.bubbleBack_=t.utils.dom.createSvgElement("rect",{class:"blocklyDraggable",x:0,y:0,rx:t.Bubble.BORDER_WIDTH,ry:t.Bubble.BORDER_WIDTH},i),o?(this.resizeGroup_=t.utils.dom.createSvgElement("g",{class:this.workspace_.RTL?"blocklyResizeSW":"blocklyResizeSE"},this.bubbleGroup_),o=2*t.Bubble.BORDER_WIDTH,t.utils.dom.createSvgElement("polygon",{points:"0,x x,x x,0".replace(/x/g,o.toString())},this.resizeGroup_),t.utils.dom.createSvgElement("line",{class:"blocklyResizeLine",x1:o/3,y1:o-1,x2:o-1,y2:o/3},this.resizeGroup_),t.utils.dom.createSvgElement("line",{class:"blocklyResizeLine",x1:2*o/3,y1:o-1,x2:o-1,y2:2*o/3},this.resizeGroup_)):this.resizeGroup_=null,this.workspace_.options.readOnly||(this.onMouseDownBubbleWrapper_=t.bindEventWithChecks_(this.bubbleBack_,"mousedown",this,this.bubbleMouseDown_),this.resizeGroup_&&(this.onMouseDownResizeWrapper_=t.bindEventWithChecks_(this.resizeGroup_,"mousedown",this,this.resizeMouseDown_))),this.bubbleGroup_.appendChild(e),this.bubbleGroup_},t.Bubble.prototype.getSvgRoot=function(){return this.bubbleGroup_},t.Bubble.prototype.setSvgId=function(t){this.bubbleGroup_.dataset&&(this.bubbleGroup_.dataset.blockId=t)},t.Bubble.prototype.bubbleMouseDown_=function(t){var e=this.workspace_.getGesture(t);e&&e.handleBubbleStart(t,this)},t.Bubble.prototype.showContextMenu=function(t){},t.Bubble.prototype.isDeletable=function(){return!1},t.Bubble.prototype.resizeMouseDown_=function(e){this.promote(),t.Bubble.unbindDragEvents_(),t.utils.isRightButton(e)||(this.workspace_.startDrag(e,new t.utils.Coordinate(this.workspace_.RTL?-this.width_:this.width_,this.height_)),t.Bubble.onMouseUpWrapper_=t.bindEventWithChecks_(document,"mouseup",this,t.Bubble.bubbleMouseUp_),t.Bubble.onMouseMoveWrapper_=t.bindEventWithChecks_(document,"mousemove",this,this.resizeMouseMove_),t.hideChaff()),e.stopPropagation()},t.Bubble.prototype.resizeMouseMove_=function(t){this.autoLayout_=!1,t=this.workspace_.moveDrag(t),this.setBubbleSize(this.workspace_.RTL?-t.x:t.x,t.y),this.workspace_.RTL&&this.positionBubble_()},t.Bubble.prototype.registerResizeEvent=function(t){this.resizeCallback_=t},t.Bubble.prototype.registerMoveEvent=function(t){this.moveCallback_=t},t.Bubble.prototype.promote=function(){var t=this.bubbleGroup_.parentNode;return t.lastChild!==this.bubbleGroup_&&(t.appendChild(this.bubbleGroup_),!0)},t.Bubble.prototype.setAnchorLocation=function(t){this.anchorXY_=t,this.rendered_&&this.positionBubble_()},t.Bubble.prototype.layoutBubble_=function(){var t=this.workspace_.getMetrics();t.viewLeft/=this.workspace_.scale,t.viewWidth/=this.workspace_.scale,t.viewTop/=this.workspace_.scale,t.viewHeight/=this.workspace_.scale;var e=this.getOptimalRelativeLeft_(t),o=this.getOptimalRelativeTop_(t),i=this.shape_.getBBox(),n={x:e,y:-this.height_-this.workspace_.getRenderer().getConstants().MIN_BLOCK_HEIGHT},s={x:-this.width_-30,y:o};o={x:i.width,y:o};var r={x:e,y:i.height};e=i.widthe.viewWidth)return o;if(this.workspace_.RTL)var i=this.anchorXY_.x-o,n=i-this.width_,s=e.viewLeft+e.viewWidth,r=e.viewLeft+t.Scrollbar.scrollbarThickness/this.workspace_.scale;else i=(n=o+this.anchorXY_.x)+this.width_,r=e.viewLeft,s=e.viewLeft+e.viewWidth-t.Scrollbar.scrollbarThickness/this.workspace_.scale;return this.workspace_.RTL?ns&&(o=-(s-this.anchorXY_.x)):ns&&(o=s-this.anchorXY_.x-this.width_),o},t.Bubble.prototype.getOptimalRelativeTop_=function(e){var o=-this.height_/4;if(this.height_>e.viewHeight)return o;var i=this.anchorXY_.y+o,n=i+this.height_,s=e.viewTop;e=e.viewTop+e.viewHeight-t.Scrollbar.scrollbarThickness/this.workspace_.scale;var r=this.anchorXY_.y;return ie&&(o=e-r-this.height_),o},t.Bubble.prototype.positionBubble_=function(){var t=this.anchorXY_.x;t=this.workspace_.RTL?t-(this.relativeLeft_+this.width_):t+this.relativeLeft_,this.moveTo(t,this.relativeTop_+this.anchorXY_.y)},t.Bubble.prototype.moveTo=function(t,e){this.bubbleGroup_.setAttribute("transform","translate("+t+","+e+")")},t.Bubble.prototype.setDragging=function(t){!t&&this.moveCallback_&&this.moveCallback_()},t.Bubble.prototype.getBubbleSize=function(){return new t.utils.Size(this.width_,this.height_)},t.Bubble.prototype.setBubbleSize=function(e,o){var i=2*t.Bubble.BORDER_WIDTH;e=Math.max(e,i+45),o=Math.max(o,i+20),this.width_=e,this.height_=o,this.bubbleBack_.setAttribute("width",e),this.bubbleBack_.setAttribute("height",o),this.resizeGroup_&&(this.workspace_.RTL?this.resizeGroup_.setAttribute("transform","translate("+2*t.Bubble.BORDER_WIDTH+","+(o-i)+") scale(-1 1)"):this.resizeGroup_.setAttribute("transform","translate("+(e-i)+","+(o-i)+")")),this.autoLayout_&&this.layoutBubble_(),this.positionBubble_(),this.renderArrow_(),this.resizeCallback_&&this.resizeCallback_()},t.Bubble.prototype.renderArrow_=function(){var e=[],o=this.width_/2,i=this.height_/2,n=-this.relativeLeft_,s=-this.relativeTop_;if(o==n&&i==s)e.push("M "+o+","+i);else{s-=i,n-=o,this.workspace_.RTL&&(n*=-1);var r=Math.sqrt(s*s+n*n),a=Math.acos(n/r);0>s&&(a=2*Math.PI-a);var l=a+Math.PI/2;l>2*Math.PI&&(l-=2*Math.PI);var c=Math.sin(l),h=Math.cos(l),u=this.getBubbleSize();l=(u.width+u.height)/t.Bubble.ARROW_THICKNESS,l=Math.min(l,u.width,u.height)/4,n=o+(u=1-t.Bubble.ANCHOR_RADIUS/r)*n,s=i+u*s,u=o+l*h;var p=i+l*c;o-=l*h,i-=l*c,(c=a+this.arrow_radians_)>2*Math.PI&&(c-=2*Math.PI),a=Math.sin(c)*r/t.Bubble.ARROW_BEND,r=Math.cos(c)*r/t.Bubble.ARROW_BEND,e.push("M"+u+","+p),e.push("C"+(u+r)+","+(p+a)+" "+n+","+s+" "+n+","+s),e.push("C"+n+","+s+" "+(o+r)+","+(i+a)+" "+o+","+i)}e.push("z"),this.bubbleArrow_.setAttribute("d",e.join(" "))},t.Bubble.prototype.setColour=function(t){this.bubbleBack_.setAttribute("fill",t),this.bubbleArrow_.setAttribute("fill",t)},t.Bubble.prototype.dispose=function(){this.onMouseDownBubbleWrapper_&&t.unbindEvent_(this.onMouseDownBubbleWrapper_),this.onMouseDownResizeWrapper_&&t.unbindEvent_(this.onMouseDownResizeWrapper_),t.Bubble.unbindDragEvents_(),t.utils.dom.removeNode(this.bubbleGroup_),this.disposed=!0},t.Bubble.prototype.moveDuringDrag=function(t,e){t?t.translateSurface(e.x,e.y):this.moveTo(e.x,e.y),this.relativeLeft_=this.workspace_.RTL?this.anchorXY_.x-e.x-this.width_:e.x-this.anchorXY_.x,this.relativeTop_=e.y-this.anchorXY_.y,this.renderArrow_()},t.Bubble.prototype.getRelativeToSurfaceXY=function(){return new t.utils.Coordinate(this.workspace_.RTL?-this.relativeLeft_+this.anchorXY_.x-this.width_:this.anchorXY_.x+this.relativeLeft_,this.anchorXY_.y+this.relativeTop_)},t.Bubble.prototype.setAutoLayout=function(t){this.autoLayout_=t},t.Events.CommentBase=function(e){this.commentId=e.id,this.workspaceId=e.workspace.id,this.group=t.Events.getGroup(),this.recordUndo=t.Events.recordUndo},t.utils.object.inherits(t.Events.CommentBase,t.Events.Abstract),t.Events.CommentBase.prototype.toJson=function(){var e=t.Events.CommentBase.superClass_.toJson.call(this);return this.commentId&&(e.commentId=this.commentId),e},t.Events.CommentBase.prototype.fromJson=function(e){t.Events.CommentBase.superClass_.fromJson.call(this,e),this.commentId=e.commentId},t.Events.CommentChange=function(e,o,i){e&&(t.Events.CommentChange.superClass_.constructor.call(this,e),this.oldContents_=o,this.newContents_=i)},t.utils.object.inherits(t.Events.CommentChange,t.Events.CommentBase),t.Events.CommentChange.prototype.type=t.Events.COMMENT_CHANGE,t.Events.CommentChange.prototype.toJson=function(){var e=t.Events.CommentChange.superClass_.toJson.call(this);return e.newContents=this.newContents_,e},t.Events.CommentChange.prototype.fromJson=function(e){t.Events.CommentChange.superClass_.fromJson.call(this,e),this.newContents_=e.newValue},t.Events.CommentChange.prototype.isNull=function(){return this.oldContents_==this.newContents_},t.Events.CommentChange.prototype.run=function(t){var e=this.getEventWorkspace_().getCommentById(this.commentId);e?e.setContent(t?this.newContents_:this.oldContents_):console.warn("Can't change non-existent comment: "+this.commentId)},t.Events.CommentCreate=function(e){e&&(t.Events.CommentCreate.superClass_.constructor.call(this,e),this.xml=e.toXmlWithXY())},t.utils.object.inherits(t.Events.CommentCreate,t.Events.CommentBase),t.Events.CommentCreate.prototype.type=t.Events.COMMENT_CREATE,t.Events.CommentCreate.prototype.toJson=function(){var e=t.Events.CommentCreate.superClass_.toJson.call(this);return e.xml=t.Xml.domToText(this.xml),e},t.Events.CommentCreate.prototype.fromJson=function(e){t.Events.CommentCreate.superClass_.fromJson.call(this,e),this.xml=t.Xml.textToDom(e.xml)},t.Events.CommentCreate.prototype.run=function(e){t.Events.CommentCreateDeleteHelper(this,e)},t.Events.CommentCreateDeleteHelper=function(e,o){var i=e.getEventWorkspace_();o?((o=t.utils.xml.createElement("xml")).appendChild(e.xml),t.Xml.domToWorkspace(o,i)):(i=i.getCommentById(e.commentId))?i.dispose(!1,!1):console.warn("Can't uncreate non-existent comment: "+e.commentId)},t.Events.CommentDelete=function(e){e&&(t.Events.CommentDelete.superClass_.constructor.call(this,e),this.xml=e.toXmlWithXY())},t.utils.object.inherits(t.Events.CommentDelete,t.Events.CommentBase),t.Events.CommentDelete.prototype.type=t.Events.COMMENT_DELETE,t.Events.CommentDelete.prototype.toJson=function(){return t.Events.CommentDelete.superClass_.toJson.call(this)},t.Events.CommentDelete.prototype.fromJson=function(e){t.Events.CommentDelete.superClass_.fromJson.call(this,e)},t.Events.CommentDelete.prototype.run=function(e){t.Events.CommentCreateDeleteHelper(this,!e)},t.Events.CommentMove=function(e){e&&(t.Events.CommentMove.superClass_.constructor.call(this,e),this.comment_=e,this.oldCoordinate_=e.getXY(),this.newCoordinate_=null)},t.utils.object.inherits(t.Events.CommentMove,t.Events.CommentBase),t.Events.CommentMove.prototype.recordNew=function(){if(!this.comment_)throw Error("Tried to record the new position of a comment on the same event twice.");this.newCoordinate_=this.comment_.getXY(),this.comment_=null},t.Events.CommentMove.prototype.type=t.Events.COMMENT_MOVE,t.Events.CommentMove.prototype.setOldCoordinate=function(t){this.oldCoordinate_=t},t.Events.CommentMove.prototype.toJson=function(){var e=t.Events.CommentMove.superClass_.toJson.call(this);return this.newCoordinate_&&(e.newCoordinate=Math.round(this.newCoordinate_.x)+","+Math.round(this.newCoordinate_.y)),e},t.Events.CommentMove.prototype.fromJson=function(e){t.Events.CommentMove.superClass_.fromJson.call(this,e),e.newCoordinate&&(e=e.newCoordinate.split(","),this.newCoordinate_=new t.utils.Coordinate(Number(e[0]),Number(e[1])))},t.Events.CommentMove.prototype.isNull=function(){return t.utils.Coordinate.equals(this.oldCoordinate_,this.newCoordinate_)},t.Events.CommentMove.prototype.run=function(t){var e=this.getEventWorkspace_().getCommentById(this.commentId);if(e){t=t?this.newCoordinate_:this.oldCoordinate_;var o=e.getXY();e.moveBy(t.x-o.x,t.y-o.y)}else console.warn("Can't move non-existent comment: "+this.commentId)},t.BubbleDragger=function(e,o){this.draggingBubble_=e,this.workspace_=o,this.deleteArea_=null,this.wouldDeleteBubble_=!1,this.startXY_=this.draggingBubble_.getRelativeToSurfaceXY(),this.dragSurface_=t.utils.is3dSupported()&&o.getBlockDragSurface()?o.getBlockDragSurface():null},t.BubbleDragger.prototype.dispose=function(){this.dragSurface_=this.workspace_=this.draggingBubble_=null},t.BubbleDragger.prototype.startBubbleDrag=function(){t.Events.getGroup()||t.Events.setGroup(!0),this.workspace_.setResizesEnabled(!1),this.draggingBubble_.setAutoLayout(!1),this.dragSurface_&&this.moveToDragSurface_(),this.draggingBubble_.setDragging&&this.draggingBubble_.setDragging(!0);var e=this.workspace_.getToolbox();if(e){var o=this.draggingBubble_.isDeletable()?"blocklyToolboxDelete":"blocklyToolboxGrab";e.addStyle(o)}},t.BubbleDragger.prototype.dragBubble=function(e,o){o=this.pixelsToWorkspaceUnits_(o),o=t.utils.Coordinate.sum(this.startXY_,o),this.draggingBubble_.moveDuringDrag(this.dragSurface_,o),this.draggingBubble_.isDeletable()&&(this.deleteArea_=this.workspace_.isDeleteArea(e),this.updateCursorDuringBubbleDrag_())},t.BubbleDragger.prototype.maybeDeleteBubble_=function(){var t=this.workspace_.trashcan;return this.wouldDeleteBubble_?(t&&setTimeout(t.close.bind(t),100),this.fireMoveEvent_(),this.draggingBubble_.dispose(!1,!0)):t&&t.close(),this.wouldDeleteBubble_},t.BubbleDragger.prototype.updateCursorDuringBubbleDrag_=function(){this.wouldDeleteBubble_=this.deleteArea_!=t.DELETE_AREA_NONE;var e=this.workspace_.trashcan;this.wouldDeleteBubble_?(this.draggingBubble_.setDeleteStyle(!0),this.deleteArea_==t.DELETE_AREA_TRASH&&e&&e.setOpen(!0)):(this.draggingBubble_.setDeleteStyle(!1),e&&e.setOpen(!1))},t.BubbleDragger.prototype.endBubbleDrag=function(e,o){this.dragBubble(e,o),e=this.pixelsToWorkspaceUnits_(o),e=t.utils.Coordinate.sum(this.startXY_,e),this.draggingBubble_.moveTo(e.x,e.y),this.maybeDeleteBubble_()||(this.dragSurface_&&this.dragSurface_.clearAndHide(this.workspace_.getBubbleCanvas()),this.draggingBubble_.setDragging&&this.draggingBubble_.setDragging(!1),this.fireMoveEvent_()),this.workspace_.setResizesEnabled(!0),this.workspace_.getToolbox()&&(e=this.draggingBubble_.isDeletable()?"blocklyToolboxDelete":"blocklyToolboxGrab",this.workspace_.getToolbox().removeStyle(e)),t.Events.setGroup(!1)},t.BubbleDragger.prototype.fireMoveEvent_=function(){if(this.draggingBubble_.isComment){var e=new t.Events.CommentMove(this.draggingBubble_);e.setOldCoordinate(this.startXY_),e.recordNew(),t.Events.fire(e)}},t.BubbleDragger.prototype.pixelsToWorkspaceUnits_=function(e){return e=new t.utils.Coordinate(e.x/this.workspace_.scale,e.y/this.workspace_.scale),this.workspace_.isMutator&&e.scale(1/this.workspace_.options.parentWorkspace.scale),e},t.BubbleDragger.prototype.moveToDragSurface_=function(){this.draggingBubble_.moveTo(0,0),this.dragSurface_.translateSurface(this.startXY_.x,this.startXY_.y),this.dragSurface_.setBlocksAndShow(this.draggingBubble_.getSvgRoot())},t.WorkspaceDragger=function(e){this.workspace_=e,this.startScrollXY_=new t.utils.Coordinate(e.scrollX,e.scrollY)},t.WorkspaceDragger.prototype.dispose=function(){this.workspace_=null},t.WorkspaceDragger.prototype.startDrag=function(){t.selected&&t.selected.unselect(),this.workspace_.setupDragSurface()},t.WorkspaceDragger.prototype.endDrag=function(t){this.drag(t),this.workspace_.resetDragSurface()},t.WorkspaceDragger.prototype.drag=function(e){e=t.utils.Coordinate.sum(this.startScrollXY_,e),this.workspace_.scroll(e.x,e.y)},t.FlyoutDragger=function(e){t.FlyoutDragger.superClass_.constructor.call(this,e.getWorkspace()),this.scrollbar_=e.scrollbar_,this.horizontalLayout_=e.horizontalLayout_},t.utils.object.inherits(t.FlyoutDragger,t.WorkspaceDragger),t.FlyoutDragger.prototype.drag=function(e){e=t.utils.Coordinate.sum(this.startScrollXY_,e),this.horizontalLayout_?this.scrollbar_.set(-e.x):this.scrollbar_.set(-e.y)},t.Action=function(t,e){this.name=t,this.desc=e},t.navigation={},t.navigation.loggingCallback=null,t.navigation.STATE_FLYOUT=1,t.navigation.STATE_WS=2,t.navigation.STATE_TOOLBOX=3,t.navigation.WS_MOVE_DISTANCE=40,t.navigation.currentState_=t.navigation.STATE_WS,t.navigation.actionNames={PREVIOUS:"previous",NEXT:"next",IN:"in",OUT:"out",INSERT:"insert",MARK:"mark",DISCONNECT:"disconnect",TOOLBOX:"toolbox",EXIT:"exit",TOGGLE_KEYBOARD_NAV:"toggle_keyboard_nav",MOVE_WS_CURSOR_UP:"move workspace cursor up",MOVE_WS_CURSOR_DOWN:"move workspace cursor down",MOVE_WS_CURSOR_LEFT:"move workspace cursor left",MOVE_WS_CURSOR_RIGHT:"move workspace cursor right"},t.navigation.MARKER_NAME="local_marker_1",t.navigation.getMarker=function(){return t.getMainWorkspace().getMarker(t.navigation.MARKER_NAME)},t.navigation.focusToolbox_=function(){var e=t.getMainWorkspace().getToolbox();e&&(t.navigation.currentState_=t.navigation.STATE_TOOLBOX,t.navigation.resetFlyout_(!1),t.navigation.getMarker().getCurNode()||t.navigation.markAtCursor_(),e.selectFirstCategory())},t.navigation.focusFlyout_=function(){t.navigation.currentState_=t.navigation.STATE_FLYOUT;var e=t.getMainWorkspace(),o=e.getToolbox();e=o?o.flyout_:e.getFlyout(),t.navigation.getMarker().getCurNode()||t.navigation.markAtCursor_(),e&&e.getWorkspace()&&0<(e=e.getWorkspace().getTopBlocks(!0)).length&&(e=e[0],e=t.ASTNode.createStackNode(e),t.navigation.getFlyoutCursor_().setCurNode(e))},t.navigation.focusWorkspace_=function(){t.hideChaff();var e=t.getMainWorkspace(),o=e.getCursor(),i=!!e.getToolbox(),n=e.getTopBlocks(!0);t.navigation.resetFlyout_(i),t.navigation.currentState_=t.navigation.STATE_WS,0(this.flyout_?t.FLYOUT_DRAG_RADIUS:t.DRAG_RADIUS))},t.Gesture.prototype.updateIsDraggingFromFlyout_=function(){return!(!this.targetBlock_||!this.flyout_.isBlockCreatable_(this.targetBlock_)||this.flyout_.isScrollable()&&!this.flyout_.isDragTowardWorkspace(this.currentDragDeltaXY_)||(this.startWorkspace_=this.flyout_.targetWorkspace_,this.startWorkspace_.updateScreenCalculationsIfScrolled(),t.Events.getGroup()||t.Events.setGroup(!0),this.startBlock_=null,this.targetBlock_=this.flyout_.createBlock(this.targetBlock_),this.targetBlock_.select(),0))},t.Gesture.prototype.updateIsDraggingBubble_=function(){return!!this.startBubble_&&(this.isDraggingBubble_=!0,this.startDraggingBubble_(),!0)},t.Gesture.prototype.updateIsDraggingBlock_=function(){return!!this.targetBlock_&&(this.flyout_?this.isDraggingBlock_=this.updateIsDraggingFromFlyout_():this.targetBlock_.isMovable()&&(this.isDraggingBlock_=!0),!!this.isDraggingBlock_&&(this.startDraggingBlock_(),!0))},t.Gesture.prototype.updateIsDraggingWorkspace_=function(){(this.flyout_?this.flyout_.isScrollable():this.startWorkspace_&&this.startWorkspace_.isDraggable())&&(this.workspaceDragger_=this.flyout_?new t.FlyoutDragger(this.flyout_):new t.WorkspaceDragger(this.startWorkspace_),this.isDraggingWorkspace_=!0,this.workspaceDragger_.startDrag())},t.Gesture.prototype.updateIsDragging_=function(){if(this.calledUpdateIsDragging_)throw Error("updateIsDragging_ should only be called once per gesture.");this.calledUpdateIsDragging_=!0,this.updateIsDraggingBubble_()||this.updateIsDraggingBlock_()||this.updateIsDraggingWorkspace_()},t.Gesture.prototype.startDraggingBlock_=function(){this.blockDragger_=new t.BlockDragger(this.targetBlock_,this.startWorkspace_),this.blockDragger_.startBlockDrag(this.currentDragDeltaXY_,this.healStack_),this.blockDragger_.dragBlock(this.mostRecentEvent_,this.currentDragDeltaXY_)},t.Gesture.prototype.startDraggingBubble_=function(){this.bubbleDragger_=new t.BubbleDragger(this.startBubble_,this.startWorkspace_),this.bubbleDragger_.startBubbleDrag(),this.bubbleDragger_.dragBubble(this.mostRecentEvent_,this.currentDragDeltaXY_)},t.Gesture.prototype.doStart=function(e){t.utils.isTargetInput(e)?this.cancel():(this.hasStarted_=!0,t.blockAnimations.disconnectUiStop(),this.startWorkspace_.updateScreenCalculationsIfScrolled(),this.startWorkspace_.isMutator&&this.startWorkspace_.resize(),t.hideChaff(!!this.flyout_),this.startWorkspace_.markFocused(),this.mostRecentEvent_=e,t.Tooltip.block(),this.targetBlock_&&(!this.targetBlock_.isInFlyout&&e.shiftKey&&this.targetBlock_.workspace.keyboardAccessibilityMode?this.creatorWorkspace_.getCursor().setCurNode(t.navigation.getTopNode(this.targetBlock_)):this.targetBlock_.select()),t.utils.isRightButton(e)?this.handleRightClick(e):("touchstart"!=e.type.toLowerCase()&&"pointerdown"!=e.type.toLowerCase()||"mouse"==e.pointerType||t.longStart(e,this),this.mouseDownXY_=new t.utils.Coordinate(e.clientX,e.clientY),this.healStack_=e.altKey||e.ctrlKey||e.metaKey,this.bindMouseEvents(e)))},t.Gesture.prototype.bindMouseEvents=function(e){this.onMoveWrapper_=t.bindEventWithChecks_(document,"mousemove",null,this.handleMove.bind(this)),this.onUpWrapper_=t.bindEventWithChecks_(document,"mouseup",null,this.handleUp.bind(this)),e.preventDefault(),e.stopPropagation()},t.Gesture.prototype.handleMove=function(t){this.updateFromEvent_(t),this.isDraggingWorkspace_?this.workspaceDragger_.drag(this.currentDragDeltaXY_):this.isDraggingBlock_?this.blockDragger_.dragBlock(this.mostRecentEvent_,this.currentDragDeltaXY_):this.isDraggingBubble_&&this.bubbleDragger_.dragBubble(this.mostRecentEvent_,this.currentDragDeltaXY_),t.preventDefault(),t.stopPropagation()},t.Gesture.prototype.handleUp=function(e){this.updateFromEvent_(e),t.longStop_(),this.isEnding_?console.log("Trying to end a gesture recursively."):(this.isEnding_=!0,this.isDraggingBubble_?this.bubbleDragger_.endBubbleDrag(e,this.currentDragDeltaXY_):this.isDraggingBlock_?this.blockDragger_.endBlockDrag(e,this.currentDragDeltaXY_):this.isDraggingWorkspace_?this.workspaceDragger_.endDrag(this.currentDragDeltaXY_):this.isBubbleClick_()?this.doBubbleClick_():this.isFieldClick_()?this.doFieldClick_():this.isBlockClick_()?this.doBlockClick_():this.isWorkspaceClick_()&&this.doWorkspaceClick_(e),e.preventDefault(),e.stopPropagation(),this.dispose())},t.Gesture.prototype.cancel=function(){this.isEnding_||(t.longStop_(),this.isDraggingBubble_?this.bubbleDragger_.endBubbleDrag(this.mostRecentEvent_,this.currentDragDeltaXY_):this.isDraggingBlock_?this.blockDragger_.endBlockDrag(this.mostRecentEvent_,this.currentDragDeltaXY_):this.isDraggingWorkspace_&&this.workspaceDragger_.endDrag(this.currentDragDeltaXY_),this.dispose())},t.Gesture.prototype.handleRightClick=function(e){this.targetBlock_?(this.bringBlockToFront_(),t.hideChaff(!!this.flyout_),this.targetBlock_.showContextMenu(e)):this.startBubble_?this.startBubble_.showContextMenu(e):this.startWorkspace_&&!this.flyout_&&(t.hideChaff(),this.startWorkspace_.showContextMenu(e)),e.preventDefault(),e.stopPropagation(),this.dispose()},t.Gesture.prototype.handleWsStart=function(e,o){if(this.hasStarted_)throw Error("Tried to call gesture.handleWsStart, but the gesture had already been started.");this.setStartWorkspace_(o),this.mostRecentEvent_=e,this.doStart(e),this.startWorkspace_.keyboardAccessibilityMode&&t.navigation.setState(t.navigation.STATE_WS)},t.Gesture.prototype.handleFlyoutStart=function(t,e){if(this.hasStarted_)throw Error("Tried to call gesture.handleFlyoutStart, but the gesture had already been started.");this.setStartFlyout_(e),this.handleWsStart(t,e.getWorkspace())},t.Gesture.prototype.handleBlockStart=function(t,e){if(this.hasStarted_)throw Error("Tried to call gesture.handleBlockStart, but the gesture had already been started.");this.setStartBlock(e),this.mostRecentEvent_=t},t.Gesture.prototype.handleBubbleStart=function(t,e){if(this.hasStarted_)throw Error("Tried to call gesture.handleBubbleStart, but the gesture had already been started.");this.setStartBubble(e),this.mostRecentEvent_=t},t.Gesture.prototype.doBubbleClick_=function(){this.startBubble_.setFocus&&this.startBubble_.setFocus(),this.startBubble_.select&&this.startBubble_.select()},t.Gesture.prototype.doFieldClick_=function(){this.startField_.showEditor(this.mostRecentEvent_),this.bringBlockToFront_()},t.Gesture.prototype.doBlockClick_=function(){this.flyout_&&this.flyout_.autoClose?this.targetBlock_.isEnabled()&&(t.Events.getGroup()||t.Events.setGroup(!0),this.flyout_.createBlock(this.targetBlock_).scheduleSnapAndBump()):t.Events.fire(new t.Events.Ui(this.startBlock_,"click",void 0,void 0)),this.bringBlockToFront_(),t.Events.setGroup(!1)},t.Gesture.prototype.doWorkspaceClick_=function(e){var o=this.creatorWorkspace_;e.shiftKey&&o.keyboardAccessibilityMode?(e=new t.utils.Coordinate(e.clientX,e.clientY),e=t.utils.screenToWsCoordinates(o,e),e=t.ASTNode.createWorkspaceNode(o,e),o.getCursor().setCurNode(e)):t.selected&&t.selected.unselect()},t.Gesture.prototype.bringBlockToFront_=function(){this.targetBlock_&&!this.flyout_&&this.targetBlock_.bringToFront()},t.Gesture.prototype.setStartField=function(t){if(this.hasStarted_)throw Error("Tried to call gesture.setStartField, but the gesture had already been started.");this.startField_||(this.startField_=t)},t.Gesture.prototype.setStartBubble=function(t){this.startBubble_||(this.startBubble_=t)},t.Gesture.prototype.setStartBlock=function(t){this.startBlock_||this.startBubble_||(this.startBlock_=t,t.isInFlyout&&t!=t.getRootBlock()?this.setTargetBlock_(t.getRootBlock()):this.setTargetBlock_(t))},t.Gesture.prototype.setTargetBlock_=function(t){t.isShadow()?this.setTargetBlock_(t.getParent()):this.targetBlock_=t},t.Gesture.prototype.setStartWorkspace_=function(t){this.startWorkspace_||(this.startWorkspace_=t)},t.Gesture.prototype.setStartFlyout_=function(t){this.flyout_||(this.flyout_=t)},t.Gesture.prototype.isBubbleClick_=function(){return!!this.startBubble_&&!this.hasExceededDragRadius_},t.Gesture.prototype.isBlockClick_=function(){return!!this.startBlock_&&!this.hasExceededDragRadius_&&!this.isFieldClick_()},t.Gesture.prototype.isFieldClick_=function(){return!!this.startField_&&this.startField_.isClickable()&&!this.hasExceededDragRadius_&&(!this.flyout_||!this.flyout_.autoClose)},t.Gesture.prototype.isWorkspaceClick_=function(){return!(this.startBlock_||this.startBubble_||this.startField_||this.hasExceededDragRadius_)},t.Gesture.prototype.isDragging=function(){return this.isDraggingWorkspace_||this.isDraggingBlock_||this.isDraggingBubble_},t.Gesture.prototype.hasStarted=function(){return this.hasStarted_},t.Gesture.prototype.getInsertionMarkers=function(){return this.blockDragger_?this.blockDragger_.getInsertionMarkers():[]},t.Gesture.inProgress=function(){for(var e,o=t.Workspace.getAll(),i=0;e=o[i];i++)if(e.currentGesture_)return!0;return!1},t.Field=function(e,o,i){this.tooltip_=this.validator_=this.value_=null,this.size_=new t.utils.Size(0,0),this.constants_=this.mouseDownWrapper_=this.textContent_=this.textElement_=this.borderRect_=this.fieldGroup_=this.markerSvg_=this.cursorSvg_=null,i&&this.configure_(i),this.setValue(e),o&&this.setValidator(o)},t.Field.prototype.name=void 0,t.Field.prototype.disposed=!1,t.Field.prototype.maxDisplayLength=50,t.Field.prototype.sourceBlock_=null,t.Field.prototype.isDirty_=!0,t.Field.prototype.visible_=!0,t.Field.prototype.clickTarget_=null,t.Field.NBSP=" ",t.Field.prototype.EDITABLE=!0,t.Field.prototype.SERIALIZABLE=!1,t.Field.prototype.configure_=function(e){var o=e.tooltip;"string"==typeof o&&(o=t.utils.replaceMessageReferences(e.tooltip)),o&&this.setTooltip(o)},t.Field.prototype.setSourceBlock=function(t){if(this.sourceBlock_)throw Error("Field already bound to a block.");this.sourceBlock_=t},t.Field.prototype.getConstants=function(){return!this.constants_&&this.sourceBlock_&&this.sourceBlock_.workspace&&this.sourceBlock_.workspace.rendered&&(this.constants_=this.sourceBlock_.workspace.getRenderer().getConstants()),this.constants_},t.Field.prototype.getSourceBlock=function(){return this.sourceBlock_},t.Field.prototype.init=function(){this.fieldGroup_||(this.fieldGroup_=t.utils.dom.createSvgElement("g",{},null),this.isVisible()||(this.fieldGroup_.style.display="none"),this.sourceBlock_.getSvgRoot().appendChild(this.fieldGroup_),this.initView(),this.updateEditable(),this.setTooltip(this.tooltip_),this.bindEvents_(),this.initModel())},t.Field.prototype.initView=function(){this.createBorderRect_(),this.createTextElement_()},t.Field.prototype.initModel=function(){},t.Field.prototype.createBorderRect_=function(){this.borderRect_=t.utils.dom.createSvgElement("rect",{rx:this.getConstants().FIELD_BORDER_RECT_RADIUS,ry:this.getConstants().FIELD_BORDER_RECT_RADIUS,x:0,y:0,height:this.size_.height,width:this.size_.width,class:"blocklyFieldRect"},this.fieldGroup_)},t.Field.prototype.createTextElement_=function(){this.textElement_=t.utils.dom.createSvgElement("text",{class:"blocklyText"},this.fieldGroup_),this.getConstants().FIELD_TEXT_BASELINE_CENTER&&this.textElement_.setAttribute("dominant-baseline","central"),this.textContent_=document.createTextNode(""),this.textElement_.appendChild(this.textContent_)},t.Field.prototype.bindEvents_=function(){t.Tooltip.bindMouseEvents(this.getClickTarget_()),this.mouseDownWrapper_=t.bindEventWithChecks_(this.getClickTarget_(),"mousedown",this,this.onMouseDown_)},t.Field.prototype.fromXml=function(t){this.setValue(t.textContent)},t.Field.prototype.toXml=function(t){return t.textContent=this.getValue(),t},t.Field.prototype.dispose=function(){t.DropDownDiv.hideIfOwner(this),t.WidgetDiv.hideIfOwner(this),t.Tooltip.unbindMouseEvents(this.getClickTarget_()),this.mouseDownWrapper_&&t.unbindEvent_(this.mouseDownWrapper_),t.utils.dom.removeNode(this.fieldGroup_),this.disposed=!0},t.Field.prototype.updateEditable=function(){var e=this.fieldGroup_;this.EDITABLE&&e&&(this.sourceBlock_.isEditable()?(t.utils.dom.addClass(e,"blocklyEditableText"),t.utils.dom.removeClass(e,"blocklyNonEditableText"),e.style.cursor=this.CURSOR):(t.utils.dom.addClass(e,"blocklyNonEditableText"),t.utils.dom.removeClass(e,"blocklyEditableText"),e.style.cursor=""))},t.Field.prototype.isClickable=function(){return!!this.sourceBlock_&&this.sourceBlock_.isEditable()&&!!this.showEditor_&&"function"==typeof this.showEditor_},t.Field.prototype.isCurrentlyEditable=function(){return this.EDITABLE&&!!this.sourceBlock_&&this.sourceBlock_.isEditable()},t.Field.prototype.isSerializable=function(){var t=!1;return this.name&&(this.SERIALIZABLE?t=!0:this.EDITABLE&&(console.warn("Detected an editable field that was not serializable. Please define SERIALIZABLE property as true on all editable custom fields. Proceeding with serialization."),t=!0)),t},t.Field.prototype.isVisible=function(){return this.visible_},t.Field.prototype.setVisible=function(t){if(this.visible_!=t){this.visible_=t;var e=this.getSvgRoot();e&&(e.style.display=t?"block":"none")}},t.Field.prototype.setValidator=function(t){this.validator_=t},t.Field.prototype.getValidator=function(){return this.validator_},t.Field.prototype.classValidator=function(t){return t},t.Field.prototype.callValidator=function(t){var e=this.classValidator(t);if(null===e)return null;if(void 0!==e&&(t=e),e=this.getValidator()){if(null===(e=e.call(this,t)))return null;void 0!==e&&(t=e)}return t},t.Field.prototype.getSvgRoot=function(){return this.fieldGroup_},t.Field.prototype.applyColour=function(){},t.Field.prototype.render_=function(){this.textContent_&&(this.textContent_.nodeValue=this.getDisplayText_()),this.updateSize_()},t.Field.prototype.showEditor=function(t){this.isClickable()&&this.showEditor_(t)},t.Field.prototype.updateWidth=function(){console.warn("Deprecated call to updateWidth, call Blockly.Field.updateSize_ to force an update to the size of the field, or Blockly.utils.dom.getTextWidth() to check the size of the field."),this.updateSize_()},t.Field.prototype.updateSize_=function(e){var o=this.getConstants(),i=2*(e=null!=e?e:this.borderRect_?this.getConstants().FIELD_BORDER_RECT_X_PADDING:0),n=o.FIELD_TEXT_HEIGHT,s=0;this.textElement_&&(i+=s=t.utils.dom.getFastTextWidth(this.textElement_,o.FIELD_TEXT_FONTSIZE,o.FIELD_TEXT_FONTWEIGHT,o.FIELD_TEXT_FONTFAMILY)),this.borderRect_&&(n=Math.max(n,o.FIELD_BORDER_RECT_HEIGHT)),this.size_.height=n,this.size_.width=i,this.positionTextElement_(e,s),this.positionBorderRect_()},t.Field.prototype.positionTextElement_=function(t,e){if(this.textElement_){var o=this.getConstants(),i=this.size_.height/2;this.textElement_.setAttribute("x",this.sourceBlock_.RTL?this.size_.width-e-t:t),this.textElement_.setAttribute("y",o.FIELD_TEXT_BASELINE_CENTER?i:i-o.FIELD_TEXT_HEIGHT/2+o.FIELD_TEXT_BASELINE)}},t.Field.prototype.positionBorderRect_=function(){this.borderRect_&&(this.borderRect_.setAttribute("width",this.size_.width),this.borderRect_.setAttribute("height",this.size_.height),this.borderRect_.setAttribute("rx",this.getConstants().FIELD_BORDER_RECT_RADIUS),this.borderRect_.setAttribute("ry",this.getConstants().FIELD_BORDER_RECT_RADIUS))},t.Field.prototype.getSize=function(){return this.isVisible()?(this.isDirty_?(this.render_(),this.isDirty_=!1):this.visible_&&0==this.size_.width&&(console.warn("Deprecated use of setting size_.width to 0 to rerender a field. Set field.isDirty_ to true instead."),this.render_()),this.size_):new t.utils.Size(0,0)},t.Field.prototype.getScaledBBox=function(){if(this.borderRect_)e=this.borderRect_.getBoundingClientRect(),i=t.utils.style.getPageOffset(this.borderRect_),n=e.width,e=e.height;else{var e=this.sourceBlock_.getHeightWidth(),o=this.sourceBlock_.workspace.scale,i=this.getAbsoluteXY_(),n=e.width*o;e=e.height*o,t.utils.userAgent.GECKO?(i.x+=1.5*o,i.y+=1.5*o):t.utils.userAgent.EDGE||t.utils.userAgent.IE||(i.x-=.5*o,i.y-=.5*o),n+=1*o,e+=1*o}return{top:i.y,bottom:i.y+e,left:i.x,right:i.x+n}},t.Field.prototype.getDisplayText_=function(){var e=this.getText();return e?(e.length>this.maxDisplayLength&&(e=e.substring(0,this.maxDisplayLength-2)+"…"),e=e.replace(/\s/g,t.Field.NBSP),this.sourceBlock_&&this.sourceBlock_.RTL&&(e+="‏"),e):t.Field.NBSP},t.Field.prototype.getText=function(){if(this.getText_){var t=this.getText_.call(this);if(null!==t)return String(t)}return String(this.getValue())},t.Field.prototype.setText=function(t){throw Error("setText method is deprecated")},t.Field.prototype.markDirty=function(){this.isDirty_=!0,this.constants_=null},t.Field.prototype.forceRerender=function(){this.isDirty_=!0,this.sourceBlock_&&this.sourceBlock_.rendered&&(this.sourceBlock_.render(),this.sourceBlock_.bumpNeighbours(),this.updateMarkers_())},t.Field.prototype.setValue=function(e){if(null!==e){var o=this.doClassValidation_(e);if(!((e=this.processValidation_(e,o))instanceof Error)){if((o=this.getValidator())&&(o=o.call(this,e),(e=this.processValidation_(e,o))instanceof Error))return;(o=this.getValue())!==e&&(this.sourceBlock_&&t.Events.isEnabled()&&t.Events.fire(new t.Events.BlockChange(this.sourceBlock_,"field",this.name||null,o,e)),this.doValueUpdate_(e),this.isDirty_&&this.forceRerender())}}},t.Field.prototype.processValidation_=function(t,e){return null===e?(this.doValueInvalid_(t),this.isDirty_&&this.forceRerender(),Error()):(void 0!==e&&(t=e),t)},t.Field.prototype.getValue=function(){return this.value_},t.Field.prototype.doClassValidation_=function(t){return null==t?null:t=this.classValidator(t)},t.Field.prototype.doValueUpdate_=function(t){this.value_=t,this.isDirty_=!0},t.Field.prototype.doValueInvalid_=function(t){},t.Field.prototype.onMouseDown_=function(t){this.sourceBlock_&&this.sourceBlock_.workspace&&(t=this.sourceBlock_.workspace.getGesture(t))&&t.setStartField(this)},t.Field.prototype.setTooltip=function(t){var e=this.getClickTarget_();e?e.tooltip=t||""===t?t:this.sourceBlock_:this.tooltip_=t},t.Field.prototype.getClickTarget_=function(){return this.clickTarget_||this.getSvgRoot()},t.Field.prototype.getAbsoluteXY_=function(){return t.utils.style.getPageOffset(this.getClickTarget_())},t.Field.prototype.referencesVariables=function(){return!1},t.Field.prototype.getParentInput=function(){for(var t=null,e=this.sourceBlock_,o=e.inputList,i=0;ie||e>this.fieldRow.length)throw Error("index "+e+" out of bounds.");return o||""==o&&i?("string"==typeof o&&(o=new t.FieldLabel(o)),o.setSourceBlock(this.sourceBlock_),this.sourceBlock_.rendered&&o.init(),o.name=i,o.prefixField&&(e=this.insertFieldAt(e,o.prefixField)),this.fieldRow.splice(e,0,o),++e,o.suffixField&&(e=this.insertFieldAt(e,o.suffixField)),this.sourceBlock_.rendered&&(this.sourceBlock_.render(),this.sourceBlock_.bumpNeighbours()),e):e},t.Input.prototype.removeField=function(t){for(var e,o=0;e=this.fieldRow[o];o++)if(e.name===t)return e.dispose(),this.fieldRow.splice(o,1),void(this.sourceBlock_.rendered&&(this.sourceBlock_.render(),this.sourceBlock_.bumpNeighbours()));throw Error('Field "%s" not found.',t)},t.Input.prototype.isVisible=function(){return this.visible_},t.Input.prototype.setVisible=function(t){var e=[];if(this.visible_==t)return e;for(var o,i=(this.visible_=t)?"block":"none",n=0;o=this.fieldRow[n];n++)o.setVisible(t);return this.connection&&(t?e=this.connection.startTrackingAll():this.connection.stopTrackingAll(),n=this.connection.targetBlock())&&(n.getSvgRoot().style.display=i,t||(n.rendered=!1)),e},t.Input.prototype.markDirty=function(){for(var t,e=0;t=this.fieldRow[e];e++)t.markDirty()},t.Input.prototype.setCheck=function(t){if(!this.connection)throw Error("This input does not have a connection.");return this.connection.setCheck(t),this},t.Input.prototype.setAlign=function(t){return this.align=t,this.sourceBlock_.rendered&&this.sourceBlock_.render(),this},t.Input.prototype.init=function(){if(this.sourceBlock_.workspace.rendered)for(var t=0;tt&&(o=o.substring(0,t-3)+"..."),o},t.Block.prototype.appendValueInput=function(e){return this.appendInput_(t.INPUT_VALUE,e)},t.Block.prototype.appendStatementInput=function(e){return this.appendInput_(t.NEXT_STATEMENT,e)},t.Block.prototype.appendDummyInput=function(e){return this.appendInput_(t.DUMMY_INPUT,e||"")},t.Block.prototype.jsonInit=function(e){var o=e.type?'Block "'+e.type+'": ':"";if(e.output&&e.previousStatement)throw Error(o+"Must not have both an output and a previousStatement.");if(e.style&&e.style.hat&&(this.hat=e.style.hat,e.style=null),e.style&&e.colour)throw Error(o+"Must not have both a colour and a style.");e.style?this.jsonInitStyle_(e,o):this.jsonInitColour_(e,o);for(var i=0;void 0!==e["message"+i];)this.interpolate_(e["message"+i],e["args"+i]||[],e["lastDummyAlign"+i],o),i++;if(void 0!==e.inputsInline&&this.setInputsInline(e.inputsInline),void 0!==e.output&&this.setOutput(!0,e.output),void 0!==e.outputShape&&this.setOutputShape(e.outputShape),void 0!==e.previousStatement&&this.setPreviousStatement(!0,e.previousStatement),void 0!==e.nextStatement&&this.setNextStatement(!0,e.nextStatement),void 0!==e.tooltip&&(i=e.tooltip,i=t.utils.replaceMessageReferences(i),this.setTooltip(i)),void 0!==e.enableContextMenu&&(i=e.enableContextMenu,this.contextMenu=!!i),void 0!==e.helpUrl&&(i=e.helpUrl,i=t.utils.replaceMessageReferences(i),this.setHelpUrl(i)),"string"==typeof e.extensions&&(console.warn(o+"JSON attribute 'extensions' should be an array of strings. Found raw string in JSON for '"+e.type+"' block."),e.extensions=[e.extensions]),void 0!==e.mutator&&t.Extensions.apply(e.mutator,this,!0),Array.isArray(e.extensions))for(e=e.extensions,o=0;o=c||c>o.length)throw Error('Block "'+this.type+'": Message index %'+c+" out of range.");if(r[c])throw Error('Block "'+this.type+'": Message index %'+c+" duplicated.");r[c]=!0,a++,e.push(o[c-1])}else(c=c.trim())&&e.push(c)}if(a!=o.length)throw Error('Block "'+this.type+'": Message does not reference all '+o.length+" arg(s).");for(e.length&&("string"==typeof e[e.length-1]||t.utils.string.startsWith(e[e.length-1].type,"field_"))&&(l={type:"input_dummy"},i&&(l.align=i),e.push(l)),i={LEFT:t.ALIGN_LEFT,RIGHT:t.ALIGN_RIGHT,CENTRE:t.ALIGN_CENTRE,CENTER:t.ALIGN_CENTRE},o=[],l=0;l=this.inputList.length)throw RangeError("Input index "+t+" out of bounds.");if(e>this.inputList.length)throw RangeError("Reference input "+e+" out of bounds.");var o=this.inputList[t];this.inputList.splice(t,1),t--t?e-1:t}),this.highlightedIndex_)},t.Menu.prototype.highlightHelper=function(t,e){e=0>e?-1:e;var o=this.getChildCount();e=t.call(this,e,o);for(var i=0;i<=o;){var n=this.getChildAt(e);if(n&&this.canHighlightItem(n))return this.setHighlightedIndex(e),!0;i++,e=t.call(this,e,o)}return!1},t.Menu.prototype.canHighlightItem=function(t){return t.isEnabled()},t.Menu.prototype.handleMouseOver_=function(t){(t=this.getMenuItem(t.target))&&(t.isEnabled()?this.getHighlighted()!==t&&(this.unhighlightCurrent(),this.setHighlighted(t)):this.unhighlightCurrent())},t.Menu.prototype.handleClick_=function(e){var o=this.openingCoords;if(this.openingCoords=null,o&&"number"==typeof e.clientX){var i=new t.utils.Coordinate(e.clientX,e.clientY);if(1>t.utils.Coordinate.distance(o,i))return}(o=this.getMenuItem(e.target))&&o.handleClick(e)&&e.preventDefault()},t.Menu.prototype.handleMouseEnter_=function(t){this.focus()},t.Menu.prototype.handleMouseLeave_=function(t){this.getElement()&&(this.blur(),this.clearHighlighted())},t.Menu.prototype.handleKeyEvent=function(t){return!(0==this.getChildCount()||!this.handleKeyEventInternal(t)||(t.preventDefault(),t.stopPropagation(),0))},t.Menu.prototype.handleKeyEventInternal=function(e){var o=this.getHighlighted();if(o&&"function"==typeof o.handleKeyEvent&&o.handleKeyEvent(e))return!0;if(e.shiftKey||e.ctrlKey||e.metaKey||e.altKey)return!1;switch(e.keyCode){case t.utils.KeyCodes.ENTER:o&&o.performActionInternal(e);break;case t.utils.KeyCodes.UP:this.highlightPrevious();break;case t.utils.KeyCodes.DOWN:this.highlightNext();break;default:return!1}return!0},t.MenuItem=function(e,o){t.Component.call(this),this.setContentInternal(e),this.setValue(o),this.enabled_=!0},t.utils.object.inherits(t.MenuItem,t.Component),t.MenuItem.prototype.createDom=function(){var e=document.createElement("div");e.id=this.getId(),this.setElementInternal(e),e.className="goog-menuitem goog-option "+(this.enabled_?"":"goog-menuitem-disabled ")+(this.checked_?"goog-option-selected ":"")+(this.rightToLeft_?"goog-menuitem-rtl ":"");var o=this.getContentWrapperDom();e.appendChild(o);var i=this.getCheckboxDom();i&&o.appendChild(i),o.appendChild(this.getContentDom()),t.utils.aria.setRole(e,this.roleName_||(this.checkable_?t.utils.aria.Role.MENUITEMCHECKBOX:t.utils.aria.Role.MENUITEM)),t.utils.aria.setState(e,t.utils.aria.State.SELECTED,this.checkable_&&this.checked_||!1)},t.MenuItem.prototype.getCheckboxDom=function(){if(!this.checkable_)return null;var t=document.createElement("div");return t.className="goog-menuitem-checkbox",t},t.MenuItem.prototype.getContentDom=function(){var t=this.content_;return"string"==typeof t&&(t=document.createTextNode(t)),t},t.MenuItem.prototype.getContentWrapperDom=function(){var t=document.createElement("div");return t.className="goog-menuitem-content",t},t.MenuItem.prototype.setContentInternal=function(t){this.content_=t},t.MenuItem.prototype.setValue=function(t){this.value_=t},t.MenuItem.prototype.getValue=function(){return this.value_},t.MenuItem.prototype.setRole=function(t){this.roleName_=t},t.MenuItem.prototype.setCheckable=function(t){this.checkable_=t},t.MenuItem.prototype.setChecked=function(e){if(this.checkable_){this.checked_=e;var o=this.getElement();o&&this.isEnabled()&&(e?(t.utils.dom.addClass(o,"goog-option-selected"),t.utils.aria.setState(o,t.utils.aria.State.SELECTED,!0)):(t.utils.dom.removeClass(o,"goog-option-selected"),t.utils.aria.setState(o,t.utils.aria.State.SELECTED,!1)))}},t.MenuItem.prototype.setHighlighted=function(e){this.highlight_=e;var o=this.getElement();o&&this.isEnabled()&&(e?t.utils.dom.addClass(o,"goog-menuitem-highlight"):t.utils.dom.removeClass(o,"goog-menuitem-highlight"))},t.MenuItem.prototype.isEnabled=function(){return this.enabled_},t.MenuItem.prototype.setEnabled=function(e){this.enabled_=e,(e=this.getElement())&&(this.enabled_?t.utils.dom.removeClass(e,"goog-menuitem-disabled"):t.utils.dom.addClass(e,"goog-menuitem-disabled"))},t.MenuItem.prototype.handleClick=function(t){this.isEnabled()&&(this.setHighlighted(!0),this.performActionInternal())},t.MenuItem.prototype.performActionInternal=function(){this.checkable_&&this.setChecked(!this.checked_),this.actionHandler_&&this.actionHandler_.call(this.actionHandlerObj_,this)},t.MenuItem.prototype.onAction=function(t,e){this.actionHandler_=t,this.actionHandlerObj_=e},t.utils.uiMenu={},t.utils.uiMenu.getSize=function(e){e=e.getElement();var o=t.utils.style.getSize(e);return o.height=e.scrollHeight,o},t.utils.uiMenu.adjustBBoxesForRTL=function(t,e,o){e.left+=o.width,e.right+=o.width,t.left+=o.width,t.right+=o.width},t.ContextMenu={},t.ContextMenu.currentBlock=null,t.ContextMenu.eventWrapper_=null,t.ContextMenu.show=function(e,o,i){if(t.WidgetDiv.show(t.ContextMenu,i,null),o.length){var n=t.ContextMenu.populate_(o,i);t.ContextMenu.position_(n,e,i),setTimeout((function(){n.getElement().focus()}),1),t.ContextMenu.currentBlock=null}else t.ContextMenu.hide()},t.ContextMenu.populate_=function(e,o){var i=new t.Menu;i.setRightToLeft(o);for(var n,s=0;n=e[s];s++){var r=new t.MenuItem(n.text);r.setRightToLeft(o),i.addChild(r,!0),r.setEnabled(n.enabled),n.enabled&&r.onAction((function(){t.ContextMenu.hide(),this.callback()}),n)}return i},t.ContextMenu.position_=function(e,o,i){var n=t.utils.getViewportBBox();o={top:o.clientY+n.top,bottom:o.clientY+n.top,left:o.clientX+n.left,right:o.clientX+n.left},t.ContextMenu.createWidget_(e);var s=t.utils.uiMenu.getSize(e);i&&t.utils.uiMenu.adjustBBoxesForRTL(n,o,s),t.WidgetDiv.positionWithAnchor(n,o,s,i),e.getElement().focus()},t.ContextMenu.createWidget_=function(e){e.render(t.WidgetDiv.DIV);var o=e.getElement();t.utils.dom.addClass(o,"blocklyContextMenu"),t.bindEventWithChecks_(o,"contextmenu",null,t.utils.noEvent),e.focus()},t.ContextMenu.hide=function(){t.WidgetDiv.hideIfOwner(t.ContextMenu),t.ContextMenu.currentBlock=null,t.ContextMenu.eventWrapper_&&(t.unbindEvent_(t.ContextMenu.eventWrapper_),t.ContextMenu.eventWrapper_=null)},t.ContextMenu.callbackFactory=function(e,o){return function(){t.Events.disable();try{var i=t.Xml.domToBlock(o,e.workspace),n=e.getRelativeToSurfaceXY();n.x=e.RTL?n.x-t.SNAP_RADIUS:n.x+t.SNAP_RADIUS,n.y+=2*t.SNAP_RADIUS,i.moveBy(n.x,n.y)}finally{t.Events.enable()}t.Events.isEnabled()&&!i.isShadow()&&t.Events.fire(new t.Events.BlockCreate(i)),i.select()}},t.ContextMenu.blockDeleteOption=function(e){var o=e.getDescendants(!1).length,i=e.getNextBlock();return i&&(o-=i.getDescendants(!1).length),{text:1==o?t.Msg.DELETE_BLOCK:t.Msg.DELETE_X_BLOCKS.replace("%1",String(o)),enabled:!0,callback:function(){t.Events.setGroup(!0),e.dispose(!0,!0),t.Events.setGroup(!1)}}},t.ContextMenu.blockHelpOption=function(e){return{enabled:!("function"==typeof e.helpUrl?!e.helpUrl():!e.helpUrl),text:t.Msg.HELP,callback:function(){e.showHelp()}}},t.ContextMenu.blockDuplicateOption=function(e){var o=e.isDuplicatable();return{text:t.Msg.DUPLICATE_BLOCK,enabled:o,callback:function(){t.duplicate(e)}}},t.ContextMenu.blockCommentOption=function(e){var o={enabled:!t.utils.userAgent.IE};return e.getCommentIcon()?(o.text=t.Msg.REMOVE_COMMENT,o.callback=function(){e.setCommentText(null)}):(o.text=t.Msg.ADD_COMMENT,o.callback=function(){e.setCommentText("")}),o},t.ContextMenu.commentDeleteOption=function(e){return{text:t.Msg.REMOVE_COMMENT,enabled:!0,callback:function(){t.Events.setGroup(!0),e.dispose(!0,!0),t.Events.setGroup(!1)}}},t.ContextMenu.commentDuplicateOption=function(e){return{text:t.Msg.DUPLICATE_COMMENT,enabled:!0,callback:function(){t.duplicate(e)}}},t.ContextMenu.workspaceCommentOption=function(e,o){if(!t.WorkspaceCommentSvg)throw Error("Missing require for Blockly.WorkspaceCommentSvg");var i={enabled:!t.utils.userAgent.IE};return i.text=t.Msg.ADD_COMMENT,i.callback=function(){var i=new t.WorkspaceCommentSvg(e,t.Msg.WORKSPACE_COMMENT_DEFAULT_TEXT,t.WorkspaceCommentSvg.DEFAULT_SIZE,t.WorkspaceCommentSvg.DEFAULT_SIZE),n=e.getInjectionDiv().getBoundingClientRect();n=new t.utils.Coordinate(o.clientX-n.left,o.clientY-n.top);var s=e.getOriginOffsetInPixels();(n=t.utils.Coordinate.difference(n,s)).scale(1/e.scale),i.moveBy(n.x,n.y),e.rendered&&(i.initSvg(),i.render(),i.select())},i},t.RenderedConnection=function(e,o){t.RenderedConnection.superClass_.constructor.call(this,e,o),this.db_=e.workspace.connectionDBList[o],this.dbOpposite_=e.workspace.connectionDBList[t.OPPOSITE_TYPE[o]],this.offsetInBlock_=new t.utils.Coordinate(0,0),this.trackedState_=t.RenderedConnection.TrackedState.WILL_TRACK},t.utils.object.inherits(t.RenderedConnection,t.Connection),t.RenderedConnection.TrackedState={WILL_TRACK:-1,UNTRACKED:0,TRACKED:1},t.RenderedConnection.prototype.dispose=function(){t.RenderedConnection.superClass_.dispose.call(this),this.trackedState_==t.RenderedConnection.TrackedState.TRACKED&&this.db_.removeConnection(this,this.y)},t.RenderedConnection.prototype.getSourceBlock=function(){return t.RenderedConnection.superClass_.getSourceBlock.call(this)},t.RenderedConnection.prototype.targetBlock=function(){return t.RenderedConnection.superClass_.targetBlock.call(this)},t.RenderedConnection.prototype.distanceFrom=function(t){var e=this.x-t.x;return t=this.y-t.y,Math.sqrt(e*e+t*t)},t.RenderedConnection.prototype.bumpAwayFrom=function(e){if(!this.sourceBlock_.workspace.isDragging()){var o=this.sourceBlock_.getRootBlock();if(!o.isInFlyout){var i=!1;if(!o.isMovable()){if(!(o=e.getSourceBlock().getRootBlock()).isMovable())return;e=this,i=!0}var n=t.selected==o;n||o.addSelect();var s=e.x+t.SNAP_RADIUS+Math.floor(Math.random()*t.BUMP_RANDOMNESS)-this.x,r=e.y+t.SNAP_RADIUS+Math.floor(Math.random()*t.BUMP_RANDOMNESS)-this.y;i&&(r=-r),o.RTL&&(s=e.x-t.SNAP_RADIUS-Math.floor(Math.random()*t.BUMP_RANDOMNESS)-this.x),o.moveBy(s,r),n||o.removeSelect()}}},t.RenderedConnection.prototype.moveTo=function(e,o){this.trackedState_==t.RenderedConnection.TrackedState.WILL_TRACK?(this.db_.addConnection(this,o),this.trackedState_=t.RenderedConnection.TrackedState.TRACKED):this.trackedState_==t.RenderedConnection.TrackedState.TRACKED&&(this.db_.removeConnection(this,this.y),this.db_.addConnection(this,o)),this.x=e,this.y=o},t.RenderedConnection.prototype.moveBy=function(t,e){this.moveTo(this.x+t,this.y+e)},t.RenderedConnection.prototype.moveToOffset=function(t){this.moveTo(t.x+this.offsetInBlock_.x,t.y+this.offsetInBlock_.y)},t.RenderedConnection.prototype.setOffsetInBlock=function(t,e){this.offsetInBlock_.x=t,this.offsetInBlock_.y=e},t.RenderedConnection.prototype.getOffsetInBlock=function(){return this.offsetInBlock_},t.RenderedConnection.prototype.tighten=function(){var e=this.targetConnection.x-this.x,o=this.targetConnection.y-this.y;if(0!=e||0!=o){var i=this.targetBlock(),n=i.getSvgRoot();if(!n)throw Error("block is not rendered.");n=t.utils.getRelativeXY(n),i.getSvgRoot().setAttribute("transform","translate("+(n.x-e)+","+(n.y-o)+")"),i.moveConnections(-e,-o)}},t.RenderedConnection.prototype.closest=function(t,e){return this.dbOpposite_.searchForClosest(this,t,e)},t.RenderedConnection.prototype.highlight=function(){var e=this.sourceBlock_.workspace.getRenderer().getConstants(),o=e.shapeFor(this);this.type==t.INPUT_VALUE||this.type==t.OUTPUT_VALUE?(e=e.TAB_OFFSET_FROM_TOP,o=t.utils.svgPaths.moveBy(0,-e)+t.utils.svgPaths.lineOnAxis("v",e)+o.pathDown+t.utils.svgPaths.lineOnAxis("v",e)):(e=e.NOTCH_OFFSET_LEFT-e.CORNER_RADIUS,o=t.utils.svgPaths.moveBy(-e,0)+t.utils.svgPaths.lineOnAxis("h",e)+o.pathLeft+t.utils.svgPaths.lineOnAxis("h",e)),e=this.sourceBlock_.getRelativeToSurfaceXY(),t.Connection.highlightedPath_=t.utils.dom.createSvgElement("path",{class:"blocklyHighlightedConnectionPath",d:o,transform:"translate("+(this.x-e.x)+","+(this.y-e.y)+")"+(this.sourceBlock_.RTL?" scale(-1 1)":"")},this.sourceBlock_.getSvgRoot())},t.RenderedConnection.prototype.unhighlight=function(){t.utils.dom.removeNode(t.Connection.highlightedPath_),delete t.Connection.highlightedPath_},t.RenderedConnection.prototype.setTracking=function(e){e&&this.trackedState_==t.RenderedConnection.TrackedState.TRACKED||!e&&this.trackedState_==t.RenderedConnection.TrackedState.UNTRACKED||this.sourceBlock_.isInFlyout||(e?(this.db_.addConnection(this,this.y),this.trackedState_=t.RenderedConnection.TrackedState.TRACKED):(this.trackedState_==t.RenderedConnection.TrackedState.TRACKED&&this.db_.removeConnection(this,this.y),this.trackedState_=t.RenderedConnection.TrackedState.UNTRACKED))},t.RenderedConnection.prototype.stopTrackingAll=function(){if(this.setTracking(!1),this.targetConnection)for(var t=this.targetBlock().getDescendants(!1),e=0;eo)&&t.RenderedConnection.superClass_.isConnectionAllowed.call(this,e)},t.RenderedConnection.prototype.onFailedConnect=function(t){this.bumpAwayFrom(t)},t.RenderedConnection.prototype.disconnectInternal_=function(e,o){t.RenderedConnection.superClass_.disconnectInternal_.call(this,e,o),e.rendered&&e.render(),o.rendered&&(o.updateDisabled(),o.render())},t.RenderedConnection.prototype.respawnShadow_=function(){var e=this.getSourceBlock(),o=this.getShadowDom();if(e.workspace&&o&&t.Events.recordUndo){if(t.RenderedConnection.superClass_.respawnShadow_.call(this),!(o=this.targetBlock()))throw Error("Couldn't respawn the shadow block that should exist here.");o.initSvg(),o.render(!1),e.rendered&&e.render()}},t.RenderedConnection.prototype.neighbours=function(t){return this.dbOpposite_.getNeighbours(this,t)},t.RenderedConnection.prototype.connect_=function(e){t.RenderedConnection.superClass_.connect_.call(this,e);var o=this.getSourceBlock();e=e.getSourceBlock(),o.rendered&&o.updateDisabled(),e.rendered&&e.updateDisabled(),o.rendered&&e.rendered&&(this.type==t.NEXT_STATEMENT||this.type==t.PREVIOUS_STATEMENT?e.render():o.render())},t.RenderedConnection.prototype.onCheckChanged_=function(){!this.isConnected()||this.targetConnection&&this.checkType(this.targetConnection)||((this.isSuperior()?this.targetBlock():this.sourceBlock_).unplug(),this.sourceBlock_.bumpNeighbours())},t.Marker=function(){this.drawer_=this.curNode_=this.colour=null,this.type="marker"},t.Marker.prototype.setDrawer=function(t){this.drawer_=t},t.Marker.prototype.getDrawer=function(){return this.drawer_},t.Marker.prototype.getCurNode=function(){return this.curNode_},t.Marker.prototype.setCurNode=function(t){var e=this.curNode_;this.curNode_=t,this.drawer_&&this.drawer_.draw(e,this.curNode_)},t.Marker.prototype.draw=function(){this.drawer_&&this.drawer_.draw(this.curNode_,this.curNode_)},t.Marker.prototype.hide=function(){this.drawer_&&this.drawer_.hide()},t.Marker.prototype.dispose=function(){this.getDrawer()&&this.getDrawer().dispose()},t.Cursor=function(){t.Cursor.superClass_.constructor.call(this),this.type="cursor"},t.utils.object.inherits(t.Cursor,t.Marker),t.Cursor.prototype.next=function(){var e=this.getCurNode();if(!e)return null;for(e=e.next();e&&e.next()&&(e.getType()==t.ASTNode.types.NEXT||e.getType()==t.ASTNode.types.BLOCK);)e=e.next();return e&&this.setCurNode(e),e},t.Cursor.prototype.in=function(){var e=this.getCurNode();return e?(e.getType()!=t.ASTNode.types.PREVIOUS&&e.getType()!=t.ASTNode.types.OUTPUT||(e=e.next()),(e=e.in())&&this.setCurNode(e),e):null},t.Cursor.prototype.prev=function(){var e=this.getCurNode();if(!e)return null;for(e=e.prev();e&&e.prev()&&(e.getType()==t.ASTNode.types.NEXT||e.getType()==t.ASTNode.types.BLOCK);)e=e.prev();return e&&this.setCurNode(e),e},t.Cursor.prototype.out=function(){var e=this.getCurNode();return e?((e=e.out())&&e.getType()==t.ASTNode.types.BLOCK&&(e=e.prev()||e),e&&this.setCurNode(e),e):null},t.Cursor.prototype.onBlocklyAction=function(e){if(this.getCurNode()&&this.getCurNode().getType()===t.ASTNode.types.FIELD&&this.getCurNode().getLocation().onBlocklyAction(e))return!0;switch(e.name){case t.navigation.actionNames.PREVIOUS:return this.prev(),!0;case t.navigation.actionNames.OUT:return this.out(),!0;case t.navigation.actionNames.NEXT:return this.next(),!0;case t.navigation.actionNames.IN:return this.in(),!0;default:return!1}},t.BasicCursor=function(){t.BasicCursor.superClass_.constructor.call(this)},t.utils.object.inherits(t.BasicCursor,t.Cursor),t.BasicCursor.prototype.next=function(){var t=this.getCurNode();return t?((t=this.getNextNode_(t,this.validNode_))&&this.setCurNode(t),t):null},t.BasicCursor.prototype.in=function(){return this.next()},t.BasicCursor.prototype.prev=function(){var t=this.getCurNode();return t?((t=this.getPreviousNode_(t,this.validNode_))&&this.setCurNode(t),t):null},t.BasicCursor.prototype.out=function(){return this.prev()},t.BasicCursor.prototype.getNextNode_=function(t,e){if(!t)return null;var o=t.in()||t.next();return e(o)?o:o?this.getNextNode_(o,e):e(t=this.findSiblingOrParent_(t.out()))?t:t?this.getNextNode_(t,e):null},t.BasicCursor.prototype.getPreviousNode_=function(t,e){if(!t)return null;var o=t.prev();return e(o=o?this.getRightMostChild_(o):t.out())?o:o?this.getPreviousNode_(o,e):null},t.BasicCursor.prototype.validNode_=function(e){var o=!1;return(e=e&&e.getType())!=t.ASTNode.types.OUTPUT&&e!=t.ASTNode.types.INPUT&&e!=t.ASTNode.types.FIELD&&e!=t.ASTNode.types.NEXT&&e!=t.ASTNode.types.PREVIOUS&&e!=t.ASTNode.types.WORKSPACE||(o=!0),o},t.BasicCursor.prototype.findSiblingOrParent_=function(t){if(!t)return null;var e=t.next();return e||this.findSiblingOrParent_(t.out())},t.BasicCursor.prototype.getRightMostChild_=function(t){if(!t.in())return t;for(t=t.in();t.next();)t=t.next();return this.getRightMostChild_(t)},t.TabNavigateCursor=function(){t.TabNavigateCursor.superClass_.constructor.call(this)},t.utils.object.inherits(t.TabNavigateCursor,t.BasicCursor),t.TabNavigateCursor.prototype.validNode_=function(e){var o=!1,i=e&&e.getType();return e&&(e=e.getLocation(),i==t.ASTNode.types.FIELD&&e&&e.isTabNavigable()&&e.isClickable()&&(o=!0)),o},t.utils.Rect=function(t,e,o,i){this.top=t,this.bottom=e,this.left=o,this.right=i},t.utils.Rect.prototype.contains=function(t,e){return t>=this.left&&t<=this.right&&e>=this.top&&e<=this.bottom},t.BlockSvg=function(e,o,i){this.svgGroup_=t.utils.dom.createSvgElement("g",{},null),this.svgGroup_.translate_="",this.style=e.getRenderer().getConstants().getBlockStyle(null),this.pathObject=e.getRenderer().makePathObject(this.svgGroup_,this.style),this.rendered=!1,this.workspace=e,this.previousConnection=this.nextConnection=this.outputConnection=null,this.useDragSurface_=t.utils.is3dSupported()&&!!e.getBlockDragSurface();var n=this.pathObject.svgPath;n.tooltip=this,t.Tooltip.bindMouseEvents(n),t.BlockSvg.superClass_.constructor.call(this,e,o,i),this.svgGroup_.dataset&&(this.svgGroup_.dataset.id=this.id)},t.utils.object.inherits(t.BlockSvg,t.Block),t.BlockSvg.prototype.height=0,t.BlockSvg.prototype.width=0,t.BlockSvg.prototype.dragStartXY_=null,t.BlockSvg.prototype.warningTextDb_=null,t.BlockSvg.INLINE=-1,t.BlockSvg.COLLAPSED_WARNING_ID="TEMP_COLLAPSED_WARNING_",t.BlockSvg.prototype.initSvg=function(){if(!this.workspace.rendered)throw TypeError("Workspace is headless.");for(var e,o=0;e=this.inputList[o];o++)e.init();for(e=this.getIcons(),o=0;o=this.connections_.length)return-1;e=t.y;for(var i=o;0<=i&&this.connections_[i].y==e;){if(this.connections_[i]==t)return i;i--}for(;ot)){e=i;break}o=i}}return e},t.ConnectionDB.prototype.removeConnection=function(t,e){if(-1==(t=this.findIndexOfConnection_(t,e)))throw Error("Unable to find connection in connectionDB.");this.connections_.splice(t,1)},t.ConnectionDB.prototype.getNeighbours=function(t,e){function o(t){var o=n-i[t].x,r=s-i[t].y;return Math.sqrt(o*o+r*r)<=e&&l.push(i[t]),r(t=this.subscribedWorkspaces_.indexOf(t)))throw Error("Cannot unsubscribe a workspace that hasn't been subscribed.");this.subscribedWorkspaces_.splice(t,1)},t.ThemeManager.prototype.subscribe=function(t,e,o){this.componentDB_[e]||(this.componentDB_[e]=[]),this.componentDB_[e].push({element:t,propertyName:o}),e=this.theme_&&this.theme_.getComponentStyle(e),t.style[o]=e||""},t.ThemeManager.prototype.unsubscribe=function(t){if(t)for(var e,o=Object.keys(this.componentDB_),i=0;e=o[i];i++){for(var n=this.componentDB_[e],s=n.length-1;0<=s;s--)n[s].element===t&&n.splice(s,1);this.componentDB_[e].length||delete this.componentDB_[e]}},t.ThemeManager.prototype.dispose=function(){this.componentDB_=this.subscribedWorkspaces_=this.theme_=this.owner_=null},t.TouchGesture=function(e,o){t.TouchGesture.superClass_.constructor.call(this,e,o),this.isMultiTouch_=!1,this.cachedPoints_=Object.create(null),this.startDistance_=this.previousScale_=0,this.isPinchZoomEnabled_=this.onStartWrapper_=null},t.utils.object.inherits(t.TouchGesture,t.Gesture),t.TouchGesture.ZOOM_IN_MULTIPLIER=5,t.TouchGesture.ZOOM_OUT_MULTIPLIER=6,t.TouchGesture.prototype.doStart=function(e){this.isPinchZoomEnabled_=this.startWorkspace_.options.zoomOptions&&this.startWorkspace_.options.zoomOptions.pinch,t.TouchGesture.superClass_.doStart.call(this,e),!this.isEnding_&&t.Touch.isTouchEvent(e)&&this.handleTouchStart(e)},t.TouchGesture.prototype.bindMouseEvents=function(e){this.onStartWrapper_=t.bindEventWithChecks_(document,"mousedown",null,this.handleStart.bind(this),!0),this.onMoveWrapper_=t.bindEventWithChecks_(document,"mousemove",null,this.handleMove.bind(this),!0),this.onUpWrapper_=t.bindEventWithChecks_(document,"mouseup",null,this.handleUp.bind(this),!0),e.preventDefault(),e.stopPropagation()},t.TouchGesture.prototype.handleStart=function(e){!this.isDragging()&&t.Touch.isTouchEvent(e)&&(this.handleTouchStart(e),this.isMultiTouch()&&t.longStop_())},t.TouchGesture.prototype.handleMove=function(e){this.isDragging()?t.Touch.shouldHandleEvent(e)&&t.TouchGesture.superClass_.handleMove.call(this,e):this.isMultiTouch()?(t.Touch.isTouchEvent(e)&&this.handleTouchMove(e),t.longStop_()):t.TouchGesture.superClass_.handleMove.call(this,e)},t.TouchGesture.prototype.handleUp=function(e){t.Touch.isTouchEvent(e)&&!this.isDragging()&&this.handleTouchEnd(e),!this.isMultiTouch()||this.isDragging()?t.Touch.shouldHandleEvent(e)&&t.TouchGesture.superClass_.handleUp.call(this,e):(e.preventDefault(),e.stopPropagation(),this.dispose())},t.TouchGesture.prototype.isMultiTouch=function(){return this.isMultiTouch_},t.TouchGesture.prototype.dispose=function(){t.TouchGesture.superClass_.dispose.call(this),this.onStartWrapper_&&t.unbindEvent_(this.onStartWrapper_)},t.TouchGesture.prototype.handleTouchStart=function(e){var o=t.Touch.getTouchIdentifierFromEvent(e);this.cachedPoints_[o]=this.getTouchPoint(e),2==(o=Object.keys(this.cachedPoints_)).length&&(this.startDistance_=t.utils.Coordinate.distance(this.cachedPoints_[o[0]],this.cachedPoints_[o[1]]),this.isMultiTouch_=!0,e.preventDefault())},t.TouchGesture.prototype.handleTouchMove=function(e){var o=t.Touch.getTouchIdentifierFromEvent(e);this.cachedPoints_[o]=this.getTouchPoint(e),o=Object.keys(this.cachedPoints_),this.isPinchZoomEnabled_&&2===o.length?this.handlePinch_(e):t.TouchGesture.superClass_.handleMove.call(this,e)},t.TouchGesture.prototype.handlePinch_=function(e){var o=Object.keys(this.cachedPoints_);if(o=t.utils.Coordinate.distance(this.cachedPoints_[o[0]],this.cachedPoints_[o[1]])/this.startDistance_,0this.previousScale_){var i=o-this.previousScale_;i=0Object.keys(this.cachedPoints_).length&&(this.cachedPoints_=Object.create(null),this.previousScale_=0)},t.TouchGesture.prototype.getTouchPoint=function(e){return this.startWorkspace_?new t.utils.Coordinate(e.pageX?e.pageX:e.changedTouches[0].pageX,e.pageY?e.pageY:e.changedTouches[0].pageY):null},t.WorkspaceAudio=function(t){this.parentWorkspace_=t,this.SOUNDS_=Object.create(null)},t.WorkspaceAudio.prototype.lastSound_=null,t.WorkspaceAudio.prototype.dispose=function(){this.SOUNDS_=this.parentWorkspace_=null},t.WorkspaceAudio.prototype.load=function(e,o){if(e.length){try{var i=new t.utils.global.Audio}catch(t){return}for(var n,s=0;s=this.remainingCapacity()||(this.currentGesture_&&this.currentGesture_.cancel(),"comment"==t.tagName.toLowerCase()?this.pasteWorkspaceComment_(t):this.pasteBlock_(t))},t.WorkspaceSvg.prototype.pasteBlock_=function(e){t.Events.disable();try{var o=t.Xml.domToBlock(e,this),i=this.getMarker(t.navigation.MARKER_NAME).getCurNode();if(this.keyboardAccessibilityMode&&i&&i.isConnection()){var n=i.getLocation();return void t.navigation.insertBlock(o,n)}var s=parseInt(e.getAttribute("x"),10),r=parseInt(e.getAttribute("y"),10);if(!isNaN(s)&&!isNaN(r)){this.RTL&&(s=-s);do{e=!1;var a,l=this.getAllBlocks(!1);for(i=0;a=l[i];i++){var c=a.getRelativeToSurfaceXY();if(1>=Math.abs(s-c.x)&&1>=Math.abs(r-c.y)){e=!0;break}}if(!e){var h,u=o.getConnections_(!1);for(i=0;h=u[i];i++)if(h.closest(t.SNAP_RADIUS,new t.utils.Coordinate(s,r)).connection){e=!0;break}}e&&(s=this.RTL?s-t.SNAP_RADIUS:s+t.SNAP_RADIUS,r+=2*t.SNAP_RADIUS)}while(e);o.moveBy(s,r)}}finally{t.Events.enable()}t.Events.isEnabled()&&!o.isShadow()&&t.Events.fire(new t.Events.BlockCreate(o)),o.select()},t.WorkspaceSvg.prototype.pasteWorkspaceComment_=function(e){t.Events.disable();try{var o=t.WorkspaceCommentSvg.fromXml(e,this),i=parseInt(e.getAttribute("x"),10),n=parseInt(e.getAttribute("y"),10);isNaN(i)||isNaN(n)||(this.RTL&&(i=-i),o.moveBy(i+50,n+50))}finally{t.Events.enable()}t.Events.isEnabled(),o.select()},t.WorkspaceSvg.prototype.refreshToolboxSelection=function(){var t=this.isFlyout?this.targetWorkspace:this;t&&!t.currentGesture_&&t.toolbox_&&t.toolbox_.getFlyout()&&t.toolbox_.refreshSelection()},t.WorkspaceSvg.prototype.renameVariableById=function(e,o){t.WorkspaceSvg.superClass_.renameVariableById.call(this,e,o),this.refreshToolboxSelection()},t.WorkspaceSvg.prototype.deleteVariableById=function(e){t.WorkspaceSvg.superClass_.deleteVariableById.call(this,e),this.refreshToolboxSelection()},t.WorkspaceSvg.prototype.createVariable=function(e,o,i){return e=t.WorkspaceSvg.superClass_.createVariable.call(this,e,o,i),this.refreshToolboxSelection(),e},t.WorkspaceSvg.prototype.recordDeleteAreas=function(){this.deleteAreaTrash_=this.trashcan&&this.svgGroup_.parentNode?this.trashcan.getClientRect():null,this.deleteAreaToolbox_=this.flyout_?this.flyout_.getClientRect():this.toolbox_?this.toolbox_.getClientRect():null},t.WorkspaceSvg.prototype.isDeleteArea=function(e){return this.deleteAreaTrash_&&this.deleteAreaTrash_.contains(e.clientX,e.clientY)?t.DELETE_AREA_TRASH:this.deleteAreaToolbox_&&this.deleteAreaToolbox_.contains(e.clientX,e.clientY)?t.DELETE_AREA_TOOLBOX:t.DELETE_AREA_NONE},t.WorkspaceSvg.prototype.onMouseDown_=function(t){var e=this.getGesture(t);e&&e.handleWsStart(t,this)},t.WorkspaceSvg.prototype.startDrag=function(e,o){(e=t.utils.mouseToSvg(e,this.getParentSvg(),this.getInverseScreenCTM())).x/=this.scale,e.y/=this.scale,this.dragDeltaXY_=t.utils.Coordinate.difference(o,e)},t.WorkspaceSvg.prototype.moveDrag=function(e){return(e=t.utils.mouseToSvg(e,this.getParentSvg(),this.getInverseScreenCTM())).x/=this.scale,e.y/=this.scale,t.utils.Coordinate.sum(this.dragDeltaXY_,e)},t.WorkspaceSvg.prototype.isDragging=function(){return null!=this.currentGesture_&&this.currentGesture_.isDragging()},t.WorkspaceSvg.prototype.isDraggable=function(){return this.options.moveOptions&&this.options.moveOptions.drag},t.WorkspaceSvg.prototype.isContentBounded=function(){return this.options.moveOptions&&this.options.moveOptions.scrollbars||this.options.moveOptions&&this.options.moveOptions.wheel||this.options.moveOptions&&this.options.moveOptions.drag||this.options.zoomOptions&&this.options.zoomOptions.controls||this.options.zoomOptions&&this.options.zoomOptions.wheel||this.options.zoomOptions&&this.options.zoomOptions.pinch},t.WorkspaceSvg.prototype.isMovable=function(){return this.options.moveOptions&&this.options.moveOptions.scrollbars||this.options.moveOptions&&this.options.moveOptions.wheel||this.options.moveOptions&&this.options.moveOptions.drag||this.options.zoomOptions&&this.options.zoomOptions.wheel||this.options.zoomOptions&&this.options.zoomOptions.pinch},t.WorkspaceSvg.prototype.onMouseWheel_=function(e){if(t.Gesture.inProgress())e.preventDefault(),e.stopPropagation();else{var o=this.options.zoomOptions&&this.options.zoomOptions.wheel,i=this.options.moveOptions&&this.options.moveOptions.wheel;if(o||i){var n=t.utils.getScrollDeltaPixels(e);!o||!e.ctrlKey&&i?(o=this.scrollX-n.x,i=this.scrollY-n.y,e.shiftKey&&!n.x&&(o=this.scrollX-n.y,i=this.scrollY),this.scroll(o,i)):(n=-n.y/50,o=t.utils.mouseToSvg(e,this.getParentSvg(),this.getInverseScreenCTM()),this.zoom(o.x,o.y,n)),e.preventDefault()}}},t.WorkspaceSvg.prototype.getBlocksBoundingBox=function(){var e=this.getTopBlocks(!1),o=this.getTopComments(!1);if(!(e=e.concat(o)).length)return new t.utils.Rect(0,0,0,0);o=e[0].getBoundingRectangle();for(var i=1;io.bottom&&(o.bottom=n.bottom),n.lefto.right&&(o.right=n.right)}return o},t.WorkspaceSvg.prototype.cleanUp=function(){this.setResizesEnabled(!1),t.Events.setGroup(!0);for(var e,o=this.getTopBlocks(!0),i=0,n=0;e=o[n];n++)if(e.isMovable()){var s=e.getRelativeToSurfaceXY();e.moveBy(-s.x,i-s.y),e.snapToGrid(),i=e.getRelativeToSurfaceXY().y+e.getHeightWidth().height+this.renderer_.getConstants().MIN_BLOCK_HEIGHT}t.Events.setGroup(!1),this.setResizesEnabled(!0)},t.WorkspaceSvg.prototype.showContextMenu=function(e){function o(t){if(t.isDeletable())_=_.concat(t.getDescendants(!1));else{t=t.getChildren(!1);for(var e=0;e_.length?i():t.confirm(t.Msg.DELETE_ALL_BLOCKS.replace("%1",_.length),(function(t){t&&i()}))}},n.push(l),this.configureContextMenu&&this.configureContextMenu(n,e),t.ContextMenu.show(e,n,this.RTL)}},t.WorkspaceSvg.prototype.updateToolbox=function(e){if(e=t.Options.parseToolboxTree(e)){if(!this.options.languageTree)throw Error("Existing toolbox is null. Can't create new toolbox.");if(e.getElementsByTagName("category").length){if(!this.toolbox_)throw Error("Existing toolbox has no categories. Can't change mode.");this.options.languageTree=e,this.toolbox_.renderTree(e)}else{if(!this.flyout_)throw Error("Existing toolbox has categories. Can't change mode.");this.options.languageTree=e,this.flyout_.show(e.childNodes)}}else if(this.options.languageTree)throw Error("Can't nullify an existing toolbox.")},t.WorkspaceSvg.prototype.markFocused=function(){this.options.parentWorkspace?this.options.parentWorkspace.markFocused():(t.mainWorkspace=this,this.setBrowserFocus())},t.WorkspaceSvg.prototype.setBrowserFocus=function(){document.activeElement&&document.activeElement.blur();try{this.getParentSvg().focus({preventScroll:!0})}catch(t){try{this.getParentSvg().parentNode.setActive()}catch(t){this.getParentSvg().parentNode.focus({preventScroll:!0})}}},t.WorkspaceSvg.prototype.zoom=function(t,e,o){o=Math.pow(this.options.zoomOptions.scaleSpeed,o);var i=this.scale*o;if(this.scale!=i){i>this.options.zoomOptions.maxScale?o=this.options.zoomOptions.maxScale/this.scale:ithis.options.zoomOptions.maxScale?e=this.options.zoomOptions.maxScale:this.options.zoomOptions.minScale&&eo.viewBottom||o.contentLefto.viewRight){switch(i=null,e&&(i=t.Events.getGroup(),t.Events.setGroup(e.group)),e.type){case t.Events.BLOCK_CREATE:case t.Events.BLOCK_MOVE:var r=s.getBlockById(e.blockId);r&&(r=r.getRootBlock());break;case t.Events.COMMENT_CREATE:case t.Events.COMMENT_MOVE:r=s.getCommentById(e.commentId)}if(r){(n=r.getBoundingRectangle()).height=n.bottom-n.top,n.width=n.right-n.left;var a=o.viewTop,l=o.viewBottom-n.height;l=Math.max(a,l),a=t.utils.math.clamp(a,n.top,l)-n.top,l=o.viewLeft;var c=o.viewRight-n.width;o.RTL?l=Math.min(c,l):c=Math.max(l,c),o=t.utils.math.clamp(l,n.left,c)-n.left,r.moveBy(o,a)}e&&(!e.group&&r&&console.log("WARNING: Moved object in bounds but there was no event group. This may break undo."),null!==i&&t.Events.setGroup(i))}}})),t.svgResize(s),t.WidgetDiv.createDom(),t.DropDownDiv.createDom(),t.Tooltip.createDom(),s},t.init_=function(e){var o=e.options,i=e.getParentSvg();if(t.bindEventWithChecks_(i.parentNode,"contextmenu",null,(function(e){t.utils.isTargetInput(e)||e.preventDefault()})),i=t.bindEventWithChecks_(window,"resize",null,(function(){t.hideChaff(!0),t.svgResize(e)})),e.setResizeHandlerWrapper(i),t.inject.bindDocumentEvents_(),o.languageTree){i=e.getToolbox();var n=e.getFlyout(!0);i?i.init():n&&(n.init(e),n.show(o.languageTree.childNodes),n.scrollToStart())}i=t.Scrollbar.scrollbarThickness,o.hasTrashcan&&(i=e.trashcan.init(i)),o.zoomOptions&&o.zoomOptions.controls&&e.zoomControls_.init(i),o.moveOptions&&o.moveOptions.scrollbars?(e.scrollbar=new t.ScrollbarPair(e),e.scrollbar.resize()):e.setMetrics({x:.5,y:.5}),o.hasSounds&&t.inject.loadSounds_(o.pathToMedia,e)},t.inject.bindDocumentEvents_=function(){t.documentEventsBound_||(t.bindEventWithChecks_(document,"scroll",null,(function(){for(var e,o=t.Workspace.getAll(),i=0;e=o[i];i++)e.updateInverseScreenCTM&&e.updateInverseScreenCTM()})),t.bindEventWithChecks_(document,"keydown",null,t.onKeyDown),t.bindEvent_(document,"touchend",null,t.longStop_),t.bindEvent_(document,"touchcancel",null,t.longStop_),t.utils.userAgent.IPAD&&t.bindEventWithChecks_(window,"orientationchange",document,(function(){t.svgResize(t.getMainWorkspace())}))),t.documentEventsBound_=!0},t.inject.loadSounds_=function(e,o){var i=o.getAudioManager();i.load([e+"click.mp3",e+"click.wav",e+"click.ogg"],"click"),i.load([e+"disconnect.wav",e+"disconnect.mp3",e+"disconnect.ogg"],"disconnect"),i.load([e+"delete.mp3",e+"delete.ogg",e+"delete.wav"],"delete");var n=[];e=function(){for(;n.length;)t.unbindEvent_(n.pop());i.preload()},n.push(t.bindEventWithChecks_(document,"mousemove",null,e,!0)),n.push(t.bindEventWithChecks_(document,"touchstart",null,e,!0))},t.Names=function(t,e){if(this.variablePrefix_=e||"",this.reservedDict_=Object.create(null),t)for(t=t.split(","),e=0;e1'),n.appendChild(i),o.push(n)),t.Blocks.variables_get){e.sort(t.VariableModel.compareByName),i=0;for(var s;s=e[i];i++)(n=t.utils.xml.createElement("block")).setAttribute("type","variables_get"),n.setAttribute("gap",8),n.appendChild(t.Variables.generateVariableFieldDom(s)),o.push(n)}}return o},t.Variables.VAR_LETTER_OPTIONS="ijkmnopqrstuvwxyzabcdefgh",t.Variables.generateUniqueName=function(e){return t.Variables.generateUniqueNameFromOptions(t.Variables.VAR_LETTER_OPTIONS.charAt(0),e.getAllVariableNames())},t.Variables.generateUniqueNameFromOptions=function(e,o){if(!o.length)return e;for(var i=t.Variables.VAR_LETTER_OPTIONS,n="",s=i.indexOf(e);;){for(var r=!1,a=0;as?t.WidgetDiv.positionInternal_(e,0,i.height+s):t.WidgetDiv.positionInternal_(e,s,i.height)},t.WidgetDiv.calculateX_=function(t,e,o,i){return i?(e=Math.max(e.right-o.width,t.left),Math.min(e,t.right-o.width)):(e=Math.min(e.left,t.right-o.width),Math.max(e,t.left))},t.WidgetDiv.calculateY_=function(t,e,o){return e.bottom+o.height>=t.bottom?e.top-o.height:e.bottom},t.VERSION="3.20200402.1",t.mainWorkspace=null,t.selected=null,t.draggingConnections=[],t.clipboardXml_=null,t.clipboardSource_=null,t.clipboardTypeCounts_=null,t.cache3dSupported_=null,t.parentContainer=null,t.svgSize=function(t){return{width:t.cachedWidth_,height:t.cachedHeight_}},t.resizeSvgContents=function(t){t.resizeContents()},t.svgResize=function(t){for(;t.options.parentWorkspace;)t=t.options.parentWorkspace;var e=t.getParentSvg(),o=e.parentNode;if(o){var i=o.offsetWidth;o=o.offsetHeight,e.cachedWidth_!=i&&(e.setAttribute("width",i+"px"),e.cachedWidth_=i),e.cachedHeight_!=o&&(e.setAttribute("height",o+"px"),e.cachedHeight_=o),t.resize()}},t.onKeyDown=function(e){var o=t.mainWorkspace;if(o&&!(t.utils.isTargetInput(e)||o.rendered&&!o.isVisible()))if(o.options.readOnly)t.navigation.onKeyPress(e);else{var i=!1;if(e.keyCode==t.utils.KeyCodes.ESC)t.hideChaff(),t.navigation.onBlocklyAction(t.navigation.ACTION_EXIT);else{if(t.navigation.onKeyPress(e))return;if(e.keyCode==t.utils.KeyCodes.BACKSPACE||e.keyCode==t.utils.KeyCodes.DELETE){if(e.preventDefault(),t.Gesture.inProgress())return;t.selected&&t.selected.isDeletable()&&(i=!0)}else if(e.altKey||e.ctrlKey||e.metaKey){if(t.Gesture.inProgress())return;t.selected&&t.selected.isDeletable()&&t.selected.isMovable()&&(e.keyCode==t.utils.KeyCodes.C?(t.hideChaff(),t.copy_(t.selected)):e.keyCode!=t.utils.KeyCodes.X||t.selected.workspace.isFlyout||(t.copy_(t.selected),i=!0)),e.keyCode==t.utils.KeyCodes.V?t.clipboardXml_&&((e=t.clipboardSource_).isFlyout&&(e=e.targetWorkspace),t.clipboardTypeCounts_&&e.isCapacityAvailable(t.clipboardTypeCounts_)&&(t.Events.setGroup(!0),e.paste(t.clipboardXml_),t.Events.setGroup(!1))):e.keyCode==t.utils.KeyCodes.Z&&(t.hideChaff(),o.undo(e.shiftKey))}}i&&!t.selected.workspace.isFlyout&&(t.Events.setGroup(!0),t.hideChaff(),t.selected.dispose(!0,!0),t.Events.setGroup(!1))}},t.copy_=function(e){if(e.isComment)var o=e.toXmlWithXY();else{o=t.Xml.blockToDom(e,!0),t.Xml.deleteNext(o);var i=e.getRelativeToSurfaceXY();o.setAttribute("x",e.RTL?-i.x:i.x),o.setAttribute("y",i.y)}t.clipboardXml_=o,t.clipboardSource_=e.workspace,t.clipboardTypeCounts_=e.isComment?null:t.utils.getBlockTypeCounts(e,!0)},t.duplicate=function(e){var o=t.clipboardXml_,i=t.clipboardSource_;t.copy_(e),e.workspace.paste(t.clipboardXml_),t.clipboardXml_=o,t.clipboardSource_=i},t.onContextMenu_=function(e){t.utils.isTargetInput(e)||e.preventDefault()},t.hideChaff=function(e){t.Tooltip.hide(),t.WidgetDiv.hide(),t.DropDownDiv.hideWithoutAnimation(),e||((e=t.getMainWorkspace()).trashcan&&e.trashcan.flyout&&e.trashcan.flyout.hide(),(e=e.getToolbox())&&e.getFlyout()&&e.getFlyout().autoClose&&e.clearSelection())},t.getMainWorkspace=function(){return t.mainWorkspace},t.alert=function(t,e){alert(t),e&&e()},t.confirm=function(t,e){e(confirm(t))},t.prompt=function(t,e,o){o(prompt(t,e))},t.jsonInitFactory_=function(t){return function(){this.jsonInit(t)}},t.defineBlocksWithJsonArray=function(e){for(var o=0;o90-e||t>-90-e&&t<-90+e},t.HorizontalFlyout.prototype.getClientRect=function(){if(!this.svgGroup_)return null;var e=this.svgGroup_.getBoundingClientRect(),o=e.top;return this.toolboxPosition_==t.TOOLBOX_AT_TOP?new t.utils.Rect(-1e9,o+e.height,-1e9,1e9):new t.utils.Rect(o,1e9,-1e9,1e9)},t.HorizontalFlyout.prototype.reflowInternal_=function(){this.workspace_.scale=this.targetWorkspace_.scale;for(var e,o=0,i=this.workspace_.getTopBlocks(!1),n=0;e=i[n];n++)o=Math.max(o,e.getHeightWidth().height);if(o+=1.5*this.MARGIN,o*=this.workspace_.scale,o+=t.Scrollbar.scrollbarThickness,this.height_!=o){for(n=0;e=i[n];n++)e.flyoutRect_&&this.moveRectToBlock_(e.flyoutRect_,e);this.height_=o,this.position()}},t.VerticalFlyout=function(e){e.getMetrics=this.getMetrics_.bind(this),e.setMetrics=this.setMetrics_.bind(this),t.VerticalFlyout.superClass_.constructor.call(this,e),this.horizontalLayout_=!1},t.utils.object.inherits(t.VerticalFlyout,t.Flyout),t.VerticalFlyout.prototype.getMetrics_=function(){if(!this.isVisible())return null;try{var t=this.workspace_.getCanvas().getBBox()}catch(e){t={height:0,y:0,width:0,x:0}}var e=this.SCROLLBAR_PADDING,o=this.height_-2*this.SCROLLBAR_PADDING,i=this.width_;return this.RTL||(i-=this.SCROLLBAR_PADDING),{viewHeight:o,viewWidth:i,contentHeight:t.height*this.workspace_.scale+2*this.MARGIN,contentWidth:t.width*this.workspace_.scale+2*this.MARGIN,viewTop:-this.workspace_.scrollY+t.y,viewLeft:-this.workspace_.scrollX,contentTop:t.y,contentLeft:t.x,absoluteTop:e,absoluteLeft:0}},t.VerticalFlyout.prototype.setMetrics_=function(t){var e=this.getMetrics_();e&&("number"==typeof t.y&&(this.workspace_.scrollY=-e.contentHeight*t.y),this.workspace_.translate(this.workspace_.scrollX+e.absoluteLeft,this.workspace_.scrollY+e.absoluteTop))},t.VerticalFlyout.prototype.position=function(){if(this.isVisible()){var e=this.targetWorkspace_.getMetrics();e&&(this.height_=e.viewHeight,this.setBackgroundPath_(this.width_-this.CORNER_RADIUS,e.viewHeight-2*this.CORNER_RADIUS),this.positionAt_(this.width_,this.height_,this.targetWorkspace_.toolboxPosition==this.toolboxPosition_?e.toolboxWidth?this.toolboxPosition_==t.TOOLBOX_AT_LEFT?e.toolboxWidth:e.viewWidth-this.width_:this.toolboxPosition_==t.TOOLBOX_AT_LEFT?0:e.viewWidth:this.toolboxPosition_==t.TOOLBOX_AT_LEFT?0:e.viewWidth+e.absoluteLeft-this.width_,0))}},t.VerticalFlyout.prototype.setBackgroundPath_=function(e,o){var i=this.toolboxPosition_==t.TOOLBOX_AT_RIGHT,n=e+this.CORNER_RADIUS;(n=["M "+(i?n:0)+",0"]).push("h",i?-e:e),n.push("a",this.CORNER_RADIUS,this.CORNER_RADIUS,0,0,i?0:1,i?-this.CORNER_RADIUS:this.CORNER_RADIUS,this.CORNER_RADIUS),n.push("v",Math.max(0,o)),n.push("a",this.CORNER_RADIUS,this.CORNER_RADIUS,0,0,i?0:1,i?this.CORNER_RADIUS:-this.CORNER_RADIUS,this.CORNER_RADIUS),n.push("h",i?e:-e),n.push("z"),this.svgBackground_.setAttribute("d",n.join(" "))},t.VerticalFlyout.prototype.scrollToStart=function(){this.scrollbar_.set(0)},t.VerticalFlyout.prototype.wheel_=function(e){var o=t.utils.getScrollDeltaPixels(e);if(o.y){var i=this.getMetrics_();o=i.viewTop-i.contentTop+o.y,o=Math.min(o,i.contentHeight-i.viewHeight),o=Math.max(o,0),this.scrollbar_.set(o),t.WidgetDiv.hide()}e.preventDefault(),e.stopPropagation()},t.VerticalFlyout.prototype.layout_=function(t,e){this.workspace_.scale=this.targetWorkspace_.scale;for(var o,i=this.MARGIN,n=this.RTL?i:i+this.tabWidth_,s=0;o=t[s];s++)if("block"==o.type){for(var r,a=(o=o.block).getDescendants(!1),l=0;r=a[l];l++)r.isInFlyout=!0;o.render(),a=o.getSvgRoot(),l=o.getHeightWidth(),r=o.outputConnection?n-this.tabWidth_:n,o.moveBy(r,i),r=this.createRect_(o,this.RTL?r-l.width:r,i,l,s),this.addBlockListeners_(a,o,r),i+=l.height+e[s]}else"button"==o.type&&(this.initFlyoutButton_(o.button,n,i),i+=o.button.height+e[s])},t.VerticalFlyout.prototype.isDragTowardWorkspace=function(t){t=Math.atan2(t.y,t.x)/Math.PI*180;var e=this.dragAngleRange_;return t-e||t<-180+e||t>180-e},t.VerticalFlyout.prototype.getClientRect=function(){if(!this.svgGroup_)return null;var e=this.svgGroup_.getBoundingClientRect(),o=e.left;return this.toolboxPosition_==t.TOOLBOX_AT_LEFT?new t.utils.Rect(-1e9,1e9,-1e9,o+e.width):new t.utils.Rect(-1e9,1e9,o,1e9)},t.VerticalFlyout.prototype.reflowInternal_=function(){this.workspace_.scale=this.targetWorkspace_.scale;for(var e,o=0,i=this.workspace_.getTopBlocks(!1),n=0;e=i[n];n++){var s=e.getHeightWidth().width;e.outputConnection&&(s-=this.tabWidth_),o=Math.max(o,s)}for(n=0;e=this.buttons_[n];n++)o=Math.max(o,e.width);if(o+=1.5*this.MARGIN+this.tabWidth_,o*=this.workspace_.scale,o+=t.Scrollbar.scrollbarThickness,this.width_!=o){for(n=0;e=i[n];n++){if(this.RTL){s=e.getRelativeToSurfaceXY().x;var r=o/this.workspace_.scale-this.MARGIN;e.outputConnection||(r-=this.tabWidth_),e.moveBy(r-s,0)}e.flyoutRect_&&this.moveRectToBlock_(e.flyoutRect_,e)}if(this.RTL)for(n=0;e=this.buttons_[n];n++)i=e.getPosition().y,e.moveTo(o/this.workspace_.scale-e.width-this.MARGIN-this.tabWidth_,i);this.width_=o,this.position()}},t.FlyoutButton=function(e,o,i,n){this.workspace_=e,this.targetWorkspace_=o,this.text_=i.getAttribute("text"),this.position_=new t.utils.Coordinate(0,0),this.isLabel_=n,this.callbackKey_=i.getAttribute("callbackKey")||i.getAttribute("callbackkey"),this.cssClass_=i.getAttribute("web-class")||null,this.onMouseUpWrapper_=null},t.FlyoutButton.MARGIN_X=5,t.FlyoutButton.MARGIN_Y=2,t.FlyoutButton.prototype.width=0,t.FlyoutButton.prototype.height=0,t.FlyoutButton.prototype.createDom=function(){var e=this.isLabel_?"blocklyFlyoutLabel":"blocklyFlyoutButton";if(this.cssClass_&&(e+=" "+this.cssClass_),this.svgGroup_=t.utils.dom.createSvgElement("g",{class:e},this.workspace_.getCanvas()),!this.isLabel_)var o=t.utils.dom.createSvgElement("rect",{class:"blocklyFlyoutButtonShadow",rx:4,ry:4,x:1,y:1},this.svgGroup_);e=t.utils.dom.createSvgElement("rect",{class:this.isLabel_?"blocklyFlyoutLabelBackground":"blocklyFlyoutButtonBackground",rx:4,ry:4},this.svgGroup_);var i=t.utils.dom.createSvgElement("text",{class:this.isLabel_?"blocklyFlyoutLabelText":"blocklyText",x:0,y:0,"text-anchor":"middle"},this.svgGroup_),n=t.utils.replaceMessageReferences(this.text_);this.workspace_.RTL&&(n+="‏"),i.textContent=n,this.isLabel_&&(this.svgText_=i,this.workspace_.getThemeManager().subscribe(this.svgText_,"flyoutForegroundColour","fill"));var s=t.utils.style.getComputedStyle(i,"fontSize"),r=t.utils.style.getComputedStyle(i,"fontWeight"),a=t.utils.style.getComputedStyle(i,"fontFamily");return this.width=t.utils.dom.getFastTextWidthWithSizeString(i,s,r,a),n=t.utils.dom.measureFontMetrics(n,s,r,a),this.height=n.height,this.isLabel_||(this.width+=2*t.FlyoutButton.MARGIN_X,this.height+=2*t.FlyoutButton.MARGIN_Y,o.setAttribute("width",this.width),o.setAttribute("height",this.height)),e.setAttribute("width",this.width),e.setAttribute("height",this.height),i.setAttribute("x",this.width/2),i.setAttribute("y",this.height/2-n.height/2+n.baseline),this.updateTransform_(),this.onMouseUpWrapper_=t.bindEventWithChecks_(this.svgGroup_,"mouseup",this,this.onMouseUp_),this.svgGroup_},t.FlyoutButton.prototype.show=function(){this.updateTransform_(),this.svgGroup_.setAttribute("display","block")},t.FlyoutButton.prototype.updateTransform_=function(){this.svgGroup_.setAttribute("transform","translate("+this.position_.x+","+this.position_.y+")")},t.FlyoutButton.prototype.moveTo=function(t,e){this.position_.x=t,this.position_.y=e,this.updateTransform_()},t.FlyoutButton.prototype.getPosition=function(){return this.position_},t.FlyoutButton.prototype.getTargetWorkspace=function(){return this.targetWorkspace_},t.FlyoutButton.prototype.dispose=function(){this.onMouseUpWrapper_&&t.unbindEvent_(this.onMouseUpWrapper_),this.svgGroup_&&t.utils.dom.removeNode(this.svgGroup_),this.svgText_&&this.workspace_.getThemeManager().unsubscribe(this.svgText_)},t.FlyoutButton.prototype.onMouseUp_=function(t){(t=this.targetWorkspace_.getGesture(t))&&t.cancel(),this.isLabel_&&this.callbackKey_?console.warn("Labels should not have callbacks. Label text: "+this.text_):this.isLabel_||this.callbackKey_&&this.targetWorkspace_.getButtonCallback(this.callbackKey_)?this.isLabel_||this.targetWorkspace_.getButtonCallback(this.callbackKey_)(this):console.warn("Buttons should have callbacks. Button text: "+this.text_)},t.Css.register(".blocklyFlyoutButton {,fill: #888;,cursor: default;,},.blocklyFlyoutButtonShadow {,fill: #666;,},.blocklyFlyoutButton:hover {,fill: #aaa;,},.blocklyFlyoutLabel {,cursor: default;,},.blocklyFlyoutLabelBackground {,opacity: 0;,}".split(",")),t.Generator=function(t){this.name_=t,this.FUNCTION_NAME_PLACEHOLDER_REGEXP_=new RegExp(this.FUNCTION_NAME_PLACEHOLDER_,"g")},t.Generator.NAME_TYPE="generated_function",t.Generator.prototype.INFINITE_LOOP_TRAP=null,t.Generator.prototype.STATEMENT_PREFIX=null,t.Generator.prototype.STATEMENT_SUFFIX=null,t.Generator.prototype.INDENT=" ",t.Generator.prototype.COMMENT_WRAP=60,t.Generator.prototype.ORDER_OVERRIDES=[],t.Generator.prototype.workspaceToCode=function(e){e||(console.warn("No workspace specified in workspaceToCode call. Guessing."),e=t.getMainWorkspace());var o=[];this.init(e),e=e.getTopBlocks(!0);for(var i,n=0;i=e[n];n++){var s=this.blockToCode(i);Array.isArray(s)&&(s=s[0]),s&&(i.outputConnection&&(s=this.scrubNakedValue(s),this.STATEMENT_PREFIX&&!i.suppressPrefixSuffix&&(s=this.injectId(this.STATEMENT_PREFIX,i)+s),this.STATEMENT_SUFFIX&&!i.suppressPrefixSuffix&&(s+=this.injectId(this.STATEMENT_SUFFIX,i))),o.push(s))}return o=o.join("\n"),(o=(o=(o=this.finish(o)).replace(/^\s+\n/,"")).replace(/\n\s+$/,"\n")).replace(/[ \t]+\n/g,"\n")},t.Generator.prototype.prefixLines=function(t,e){return e+t.replace(/(?!\n$)\n/g,"\n"+e)},t.Generator.prototype.allNestedComments=function(t){var e=[];t=t.getDescendants(!0);for(var o=0;ot&&(t=(t=this.getParent())?t.getDepth()+1:0,this.setDepth_(t)),t},t.tree.BaseNode.prototype.setDepth_=function(t){if(t!=this.depth_){this.depth_=t;var e=this.getRowElement();if(e){var o=this.getPixelIndent_()+"px";this.rightToLeft_?e.style.paddingRight=o:e.style.paddingLeft=o}this.forEachChild((function(e){e.setDepth_(t+1)}))}},t.tree.BaseNode.prototype.contains=function(t){for(;t;){if(t==this)return!0;t=t.getParent()}return!1},t.tree.BaseNode.prototype.getChildren=function(){var t=[];return this.forEachChild((function(e){t.push(e)})),t},t.tree.BaseNode.prototype.getPreviousSibling=function(){return this.previousSibling_},t.tree.BaseNode.prototype.getNextSibling=function(){return this.nextSibling_},t.tree.BaseNode.prototype.isLastSibling=function(){return!this.nextSibling_},t.tree.BaseNode.prototype.isSelected=function(){return this.selected_},t.tree.BaseNode.prototype.select=function(){var t=this.getTree();t&&t.setSelectedItem(this)},t.tree.BaseNode.prototype.setSelected=function(e){if(this.selected_!=e){this.selected_=e,this.updateRow();var o=this.getElement();o&&(t.utils.aria.setState(o,t.utils.aria.State.SELECTED,e),e&&(e=this.getTree().getElement(),t.utils.aria.setState(e,t.utils.aria.State.ACTIVEDESCENDANT,this.getId())))}},t.tree.BaseNode.prototype.setExpanded=function(e){var o,i=e!=this.expanded_;this.expanded_=e;var n=this.getTree(),s=this.getElement();this.hasChildren()?(!e&&n&&this.contains(n.getSelectedItem())&&this.select(),s&&((o=this.getChildrenElement())&&(t.utils.style.setElementShown(o,e),t.utils.aria.setState(s,t.utils.aria.State.EXPANDED,e),e&&this.isInDocument()&&!o.hasChildNodes()&&(this.forEachChild((function(t){o.appendChild(t.toDom())})),this.forEachChild((function(t){t.enterDocument()})))),this.updateExpandIcon())):(o=this.getChildrenElement())&&t.utils.style.setElementShown(o,!1),s&&this.updateIcon_(),i&&(e?this.doNodeExpanded():this.doNodeCollapsed())},t.tree.BaseNode.prototype.doNodeExpanded=function(){},t.tree.BaseNode.prototype.doNodeCollapsed=function(){},t.tree.BaseNode.prototype.toggle=function(){this.setExpanded(!this.expanded_)},t.tree.BaseNode.prototype.toDom=function(){var t=this.expanded_&&this.hasChildren(),e=document.createElement("div");return e.style.backgroundPosition=this.getBackgroundPosition(),t||(e.style.display="none"),t&&this.forEachChild((function(t){e.appendChild(t.toDom())})),(t=document.createElement("div")).id=this.getId(),t.appendChild(this.getRowDom()),t.appendChild(e),t},t.tree.BaseNode.prototype.getPixelIndent_=function(){return Math.max(0,(this.getDepth()-1)*this.config_.indentWidth)},t.tree.BaseNode.prototype.getRowDom=function(){var t=document.createElement("div");return t.className=this.getRowClassName(),t.style["padding-"+(this.rightToLeft_?"right":"left")]=this.getPixelIndent_()+"px",t.appendChild(this.getIconDom()),t.appendChild(this.getLabelDom()),t},t.tree.BaseNode.prototype.getRowClassName=function(){var t="";return this.isSelected()&&(t=" "+(this.config_.cssSelectedRow||"")),this.config_.cssTreeRow+t},t.tree.BaseNode.prototype.getLabelDom=function(){var t=document.createElement("span");return t.className=this.config_.cssItemLabel||"",t.textContent=this.content,t},t.tree.BaseNode.prototype.getIconDom=function(){var t=document.createElement("span");return t.style.display="inline-block",t.className=this.getCalculatedIconClass(),t},t.tree.BaseNode.prototype.getCalculatedIconClass=function(){throw Error("unimplemented abstract method")},t.tree.BaseNode.prototype.getBackgroundPosition=function(){return(this.isLastSibling()?"-100":(this.getDepth()-1)*this.config_.indentWidth)+"px 0"},t.tree.BaseNode.prototype.getElement=function(){var e=t.tree.BaseNode.superClass_.getElement.call(this);return e||(e=document.getElementById(this.getId()),this.setElementInternal(e)),e},t.tree.BaseNode.prototype.getRowElement=function(){var t=this.getElement();return t?t.firstChild:null},t.tree.BaseNode.prototype.getIconElement=function(){var t=this.getRowElement();return t?t.firstChild:null},t.tree.BaseNode.prototype.getLabelElement=function(){var t=this.getRowElement();return t&&t.lastChild?t.lastChild.previousSibling:null},t.tree.BaseNode.prototype.getChildrenElement=function(){var t=this.getElement();return t?t.lastChild:null},t.tree.BaseNode.prototype.updateRow=function(){var t=this.getRowElement();t&&(t.className=this.getRowClassName())},t.tree.BaseNode.prototype.updateExpandIcon=function(){var t=this.getChildrenElement();t&&(t.style.backgroundPosition=this.getBackgroundPosition())},t.tree.BaseNode.prototype.updateIcon_=function(){this.getIconElement().className=this.getCalculatedIconClass()},t.tree.BaseNode.prototype.onMouseDown=function(t){"expand"==t.target.getAttribute("type")&&this.hasChildren()?this.isUserCollapsible_&&this.toggle():(this.select(),this.updateRow())},t.tree.BaseNode.prototype.onClick_=function(t){t.preventDefault()},t.tree.BaseNode.prototype.onKeyDown=function(e){var o=!0;switch(e.keyCode){case t.utils.KeyCodes.RIGHT:if(e.altKey)break;o=this.selectChild();break;case t.utils.KeyCodes.LEFT:if(e.altKey)break;o=this.selectParent();break;case t.utils.KeyCodes.DOWN:o=this.selectNext();break;case t.utils.KeyCodes.UP:o=this.selectPrevious();break;default:o=!1}return o&&e.preventDefault(),o},t.tree.BaseNode.prototype.selectNext=function(){var t=this.getNextShownNode();return t&&t.select(),!0},t.tree.BaseNode.prototype.selectPrevious=function(){var t=this.getPreviousShownNode();return t&&t.select(),!0},t.tree.BaseNode.prototype.selectParent=function(){if(this.hasChildren()&&this.expanded_&&this.isUserCollapsible_)this.setExpanded(!1);else{var t=this.getParent(),e=this.getTree();t&&t!=e&&t.select()}return!0},t.tree.BaseNode.prototype.selectChild=function(){return!!this.hasChildren()&&(this.expanded_?this.getChildAt(0).select():this.setExpanded(!0),!0)},t.tree.BaseNode.prototype.getLastShownDescendant=function(){return this.expanded_&&this.hasChildren()?this.getChildAt(this.getChildCount()-1).getLastShownDescendant():this},t.tree.BaseNode.prototype.getNextShownNode=function(){if(this.hasChildren()&&this.expanded_)return this.getChildAt(0);for(var t,e=this;e!=this.getTree();){if(null!=(t=e.getNextSibling()))return t;e=e.getParent()}return null},t.tree.BaseNode.prototype.getPreviousShownNode=function(){var t=this.getPreviousSibling();if(null!=t)return t.getLastShownDescendant();t=this.getParent();var e=this.getTree();return t==e||this==e?null:t},t.tree.BaseNode.prototype.setTreeInternal=function(t){this.tree!=t&&(this.tree=t,this.forEachChild((function(e){e.setTreeInternal(t)})))},t.tree.TreeNode=function(e,o,i){this.toolbox_=e,t.tree.BaseNode.call(this,o,i)},t.utils.object.inherits(t.tree.TreeNode,t.tree.BaseNode),t.tree.TreeNode.prototype.getTree=function(){if(this.tree)return this.tree;var t=this.getParent();return t&&(t=t.getTree())?(this.setTreeInternal(t),t):null},t.tree.TreeNode.prototype.getCalculatedIconClass=function(){var t=this.expanded_;if(t&&this.expandedIconClass)return this.expandedIconClass;var e=this.iconClass;if(!t&&e)return e;if(e=this.config_,this.hasChildren()){if(t&&e.cssExpandedFolderIcon)return e.cssTreeIcon+" "+e.cssExpandedFolderIcon;if(!t&&e.cssCollapsedFolderIcon)return e.cssTreeIcon+" "+e.cssCollapsedFolderIcon}else if(e.cssFileIcon)return e.cssTreeIcon+" "+e.cssFileIcon;return""},t.tree.TreeNode.prototype.onClick_=function(t){this.hasChildren()&&this.isUserCollapsible_?(this.toggle(),this.select()):this.isSelected()?this.getTree().setSelectedItem(null):this.select(),this.updateRow()},t.tree.TreeNode.prototype.onMouseDown=function(t){},t.tree.TreeNode.prototype.onKeyDown=function(e){if(this.tree.toolbox_.horizontalLayout_){var o={},i=t.utils.KeyCodes.DOWN,n=t.utils.KeyCodes.UP;o[t.utils.KeyCodes.RIGHT]=this.rightToLeft_?n:i,o[t.utils.KeyCodes.LEFT]=this.rightToLeft_?i:n,o[t.utils.KeyCodes.UP]=t.utils.KeyCodes.LEFT,o[t.utils.KeyCodes.DOWN]=t.utils.KeyCodes.RIGHT,Object.defineProperties(e,{keyCode:{value:o[e.keyCode]||e.keyCode}})}return t.tree.TreeNode.superClass_.onKeyDown.call(this,e)},t.tree.TreeNode.prototype.onSizeChanged=function(t){this.onSizeChanged_=t},t.tree.TreeNode.prototype.resizeToolbox_=function(){this.onSizeChanged_&&this.onSizeChanged_.call(this.toolbox_)},t.tree.TreeNode.prototype.doNodeExpanded=t.tree.TreeNode.prototype.resizeToolbox_,t.tree.TreeNode.prototype.doNodeCollapsed=t.tree.TreeNode.prototype.resizeToolbox_,t.tree.TreeControl=function(e,o){this.toolbox_=e,this.onKeydownWrapper_=this.onClickWrapper_=this.onBlurWrapper_=this.onFocusWrapper_=null,t.tree.BaseNode.call(this,"",o),this.selected_=this.expanded_=!0,this.selectedItem_=this},t.utils.object.inherits(t.tree.TreeControl,t.tree.BaseNode),t.tree.TreeControl.prototype.getTree=function(){return this},t.tree.TreeControl.prototype.getToolbox=function(){return this.toolbox_},t.tree.TreeControl.prototype.getDepth=function(){return 0},t.tree.TreeControl.prototype.handleFocus_=function(e){this.focused_=!0,e=this.getElement(),t.utils.dom.addClass(e,"focused"),this.selectedItem_&&this.selectedItem_.select()},t.tree.TreeControl.prototype.handleBlur_=function(e){this.focused_=!1,e=this.getElement(),t.utils.dom.removeClass(e,"focused")},t.tree.TreeControl.prototype.hasFocus=function(){return this.focused_},t.tree.TreeControl.prototype.setExpanded=function(t){this.expanded_=t},t.tree.TreeControl.prototype.getIconElement=function(){var t=this.getRowElement();return t?t.firstChild:null},t.tree.TreeControl.prototype.updateExpandIcon=function(){},t.tree.TreeControl.prototype.getRowClassName=function(){return t.tree.TreeControl.superClass_.getRowClassName.call(this)+" "+this.config_.cssHideRoot},t.tree.TreeControl.prototype.getCalculatedIconClass=function(){var t=this.expanded_;if(t&&this.expandedIconClass)return this.expandedIconClass;var e=this.iconClass;return!t&&e?e:t&&this.config_.cssExpandedRootIcon?this.config_.cssTreeIcon+" "+this.config_.cssExpandedRootIcon:""},t.tree.TreeControl.prototype.setSelectedItem=function(t){if(t!=this.selectedItem_&&(!this.onBeforeSelected_||this.onBeforeSelected_.call(this.toolbox_,t))){var e=this.getSelectedItem();this.selectedItem_&&this.selectedItem_.setSelected(!1),(this.selectedItem_=t)&&t.setSelected(!0),this.onAfterSelected_&&this.onAfterSelected_.call(this.toolbox_,e,t)}},t.tree.TreeControl.prototype.onBeforeSelected=function(t){this.onBeforeSelected_=t},t.tree.TreeControl.prototype.onAfterSelected=function(t){this.onAfterSelected_=t},t.tree.TreeControl.prototype.getSelectedItem=function(){return this.selectedItem_},t.tree.TreeControl.prototype.initAccessibility=function(){t.tree.TreeControl.superClass_.initAccessibility.call(this);var e=this.getElement();t.utils.aria.setRole(e,t.utils.aria.Role.TREE),t.utils.aria.setState(e,t.utils.aria.State.LABELLEDBY,this.getLabelElement().id)},t.tree.TreeControl.prototype.enterDocument=function(){t.tree.TreeControl.superClass_.enterDocument.call(this);var e=this.getElement();e.className=this.config_.cssRoot,e.setAttribute("hideFocus","true"),this.attachEvents_(),this.initAccessibility()},t.tree.TreeControl.prototype.exitDocument=function(){t.tree.TreeControl.superClass_.exitDocument.call(this),this.detachEvents_()},t.tree.TreeControl.prototype.attachEvents_=function(){var e=this.getElement();e.tabIndex=0,this.onFocusWrapper_=t.bindEvent_(e,"focus",this,this.handleFocus_),this.onBlurWrapper_=t.bindEvent_(e,"blur",this,this.handleBlur_),this.onClickWrapper_=t.bindEventWithChecks_(e,"click",this,this.handleMouseEvent_),this.onKeydownWrapper_=t.bindEvent_(e,"keydown",this,this.handleKeyEvent_)},t.tree.TreeControl.prototype.detachEvents_=function(){this.onFocusWrapper_&&(t.unbindEvent_(this.onFocusWrapper_),this.onFocusWrapper_=null),this.onBlurWrapper_&&(t.unbindEvent_(this.onBlurWrapper_),this.onBlurWrapper_=null),this.onClickWrapper_&&(t.unbindEvent_(this.onClickWrapper_),this.onClickWrapper_=null),this.onKeydownWrapper_&&(t.unbindEvent_(this.onKeydownWrapper_),this.onKeydownWrapper_=null)},t.tree.TreeControl.prototype.handleMouseEvent_=function(t){var e=this.getNodeFromEvent_(t);if(e)switch(t.type){case"mousedown":e.onMouseDown(t);break;case"click":e.onClick_(t)}},t.tree.TreeControl.prototype.handleKeyEvent_=function(e){var o=!1;return(o=this.selectedItem_&&this.selectedItem_.onKeyDown(e)||o)&&(t.utils.style.scrollIntoContainerView(this.selectedItem_.getElement(),this.getElement().parentNode),e.preventDefault()),o},t.tree.TreeControl.prototype.getNodeFromEvent_=function(e){for(var o=e.target;null!=o;){if(e=t.tree.BaseNode.allNodes[o.id])return e;if(o==this.getElement())break;if(o.getAttribute("role")==t.utils.aria.Role.GROUP)break;o=o.parentNode}return null},t.tree.TreeControl.prototype.createNode=function(e){return new t.tree.TreeNode(this.toolbox_,e||"",this.config_)},t.Toolbox=function(t){this.workspace_=t,this.RTL=t.options.RTL,this.horizontalLayout_=t.options.horizontalLayout,this.toolboxPosition=t.options.toolboxPosition,this.config_={indentWidth:19,cssRoot:"blocklyTreeRoot",cssHideRoot:"blocklyHidden",cssTreeRow:"blocklyTreeRow",cssItemLabel:"blocklyTreeLabel",cssTreeIcon:"blocklyTreeIcon",cssExpandedFolderIcon:"blocklyTreeIconOpen",cssFileIcon:"blocklyTreeIconNone",cssSelectedRow:"blocklyTreeSelected"},this.treeSeparatorConfig_={cssTreeRow:"blocklyTreeSeparator"},this.horizontalLayout_&&(this.config_.cssTreeRow+=t.RTL?" blocklyHorizontalTreeRtl":" blocklyHorizontalTree",this.treeSeparatorConfig_.cssTreeRow="blocklyTreeSeparatorHorizontal "+(t.RTL?"blocklyHorizontalTreeRtl":"blocklyHorizontalTree"),this.config_.cssTreeIcon=""),this.flyout_=null},t.Toolbox.prototype.width=0,t.Toolbox.prototype.height=0,t.Toolbox.prototype.selectedOption_=null,t.Toolbox.prototype.lastCategory_=null,t.Toolbox.prototype.init=function(){var e=this.workspace_,o=this.workspace_.getParentSvg();this.HtmlDiv=document.createElement("div"),this.HtmlDiv.className="blocklyToolboxDiv blocklyNonSelectable",this.HtmlDiv.setAttribute("dir",e.RTL?"RTL":"LTR"),o.parentNode.insertBefore(this.HtmlDiv,o);var i=e.getThemeManager();if(i.subscribe(this.HtmlDiv,"toolboxBackgroundColour","background-color"),i.subscribe(this.HtmlDiv,"toolboxForegroundColour","color"),t.bindEventWithChecks_(this.HtmlDiv,"mousedown",this,(function(e){t.utils.isRightButton(e)||e.target==this.HtmlDiv?t.hideChaff(!1):t.hideChaff(!0),t.Touch.clearTouchIdentifier()}),!1,!0),(i=new t.Options({parentWorkspace:e,rtl:e.RTL,oneBasedIndex:e.options.oneBasedIndex,horizontalLayout:e.horizontalLayout,renderer:e.options.renderer,rendererOverrides:e.options.rendererOverrides})).toolboxPosition=e.options.toolboxPosition,e.horizontalLayout){if(!t.HorizontalFlyout)throw Error("Missing require for Blockly.HorizontalFlyout");this.flyout_=new t.HorizontalFlyout(i)}else{if(!t.VerticalFlyout)throw Error("Missing require for Blockly.VerticalFlyout");this.flyout_=new t.VerticalFlyout(i)}if(!this.flyout_)throw Error("One of Blockly.VerticalFlyout or Blockly.Horizontal must berequired.");t.utils.dom.insertAfter(this.flyout_.createDom("svg"),o),this.flyout_.init(e),this.config_.cleardotPath=e.options.pathToMedia+"1x1.gif",this.config_.cssCollapsedFolderIcon="blocklyTreeIconClosed"+(e.RTL?"Rtl":"Ltr"),this.renderTree(e.options.languageTree)},t.Toolbox.prototype.renderTree=function(e){this.tree_&&(this.tree_.dispose(),this.lastCategory_=null);var o=new t.tree.TreeControl(this,this.config_);this.tree_=o,o.setSelectedItem(null),o.onBeforeSelected(this.handleBeforeTreeSelected_),o.onAfterSelected(this.handleAfterTreeSelected_);var i=null;if(e){if(this.tree_.blocks=[],this.hasColours_=!1,i=this.syncTrees_(e,this.tree_,this.workspace_.options.pathToMedia),this.tree_.blocks.length)throw Error("Toolbox cannot have both blocks and categories in the root level.");this.workspace_.resizeContents()}o.render(this.HtmlDiv),i&&o.setSelectedItem(i),this.addColour_(),this.position(),this.horizontalLayout_&&t.utils.aria.setState(this.tree_.getElement(),t.utils.aria.State.ORIENTATION,"horizontal")},t.Toolbox.prototype.handleBeforeTreeSelected_=function(t){if(t==this.tree_)return!1;if(this.lastCategory_&&(this.lastCategory_.getRowElement().style.backgroundColor=""),t){var e=t.hexColour||"#57e";t.getRowElement().style.backgroundColor=e,this.addColour_(t)}return!0},t.Toolbox.prototype.handleAfterTreeSelected_=function(e,o){o&&o.blocks&&o.blocks.length?(this.flyout_.show(o.blocks),this.lastCategory_!=o&&this.flyout_.scrollToStart(),this.workspace_.keyboardAccessibilityMode&&t.navigation.setState(t.navigation.STATE_TOOLBOX)):(this.flyout_.hide(),!this.workspace_.keyboardAccessibilityMode||o instanceof t.Toolbox.TreeSeparator||t.navigation.setState(t.navigation.STATE_WS)),e!=o&&e!=this&&((e=new t.Events.Ui(null,"category",e&&e.content,o&&o.content)).workspaceId=this.workspace_.id,t.Events.fire(e)),o&&(this.lastCategory_=o)},t.Toolbox.prototype.handleNodeSizeChanged_=function(){t.svgResize(this.workspace_)},t.Toolbox.prototype.onBlocklyAction=function(e){var o=this.tree_.getSelectedItem();if(!o)return!1;switch(e.name){case t.navigation.actionNames.PREVIOUS:return o.selectPrevious();case t.navigation.actionNames.OUT:return o.selectParent();case t.navigation.actionNames.NEXT:return o.selectNext();case t.navigation.actionNames.IN:return o.selectChild();default:return!1}},t.Toolbox.prototype.dispose=function(){this.flyout_.dispose(),this.tree_.dispose(),this.workspace_.getThemeManager().unsubscribe(this.HtmlDiv),t.utils.dom.removeNode(this.HtmlDiv),this.lastCategory_=null},t.Toolbox.prototype.getWidth=function(){return this.width},t.Toolbox.prototype.getHeight=function(){return this.height},t.Toolbox.prototype.getFlyout=function(){return this.flyout_},t.Toolbox.prototype.position=function(){var e=this.HtmlDiv;if(e){var o=t.svgSize(this.workspace_.getParentSvg());this.horizontalLayout_?(e.style.left="0",e.style.height="auto",e.style.width=o.width+"px",this.height=e.offsetHeight,this.toolboxPosition==t.TOOLBOX_AT_TOP?e.style.top="0":e.style.bottom="0"):(this.toolboxPosition==t.TOOLBOX_AT_RIGHT?e.style.right="0":e.style.left="0",e.style.height=o.height+"px",this.width=e.offsetWidth),this.flyout_.position()}},t.Toolbox.prototype.syncTrees_=function(e,o,i){for(var n,s=null,r=null,a=0;n=e.childNodes[a];a++)if(n.tagName)switch(n.tagName.toUpperCase()){case"CATEGORY":r=t.utils.replaceMessageReferences(n.getAttribute("name"));var l=this.tree_.createNode(r);l.onSizeChanged(this.handleNodeSizeChanged_),l.blocks=[],o.add(l);var c=n.getAttribute("custom");c?l.blocks=c:(c=this.syncTrees_(n,l,i))&&(s=c),c=n.getAttribute("categorystyle");var h=n.getAttribute("colour");h&&c?(l.hexColour="",console.warn('Toolbox category "'+r+'" can not have both a style and a colour')):c?this.setColourFromStyle_(c,l,r):this.setColour_(h,l,r),"true"==n.getAttribute("expanded")?(l.blocks.length&&(s=l),l.setExpanded(!0)):l.setExpanded(!1),r=n;break;case"SEP":if(r&&"CATEGORY"==r.tagName.toUpperCase()){o.add(new t.Toolbox.TreeSeparator(this.treeSeparatorConfig_));break}case"BLOCK":case"SHADOW":case"LABEL":case"BUTTON":o.blocks.push(n),r=n}return s},t.Toolbox.prototype.setColour_=function(e,o,i){if(null===(e=t.utils.replaceMessageReferences(e))||""===e)o.hexColour="";else{var n=Number(e);isNaN(n)?(n=t.utils.colour.parse(e))?(o.hexColour=n,this.hasColours_=!0):(o.hexColour="",console.warn('Toolbox category "'+i+'" has unrecognized colour attribute: '+e)):(o.hexColour=t.hueToHex(n),this.hasColours_=!0)}},t.Toolbox.prototype.setColourFromStyle_=function(t,e,o){e.styleName=t;var i=this.workspace_.getTheme();t&&i&&((i=i.categoryStyles[t])&&i.colour?this.setColour_(i.colour,e,o):console.warn('Style "'+t+'" must exist and contain a colour value'))},t.Toolbox.prototype.updateColourFromTheme_=function(t){if(t=t||this.tree_){t=t.getChildren(!1);for(var e,o=0;e=t[o];o++)e.styleName&&(this.setColourFromStyle_(e.styleName,e,""),this.addColour_()),this.updateColourFromTheme_(e)}},t.Toolbox.prototype.updateColourFromTheme=function(){var t=this.tree_;t&&(this.updateColourFromTheme_(t),this.updateSelectedItemColour_(t))},t.Toolbox.prototype.updateSelectedItemColour_=function(t){if(t=t.getSelectedItem()){var e=t.hexColour||"#57e";t.getRowElement().style.backgroundColor=e,this.addColour_(t)}},t.Toolbox.prototype.addColour_=function(t){t=(t||this.tree_).getChildren(!1);for(var e,o=0;e=t[o];o++){var i=e.getRowElement();if(i){var n=this.hasColours_?"8px solid "+(e.hexColour||"#ddd"):"none";this.workspace_.RTL?i.style.borderRight=n:i.style.borderLeft=n}this.addColour_(e)}},t.Toolbox.prototype.clearSelection=function(){this.tree_.setSelectedItem(null)},t.Toolbox.prototype.addStyle=function(e){t.utils.dom.addClass(this.HtmlDiv,e)},t.Toolbox.prototype.removeStyle=function(e){t.utils.dom.removeClass(this.HtmlDiv,e)},t.Toolbox.prototype.getClientRect=function(){if(!this.HtmlDiv)return null;var e=this.HtmlDiv.getBoundingClientRect(),o=e.top,i=o+e.height,n=e.left;return e=n+e.width,this.toolboxPosition==t.TOOLBOX_AT_TOP?new t.utils.Rect(-1e7,i,-1e7,1e7):this.toolboxPosition==t.TOOLBOX_AT_BOTTOM?new t.utils.Rect(o,1e7,-1e7,1e7):this.toolboxPosition==t.TOOLBOX_AT_LEFT?new t.utils.Rect(-1e7,1e7,-1e7,e):new t.utils.Rect(-1e7,1e7,n,1e7)},t.Toolbox.prototype.refreshSelection=function(){var t=this.tree_.getSelectedItem();t&&t.blocks&&this.flyout_.show(t.blocks)},t.Toolbox.prototype.selectFirstCategory=function(){this.tree_.getSelectedItem()||this.tree_.selectChild()},t.Toolbox.TreeSeparator=function(e){t.tree.TreeNode.call(this,null,"",e)},t.utils.object.inherits(t.Toolbox.TreeSeparator,t.tree.TreeNode),t.Css.register([".blocklyToolboxDelete {",'cursor: url("<<>>/handdelete.cur"), auto;',"}",".blocklyToolboxGrab {",'cursor: url("<<>>/handclosed.cur"), auto;',"cursor: grabbing;","cursor: -webkit-grabbing;","}",".blocklyToolboxDiv {","background-color: #ddd;","overflow-x: visible;","overflow-y: auto;","position: absolute;","z-index: 70;","-webkit-tap-highlight-color: transparent;","}",".blocklyTreeRoot {","padding: 4px 0;","}",".blocklyTreeRoot:focus {","outline: none;","}",".blocklyTreeRow {","height: 22px;","line-height: 22px;","margin-bottom: 3px;","padding-right: 8px;","white-space: nowrap;","}",".blocklyHorizontalTree {","float: left;","margin: 1px 5px 8px 0;","}",".blocklyHorizontalTreeRtl {","float: right;","margin: 1px 0 8px 5px;","}",'.blocklyToolboxDiv[dir="RTL"] .blocklyTreeRow {',"margin-left: 8px;","}",".blocklyTreeRow:not(.blocklyTreeSelected):hover {","background-color: rgba(255, 255, 255, 0.2);","}",".blocklyTreeSeparator {","border-bottom: solid #e5e5e5 1px;","height: 0;","margin: 5px 0;","}",".blocklyTreeSeparatorHorizontal {","border-right: solid #e5e5e5 1px;","width: 0;","padding: 5px 0;","margin: 0 5px;","}",".blocklyTreeIcon {","background-image: url(<<>>/sprites.png);","height: 16px;","vertical-align: middle;","width: 16px;","}",".blocklyTreeIconClosedLtr {","background-position: -32px -1px;","}",".blocklyTreeIconClosedRtl {","background-position: 0 -1px;","}",".blocklyTreeIconOpen {","background-position: -16px -1px;","}",".blocklyTreeSelected>.blocklyTreeIconClosedLtr {","background-position: -32px -17px;","}",".blocklyTreeSelected>.blocklyTreeIconClosedRtl {","background-position: 0 -17px;","}",".blocklyTreeSelected>.blocklyTreeIconOpen {","background-position: -16px -17px;","}",".blocklyTreeIconNone,",".blocklyTreeSelected>.blocklyTreeIconNone {","background-position: -48px -1px;","}",".blocklyTreeLabel {","cursor: default;","font-family: sans-serif;","font-size: 16px;","padding: 0 3px;","vertical-align: middle;","}",".blocklyToolboxDelete .blocklyTreeLabel {",'cursor: url("<<>>/handdelete.cur"), auto;',"}",".blocklyTreeSelected .blocklyTreeLabel {","color: #fff;","}"]),t.Trashcan=function(e){if(this.workspace_=e,this.contents_=[],this.flyout=null,!(0>=this.workspace_.options.maxTrashcanContents)){if(e=new t.Options({scrollbars:!0,parentWorkspace:this.workspace_,rtl:this.workspace_.RTL,oneBasedIndex:this.workspace_.options.oneBasedIndex,renderer:this.workspace_.options.renderer,rendererOverrides:this.workspace_.options.rendererOverrides}),this.workspace_.horizontalLayout){if(e.toolboxPosition=this.workspace_.toolboxPosition==t.TOOLBOX_AT_TOP?t.TOOLBOX_AT_BOTTOM:t.TOOLBOX_AT_TOP,!t.HorizontalFlyout)throw Error("Missing require for Blockly.HorizontalFlyout");this.flyout=new t.HorizontalFlyout(e)}else{if(e.toolboxPosition=this.workspace_.toolboxPosition==t.TOOLBOX_AT_RIGHT?t.TOOLBOX_AT_LEFT:t.TOOLBOX_AT_RIGHT,!t.VerticalFlyout)throw Error("Missing require for Blockly.VerticalFlyout");this.flyout=new t.VerticalFlyout(e)}this.workspace_.addChangeListener(this.onDelete_.bind(this))}},t.Trashcan.prototype.WIDTH_=47,t.Trashcan.prototype.BODY_HEIGHT_=44,t.Trashcan.prototype.LID_HEIGHT_=16,t.Trashcan.prototype.MARGIN_BOTTOM_=20,t.Trashcan.prototype.MARGIN_SIDE_=20,t.Trashcan.prototype.MARGIN_HOTSPOT_=10,t.Trashcan.prototype.SPRITE_LEFT_=0,t.Trashcan.prototype.SPRITE_TOP_=32,t.Trashcan.prototype.HAS_BLOCKS_LID_ANGLE_=.1,t.Trashcan.ANIMATION_LENGTH_=80,t.Trashcan.ANIMATION_FRAMES_=4,t.Trashcan.OPACITY_MIN_=.4,t.Trashcan.OPACITY_MAX_=.8,t.Trashcan.MAX_LID_ANGLE_=45,t.Trashcan.prototype.isOpen=!1,t.Trashcan.prototype.minOpenness_=0,t.Trashcan.prototype.svgGroup_=null,t.Trashcan.prototype.svgLid_=null,t.Trashcan.prototype.lidTask_=0,t.Trashcan.prototype.lidOpen_=0,t.Trashcan.prototype.left_=0,t.Trashcan.prototype.top_=0,t.Trashcan.prototype.createDom=function(){this.svgGroup_=t.utils.dom.createSvgElement("g",{class:"blocklyTrash"},null);var e=String(Math.random()).substring(2),o=t.utils.dom.createSvgElement("clipPath",{id:"blocklyTrashBodyClipPath"+e},this.svgGroup_);t.utils.dom.createSvgElement("rect",{width:this.WIDTH_,height:this.BODY_HEIGHT_,y:this.LID_HEIGHT_},o);var i=t.utils.dom.createSvgElement("image",{width:t.SPRITE.width,x:-this.SPRITE_LEFT_,height:t.SPRITE.height,y:-this.SPRITE_TOP_,"clip-path":"url(#blocklyTrashBodyClipPath"+e+")"},this.svgGroup_);return i.setAttributeNS(t.utils.dom.XLINK_NS,"xlink:href",this.workspace_.options.pathToMedia+t.SPRITE.url),o=t.utils.dom.createSvgElement("clipPath",{id:"blocklyTrashLidClipPath"+e},this.svgGroup_),t.utils.dom.createSvgElement("rect",{width:this.WIDTH_,height:this.LID_HEIGHT_},o),this.svgLid_=t.utils.dom.createSvgElement("image",{width:t.SPRITE.width,x:-this.SPRITE_LEFT_,height:t.SPRITE.height,y:-this.SPRITE_TOP_,"clip-path":"url(#blocklyTrashLidClipPath"+e+")"},this.svgGroup_),this.svgLid_.setAttributeNS(t.utils.dom.XLINK_NS,"xlink:href",this.workspace_.options.pathToMedia+t.SPRITE.url),t.bindEventWithChecks_(this.svgGroup_,"mouseup",this,this.click),t.bindEvent_(i,"mouseover",this,this.mouseOver_),t.bindEvent_(i,"mouseout",this,this.mouseOut_),this.animateLid_(),this.svgGroup_},t.Trashcan.prototype.init=function(e){return 0this.minOpenness_&&1>this.lidOpen_&&(this.lidTask_=setTimeout(this.animateLid_.bind(this),t.Trashcan.ANIMATION_LENGTH_/e))},t.Trashcan.prototype.setLidAngle_=function(e){var o=this.workspace_.toolboxPosition==t.TOOLBOX_AT_RIGHT||this.workspace_.horizontalLayout&&this.workspace_.RTL;this.svgLid_.setAttribute("transform","rotate("+(o?-e:e)+","+(o?4:this.WIDTH_-4)+","+(this.LID_HEIGHT_-2)+")")},t.Trashcan.prototype.setMinOpenness_=function(e){this.minOpenness_=e,this.isOpen||this.setLidAngle_(e*t.Trashcan.MAX_LID_ANGLE_)},t.Trashcan.prototype.close=function(){this.setOpen(!1)},t.Trashcan.prototype.click=function(){if(this.contents_.length){for(var e,o=[],i=0;e=this.contents_[i];i++)o[i]=t.Xml.textToDom(e);this.flyout.show(o)}},t.Trashcan.prototype.mouseOver_=function(){this.contents_.length&&this.setOpen(!0)},t.Trashcan.prototype.mouseOut_=function(){this.setOpen(!1)},t.Trashcan.prototype.onDelete_=function(e){if(!(0>=this.workspace_.options.maxTrashcanContents)&&e.type==t.Events.BLOCK_DELETE&&"shadow"!=e.oldXml.tagName.toLowerCase()&&(e=this.cleanBlockXML_(e.oldXml),-1==this.contents_.indexOf(e))){for(this.contents_.unshift(e);this.contents_.length>this.workspace_.options.maxTrashcanContents;)this.contents_.pop();this.setMinOpenness_(this.HAS_BLOCKS_LID_ANGLE_)}},t.Trashcan.prototype.cleanBlockXML_=function(e){for(var o=e=e.cloneNode(!0);o;){o.removeAttribute&&(o.removeAttribute("x"),o.removeAttribute("y"),o.removeAttribute("id"),o.removeAttribute("disabled"),"comment"==o.nodeName&&(o.removeAttribute("h"),o.removeAttribute("w"),o.removeAttribute("pinned")));var i=o.firstChild||o.nextSibling;if(!i)for(i=o.parentNode;i;){if(i.nextSibling){i=i.nextSibling;break}i=i.parentNode}o=i}return t.Xml.domToText(e)},t.VariablesDynamic={},t.VariablesDynamic.onCreateVariableButtonClick_String=function(e){t.Variables.createVariableButtonHandler(e.getTargetWorkspace(),void 0,"String")},t.VariablesDynamic.onCreateVariableButtonClick_Number=function(e){t.Variables.createVariableButtonHandler(e.getTargetWorkspace(),void 0,"Number")},t.VariablesDynamic.onCreateVariableButtonClick_Colour=function(e){t.Variables.createVariableButtonHandler(e.getTargetWorkspace(),void 0,"Colour")},t.VariablesDynamic.flyoutCategory=function(e){var o=[],i=document.createElement("button");return i.setAttribute("text",t.Msg.NEW_STRING_VARIABLE),i.setAttribute("callbackKey","CREATE_VARIABLE_STRING"),o.push(i),(i=document.createElement("button")).setAttribute("text",t.Msg.NEW_NUMBER_VARIABLE),i.setAttribute("callbackKey","CREATE_VARIABLE_NUMBER"),o.push(i),(i=document.createElement("button")).setAttribute("text",t.Msg.NEW_COLOUR_VARIABLE),i.setAttribute("callbackKey","CREATE_VARIABLE_COLOUR"),o.push(i),e.registerButtonCallback("CREATE_VARIABLE_STRING",t.VariablesDynamic.onCreateVariableButtonClick_String),e.registerButtonCallback("CREATE_VARIABLE_NUMBER",t.VariablesDynamic.onCreateVariableButtonClick_Number),e.registerButtonCallback("CREATE_VARIABLE_COLOUR",t.VariablesDynamic.onCreateVariableButtonClick_Colour),e=t.VariablesDynamic.flyoutCategoryBlocks(e),o.concat(e)},t.VariablesDynamic.flyoutCategoryBlocks=function(e){var o=[];if(0<(e=e.getAllVariables()).length){if(t.Blocks.variables_set_dynamic){var i=e[e.length-1],n=t.utils.xml.createElement("block");n.setAttribute("type","variables_set_dynamic"),n.setAttribute("gap",24),n.appendChild(t.Variables.generateVariableFieldDom(i)),o.push(n)}if(t.Blocks.variables_get_dynamic){e.sort(t.VariableModel.compareByName),i=0;for(var s;s=e[i];i++)(n=t.utils.xml.createElement("block")).setAttribute("type","variables_get_dynamic"),n.setAttribute("gap",8),n.appendChild(t.Variables.generateVariableFieldDom(s)),o.push(n)}}return o},t.ZoomControls=function(t){this.workspace_=t},t.ZoomControls.prototype.WIDTH_=32,t.ZoomControls.prototype.HEIGHT_=110,t.ZoomControls.prototype.MARGIN_BOTTOM_=20,t.ZoomControls.prototype.MARGIN_SIDE_=20,t.ZoomControls.prototype.svgGroup_=null,t.ZoomControls.prototype.left_=0,t.ZoomControls.prototype.top_=0,t.ZoomControls.prototype.createDom=function(){this.svgGroup_=t.utils.dom.createSvgElement("g",{},null);var e=String(Math.random()).substring(2);return this.createZoomOutSvg_(e),this.createZoomInSvg_(e),this.workspace_.isMovable()&&this.createZoomResetSvg_(e),this.svgGroup_},t.ZoomControls.prototype.init=function(t){return this.verticalSpacing_=this.MARGIN_BOTTOM_+t,this.verticalSpacing_+this.HEIGHT_},t.ZoomControls.prototype.dispose=function(){this.svgGroup_&&t.utils.dom.removeNode(this.svgGroup_)},t.ZoomControls.prototype.position=function(){if(this.verticalSpacing_){var e=this.workspace_.getMetrics();e&&(this.left_=e.toolboxPosition==t.TOOLBOX_AT_LEFT||this.workspace_.horizontalLayout&&!this.workspace_.RTL?e.viewWidth+e.absoluteLeft-this.WIDTH_-this.MARGIN_SIDE_-t.Scrollbar.scrollbarThickness:this.MARGIN_SIDE_+t.Scrollbar.scrollbarThickness,e.toolboxPosition==t.TOOLBOX_AT_BOTTOM?(this.top_=this.verticalSpacing_,this.zoomInGroup_.setAttribute("transform","translate(0, 34)"),this.zoomResetGroup_&&this.zoomResetGroup_.setAttribute("transform","translate(0, 77)")):(this.top_=e.viewHeight+e.absoluteTop-this.HEIGHT_-this.verticalSpacing_,this.zoomInGroup_.setAttribute("transform","translate(0, 43)"),this.zoomOutGroup_.setAttribute("transform","translate(0, 77)")),this.svgGroup_.setAttribute("transform","translate("+this.left_+","+this.top_+")"))}},t.ZoomControls.prototype.createZoomOutSvg_=function(e){var o=this.workspace_;this.zoomOutGroup_=t.utils.dom.createSvgElement("g",{class:"blocklyZoom"},this.svgGroup_);var i=t.utils.dom.createSvgElement("clipPath",{id:"blocklyZoomoutClipPath"+e},this.zoomOutGroup_);t.utils.dom.createSvgElement("rect",{width:32,height:32},i),(e=t.utils.dom.createSvgElement("image",{width:t.SPRITE.width,height:t.SPRITE.height,x:-64,y:-92,"clip-path":"url(#blocklyZoomoutClipPath"+e+")"},this.zoomOutGroup_)).setAttributeNS(t.utils.dom.XLINK_NS,"xlink:href",o.options.pathToMedia+t.SPRITE.url),t.bindEventWithChecks_(e,"mousedown",null,(function(e){o.markFocused(),o.zoomCenter(-1),t.Touch.clearTouchIdentifier(),e.stopPropagation(),e.preventDefault()}))},t.ZoomControls.prototype.createZoomInSvg_=function(e){var o=this.workspace_;this.zoomInGroup_=t.utils.dom.createSvgElement("g",{class:"blocklyZoom"},this.svgGroup_);var i=t.utils.dom.createSvgElement("clipPath",{id:"blocklyZoominClipPath"+e},this.zoomInGroup_);t.utils.dom.createSvgElement("rect",{width:32,height:32},i),(e=t.utils.dom.createSvgElement("image",{width:t.SPRITE.width,height:t.SPRITE.height,x:-32,y:-92,"clip-path":"url(#blocklyZoominClipPath"+e+")"},this.zoomInGroup_)).setAttributeNS(t.utils.dom.XLINK_NS,"xlink:href",o.options.pathToMedia+t.SPRITE.url),t.bindEventWithChecks_(e,"mousedown",null,(function(e){o.markFocused(),o.zoomCenter(1),t.Touch.clearTouchIdentifier(),e.stopPropagation(),e.preventDefault()}))},t.ZoomControls.prototype.createZoomResetSvg_=function(e){var o=this.workspace_;this.zoomResetGroup_=t.utils.dom.createSvgElement("g",{class:"blocklyZoom"},this.svgGroup_);var i=t.utils.dom.createSvgElement("clipPath",{id:"blocklyZoomresetClipPath"+e},this.zoomResetGroup_);t.utils.dom.createSvgElement("rect",{width:32,height:32},i),(e=t.utils.dom.createSvgElement("image",{width:t.SPRITE.width,height:t.SPRITE.height,y:-92,"clip-path":"url(#blocklyZoomresetClipPath"+e+")"},this.zoomResetGroup_)).setAttributeNS(t.utils.dom.XLINK_NS,"xlink:href",o.options.pathToMedia+t.SPRITE.url),t.bindEventWithChecks_(e,"mousedown",null,(function(e){o.markFocused(),o.setScale(o.options.zoomOptions.startScale),o.beginCanvasTransition(),o.scrollCenter(),setTimeout(o.endCanvasTransition.bind(o),500),t.Touch.clearTouchIdentifier(),e.stopPropagation(),e.preventDefault()}))},t.Css.register([".blocklyZoom>image, .blocklyZoom>svg>image {","opacity: .4;","}",".blocklyZoom>image:hover, .blocklyZoom>svg>image:hover {","opacity: .6;","}",".blocklyZoom>image:active, .blocklyZoom>svg>image:active {","opacity: .8;","}"]),t.Mutator=function(e){t.Mutator.superClass_.constructor.call(this,null),this.quarkNames_=e},t.utils.object.inherits(t.Mutator,t.Icon),t.Mutator.prototype.workspaceWidth_=0,t.Mutator.prototype.workspaceHeight_=0,t.Mutator.prototype.setBlock=function(t){this.block_=t},t.Mutator.prototype.getWorkspace=function(){return this.workspace_},t.Mutator.prototype.drawIcon_=function(e){t.utils.dom.createSvgElement("rect",{class:"blocklyIconShape",rx:"4",ry:"4",height:"16",width:"16"},e),t.utils.dom.createSvgElement("path",{class:"blocklyIconSymbol",d:"m4.203,7.296 0,1.368 -0.92,0.677 -0.11,0.41 0.9,1.559 0.41,0.11 1.043,-0.457 1.187,0.683 0.127,1.134 0.3,0.3 1.8,0 0.3,-0.299 0.127,-1.138 1.185,-0.682 1.046,0.458 0.409,-0.11 0.9,-1.559 -0.11,-0.41 -0.92,-0.677 0,-1.366 0.92,-0.677 0.11,-0.41 -0.9,-1.559 -0.409,-0.109 -1.046,0.458 -1.185,-0.682 -0.127,-1.138 -0.3,-0.299 -1.8,0 -0.3,0.3 -0.126,1.135 -1.187,0.682 -1.043,-0.457 -0.41,0.11 -0.899,1.559 0.108,0.409z"},e),t.utils.dom.createSvgElement("circle",{class:"blocklyIconShape",r:"2.7",cx:"8",cy:"8"},e)},t.Mutator.prototype.iconClick_=function(e){this.block_.isEditable()&&t.Icon.prototype.iconClick_.call(this,e)},t.Mutator.prototype.createEditor_=function(){if(this.svgDialog_=t.utils.dom.createSvgElement("svg",{x:t.Bubble.BORDER_WIDTH,y:t.Bubble.BORDER_WIDTH},null),this.quarkNames_.length)for(var e,o=t.utils.xml.createElement("xml"),i=0;e=this.quarkNames_[i];i++){var n=t.utils.xml.createElement("block");n.setAttribute("type",e),o.appendChild(n)}else o=null;return(i=new t.Options({disable:!1,parentWorkspace:this.block_.workspace,media:this.block_.workspace.options.pathToMedia,rtl:this.block_.RTL,horizontalLayout:!1,renderer:this.block_.workspace.options.renderer,rendererOverrides:this.block_.workspace.options.rendererOverrides})).toolboxPosition=this.block_.RTL?t.TOOLBOX_AT_RIGHT:t.TOOLBOX_AT_LEFT,i.languageTree=o,i.getMetrics=this.getFlyoutMetrics_.bind(this),this.workspace_=new t.WorkspaceSvg(i),this.workspace_.isMutator=!0,this.workspace_.addChangeListener(t.Events.disableOrphans),o=this.workspace_.addFlyout("g"),(i=this.workspace_.createDom("blocklyMutatorBackground")).insertBefore(o,this.workspace_.svgBlockCanvas_),this.svgDialog_.appendChild(i),this.svgDialog_},t.Mutator.prototype.updateEditable=function(){t.Mutator.superClass_.updateEditable.call(this),this.block_.isInFlyout||(this.block_.isEditable()?this.iconGroup_&&t.utils.dom.removeClass(this.iconGroup_,"blocklyIconGroupReadonly"):(this.setVisible(!1),this.iconGroup_&&t.utils.dom.addClass(this.iconGroup_,"blocklyIconGroupReadonly")))},t.Mutator.prototype.resizeBubble_=function(){var e=2*t.Bubble.BORDER_WIDTH,o=this.workspace_.getCanvas().getBBox(),i=this.block_.RTL?-o.x:o.width+o.x;o=o.height+3*e;var n=this.workspace_.getFlyout();n&&(n=n.getMetrics_(),o=Math.max(o,n.contentHeight+20)),i+=3*e,(Math.abs(this.workspaceWidth_-i)>e||Math.abs(this.workspaceHeight_-o)>e)&&(this.workspaceWidth_=i,this.workspaceHeight_=o,this.bubble_.setBubbleSize(i+e,o+e),this.svgDialog_.setAttribute("width",this.workspaceWidth_),this.svgDialog_.setAttribute("height",this.workspaceHeight_)),this.block_.RTL&&(e="translate("+this.workspaceWidth_+",0)",this.workspace_.getCanvas().setAttribute("transform",e)),this.workspace_.resize()},t.Mutator.prototype.onBubbleMove_=function(){this.workspace_&&this.workspace_.recordDeleteAreas()},t.Mutator.prototype.setVisible=function(e){if(e!=this.isVisible())if(t.Events.fire(new t.Events.Ui(this.block_,"mutatorOpen",!e,e)),e){this.bubble_=new t.Bubble(this.block_.workspace,this.createEditor_(),this.block_.pathObject.svgPath,this.iconXY_,null,null),this.bubble_.setSvgId(this.block_.id),this.bubble_.registerMoveEvent(this.onBubbleMove_.bind(this));var o=this.workspace_.options.languageTree;e=this.workspace_.getFlyout(),o&&(e.init(this.workspace_),e.show(o.childNodes)),this.rootBlock_=this.block_.decompose(this.workspace_),o=this.rootBlock_.getDescendants(!1);for(var i,n=0;i=o[n];n++)i.render();if(this.rootBlock_.setMovable(!1),this.rootBlock_.setDeletable(!1),e?(o=2*e.CORNER_RADIUS,e=e.getWidth()+o):e=o=16,this.block_.RTL&&(e=-e),this.rootBlock_.moveBy(e,o),this.block_.saveConnections){var s=this,r=this.block_;r.saveConnections(this.rootBlock_),this.sourceListener_=function(){r.saveConnections(s.rootBlock_)},this.block_.workspace.addChangeListener(this.sourceListener_)}this.resizeBubble_(),this.workspace_.addChangeListener(this.workspaceChanged_.bind(this)),this.applyColour()}else this.svgDialog_=null,this.workspace_.dispose(),this.rootBlock_=this.workspace_=null,this.bubble_.dispose(),this.bubble_=null,this.workspaceHeight_=this.workspaceWidth_=0,this.sourceListener_&&(this.block_.workspace.removeChangeListener(this.sourceListener_),this.sourceListener_=null)},t.Mutator.prototype.workspaceChanged_=function(e){if(e.type!=t.Events.UI&&(e.type!=t.Events.CHANGE||"disabled"!=e.element)){if(!this.workspace_.isDragging()){e=this.workspace_.getTopBlocks(!1);for(var o,i=0;o=e[i];i++){var n=o.getRelativeToSurfaceXY(),s=o.getHeightWidth();20>n.y+s.height&&o.moveBy(0,20-s.height-n.y)}}if(this.rootBlock_.workspace==this.workspace_){if(t.Events.setGroup(!0),e=(e=(o=this.block_).mutationToDom())&&t.Xml.domToText(e),o.compose(this.rootBlock_),o.initSvg(),o.render(),t.getMainWorkspace().keyboardAccessibilityMode&&t.navigation.moveCursorOnBlockMutation(o),e!=(i=(i=o.mutationToDom())&&t.Xml.domToText(i))){t.Events.fire(new t.Events.BlockChange(o,"mutation",null,e,i));var r=t.Events.getGroup();setTimeout((function(){t.Events.setGroup(r),o.bumpNeighbours(),t.Events.setGroup(!1)}),t.BUMP_DELAY)}this.workspace_.isDragging()||this.resizeBubble_(),t.Events.setGroup(!1)}}},t.Mutator.prototype.getFlyoutMetrics_=function(){return{viewHeight:this.workspaceHeight_,viewWidth:this.workspaceWidth_-this.workspace_.getFlyout().getWidth(),absoluteTop:0,absoluteLeft:this.workspace_.RTL?0:this.workspace_.getFlyout().getWidth()}},t.Mutator.prototype.dispose=function(){this.block_.mutator=null,t.Icon.prototype.dispose.call(this)},t.Mutator.prototype.updateBlockStyle=function(){var t=this.workspace_;if(t&&t.getAllBlocks(!1)){for(var e=t.getAllBlocks(!1),o=0;o=e&&this.sourceBlock_.outputConnection&&!o}else this.fullBlockClickTarget_=!1;this.fullBlockClickTarget_?this.clickTarget_=this.sourceBlock_.getSvgRoot():this.createBorderRect_(),this.createTextElement_()},t.FieldTextInput.prototype.doClassValidation_=function(t){return null==t?null:String(t)},t.FieldTextInput.prototype.doValueInvalid_=function(e){this.isBeingEdited_&&(this.isTextValid_=!1,e=this.value_,this.value_=this.htmlInput_.untypedDefaultValue_,this.sourceBlock_&&t.Events.isEnabled()&&t.Events.fire(new t.Events.BlockChange(this.sourceBlock_,"field",this.name||null,e,this.value_)))},t.FieldTextInput.prototype.doValueUpdate_=function(t){this.isTextValid_=!0,this.value_=t,this.isBeingEdited_||(this.isDirty_=!0)},t.FieldTextInput.prototype.applyColour=function(){this.sourceBlock_&&this.getConstants().FULL_BLOCK_FIELDS&&(this.borderRect_?this.borderRect_.setAttribute("stroke",this.sourceBlock_.style.colourTertiary):this.sourceBlock_.pathObject.svgPath.setAttribute("fill",this.getConstants().FIELD_BORDER_RECT_COLOUR))},t.FieldTextInput.prototype.render_=function(){if(t.FieldTextInput.superClass_.render_.call(this),this.isBeingEdited_){this.resizeEditor_();var e=this.htmlInput_;this.isTextValid_?(t.utils.dom.removeClass(e,"blocklyInvalidInput"),t.utils.aria.setState(e,t.utils.aria.State.INVALID,!1)):(t.utils.dom.addClass(e,"blocklyInvalidInput"),t.utils.aria.setState(e,t.utils.aria.State.INVALID,!0))}},t.FieldTextInput.prototype.setSpellcheck=function(t){t!=this.spellcheck_&&(this.spellcheck_=t,this.htmlInput_&&this.htmlInput_.setAttribute("spellcheck",this.spellcheck_))},t.FieldTextInput.prototype.showEditor_=function(e,o){this.workspace_=this.sourceBlock_.workspace,!(e=o||!1)&&(t.utils.userAgent.MOBILE||t.utils.userAgent.ANDROID||t.utils.userAgent.IPAD)?this.showPromptEditor_():this.showInlineEditor_(e)},t.FieldTextInput.prototype.showPromptEditor_=function(){var e=this;t.prompt(t.Msg.CHANGE_VALUE_TITLE,this.getText(),(function(t){e.setValue(t)}))},t.FieldTextInput.prototype.showInlineEditor_=function(e){t.WidgetDiv.show(this,this.sourceBlock_.RTL,this.widgetDispose_.bind(this)),this.htmlInput_=this.widgetCreate_(),this.isBeingEdited_=!0,e||(this.htmlInput_.focus({preventScroll:!0}),this.htmlInput_.select())},t.FieldTextInput.prototype.widgetCreate_=function(){var e=t.WidgetDiv.DIV;t.utils.dom.addClass(this.getClickTarget_(),"editing");var o=document.createElement("input");o.className="blocklyHtmlInput",o.setAttribute("spellcheck",this.spellcheck_);var i=this.workspace_.getScale(),n=this.getConstants().FIELD_TEXT_FONTSIZE*i+"pt";if(e.style.fontSize=n,o.style.fontSize=n,n=t.FieldTextInput.BORDERRADIUS*i+"px",this.fullBlockClickTarget_){n=((n=this.getScaledBBox()).bottom-n.top)/2+"px";var s=this.sourceBlock_.getParent()?this.sourceBlock_.getParent().style.colourTertiary:this.sourceBlock_.style.colourTertiary;o.style.border=1*i+"px solid "+s,e.style.borderRadius=n,e.style.transition="box-shadow 0.25s ease 0s",this.getConstants().FIELD_TEXTINPUT_BOX_SHADOW&&(e.style.boxShadow="rgba(255, 255, 255, 0.3) 0px 0px 0px "+4*i+"px")}return o.style.borderRadius=n,e.appendChild(o),o.value=o.defaultValue=this.getEditorText_(this.value_),o.untypedDefaultValue_=this.value_,o.oldValue_=null,this.resizeEditor_(),this.bindInputEvents_(o),o},t.FieldTextInput.prototype.widgetDispose_=function(){this.isBeingEdited_=!1,this.isTextValid_=!0,this.forceRerender(),this.onFinishEditing_&&this.onFinishEditing_(this.value_),this.unbindInputEvents_();var e=t.WidgetDiv.DIV.style;e.width="auto",e.height="auto",e.fontSize="",e.transition="",e.boxShadow="",this.htmlInput_=null,t.utils.dom.removeClass(this.getClickTarget_(),"editing")},t.FieldTextInput.prototype.bindInputEvents_=function(e){this.onKeyDownWrapper_=t.bindEventWithChecks_(e,"keydown",this,this.onHtmlInputKeyDown_),this.onKeyInputWrapper_=t.bindEventWithChecks_(e,"input",this,this.onHtmlInputChange_)},t.FieldTextInput.prototype.unbindInputEvents_=function(){this.onKeyDownWrapper_&&(t.unbindEvent_(this.onKeyDownWrapper_),this.onKeyDownWrapper_=null),this.onKeyInputWrapper_&&(t.unbindEvent_(this.onKeyInputWrapper_),this.onKeyInputWrapper_=null)},t.FieldTextInput.prototype.onHtmlInputKeyDown_=function(e){e.keyCode==t.utils.KeyCodes.ENTER?(t.WidgetDiv.hide(),t.DropDownDiv.hideWithoutAnimation()):e.keyCode==t.utils.KeyCodes.ESC?(this.htmlInput_.value=this.htmlInput_.defaultValue,t.WidgetDiv.hide(),t.DropDownDiv.hideWithoutAnimation()):e.keyCode==t.utils.KeyCodes.TAB&&(t.WidgetDiv.hide(),t.DropDownDiv.hideWithoutAnimation(),this.sourceBlock_.tab(this,!e.shiftKey),e.preventDefault())},t.FieldTextInput.prototype.onHtmlInputChange_=function(e){(e=this.htmlInput_.value)!==this.htmlInput_.oldValue_&&(this.htmlInput_.oldValue_=e,t.Events.setGroup(!0),e=this.getValueFromEditorText_(e),this.setValue(e),this.forceRerender(),this.resizeEditor_(),t.Events.setGroup(!1))},t.FieldTextInput.prototype.setEditorValue_=function(t){this.isDirty_=!0,this.isBeingEdited_&&(this.htmlInput_.value=this.getEditorText_(t)),this.setValue(t)},t.FieldTextInput.prototype.resizeEditor_=function(){var e=t.WidgetDiv.DIV,o=this.getScaledBBox();e.style.width=o.right-o.left+"px",e.style.height=o.bottom-o.top+"px",o=new t.utils.Coordinate(this.sourceBlock_.RTL?o.right-e.offsetWidth:o.left,o.top),e.style.left=o.x+"px",e.style.top=o.y+"px"},t.FieldTextInput.numberValidator=function(t){return console.warn("Blockly.FieldTextInput.numberValidator is deprecated. Use Blockly.FieldNumber instead."),null===t?null:(t=(t=(t=String(t)).replace(/O/gi,"0")).replace(/,/g,""),t=Number(t||0),isNaN(t)?null:String(t))},t.FieldTextInput.nonnegativeIntegerValidator=function(e){return(e=t.FieldTextInput.numberValidator(e))&&(e=String(Math.max(0,Math.floor(e)))),e},t.FieldTextInput.prototype.isTabNavigable=function(){return!0},t.FieldTextInput.prototype.getText_=function(){return this.isBeingEdited_&&this.htmlInput_?this.htmlInput_.value:null},t.FieldTextInput.prototype.getEditorText_=function(t){return String(t)},t.FieldTextInput.prototype.getValueFromEditorText_=function(t){return t},t.fieldRegistry.register("field_input",t.FieldTextInput),t.FieldAngle=function(e,o,i){this.clockwise_=t.FieldAngle.CLOCKWISE,this.offset_=t.FieldAngle.OFFSET,this.wrap_=t.FieldAngle.WRAP,this.round_=t.FieldAngle.ROUND,t.FieldAngle.superClass_.constructor.call(this,e||0,o,i),this.moveSurfaceWrapper_=this.clickSurfaceWrapper_=this.clickWrapper_=this.line_=this.gauge_=null},t.utils.object.inherits(t.FieldAngle,t.FieldTextInput),t.FieldAngle.fromJson=function(e){return new t.FieldAngle(e.angle,void 0,e)},t.FieldAngle.prototype.SERIALIZABLE=!0,t.FieldAngle.ROUND=15,t.FieldAngle.HALF=50,t.FieldAngle.CLOCKWISE=!1,t.FieldAngle.OFFSET=0,t.FieldAngle.WRAP=360,t.FieldAngle.RADIUS=t.FieldAngle.HALF-1,t.FieldAngle.prototype.configure_=function(e){switch(t.FieldAngle.superClass_.configure_.call(this,e),e.mode){case"compass":this.clockwise_=!0,this.offset_=90;break;case"protractor":this.clockwise_=!1,this.offset_=0}var o=e.clockwise;"boolean"==typeof o&&(this.clockwise_=o),null!=(o=e.offset)&&(o=Number(o),isNaN(o)||(this.offset_=o)),null!=(o=e.wrap)&&(o=Number(o),isNaN(o)||(this.wrap_=o)),null!=(e=e.round)&&(e=Number(e),isNaN(e)||(this.round_=e))},t.FieldAngle.prototype.initView=function(){t.FieldAngle.superClass_.initView.call(this),this.symbol_=t.utils.dom.createSvgElement("tspan",{},null),this.symbol_.appendChild(document.createTextNode("°")),this.textElement_.appendChild(this.symbol_)},t.FieldAngle.prototype.render_=function(){t.FieldAngle.superClass_.render_.call(this),this.updateGraph_()},t.FieldAngle.prototype.showEditor_=function(e){t.FieldAngle.superClass_.showEditor_.call(this,e,t.utils.userAgent.MOBILE||t.utils.userAgent.ANDROID||t.utils.userAgent.IPAD),e=this.dropdownCreate_(),t.DropDownDiv.getContentDiv().appendChild(e),t.DropDownDiv.setColour(this.sourceBlock_.style.colourPrimary,this.sourceBlock_.style.colourTertiary),t.DropDownDiv.showPositionedByField(this,this.dropdownDispose_.bind(this)),this.updateGraph_()},t.FieldAngle.prototype.dropdownCreate_=function(){var e=t.utils.dom.createSvgElement("svg",{xmlns:t.utils.dom.SVG_NS,"xmlns:html":t.utils.dom.HTML_NS,"xmlns:xlink":t.utils.dom.XLINK_NS,version:"1.1",height:2*t.FieldAngle.HALF+"px",width:2*t.FieldAngle.HALF+"px",style:"touch-action: none"},null),o=t.utils.dom.createSvgElement("circle",{cx:t.FieldAngle.HALF,cy:t.FieldAngle.HALF,r:t.FieldAngle.RADIUS,class:"blocklyAngleCircle"},e);this.gauge_=t.utils.dom.createSvgElement("path",{class:"blocklyAngleGauge"},e),this.line_=t.utils.dom.createSvgElement("line",{x1:t.FieldAngle.HALF,y1:t.FieldAngle.HALF,class:"blocklyAngleLine"},e);for(var i=0;360>i;i+=15)t.utils.dom.createSvgElement("line",{x1:t.FieldAngle.HALF+t.FieldAngle.RADIUS,y1:t.FieldAngle.HALF,x2:t.FieldAngle.HALF+t.FieldAngle.RADIUS-(0==i%45?10:5),y2:t.FieldAngle.HALF,class:"blocklyAngleMarks",transform:"rotate("+i+","+t.FieldAngle.HALF+","+t.FieldAngle.HALF+")"},e);return this.clickWrapper_=t.bindEventWithChecks_(e,"click",this,this.hide_),this.clickSurfaceWrapper_=t.bindEventWithChecks_(o,"click",this,this.onMouseMove_,!0,!0),this.moveSurfaceWrapper_=t.bindEventWithChecks_(o,"mousemove",this,this.onMouseMove_,!0,!0),e},t.FieldAngle.prototype.dropdownDispose_=function(){this.clickWrapper_&&(t.unbindEvent_(this.clickWrapper_),this.clickWrapper_=null),this.clickSurfaceWrapper_&&(t.unbindEvent_(this.clickSurfaceWrapper_),this.clickSurfaceWrapper_=null),this.moveSurfaceWrapper_&&(t.unbindEvent_(this.moveSurfaceWrapper_),this.moveSurfaceWrapper_=null),this.line_=this.gauge_=null},t.FieldAngle.prototype.hide_=function(){t.DropDownDiv.hideIfOwner(this),t.WidgetDiv.hide()},t.FieldAngle.prototype.onMouseMove_=function(e){var o=this.gauge_.ownerSVGElement.getBoundingClientRect(),i=e.clientX-o.left-t.FieldAngle.HALF;e=e.clientY-o.top-t.FieldAngle.HALF,o=Math.atan(-e/i),isNaN(o)||(o=t.utils.math.toDegrees(o),0>i?o+=180:0(t%=360)&&(t+=360),t>this.wrap_&&(t-=360),t},t.Css.register(".blocklyAngleCircle {,stroke: #444;,stroke-width: 1;,fill: #ddd;,fill-opacity: .8;,},.blocklyAngleMarks {,stroke: #444;,stroke-width: 1;,},.blocklyAngleGauge {,fill: #f88;,fill-opacity: .8;,pointer-events: none;,},.blocklyAngleLine {,stroke: #f00;,stroke-width: 2;,stroke-linecap: round;,pointer-events: none;,}".split(",")),t.fieldRegistry.register("field_angle",t.FieldAngle),t.FieldCheckbox=function(e,o,i){this.checkChar_=null,null==e&&(e="FALSE"),t.FieldCheckbox.superClass_.constructor.call(this,e,o,i)},t.utils.object.inherits(t.FieldCheckbox,t.Field),t.FieldCheckbox.fromJson=function(e){return new t.FieldCheckbox(e.checked,void 0,e)},t.FieldCheckbox.CHECK_CHAR="✓",t.FieldCheckbox.prototype.SERIALIZABLE=!0,t.FieldCheckbox.prototype.CURSOR="default",t.FieldCheckbox.prototype.configure_=function(e){t.FieldCheckbox.superClass_.configure_.call(this,e),e.checkCharacter&&(this.checkChar_=e.checkCharacter)},t.FieldCheckbox.prototype.initView=function(){t.FieldCheckbox.superClass_.initView.call(this),t.utils.dom.addClass(this.textElement_,"blocklyCheckbox"),this.textElement_.style.display=this.value_?"block":"none"},t.FieldCheckbox.prototype.render_=function(){this.textContent_&&(this.textContent_.nodeValue=this.getDisplayText_()),this.updateSize_(this.getConstants().FIELD_CHECKBOX_X_OFFSET)},t.FieldCheckbox.prototype.getDisplayText_=function(){return this.checkChar_||t.FieldCheckbox.CHECK_CHAR},t.FieldCheckbox.prototype.setCheckCharacter=function(t){this.checkChar_=t,this.forceRerender()},t.FieldCheckbox.prototype.showEditor_=function(){this.setValue(!this.value_)},t.FieldCheckbox.prototype.doClassValidation_=function(t){return!0===t||"TRUE"===t?"TRUE":!1===t||"FALSE"===t?"FALSE":null},t.FieldCheckbox.prototype.doValueUpdate_=function(t){this.value_=this.convertValueToBool_(t),this.textElement_&&(this.textElement_.style.display=this.value_?"block":"none")},t.FieldCheckbox.prototype.getValue=function(){return this.value_?"TRUE":"FALSE"},t.FieldCheckbox.prototype.getValueBoolean=function(){return this.value_},t.FieldCheckbox.prototype.getText=function(){return String(this.convertValueToBool_(this.value_))},t.FieldCheckbox.prototype.convertValueToBool_=function(t){return"string"==typeof t?"TRUE"==t:!!t},t.fieldRegistry.register("field_checkbox",t.FieldCheckbox),t.FieldColour=function(e,o,i){t.FieldColour.superClass_.constructor.call(this,e||t.FieldColour.COLOURS[0],o,i),this.onKeyDownWrapper_=this.onMouseLeaveWrapper_=this.onMouseEnterWrapper_=this.onMouseMoveWrapper_=this.onClickWrapper_=this.highlightedIndex_=this.picker_=null},t.utils.object.inherits(t.FieldColour,t.Field),t.FieldColour.fromJson=function(e){return new t.FieldColour(e.colour,void 0,e)},t.FieldColour.prototype.SERIALIZABLE=!0,t.FieldColour.prototype.CURSOR="default",t.FieldColour.prototype.isDirty_=!1,t.FieldColour.prototype.colours_=null,t.FieldColour.prototype.titles_=null,t.FieldColour.prototype.columns_=0,t.FieldColour.prototype.configure_=function(e){t.FieldColour.superClass_.configure_.call(this,e),e.colourOptions&&(this.colours_=e.colourOptions,this.titles_=e.colourTitles),e.columns&&(this.columns_=e.columns)},t.FieldColour.prototype.initView=function(){this.size_=new t.utils.Size(this.getConstants().FIELD_COLOUR_DEFAULT_WIDTH,this.getConstants().FIELD_COLOUR_DEFAULT_HEIGHT),this.getConstants().FIELD_COLOUR_FULL_BLOCK?this.clickTarget_=this.sourceBlock_.getSvgRoot():(this.createBorderRect_(),this.borderRect_.style.fillOpacity="1")},t.FieldColour.prototype.applyColour=function(){this.getConstants().FIELD_COLOUR_FULL_BLOCK?(this.sourceBlock_.pathObject.svgPath.setAttribute("fill",this.getValue()),this.sourceBlock_.pathObject.svgPath.setAttribute("stroke","#fff")):this.borderRect_&&(this.borderRect_.style.fill=this.getValue())},t.FieldColour.prototype.doClassValidation_=function(e){return"string"!=typeof e?null:t.utils.colour.parse(e)},t.FieldColour.prototype.doValueUpdate_=function(t){this.value_=t,this.borderRect_?this.borderRect_.style.fill=t:this.sourceBlock_&&this.sourceBlock_.rendered&&(this.sourceBlock_.pathObject.svgPath.setAttribute("fill",t),this.sourceBlock_.pathObject.svgPath.setAttribute("stroke","#fff"))},t.FieldColour.prototype.getText=function(){var t=this.value_;return/^#(.)\1(.)\2(.)\3$/.test(t)&&(t="#"+t[1]+t[3]+t[5]),t},t.FieldColour.COLOURS="#ffffff #cccccc #c0c0c0 #999999 #666666 #333333 #000000 #ffcccc #ff6666 #ff0000 #cc0000 #990000 #660000 #330000 #ffcc99 #ff9966 #ff9900 #ff6600 #cc6600 #993300 #663300 #ffff99 #ffff66 #ffcc66 #ffcc33 #cc9933 #996633 #663333 #ffffcc #ffff33 #ffff00 #ffcc00 #999900 #666600 #333300 #99ff99 #66ff99 #33ff33 #33cc00 #009900 #006600 #003300 #99ffff #33ffff #66cccc #00cccc #339999 #336666 #003333 #ccffff #66ffff #33ccff #3366ff #3333ff #000099 #000066 #ccccff #9999ff #6666cc #6633ff #6600cc #333399 #330099 #ffccff #ff99ff #cc66cc #cc33cc #993399 #663366 #330033".split(" "),t.FieldColour.TITLES=[],t.FieldColour.COLUMNS=7,t.FieldColour.prototype.setColours=function(t,e){return this.colours_=t,e&&(this.titles_=e),this},t.FieldColour.prototype.setColumns=function(t){return this.columns_=t,this},t.FieldColour.prototype.showEditor_=function(){this.picker_=this.dropdownCreate_(),t.DropDownDiv.getContentDiv().appendChild(this.picker_),t.DropDownDiv.showPositionedByField(this,this.dropdownDispose_.bind(this)),this.picker_.focus({preventScroll:!0})},t.FieldColour.prototype.onClick_=function(e){null!==(e=(e=e.target)&&e.label)&&(this.setValue(e),t.DropDownDiv.hideIfOwner(this))},t.FieldColour.prototype.onKeyDown_=function(e){var o=!1;e.keyCode===t.utils.KeyCodes.UP?(this.moveHighlightBy_(0,-1),o=!0):e.keyCode===t.utils.KeyCodes.DOWN?(this.moveHighlightBy_(0,1),o=!0):e.keyCode===t.utils.KeyCodes.LEFT?(this.moveHighlightBy_(-1,0),o=!0):e.keyCode===t.utils.KeyCodes.RIGHT?(this.moveHighlightBy_(1,0),o=!0):e.keyCode===t.utils.KeyCodes.ENTER&&((o=this.getHighlighted_())&&null!==(o=o&&o.label)&&this.setValue(o),t.DropDownDiv.hideWithoutAnimation(),o=!0),o&&e.stopPropagation()},t.FieldColour.prototype.onBlocklyAction=function(e){if(this.picker_){if(e===t.navigation.ACTION_PREVIOUS)return this.moveHighlightBy_(0,-1),!0;if(e===t.navigation.ACTION_NEXT)return this.moveHighlightBy_(0,1),!0;if(e===t.navigation.ACTION_OUT)return this.moveHighlightBy_(-1,0),!0;if(e===t.navigation.ACTION_IN)return this.moveHighlightBy_(1,0),!0}return t.FieldColour.superClass_.onBlocklyAction.call(this,e)},t.FieldColour.prototype.moveHighlightBy_=function(e,o){var i=this.colours_||t.FieldColour.COLOURS,n=this.columns_||t.FieldColour.COLUMNS,s=this.highlightedIndex_%n,r=Math.floor(this.highlightedIndex_/n);s+=e,r+=o,0>e?0>s&&0s&&(s=0):0n-1&&rn-1&&s--:0>o?0>r&&(r=0):0Math.floor(i.length/n)-1&&(r=Math.floor(i.length/n)-1),this.setHighlightedCell_(this.picker_.childNodes[r].childNodes[s],r*n+s)},t.FieldColour.prototype.onMouseMove_=function(t){var e=(t=t.target)&&Number(t.getAttribute("data-index"));null!==e&&e!==this.highlightedIndex_&&this.setHighlightedCell_(t,e)},t.FieldColour.prototype.onMouseEnter_=function(){this.picker_.focus({preventScroll:!0})},t.FieldColour.prototype.onMouseLeave_=function(){this.picker_.blur();var e=this.getHighlighted_();e&&t.utils.dom.removeClass(e,"blocklyColourHighlighted")},t.FieldColour.prototype.getHighlighted_=function(){var e=this.columns_||t.FieldColour.COLUMNS,o=this.picker_.childNodes[Math.floor(this.highlightedIndex_/e)];return o?o.childNodes[this.highlightedIndex_%e]:null},t.FieldColour.prototype.setHighlightedCell_=function(e,o){var i=this.getHighlighted_();i&&t.utils.dom.removeClass(i,"blocklyColourHighlighted"),t.utils.dom.addClass(e,"blocklyColourHighlighted"),this.highlightedIndex_=o,t.utils.aria.setState(this.picker_,t.utils.aria.State.ACTIVEDESCENDANT,e.getAttribute("id"))},t.FieldColour.prototype.dropdownCreate_=function(){var e=this.columns_||t.FieldColour.COLUMNS,o=this.colours_||t.FieldColour.COLOURS,i=this.titles_||t.FieldColour.TITLES,n=this.getValue(),s=document.createElement("table");s.className="blocklyColourTable",s.tabIndex=0,s.dir="ltr",t.utils.aria.setRole(s,t.utils.aria.Role.GRID),t.utils.aria.setState(s,t.utils.aria.State.EXPANDED,!0),t.utils.aria.setState(s,t.utils.aria.State.ROWCOUNT,Math.floor(o.length/e)),t.utils.aria.setState(s,t.utils.aria.State.COLCOUNT,e);for(var r,a=0;atr>td {","border: .5px solid #888;","box-sizing: border-box;","cursor: pointer;","display: inline-block;","height: 20px;","padding: 0;","width: 20px;","}",".blocklyColourTable>tr>td.blocklyColourHighlighted {","border-color: #eee;","box-shadow: 2px 2px 7px 2px rgba(0,0,0,.3);","position: relative;","}",".blocklyColourSelected, .blocklyColourSelected:hover {","border-color: #eee !important;","outline: 1px solid #333;","position: relative;","}"]),t.fieldRegistry.register("field_colour",t.FieldColour),t.FieldDropdown=function(e,o,i){"function"!=typeof e&&t.FieldDropdown.validateOptions_(e),this.menuGenerator_=e,this.generatedOptions_=null,this.trimOptions_(),this.selectedOption_=this.getOptions(!1)[0],t.FieldDropdown.superClass_.constructor.call(this,this.selectedOption_[1],o,i),this.svgArrow_=this.arrow_=this.imageElement_=this.menu_=this.selectedMenuItem_=null},t.utils.object.inherits(t.FieldDropdown,t.Field),t.FieldDropdown.fromJson=function(e){return new t.FieldDropdown(e.options,void 0,e)},t.FieldDropdown.prototype.SERIALIZABLE=!0,t.FieldDropdown.CHECKMARK_OVERHANG=25,t.FieldDropdown.MAX_MENU_HEIGHT_VH=.45,t.FieldDropdown.IMAGE_Y_OFFSET=5,t.FieldDropdown.IMAGE_Y_PADDING=2*t.FieldDropdown.IMAGE_Y_OFFSET,t.FieldDropdown.ARROW_CHAR=t.utils.userAgent.ANDROID?"▼":"▾",t.FieldDropdown.prototype.CURSOR="default",t.FieldDropdown.prototype.initView=function(){this.shouldAddBorderRect_()?this.createBorderRect_():this.clickTarget_=this.sourceBlock_.getSvgRoot(),this.createTextElement_(),this.imageElement_=t.utils.dom.createSvgElement("image",{},this.fieldGroup_),this.getConstants().FIELD_DROPDOWN_SVG_ARROW?this.createSVGArrow_():this.createTextArrow_(),this.borderRect_&&t.utils.dom.addClass(this.borderRect_,"blocklyDropdownRect")},t.FieldDropdown.prototype.shouldAddBorderRect_=function(){return!this.getConstants().FIELD_DROPDOWN_NO_BORDER_RECT_SHADOW||this.getConstants().FIELD_DROPDOWN_NO_BORDER_RECT_SHADOW&&!this.sourceBlock_.isShadow()},t.FieldDropdown.prototype.createTextArrow_=function(){this.arrow_=t.utils.dom.createSvgElement("tspan",{},this.textElement_),this.arrow_.appendChild(document.createTextNode(this.sourceBlock_.RTL?t.FieldDropdown.ARROW_CHAR+" ":" "+t.FieldDropdown.ARROW_CHAR)),this.sourceBlock_.RTL?this.textElement_.insertBefore(this.arrow_,this.textContent_):this.textElement_.appendChild(this.arrow_)},t.FieldDropdown.prototype.createSVGArrow_=function(){this.svgArrow_=t.utils.dom.createSvgElement("image",{height:this.getConstants().FIELD_DROPDOWN_SVG_ARROW_SIZE+"px",width:this.getConstants().FIELD_DROPDOWN_SVG_ARROW_SIZE+"px"},this.fieldGroup_),this.svgArrow_.setAttributeNS(t.utils.dom.XLINK_NS,"xlink:href",this.getConstants().FIELD_DROPDOWN_SVG_ARROW_DATAURI)},t.FieldDropdown.prototype.showEditor_=function(e){if(this.menu_=this.dropdownCreate_(),this.menu_.openingCoords=e&&"number"==typeof e.clientX?new t.utils.Coordinate(e.clientX,e.clientY):null,this.menu_.render(t.DropDownDiv.getContentDiv()),t.utils.dom.addClass(this.menu_.getElement(),"blocklyDropdownMenu"),this.getConstants().FIELD_DROPDOWN_COLOURED_DIV){e=this.sourceBlock_.isShadow()?this.sourceBlock_.getParent().getColour():this.sourceBlock_.getColour();var o=this.sourceBlock_.isShadow()?this.sourceBlock_.getParent().style.colourTertiary:this.sourceBlock_.style.colourTertiary;t.DropDownDiv.setColour(e,o)}t.DropDownDiv.showPositionedByField(this,this.dropdownDispose_.bind(this)),this.menu_.focus(),this.selectedMenuItem_&&t.utils.style.scrollIntoContainerView(this.selectedMenuItem_.getElement(),this.menu_.getElement()),this.applyColour()},t.FieldDropdown.prototype.dropdownCreate_=function(){var e=new t.Menu;e.setRightToLeft(this.sourceBlock_.RTL),e.setRole(t.utils.aria.Role.LISTBOX);var o=this.getOptions(!1);this.selectedMenuItem_=null;for(var i=0;ie.length)){for(o=[],i=0;i=i||0>=o)throw Error("Height and width values of an image field must be greater than 0.");this.flipRtl_=!1,this.altText_="",t.FieldImage.superClass_.constructor.call(this,e||"",null,a),a||(this.flipRtl_=!!r,this.altText_=t.utils.replaceMessageReferences(n)||""),this.size_=new t.utils.Size(o,i+t.FieldImage.Y_PADDING),this.imageHeight_=i,this.clickHandler_=null,"function"==typeof s&&(this.clickHandler_=s),this.imageElement_=null},t.utils.object.inherits(t.FieldImage,t.Field),t.FieldImage.fromJson=function(e){return new t.FieldImage(e.src,e.width,e.height,void 0,void 0,void 0,e)},t.FieldImage.Y_PADDING=1,t.FieldImage.prototype.EDITABLE=!1,t.FieldImage.prototype.isDirty_=!1,t.FieldImage.prototype.configure_=function(e){t.FieldImage.superClass_.configure_.call(this,e),this.flipRtl_=!!e.flipRtl,this.altText_=t.utils.replaceMessageReferences(e.alt)||""},t.FieldImage.prototype.initView=function(){this.imageElement_=t.utils.dom.createSvgElement("image",{height:this.imageHeight_+"px",width:this.size_.width+"px",alt:this.altText_},this.fieldGroup_),this.imageElement_.setAttributeNS(t.utils.dom.XLINK_NS,"xlink:href",this.value_),this.clickHandler_&&(this.imageElement_.style.cursor="pointer")},t.FieldImage.prototype.updateSize_=function(){},t.FieldImage.prototype.doClassValidation_=function(t){return"string"!=typeof t?null:t},t.FieldImage.prototype.doValueUpdate_=function(e){this.value_=e,this.imageElement_&&this.imageElement_.setAttributeNS(t.utils.dom.XLINK_NS,"xlink:href",String(this.value_))},t.FieldImage.prototype.getFlipRtl=function(){return this.flipRtl_},t.FieldImage.prototype.setAlt=function(t){t!=this.altText_&&(this.altText_=t||"",this.imageElement_&&this.imageElement_.setAttribute("alt",this.altText_))},t.FieldImage.prototype.showEditor_=function(){this.clickHandler_&&this.clickHandler_(this)},t.FieldImage.prototype.setOnClickHandler=function(t){this.clickHandler_=t},t.FieldImage.prototype.getText_=function(){return this.altText_},t.fieldRegistry.register("field_image",t.FieldImage),t.FieldMultilineInput=function(e,o,i){null==e&&(e=""),t.FieldMultilineInput.superClass_.constructor.call(this,e,o,i),this.textGroup_=null},t.utils.object.inherits(t.FieldMultilineInput,t.FieldTextInput),t.FieldMultilineInput.fromJson=function(e){var o=t.utils.replaceMessageReferences(e.text);return new t.FieldMultilineInput(o,void 0,e)},t.FieldMultilineInput.prototype.initView=function(){this.createBorderRect_(),this.textGroup_=t.utils.dom.createSvgElement("g",{class:"blocklyEditableText"},this.fieldGroup_)},t.FieldMultilineInput.prototype.getDisplayText_=function(){var e=this.value_;if(!e)return t.Field.NBSP;var o=e.split("\n");e="";for(var i=0;ithis.maxDisplayLength&&(n=n.substring(0,this.maxDisplayLength-4)+"..."),e+=n=n.replace(/\s/g,t.Field.NBSP),i!==o.length-1&&(e+="\n")}return this.sourceBlock_.RTL&&(e+="‏"),e},t.FieldMultilineInput.prototype.render_=function(){for(var e;e=this.textGroup_.firstChild;)this.textGroup_.removeChild(e);e=this.getDisplayText_().split("\n");for(var o=0,i=0;io&&(o=s),i+=this.getConstants().FIELD_TEXT_HEIGHT+(0this.max_&&t.utils.aria.setState(e,t.utils.aria.State.VALUEMAX,this.max_),e},t.fieldRegistry.register("field_number",t.FieldNumber),t.FieldVariable=function(e,o,i,n,s){this.menuGenerator_=t.FieldVariable.dropdownCreate,this.defaultVariableName=e||"",this.size_=new t.utils.Size(0,0),s&&this.configure_(s),o&&this.setValidator(o),s||this.setTypes_(i,n)},t.utils.object.inherits(t.FieldVariable,t.FieldDropdown),t.FieldVariable.fromJson=function(e){var o=t.utils.replaceMessageReferences(e.variable);return new t.FieldVariable(o,void 0,void 0,void 0,e)},t.FieldVariable.prototype.workspace_=null,t.FieldVariable.prototype.SERIALIZABLE=!0,t.FieldVariable.prototype.configure_=function(e){t.FieldVariable.superClass_.configure_.call(this,e),this.setTypes_(e.variableTypes,e.defaultType)},t.FieldVariable.prototype.initModel=function(){if(!this.variable_){var e=t.Variables.getOrCreateVariablePackage(this.sourceBlock_.workspace,null,this.defaultVariableName,this.defaultType_);this.doValueUpdate_(e.getId())}},t.FieldVariable.prototype.shouldAddBorderRect_=function(){return t.FieldVariable.superClass_.shouldAddBorderRect_.call(this)&&(!this.getConstants().FIELD_DROPDOWN_NO_BORDER_RECT_SHADOW||"variables_get"!=this.sourceBlock_.type)},t.FieldVariable.prototype.fromXml=function(e){var o=e.getAttribute("id"),i=e.textContent,n=e.getAttribute("variabletype")||e.getAttribute("variableType")||"";if(o=t.Variables.getOrCreateVariablePackage(this.sourceBlock_.workspace,o,i,n),null!=n&&n!==o.type)throw Error("Serialized variable type with id '"+o.getId()+"' had type "+o.type+", and does not match variable field that references it: "+t.Xml.domToText(e)+".");this.setValue(o.getId())},t.FieldVariable.prototype.toXml=function(t){return this.initModel(),t.id=this.variable_.getId(),t.textContent=this.variable_.name,this.variable_.type&&t.setAttribute("variabletype",this.variable_.type),t},t.FieldVariable.prototype.setSourceBlock=function(e){if(e.isShadow())throw Error("Variable fields are not allowed to exist on shadow blocks.");t.FieldVariable.superClass_.setSourceBlock.call(this,e)},t.FieldVariable.prototype.getValue=function(){return this.variable_?this.variable_.getId():null},t.FieldVariable.prototype.getText=function(){return this.variable_?this.variable_.name:""},t.FieldVariable.prototype.getVariable=function(){return this.variable_},t.FieldVariable.prototype.getValidator=function(){return this.variable_?this.validator_:null},t.FieldVariable.prototype.doClassValidation_=function(e){if(null===e)return null;var o=t.Variables.getVariable(this.sourceBlock_.workspace,e);return o?(o=o.type,this.typeIsAllowed_(o)?e:(console.warn("Variable type doesn't match this field! Type was "+o),null)):(console.warn("Variable id doesn't point to a real variable! ID was "+e),null)},t.FieldVariable.prototype.doValueUpdate_=function(e){this.variable_=t.Variables.getVariable(this.sourceBlock_.workspace,e),t.FieldVariable.superClass_.doValueUpdate_.call(this,e)},t.FieldVariable.prototype.typeIsAllowed_=function(t){var e=this.getVariableTypes_();if(!e)return!0;for(var o=0;orect,",t+" .blocklyEditableText>rect {","fill: "+this.FIELD_BORDER_RECT_COLOUR+";","fill-opacity: .6;","stroke: none;","}",t+" .blocklyNonEditableText>text,",t+" .blocklyEditableText>text {","fill: #000;","}",t+" .blocklyFlyoutLabelText {","fill: #000;","}",t+" .blocklyText.blocklyBubbleText {","fill: #000;","}",t+" .blocklyEditableText:not(.editing):hover>rect {","stroke: #fff;","stroke-width: 2;","}",t+" .blocklyHtmlInput {","font-family: "+this.FIELD_TEXT_FONTFAMILY+";","font-weight: "+this.FIELD_TEXT_FONTWEIGHT+";","}",t+" .blocklySelected>.blocklyPath {","stroke: #fc3;","stroke-width: 3px;","}",t+" .blocklyHighlightedConnectionPath {","stroke: #fc3;","}",t+" .blocklyReplaceable .blocklyPath {","fill-opacity: .5;","}",t+" .blocklyReplaceable .blocklyPathLight,",t+" .blocklyReplaceable .blocklyPathDark {","display: none;","}",t+" .blocklyInsertionMarker>.blocklyPath {","fill-opacity: "+this.INSERTION_MARKER_OPACITY+";","stroke: none","}"]},t.blockRendering.MarkerSvg=function(t,e,o){this.workspace_=t,this.marker_=o,this.parent_=null,this.constants_=e,this.currentMarkerSvg=null,t=this.isCursor()?this.constants_.CURSOR_COLOUR:this.constants_.MARKER_COLOUR,this.colour_=o.colour||t},t.blockRendering.MarkerSvg.CURSOR_CLASS="blocklyCursor",t.blockRendering.MarkerSvg.MARKER_CLASS="blocklyMarker",t.blockRendering.MarkerSvg.HEIGHT_MULTIPLIER=.75,t.blockRendering.MarkerSvg.prototype.getSvgRoot=function(){return this.svgGroup_},t.blockRendering.MarkerSvg.prototype.isCursor=function(){return"cursor"==this.marker_.type},t.blockRendering.MarkerSvg.prototype.createDom=function(){var e=this.isCursor()?t.blockRendering.MarkerSvg.CURSOR_CLASS:t.blockRendering.MarkerSvg.MARKER_CLASS;return this.svgGroup_=t.utils.dom.createSvgElement("g",{class:e},null),this.createDomInternal_(),this.applyColour_(),this.svgGroup_},t.blockRendering.MarkerSvg.prototype.setParent_=function(t){this.isCursor()?(this.parent_&&this.parent_.setCursorSvg(null),t.setCursorSvg(this.getSvgRoot())):(this.parent_&&this.parent_.setMarkerSvg(null),t.setMarkerSvg(this.getSvgRoot())),this.parent_=t},t.blockRendering.MarkerSvg.prototype.showWithBlockPrevOutput_=function(e){if(e){var o=e.width,i=e.height,n=i*t.blockRendering.MarkerSvg.HEIGHT_MULTIPLIER,s=this.constants_.CURSOR_BLOCK_PADDING;if(e.previousConnection){var r=this.constants_.shapeFor(e.previousConnection);this.positionPrevious_(o,s,n,r)}else e.outputConnection?(r=this.constants_.shapeFor(e.outputConnection),this.positionOutput_(o,i,r)):this.positionBlock_(o,s,n);this.setParent_(e),this.showCurrent_()}},t.blockRendering.MarkerSvg.prototype.showWithCoordinates_=function(t){var e=t.getWsCoordinate();t=e.x,e=e.y,this.workspace_.RTL&&(t-=this.constants_.CURSOR_WS_WIDTH),this.positionLine_(t,e,this.constants_.CURSOR_WS_WIDTH),this.setParent_(this.workspace_),this.showCurrent_()},t.blockRendering.MarkerSvg.prototype.showWithField_=function(t){var e=(t=t.getLocation()).getSize().width,o=t.getSize().height;this.positionRect_(0,0,e,o),this.setParent_(t),this.showCurrent_()},t.blockRendering.MarkerSvg.prototype.showWithInput_=function(t){var e=(t=t.getLocation()).getSourceBlock();this.positionInput_(t),this.setParent_(e),this.showCurrent_()},t.blockRendering.MarkerSvg.prototype.showWithNext_=function(t){var e=t.getLocation();t=e.getSourceBlock();var o=0;e=e.getOffsetInBlock().y;var i=t.getHeightWidth().width;this.workspace_.RTL&&(o=-i),this.positionLine_(o,e,i),this.setParent_(t),this.showCurrent_()},t.blockRendering.MarkerSvg.prototype.showWithStack_=function(t){var e=(t=t.getLocation()).getHeightWidth(),o=e.width+this.constants_.CURSOR_STACK_PADDING;e=e.height+this.constants_.CURSOR_STACK_PADDING;var i=-this.constants_.CURSOR_STACK_PADDING/2,n=-this.constants_.CURSOR_STACK_PADDING/2,s=i;this.workspace_.RTL&&(s=-(o+i)),this.positionRect_(s,n,o,e),this.setParent_(t),this.showCurrent_()},t.blockRendering.MarkerSvg.prototype.showCurrent_=function(){this.hide(),this.currentMarkerSvg.style.display=""},t.blockRendering.MarkerSvg.prototype.positionBlock_=function(e,o,i){e=t.utils.svgPaths.moveBy(-o,i)+t.utils.svgPaths.lineOnAxis("V",-o)+t.utils.svgPaths.lineOnAxis("H",e+2*o)+t.utils.svgPaths.lineOnAxis("V",i),this.markerBlock_.setAttribute("d",e),this.workspace_.RTL&&this.flipRtl_(this.markerBlock_),this.currentMarkerSvg=this.markerBlock_},t.blockRendering.MarkerSvg.prototype.positionInput_=function(e){var o=e.getOffsetInBlock().x,i=e.getOffsetInBlock().y;e=t.utils.svgPaths.moveTo(0,0)+this.constants_.shapeFor(e).pathDown,this.markerInput_.setAttribute("d",e),this.markerInput_.setAttribute("transform","translate("+o+","+i+")"+(this.workspace_.RTL?" scale(-1 1)":"")),this.currentMarkerSvg=this.markerInput_},t.blockRendering.MarkerSvg.prototype.positionLine_=function(t,e,o){this.markerSvgLine_.setAttribute("x",t),this.markerSvgLine_.setAttribute("y",e),this.markerSvgLine_.setAttribute("width",o),this.currentMarkerSvg=this.markerSvgLine_},t.blockRendering.MarkerSvg.prototype.positionOutput_=function(e,o,i){e=t.utils.svgPaths.moveBy(e,0)+t.utils.svgPaths.lineOnAxis("h",-(e-i.width))+t.utils.svgPaths.lineOnAxis("v",this.constants_.TAB_OFFSET_FROM_TOP)+i.pathDown+t.utils.svgPaths.lineOnAxis("V",o)+t.utils.svgPaths.lineOnAxis("H",e),this.markerBlock_.setAttribute("d",e),this.workspace_.RTL&&this.flipRtl_(this.markerBlock_),this.currentMarkerSvg=this.markerBlock_},t.blockRendering.MarkerSvg.prototype.positionPrevious_=function(e,o,i,n){e=t.utils.svgPaths.moveBy(-o,i)+t.utils.svgPaths.lineOnAxis("V",-o)+t.utils.svgPaths.lineOnAxis("H",this.constants_.NOTCH_OFFSET_LEFT)+n.pathLeft+t.utils.svgPaths.lineOnAxis("H",e+2*o)+t.utils.svgPaths.lineOnAxis("V",i),this.markerBlock_.setAttribute("d",e),this.workspace_.RTL&&this.flipRtl_(this.markerBlock_),this.currentMarkerSvg=this.markerBlock_},t.blockRendering.MarkerSvg.prototype.positionRect_=function(t,e,o,i){this.markerSvgRect_.setAttribute("x",t),this.markerSvgRect_.setAttribute("y",e),this.markerSvgRect_.setAttribute("width",o),this.markerSvgRect_.setAttribute("height",i),this.currentMarkerSvg=this.markerSvgRect_},t.blockRendering.MarkerSvg.prototype.flipRtl_=function(t){t.setAttribute("transform","scale(-1 1)")},t.blockRendering.MarkerSvg.prototype.hide=function(){this.markerSvgLine_.style.display="none",this.markerSvgRect_.style.display="none",this.markerInput_.style.display="none",this.markerBlock_.style.display="none"},t.blockRendering.MarkerSvg.prototype.draw=function(t,e){if(e){this.constants_=this.workspace_.getRenderer().getConstants();var o=this.isCursor()?this.constants_.CURSOR_COLOUR:this.constants_.MARKER_COLOUR;this.colour_=this.marker_.colour||o,this.applyColour_(),this.showAtLocation_(e),this.firemarkerEvent_(t,e),void 0!==(t=this.currentMarkerSvg.childNodes[0])&&t.beginElement&&t.beginElement()}else this.hide()},t.blockRendering.MarkerSvg.prototype.showAtLocation_=function(e){e.getType()==t.ASTNode.types.BLOCK?(e=e.getLocation(),this.showWithBlockPrevOutput_(e)):e.getType()==t.ASTNode.types.OUTPUT?(e=e.getLocation().getSourceBlock(),this.showWithBlockPrevOutput_(e)):e.getLocation().type==t.INPUT_VALUE?this.showWithInput_(e):e.getLocation().type==t.NEXT_STATEMENT?this.showWithNext_(e):e.getType()==t.ASTNode.types.PREVIOUS?(e=e.getLocation().getSourceBlock(),this.showWithBlockPrevOutput_(e)):e.getType()==t.ASTNode.types.FIELD?this.showWithField_(e):e.getType()==t.ASTNode.types.WORKSPACE?this.showWithCoordinates_(e):e.getType()==t.ASTNode.types.STACK&&this.showWithStack_(e)},t.blockRendering.MarkerSvg.prototype.firemarkerEvent_=function(e,o){var i=o.getSourceBlock(),n=this.isCursor()?"cursorMove":"markerMove";e=new t.Events.Ui(i,n,e,o),o.getType()==t.ASTNode.types.WORKSPACE&&(e.workspaceId=o.getLocation().id),t.Events.fire(e)},t.blockRendering.MarkerSvg.prototype.getBlinkProperties_=function(){return{attributeType:"XML",attributeName:"fill",dur:"1s",values:this.colour_+";transparent;transparent;",repeatCount:"indefinite"}},t.blockRendering.MarkerSvg.prototype.createDomInternal_=function(){if(this.markerSvg_=t.utils.dom.createSvgElement("g",{width:this.constants_.CURSOR_WS_WIDTH,height:this.constants_.WS_CURSOR_HEIGHT},this.svgGroup_),this.markerSvgLine_=t.utils.dom.createSvgElement("rect",{width:this.constants_.CURSOR_WS_WIDTH,height:this.constants_.WS_CURSOR_HEIGHT,style:"display: none"},this.markerSvg_),this.markerSvgRect_=t.utils.dom.createSvgElement("rect",{class:"blocklyVerticalMarker",rx:10,ry:10,style:"display: none"},this.markerSvg_),this.markerInput_=t.utils.dom.createSvgElement("path",{transform:"",style:"display: none"},this.markerSvg_),this.markerBlock_=t.utils.dom.createSvgElement("path",{transform:"",style:"display: none",fill:"none","stroke-width":this.constants_.CURSOR_STROKE_WIDTH},this.markerSvg_),this.isCursor()){var e=this.getBlinkProperties_();t.utils.dom.createSvgElement("animate",e,this.markerSvgLine_),t.utils.dom.createSvgElement("animate",e,this.markerInput_),e.attributeName="stroke",t.utils.dom.createSvgElement("animate",e,this.markerBlock_)}return this.markerSvg_},t.blockRendering.MarkerSvg.prototype.applyColour_=function(){if(this.markerSvgLine_.setAttribute("fill",this.colour_),this.markerSvgRect_.setAttribute("stroke",this.colour_),this.markerInput_.setAttribute("fill",this.colour_),this.markerBlock_.setAttribute("stroke",this.colour_),this.isCursor()){var t=this.colour_+";transparent;transparent;";this.markerSvgLine_.firstChild.setAttribute("values",t),this.markerInput_.firstChild.setAttribute("values",t),this.markerBlock_.firstChild.setAttribute("values",t)}},t.blockRendering.MarkerSvg.prototype.dispose=function(){this.svgGroup_&&t.utils.dom.removeNode(this.svgGroup_)},t.blockRendering.Types={NONE:0,FIELD:1,HAT:2,ICON:4,SPACER:8,BETWEEN_ROW_SPACER:16,IN_ROW_SPACER:32,EXTERNAL_VALUE_INPUT:64,INPUT:128,INLINE_INPUT:256,STATEMENT_INPUT:512,CONNECTION:1024,PREVIOUS_CONNECTION:2048,NEXT_CONNECTION:4096,OUTPUT_CONNECTION:8192,CORNER:16384,LEFT_SQUARE_CORNER:32768,LEFT_ROUND_CORNER:65536,RIGHT_SQUARE_CORNER:131072,RIGHT_ROUND_CORNER:262144,JAGGED_EDGE:524288,ROW:1048576,TOP_ROW:2097152,BOTTOM_ROW:4194304,INPUT_ROW:8388608},t.blockRendering.Types.LEFT_CORNER=t.blockRendering.Types.LEFT_SQUARE_CORNER|t.blockRendering.Types.LEFT_ROUND_CORNER,t.blockRendering.Types.RIGHT_CORNER=t.blockRendering.Types.RIGHT_SQUARE_CORNER|t.blockRendering.Types.RIGHT_ROUND_CORNER,t.blockRendering.Types.nextTypeValue_=16777216,t.blockRendering.Types.getType=function(e){return t.blockRendering.Types.hasOwnProperty(e)||(t.blockRendering.Types[e]=t.blockRendering.Types.nextTypeValue_,t.blockRendering.Types.nextTypeValue_<<=1),t.blockRendering.Types[e]},t.blockRendering.Types.isField=function(e){return e.type&t.blockRendering.Types.FIELD},t.blockRendering.Types.isHat=function(e){return e.type&t.blockRendering.Types.HAT},t.blockRendering.Types.isIcon=function(e){return e.type&t.blockRendering.Types.ICON},t.blockRendering.Types.isSpacer=function(e){return e.type&t.blockRendering.Types.SPACER},t.blockRendering.Types.isInRowSpacer=function(e){return e.type&t.blockRendering.Types.IN_ROW_SPACER},t.blockRendering.Types.isInput=function(e){return e.type&t.blockRendering.Types.INPUT},t.blockRendering.Types.isExternalInput=function(e){return e.type&t.blockRendering.Types.EXTERNAL_VALUE_INPUT},t.blockRendering.Types.isInlineInput=function(e){return e.type&t.blockRendering.Types.INLINE_INPUT},t.blockRendering.Types.isStatementInput=function(e){return e.type&t.blockRendering.Types.STATEMENT_INPUT},t.blockRendering.Types.isPreviousConnection=function(e){return e.type&t.blockRendering.Types.PREVIOUS_CONNECTION},t.blockRendering.Types.isNextConnection=function(e){return e.type&t.blockRendering.Types.NEXT_CONNECTION},t.blockRendering.Types.isPreviousOrNextConnection=function(e){return e.type&(t.blockRendering.Types.PREVIOUS_CONNECTION|t.blockRendering.Types.NEXT_CONNECTION)},t.blockRendering.Types.isLeftRoundedCorner=function(e){return e.type&t.blockRendering.Types.LEFT_ROUND_CORNER},t.blockRendering.Types.isRightRoundedCorner=function(e){return e.type&t.blockRendering.Types.RIGHT_ROUND_CORNER},t.blockRendering.Types.isLeftSquareCorner=function(e){return e.type&t.blockRendering.Types.LEFT_SQUARE_CORNER},t.blockRendering.Types.isRightSquareCorner=function(e){return e.type&t.blockRendering.Types.RIGHT_SQUARE_CORNER},t.blockRendering.Types.isCorner=function(e){return e.type&t.blockRendering.Types.CORNER},t.blockRendering.Types.isJaggedEdge=function(e){return e.type&t.blockRendering.Types.JAGGED_EDGE},t.blockRendering.Types.isRow=function(e){return e.type&t.blockRendering.Types.ROW},t.blockRendering.Types.isBetweenRowSpacer=function(e){return e.type&t.blockRendering.Types.BETWEEN_ROW_SPACER},t.blockRendering.Types.isTopRow=function(e){return e.type&t.blockRendering.Types.TOP_ROW},t.blockRendering.Types.isBottomRow=function(e){return e.type&t.blockRendering.Types.BOTTOM_ROW},t.blockRendering.Types.isTopOrBottomRow=function(e){return e.type&(t.blockRendering.Types.TOP_ROW|t.blockRendering.Types.BOTTOM_ROW)},t.blockRendering.Types.isInputRow=function(e){return e.type&t.blockRendering.Types.INPUT_ROW},t.blockRendering.Measurable=function(e){this.height=this.width=0,this.type=t.blockRendering.Types.NONE,this.centerline=this.xPos=0,this.constants_=e,this.notchOffset=this.constants_.NOTCH_OFFSET_LEFT},t.blockRendering.Connection=function(e,o){t.blockRendering.Connection.superClass_.constructor.call(this,e),this.connectionModel=o,this.shape=this.constants_.shapeFor(o),this.isDynamicShape=!!this.shape.isDynamic,this.type|=t.blockRendering.Types.CONNECTION},t.utils.object.inherits(t.blockRendering.Connection,t.blockRendering.Measurable),t.blockRendering.OutputConnection=function(e,o){t.blockRendering.OutputConnection.superClass_.constructor.call(this,e,o),this.type|=t.blockRendering.Types.OUTPUT_CONNECTION,this.height=this.isDynamicShape?0:this.shape.height,this.startX=this.width=this.isDynamicShape?0:this.shape.width,this.connectionOffsetY=this.constants_.TAB_OFFSET_FROM_TOP,this.connectionOffsetX=0},t.utils.object.inherits(t.blockRendering.OutputConnection,t.blockRendering.Connection),t.blockRendering.PreviousConnection=function(e,o){t.blockRendering.PreviousConnection.superClass_.constructor.call(this,e,o),this.type|=t.blockRendering.Types.PREVIOUS_CONNECTION,this.height=this.shape.height,this.width=this.shape.width},t.utils.object.inherits(t.blockRendering.PreviousConnection,t.blockRendering.Connection),t.blockRendering.NextConnection=function(e,o){t.blockRendering.NextConnection.superClass_.constructor.call(this,e,o),this.type|=t.blockRendering.Types.NEXT_CONNECTION,this.height=this.shape.height,this.width=this.shape.width},t.utils.object.inherits(t.blockRendering.NextConnection,t.blockRendering.Connection),t.blockRendering.InputConnection=function(e,o){t.blockRendering.InputConnection.superClass_.constructor.call(this,e,o.connection),this.type|=t.blockRendering.Types.INPUT,this.input=o,this.align=o.align,(this.connectedBlock=o.connection&&o.connection.targetBlock()?o.connection.targetBlock():null)?(e=this.connectedBlock.getHeightWidth(),this.connectedBlockWidth=e.width,this.connectedBlockHeight=e.height):this.connectedBlockHeight=this.connectedBlockWidth=0,this.connectionOffsetY=this.connectionOffsetX=0},t.utils.object.inherits(t.blockRendering.InputConnection,t.blockRendering.Connection),t.blockRendering.InlineInput=function(e,o){t.blockRendering.InlineInput.superClass_.constructor.call(this,e,o),this.type|=t.blockRendering.Types.INLINE_INPUT,this.connectedBlock?(this.width=this.connectedBlockWidth,this.height=this.connectedBlockHeight):(this.height=this.constants_.EMPTY_INLINE_INPUT_HEIGHT,this.width=this.constants_.EMPTY_INLINE_INPUT_PADDING),this.connectionHeight=this.isDynamicShape?this.shape.height(this.height):this.shape.height,this.connectionWidth=this.isDynamicShape?this.shape.width(this.height):this.shape.width,this.connectedBlock||(this.width+=this.connectionWidth*(this.isDynamicShape?2:1)),this.connectionOffsetY=this.isDynamicShape?this.shape.connectionOffsetY(this.connectionHeight):this.constants_.TAB_OFFSET_FROM_TOP,this.connectionOffsetX=this.isDynamicShape?this.shape.connectionOffsetX(this.connectionWidth):0},t.utils.object.inherits(t.blockRendering.InlineInput,t.blockRendering.InputConnection),t.blockRendering.StatementInput=function(e,o){t.blockRendering.StatementInput.superClass_.constructor.call(this,e,o),this.type|=t.blockRendering.Types.STATEMENT_INPUT,this.height=this.connectedBlock?this.connectedBlockHeight+this.constants_.STATEMENT_BOTTOM_SPACER:this.constants_.EMPTY_STATEMENT_INPUT_HEIGHT,this.width=this.constants_.STATEMENT_INPUT_NOTCH_OFFSET+this.shape.width},t.utils.object.inherits(t.blockRendering.StatementInput,t.blockRendering.InputConnection),t.blockRendering.ExternalValueInput=function(e,o){t.blockRendering.ExternalValueInput.superClass_.constructor.call(this,e,o),this.type|=t.blockRendering.Types.EXTERNAL_VALUE_INPUT,this.height=this.connectedBlock?this.connectedBlockHeight-this.constants_.TAB_OFFSET_FROM_TOP-this.constants_.MEDIUM_PADDING:this.shape.height,this.width=this.shape.width+this.constants_.EXTERNAL_VALUE_INPUT_PADDING,this.connectionOffsetY=this.constants_.TAB_OFFSET_FROM_TOP,this.connectionHeight=this.shape.height,this.connectionWidth=this.shape.width},t.utils.object.inherits(t.blockRendering.ExternalValueInput,t.blockRendering.InputConnection),t.blockRendering.Icon=function(e,o){t.blockRendering.Icon.superClass_.constructor.call(this,e),this.icon=o,this.isVisible=o.isVisible(),this.type|=t.blockRendering.Types.ICON,e=o.getCorrectedSize(),this.height=e.height,this.width=e.width},t.utils.object.inherits(t.blockRendering.Icon,t.blockRendering.Measurable),t.blockRendering.JaggedEdge=function(e){t.blockRendering.JaggedEdge.superClass_.constructor.call(this,e),this.type|=t.blockRendering.Types.JAGGED_EDGE,this.height=this.constants_.JAGGED_TEETH.height,this.width=this.constants_.JAGGED_TEETH.width},t.utils.object.inherits(t.blockRendering.JaggedEdge,t.blockRendering.Measurable),t.blockRendering.Field=function(e,o,i){t.blockRendering.Field.superClass_.constructor.call(this,e),this.field=o,this.isEditable=o.EDITABLE,this.flipRtl=o.getFlipRtl(),this.type|=t.blockRendering.Types.FIELD,e=this.field.getSize(),this.height=e.height,this.width=e.width,this.parentInput=i},t.utils.object.inherits(t.blockRendering.Field,t.blockRendering.Measurable),t.blockRendering.Hat=function(e){t.blockRendering.Hat.superClass_.constructor.call(this,e),this.type|=t.blockRendering.Types.HAT,this.height=this.constants_.START_HAT.height,this.width=this.constants_.START_HAT.width,this.ascenderHeight=this.height},t.utils.object.inherits(t.blockRendering.Hat,t.blockRendering.Measurable),t.blockRendering.SquareCorner=function(e,o){t.blockRendering.SquareCorner.superClass_.constructor.call(this,e),this.type=(o&&"left"!=o?t.blockRendering.Types.RIGHT_SQUARE_CORNER:t.blockRendering.Types.LEFT_SQUARE_CORNER)|t.blockRendering.Types.CORNER,this.width=this.height=this.constants_.NO_PADDING},t.utils.object.inherits(t.blockRendering.SquareCorner,t.blockRendering.Measurable),t.blockRendering.RoundCorner=function(e,o){t.blockRendering.RoundCorner.superClass_.constructor.call(this,e),this.type=(o&&"left"!=o?t.blockRendering.Types.RIGHT_ROUND_CORNER:t.blockRendering.Types.LEFT_ROUND_CORNER)|t.blockRendering.Types.CORNER,this.width=this.constants_.CORNER_RADIUS,this.height=this.constants_.CORNER_RADIUS/2},t.utils.object.inherits(t.blockRendering.RoundCorner,t.blockRendering.Measurable),t.blockRendering.InRowSpacer=function(e,o){t.blockRendering.InRowSpacer.superClass_.constructor.call(this,e),this.type=this.type|t.blockRendering.Types.SPACER|t.blockRendering.Types.IN_ROW_SPACER,this.width=o,this.height=this.constants_.SPACER_DEFAULT_HEIGHT},t.utils.object.inherits(t.blockRendering.InRowSpacer,t.blockRendering.Measurable),t.blockRendering.Row=function(e){this.type=t.blockRendering.Types.ROW,this.elements=[],this.xPos=this.yPos=this.widthWithConnectedBlocks=this.minWidth=this.minHeight=this.width=this.height=0,this.hasJaggedEdge=this.hasDummyInput=this.hasInlineInput=this.hasStatement=this.hasExternalInput=!1,this.constants_=e,this.notchOffset=this.constants_.NOTCH_OFFSET_LEFT,this.align=null},t.blockRendering.Row.prototype.measure=function(){throw Error("Unexpected attempt to measure a base Row.")},t.blockRendering.Row.prototype.getLastInput=function(){for(var e,o=this.elements.length-1;e=this.elements[o];o--)if(t.blockRendering.Types.isInput(e))return e;return null},t.blockRendering.Row.prototype.startsWithElemSpacer=function(){return!0},t.blockRendering.Row.prototype.endsWithElemSpacer=function(){return!0},t.blockRendering.Row.prototype.getFirstSpacer=function(){for(var e,o=0;e=this.elements[o];o++)if(t.blockRendering.Types.isSpacer(e))return e;return null},t.blockRendering.Row.prototype.getLastSpacer=function(){for(var e,o=this.elements.length-1;e=this.elements[o];o--)if(t.blockRendering.Types.isSpacer(e))return e;return null},t.blockRendering.TopRow=function(e){t.blockRendering.TopRow.superClass_.constructor.call(this,e),this.type|=t.blockRendering.Types.TOP_ROW,this.ascenderHeight=this.capline=0,this.hasPreviousConnection=!1,this.connection=null},t.utils.object.inherits(t.blockRendering.TopRow,t.blockRendering.Row),t.blockRendering.TopRow.prototype.hasLeftSquareCorner=function(t){var e=(t.hat?"cap"===t.hat:this.constants_.ADD_START_HATS)&&!t.outputConnection&&!t.previousConnection,o=t.getPreviousBlock();return!!t.outputConnection||e||!!o&&o.getNextBlock()==t},t.blockRendering.TopRow.prototype.hasRightSquareCorner=function(t){return!0},t.blockRendering.TopRow.prototype.measure=function(){for(var e,o=0,i=0,n=0,s=0;e=this.elements[s];s++)i+=e.width,t.blockRendering.Types.isSpacer(e)||(t.blockRendering.Types.isHat(e)?n=Math.max(n,e.ascenderHeight):o=Math.max(o,e.height));this.width=Math.max(this.minWidth,i),this.height=Math.max(this.minHeight,o)+n,this.capline=this.ascenderHeight=n,this.widthWithConnectedBlocks=this.width},t.blockRendering.TopRow.prototype.startsWithElemSpacer=function(){return!1},t.blockRendering.TopRow.prototype.endsWithElemSpacer=function(){return!1},t.blockRendering.BottomRow=function(e){t.blockRendering.BottomRow.superClass_.constructor.call(this,e),this.type|=t.blockRendering.Types.BOTTOM_ROW,this.hasNextConnection=!1,this.connection=null,this.baseline=this.descenderHeight=0},t.utils.object.inherits(t.blockRendering.BottomRow,t.blockRendering.Row),t.blockRendering.BottomRow.prototype.hasLeftSquareCorner=function(t){return!!t.outputConnection||!!t.getNextBlock()},t.blockRendering.BottomRow.prototype.hasRightSquareCorner=function(t){return!0},t.blockRendering.BottomRow.prototype.measure=function(){for(var e,o=0,i=0,n=0,s=0;e=this.elements[s];s++)i+=e.width,t.blockRendering.Types.isSpacer(e)||(t.blockRendering.Types.isNextConnection(e)?n=Math.max(n,e.height):o=Math.max(o,e.height));this.width=Math.max(this.minWidth,i),this.height=Math.max(this.minHeight,o)+n,this.descenderHeight=n,this.widthWithConnectedBlocks=this.width},t.blockRendering.BottomRow.prototype.startsWithElemSpacer=function(){return!1},t.blockRendering.BottomRow.prototype.endsWithElemSpacer=function(){return!1},t.blockRendering.SpacerRow=function(e,o,i){t.blockRendering.SpacerRow.superClass_.constructor.call(this,e),this.type=this.type|t.blockRendering.Types.SPACER|t.blockRendering.Types.BETWEEN_ROW_SPACER,this.width=i,this.height=o,this.followsStatement=!1,this.widthWithConnectedBlocks=0,this.elements=[new t.blockRendering.InRowSpacer(this.constants_,i)]},t.utils.object.inherits(t.blockRendering.SpacerRow,t.blockRendering.Row),t.blockRendering.SpacerRow.prototype.measure=function(){},t.blockRendering.InputRow=function(e){t.blockRendering.InputRow.superClass_.constructor.call(this,e),this.type|=t.blockRendering.Types.INPUT_ROW,this.connectedBlockWidths=0},t.utils.object.inherits(t.blockRendering.InputRow,t.blockRendering.Row),t.blockRendering.InputRow.prototype.measure=function(){this.width=this.minWidth,this.height=this.minHeight;for(var e,o=0,i=0;e=this.elements[i];i++)this.width+=e.width,t.blockRendering.Types.isInput(e)&&(t.blockRendering.Types.isStatementInput(e)?o+=e.connectedBlockWidth:t.blockRendering.Types.isExternalInput(e)&&0!=e.connectedBlockWidth&&(o+=e.connectedBlockWidth-e.connectionWidth)),t.blockRendering.Types.isSpacer(e)||(this.height=Math.max(this.height,e.height));this.connectedBlockWidths=o,this.widthWithConnectedBlocks=this.width+o},t.blockRendering.InputRow.prototype.endsWithElemSpacer=function(){return!this.hasExternalInput&&!this.hasStatement},t.blockRendering.RenderInfo=function(e,o){this.block_=o,this.renderer_=e,this.constants_=this.renderer_.getConstants(),this.outputConnection=o.outputConnection?new t.blockRendering.OutputConnection(this.constants_,o.outputConnection):null,this.isInline=o.getInputsInline()&&!o.isCollapsed(),this.isCollapsed=o.isCollapsed(),this.isInsertionMarker=o.isInsertionMarker(),this.RTL=o.RTL,this.statementEdge=this.width=this.widthWithChildren=this.height=0,this.rows=[],this.inputRows=[],this.hiddenIcons=[],this.topRow=new t.blockRendering.TopRow(this.constants_),this.bottomRow=new t.blockRendering.BottomRow(this.constants_),this.startY=this.startX=0},t.blockRendering.RenderInfo.prototype.getRenderer=function(){return this.renderer_},t.blockRendering.RenderInfo.prototype.measure=function(){this.createRows_(),this.addElemSpacing_(),this.addRowSpacing_(),this.computeBounds_(),this.alignRowElements_(),this.finalize_()},t.blockRendering.RenderInfo.prototype.createRows_=function(){this.populateTopRow_(),this.rows.push(this.topRow);var e=new t.blockRendering.InputRow(this.constants_);this.inputRows.push(e);var o=this.block_.getIcons();if(o.length)for(var i,n=0;i=o[n];n++){var s=new t.blockRendering.Icon(this.constants_,i);this.isCollapsed&&i.collapseHidden?this.hiddenIcons.push(s):e.elements.push(s)}for(i=null,n=0;o=this.block_.inputList[n];n++)if(o.isVisible()){for(this.shouldStartNewRow_(o,i)&&(this.rows.push(e),e=new t.blockRendering.InputRow(this.constants_),this.inputRows.push(e)),i=0;s=o.fieldRow[i];i++)e.elements.push(new t.blockRendering.Field(this.constants_,s,o));this.addInput_(o,e),i=o}this.isCollapsed&&(e.hasJaggedEdge=!0,e.elements.push(new t.blockRendering.JaggedEdge(this.constants_))),(e.elements.length||e.hasDummyInput)&&this.rows.push(e),this.populateBottomRow_(),this.rows.push(this.bottomRow)},t.blockRendering.RenderInfo.prototype.populateTopRow_=function(){var e=!!this.block_.previousConnection,o=(this.block_.hat?"cap"===this.block_.hat:this.constants_.ADD_START_HATS)&&!this.outputConnection&&!e;this.topRow.hasLeftSquareCorner(this.block_)?this.topRow.elements.push(new t.blockRendering.SquareCorner(this.constants_)):this.topRow.elements.push(new t.blockRendering.RoundCorner(this.constants_)),o?(e=new t.blockRendering.Hat(this.constants_),this.topRow.elements.push(e),this.topRow.capline=e.ascenderHeight):e&&(this.topRow.hasPreviousConnection=!0,this.topRow.connection=new t.blockRendering.PreviousConnection(this.constants_,this.block_.previousConnection),this.topRow.elements.push(this.topRow.connection)),this.block_.inputList.length&&this.block_.inputList[0].type==t.NEXT_STATEMENT&&!this.block_.isCollapsed()?this.topRow.minHeight=this.constants_.TOP_ROW_PRECEDES_STATEMENT_MIN_HEIGHT:this.topRow.minHeight=this.constants_.TOP_ROW_MIN_HEIGHT,this.topRow.hasRightSquareCorner(this.block_)?this.topRow.elements.push(new t.blockRendering.SquareCorner(this.constants_,"right")):this.topRow.elements.push(new t.blockRendering.RoundCorner(this.constants_,"right"))},t.blockRendering.RenderInfo.prototype.populateBottomRow_=function(){this.bottomRow.hasNextConnection=!!this.block_.nextConnection,this.bottomRow.minHeight=this.block_.inputList.length&&this.block_.inputList[this.block_.inputList.length-1].type==t.NEXT_STATEMENT?this.constants_.BOTTOM_ROW_AFTER_STATEMENT_MIN_HEIGHT:this.constants_.BOTTOM_ROW_MIN_HEIGHT,this.bottomRow.hasLeftSquareCorner(this.block_)?this.bottomRow.elements.push(new t.blockRendering.SquareCorner(this.constants_)):this.bottomRow.elements.push(new t.blockRendering.RoundCorner(this.constants_)),this.bottomRow.hasNextConnection&&(this.bottomRow.connection=new t.blockRendering.NextConnection(this.constants_,this.block_.nextConnection),this.bottomRow.elements.push(this.bottomRow.connection)),this.bottomRow.hasRightSquareCorner(this.block_)?this.bottomRow.elements.push(new t.blockRendering.SquareCorner(this.constants_,"right")):this.bottomRow.elements.push(new t.blockRendering.RoundCorner(this.constants_,"right"))},t.blockRendering.RenderInfo.prototype.addInput_=function(e,o){this.isInline&&e.type==t.INPUT_VALUE?(o.elements.push(new t.blockRendering.InlineInput(this.constants_,e)),o.hasInlineInput=!0):e.type==t.NEXT_STATEMENT?(o.elements.push(new t.blockRendering.StatementInput(this.constants_,e)),o.hasStatement=!0):e.type==t.INPUT_VALUE?(o.elements.push(new t.blockRendering.ExternalValueInput(this.constants_,e)),o.hasExternalInput=!0):e.type==t.DUMMY_INPUT&&(o.minHeight=Math.max(o.minHeight,e.getSourceBlock()&&e.getSourceBlock().isShadow()?this.constants_.DUMMY_INPUT_SHADOW_MIN_HEIGHT:this.constants_.DUMMY_INPUT_MIN_HEIGHT),o.hasDummyInput=!0),null==o.align&&(o.align=e.align)},t.blockRendering.RenderInfo.prototype.shouldStartNewRow_=function(e,o){return!(!o||e.type!=t.NEXT_STATEMENT&&o.type!=t.NEXT_STATEMENT&&(e.type!=t.INPUT_VALUE&&e.type!=t.DUMMY_INPUT||this.isInline))},t.blockRendering.RenderInfo.prototype.addElemSpacing_=function(){for(var e,o=0;e=this.rows[o];o++){var i=e.elements;if(e.elements=[],e.startsWithElemSpacer()&&e.elements.push(new t.blockRendering.InRowSpacer(this.constants_,this.getInRowSpacing_(null,i[0]))),i.length){for(var n=0;n.blocklyPathLight,",e+" .blocklyInsertionMarker>.blocklyPathDark {","fill-opacity: "+this.INSERTION_MARKER_OPACITY+";","stroke: none","}"])},t.geras.Highlighter=function(t){this.info_=t,this.inlineSteps_=this.steps_="",this.RTL_=this.info_.RTL,t=t.getRenderer(),this.constants_=t.getConstants(),this.highlightConstants_=t.getHighlightConstants(),this.highlightOffset_=this.highlightConstants_.OFFSET,this.outsideCornerPaths_=this.highlightConstants_.OUTSIDE_CORNER,this.insideCornerPaths_=this.highlightConstants_.INSIDE_CORNER,this.puzzleTabPaths_=this.highlightConstants_.PUZZLE_TAB,this.notchPaths_=this.highlightConstants_.NOTCH,this.startPaths_=this.highlightConstants_.START_HAT,this.jaggedTeethPaths_=this.highlightConstants_.JAGGED_TEETH},t.geras.Highlighter.prototype.getPath=function(){return this.steps_+"\n"+this.inlineSteps_},t.geras.Highlighter.prototype.drawTopCorner=function(e){this.steps_+=t.utils.svgPaths.moveBy(e.xPos,this.info_.startY);for(var o,i=0;o=e.elements[i];i++)t.blockRendering.Types.isLeftSquareCorner(o)?this.steps_+=this.highlightConstants_.START_POINT:t.blockRendering.Types.isLeftRoundedCorner(o)?this.steps_+=this.outsideCornerPaths_.topLeft(this.RTL_):t.blockRendering.Types.isPreviousConnection(o)?this.steps_+=this.notchPaths_.pathLeft:t.blockRendering.Types.isHat(o)?this.steps_+=this.startPaths_.path(this.RTL_):t.blockRendering.Types.isSpacer(o)&&0!=o.width&&(this.steps_+=t.utils.svgPaths.lineOnAxis("H",o.xPos+o.width-this.highlightOffset_));this.steps_+=t.utils.svgPaths.lineOnAxis("H",e.xPos+e.width-this.highlightOffset_)},t.geras.Highlighter.prototype.drawJaggedEdge_=function(e){this.info_.RTL&&(this.steps_+=this.jaggedTeethPaths_.pathLeft+t.utils.svgPaths.lineOnAxis("v",e.height-this.jaggedTeethPaths_.height-this.highlightOffset_))},t.geras.Highlighter.prototype.drawValueInput=function(e){var o=e.getLastInput();if(this.RTL_){var i=e.height-o.connectionHeight;this.steps_+=t.utils.svgPaths.moveTo(o.xPos+o.width-this.highlightOffset_,e.yPos)+this.puzzleTabPaths_.pathDown(this.RTL_)+t.utils.svgPaths.lineOnAxis("v",i)}else this.steps_+=t.utils.svgPaths.moveTo(o.xPos+o.width,e.yPos)+this.puzzleTabPaths_.pathDown(this.RTL_)},t.geras.Highlighter.prototype.drawStatementInput=function(e){var o=e.getLastInput();if(this.RTL_){var i=e.height-2*this.insideCornerPaths_.height;this.steps_+=t.utils.svgPaths.moveTo(o.xPos,e.yPos)+this.insideCornerPaths_.pathTop(this.RTL_)+t.utils.svgPaths.lineOnAxis("v",i)+this.insideCornerPaths_.pathBottom(this.RTL_)+t.utils.svgPaths.lineTo(e.width-o.xPos-this.insideCornerPaths_.width,0)}else this.steps_+=t.utils.svgPaths.moveTo(o.xPos,e.yPos+e.height)+this.insideCornerPaths_.pathBottom(this.RTL_)+t.utils.svgPaths.lineTo(e.width-o.xPos-this.insideCornerPaths_.width,0)},t.geras.Highlighter.prototype.drawRightSideRow=function(e){var o=e.xPos+e.width-this.highlightOffset_;e.followsStatement&&(this.steps_+=t.utils.svgPaths.lineOnAxis("H",o)),this.RTL_&&(this.steps_+=t.utils.svgPaths.lineOnAxis("H",o),e.height>this.highlightOffset_&&(this.steps_+=t.utils.svgPaths.lineOnAxis("V",e.yPos+e.height-this.highlightOffset_)))},t.geras.Highlighter.prototype.drawBottomRow=function(e){if(this.RTL_)this.steps_+=t.utils.svgPaths.lineOnAxis("V",e.baseline-this.highlightOffset_);else{var o=this.info_.bottomRow.elements[0];t.blockRendering.Types.isLeftSquareCorner(o)?this.steps_+=t.utils.svgPaths.moveTo(e.xPos+this.highlightOffset_,e.baseline-this.highlightOffset_):t.blockRendering.Types.isLeftRoundedCorner(o)&&(this.steps_+=t.utils.svgPaths.moveTo(e.xPos,e.baseline),this.steps_+=this.outsideCornerPaths_.bottomLeft())}},t.geras.Highlighter.prototype.drawLeft=function(){var e=this.info_.outputConnection;e&&(e=e.connectionOffsetY+e.height,this.RTL_?this.steps_+=t.utils.svgPaths.moveTo(this.info_.startX,e):(this.steps_+=t.utils.svgPaths.moveTo(this.info_.startX+this.highlightOffset_,this.info_.bottomRow.baseline-this.highlightOffset_),this.steps_+=t.utils.svgPaths.lineOnAxis("V",e)),this.steps_+=this.puzzleTabPaths_.pathUp(this.RTL_)),this.RTL_||(e=this.info_.topRow,t.blockRendering.Types.isLeftRoundedCorner(e.elements[0])?this.steps_+=t.utils.svgPaths.lineOnAxis("V",this.outsideCornerPaths_.height):this.steps_+=t.utils.svgPaths.lineOnAxis("V",e.capline+this.highlightOffset_))},t.geras.Highlighter.prototype.drawInlineInput=function(e){var o=this.highlightOffset_,i=e.xPos+e.connectionWidth,n=e.centerline-e.height/2,s=e.width-e.connectionWidth,r=n+o;this.RTL_?(n=e.connectionOffsetY-o,e=e.height-(e.connectionOffsetY+e.connectionHeight)+o,this.inlineSteps_+=t.utils.svgPaths.moveTo(i-o,r)+t.utils.svgPaths.lineOnAxis("v",n)+this.puzzleTabPaths_.pathDown(this.RTL_)+t.utils.svgPaths.lineOnAxis("v",e)+t.utils.svgPaths.lineOnAxis("h",s)):this.inlineSteps_+=t.utils.svgPaths.moveTo(e.xPos+e.width+o,r)+t.utils.svgPaths.lineOnAxis("v",e.height)+t.utils.svgPaths.lineOnAxis("h",-s)+t.utils.svgPaths.moveTo(i,n+e.connectionOffsetY)+this.puzzleTabPaths_.pathDown(this.RTL_)},t.geras.InlineInput=function(e,o){t.geras.InlineInput.superClass_.constructor.call(this,e,o),this.connectedBlock&&(this.width+=this.constants_.DARK_PATH_OFFSET,this.height+=this.constants_.DARK_PATH_OFFSET)},t.utils.object.inherits(t.geras.InlineInput,t.blockRendering.InlineInput),t.geras.StatementInput=function(e,o){t.geras.StatementInput.superClass_.constructor.call(this,e,o),this.connectedBlock&&(this.height+=this.constants_.DARK_PATH_OFFSET)},t.utils.object.inherits(t.geras.StatementInput,t.blockRendering.StatementInput),t.geras.RenderInfo=function(e,o){t.geras.RenderInfo.superClass_.constructor.call(this,e,o)},t.utils.object.inherits(t.geras.RenderInfo,t.blockRendering.RenderInfo),t.geras.RenderInfo.prototype.getRenderer=function(){return this.renderer_},t.geras.RenderInfo.prototype.populateBottomRow_=function(){t.geras.RenderInfo.superClass_.populateBottomRow_.call(this),this.block_.inputList.length&&this.block_.inputList[this.block_.inputList.length-1].type==t.NEXT_STATEMENT||(this.bottomRow.minHeight=this.constants_.MEDIUM_PADDING-this.constants_.DARK_PATH_OFFSET)},t.geras.RenderInfo.prototype.addInput_=function(e,o){this.isInline&&e.type==t.INPUT_VALUE?(o.elements.push(new t.geras.InlineInput(this.constants_,e)),o.hasInlineInput=!0):e.type==t.NEXT_STATEMENT?(o.elements.push(new t.geras.StatementInput(this.constants_,e)),o.hasStatement=!0):e.type==t.INPUT_VALUE?(o.elements.push(new t.blockRendering.ExternalValueInput(this.constants_,e)),o.hasExternalInput=!0):e.type==t.DUMMY_INPUT&&(o.minHeight=Math.max(o.minHeight,this.constants_.DUMMY_INPUT_MIN_HEIGHT),o.hasDummyInput=!0),this.isInline||null!=o.align||(o.align=e.align)},t.geras.RenderInfo.prototype.addElemSpacing_=function(){for(var e,o=!1,i=0;e=this.rows[i];i++)e.hasExternalInput&&(o=!0);for(i=0;e=this.rows[i];i++){var n=e.elements;if(e.elements=[],e.startsWithElemSpacer()&&e.elements.push(new t.blockRendering.InRowSpacer(this.constants_,this.getInRowSpacing_(null,n[0]))),n.length){for(var s=0;so?o:s,n=n?-1:1,e=(i?-1:1)*e/2,t.utils.svgPaths.lineTo(-n*s,e)+t.utils.svgPaths.lineTo(n*s,e)}var o=this.MAX_DYNAMIC_CONNECTION_SHAPE_WIDTH;return{type:this.SHAPES.HEXAGONAL,isDynamic:!0,width:function(t){return(t/=2)>o?o:t},height:function(t){return t},connectionOffsetY:function(t){return t/2},connectionOffsetX:function(t){return-t},pathDown:function(t){return e(t,!1,!1)},pathUp:function(t){return e(t,!0,!1)},pathRightDown:function(t){return e(t,!1,!0)},pathRightUp:function(t){return e(t,!1,!0)}}},t.zelos.ConstantProvider.prototype.makeRounded=function(){function e(e,o,n){var s=e>i?e-i:0;return e=(e>i?i:e)/2,t.utils.svgPaths.arc("a","0 0,1",e,t.utils.svgPaths.point((o?-1:1)*e,(o?-1:1)*e))+t.utils.svgPaths.lineOnAxis("v",(n?1:-1)*s)+t.utils.svgPaths.arc("a","0 0,1",e,t.utils.svgPaths.point((o?1:-1)*e,(o?-1:1)*e))}var o=this.MAX_DYNAMIC_CONNECTION_SHAPE_WIDTH,i=2*o;return{type:this.SHAPES.ROUND,isDynamic:!0,width:function(t){return(t/=2)>o?o:t},height:function(t){return t},connectionOffsetY:function(t){return t/2},connectionOffsetX:function(t){return-t},pathDown:function(t){return e(t,!1,!1)},pathUp:function(t){return e(t,!0,!1)},pathRightDown:function(t){return e(t,!1,!0)},pathRightUp:function(t){return e(t,!1,!0)}}},t.zelos.ConstantProvider.prototype.makeSquared=function(){function e(e,i,n){return e-=2*o,t.utils.svgPaths.arc("a","0 0,1",o,t.utils.svgPaths.point((i?-1:1)*o,(i?-1:1)*o))+t.utils.svgPaths.lineOnAxis("v",(n?1:-1)*e)+t.utils.svgPaths.arc("a","0 0,1",o,t.utils.svgPaths.point((i?1:-1)*o,(i?-1:1)*o))}var o=this.CORNER_RADIUS;return{type:this.SHAPES.SQUARE,isDynamic:!0,width:function(t){return o},height:function(t){return t},connectionOffsetY:function(t){return t/2},connectionOffsetX:function(t){return-t},pathDown:function(t){return e(t,!1,!1)},pathUp:function(t){return e(t,!0,!1)},pathRightDown:function(t){return e(t,!1,!0)},pathRightUp:function(t){return e(t,!1,!0)}}},t.zelos.ConstantProvider.prototype.shapeFor=function(e){var o=e.getCheck();switch(!o&&e.targetConnection&&(o=e.targetConnection.getCheck()),e.type){case t.INPUT_VALUE:case t.OUTPUT_VALUE:if(null!=(e=e.getSourceBlock().getOutputShape()))switch(e){case this.SHAPES.HEXAGONAL:return this.HEXAGONAL;case this.SHAPES.ROUND:return this.ROUNDED;case this.SHAPES.SQUARE:return this.SQUARED}return o&&-1!=o.indexOf("Boolean")?this.HEXAGONAL:(o&&-1!=o.indexOf("Number")||o&&o.indexOf("String"),this.ROUNDED);case t.PREVIOUS_STATEMENT:case t.NEXT_STATEMENT:return this.NOTCH;default:throw Error("Unknown type")}},t.zelos.ConstantProvider.prototype.makeNotch=function(){function e(e){return t.utils.svgPaths.curve("c",[t.utils.svgPaths.point(e*s/2,0),t.utils.svgPaths.point(e*s*3/4,a/2),t.utils.svgPaths.point(e*s,a)])+t.utils.svgPaths.line([t.utils.svgPaths.point(e*s,r)])+t.utils.svgPaths.curve("c",[t.utils.svgPaths.point(e*s/4,a/2),t.utils.svgPaths.point(e*s/2,a),t.utils.svgPaths.point(e*s,a)])+t.utils.svgPaths.lineOnAxis("h",e*n)+t.utils.svgPaths.curve("c",[t.utils.svgPaths.point(e*s/2,0),t.utils.svgPaths.point(e*s*3/4,-a/2),t.utils.svgPaths.point(e*s,-a)])+t.utils.svgPaths.line([t.utils.svgPaths.point(e*s,-r)])+t.utils.svgPaths.curve("c",[t.utils.svgPaths.point(e*s/4,-a/2),t.utils.svgPaths.point(e*s/2,-a),t.utils.svgPaths.point(e*s,-a)])}var o=this.NOTCH_WIDTH,i=this.NOTCH_HEIGHT,n=o/3,s=n/3,r=i/2,a=r/2,l=e(1),c=e(-1);return{type:this.SHAPES.NOTCH,width:o,height:i,pathLeft:l,pathRight:c}},t.zelos.ConstantProvider.prototype.makeInsideCorners=function(){var e=this.CORNER_RADIUS,o=t.utils.svgPaths.arc("a","0 0,0",e,t.utils.svgPaths.point(-e,e)),i=t.utils.svgPaths.arc("a","0 0,1",e,t.utils.svgPaths.point(-e,e));return{width:e,height:e,pathTop:o,pathBottom:t.utils.svgPaths.arc("a","0 0,0",e,t.utils.svgPaths.point(e,e)),rightWidth:e,rightHeight:e,pathTopRight:i,pathBottomRight:t.utils.svgPaths.arc("a","0 0,1",e,t.utils.svgPaths.point(e,e))}},t.zelos.ConstantProvider.prototype.generateSecondaryColour_=function(e){return t.utils.colour.blend("#000",e,.15)||e},t.zelos.ConstantProvider.prototype.generateTertiaryColour_=function(e){return t.utils.colour.blend("#000",e,.25)||e},t.zelos.ConstantProvider.prototype.createDom=function(e,o,i){t.zelos.ConstantProvider.superClass_.createDom.call(this,e,o,i),e=t.utils.dom.createSvgElement("defs",{},e),o=t.utils.dom.createSvgElement("filter",{id:"blocklySelectedGlowFilter"+this.randomIdentifier,height:"160%",width:"180%",y:"-30%",x:"-40%"},e),t.utils.dom.createSvgElement("feGaussianBlur",{in:"SourceGraphic",stdDeviation:this.SELECTED_GLOW_SIZE},o),i=t.utils.dom.createSvgElement("feComponentTransfer",{result:"outBlur"},o),t.utils.dom.createSvgElement("feFuncA",{type:"table",tableValues:"0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"},i),t.utils.dom.createSvgElement("feFlood",{"flood-color":this.SELECTED_GLOW_COLOUR,"flood-opacity":1,result:"outColor"},o),t.utils.dom.createSvgElement("feComposite",{in:"outColor",in2:"outBlur",operator:"in",result:"outGlow"},o),this.selectedGlowFilterId=o.id,this.selectedGlowFilter_=o,e=t.utils.dom.createSvgElement("filter",{id:"blocklyReplacementGlowFilter"+this.randomIdentifier,height:"160%",width:"180%",y:"-30%",x:"-40%"},e),t.utils.dom.createSvgElement("feGaussianBlur",{in:"SourceGraphic",stdDeviation:this.REPLACEMENT_GLOW_SIZE},e),o=t.utils.dom.createSvgElement("feComponentTransfer",{result:"outBlur"},e),t.utils.dom.createSvgElement("feFuncA",{type:"table",tableValues:"0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"},o),t.utils.dom.createSvgElement("feFlood",{"flood-color":this.REPLACEMENT_GLOW_COLOUR,"flood-opacity":1,result:"outColor"},e),t.utils.dom.createSvgElement("feComposite",{in:"outColor",in2:"outBlur",operator:"in",result:"outGlow"},e),t.utils.dom.createSvgElement("feComposite",{in:"SourceGraphic",in2:"outGlow",operator:"over"},e),this.replacementGlowFilterId=e.id,this.replacementGlowFilter_=e},t.zelos.ConstantProvider.prototype.getCSS_=function(t){return[t+" .blocklyText, ",t+" .blocklyFlyoutLabelText {","font-family: "+this.FIELD_TEXT_FONTFAMILY+";","font-size: "+this.FIELD_TEXT_FONTSIZE+"pt;","font-weight: "+this.FIELD_TEXT_FONTWEIGHT+";","}",t+" .blocklyText {","fill: #fff;","}",t+" .blocklyNonEditableText>rect:not(.blocklyDropdownRect),",t+" .blocklyEditableText>rect:not(.blocklyDropdownRect) {","fill: "+this.FIELD_BORDER_RECT_COLOUR+";","}",t+" .blocklyNonEditableText>text,",t+" .blocklyEditableText>text,",t+" .blocklyNonEditableText>g>text,",t+" .blocklyEditableText>g>text {","fill: #575E75;","}",t+" .blocklyFlyoutLabelText {","fill: #575E75;","}",t+" .blocklyText.blocklyBubbleText {","fill: #575E75;","}",t+" .blocklyDraggable:not(.blocklyDisabled)"," .blocklyEditableText:not(.editing):hover>rect ,",t+" .blocklyDraggable:not(.blocklyDisabled)"," .blocklyEditableText:not(.editing):hover>.blocklyPath {","stroke: #fff;","stroke-width: 2;","}",t+" .blocklyHtmlInput {","font-family: "+this.FIELD_TEXT_FONTFAMILY+";","font-weight: "+this.FIELD_TEXT_FONTWEIGHT+";","color: #575E75;","}",t+" .blocklyDropdownText {","fill: #fff !important;","}",t+".blocklyWidgetDiv .goog-menuitem,",t+".blocklyDropDownDiv .goog-menuitem {","font-family: "+this.FIELD_TEXT_FONTFAMILY+";","}",t+".blocklyDropDownDiv .goog-menuitem-content {","color: #fff;","}",t+" .blocklyHighlightedConnectionPath {","stroke: "+this.SELECTED_GLOW_COLOUR+";","}",t+" .blocklyDisabled > .blocklyOutlinePath {","fill: url(#blocklyDisabledPattern"+this.randomIdentifier+")","}",t+" .blocklyInsertionMarker>.blocklyPath {","fill-opacity: "+this.INSERTION_MARKER_OPACITY+";","stroke: none","}"]},t.zelos.TopRow=function(e){t.zelos.TopRow.superClass_.constructor.call(this,e)},t.utils.object.inherits(t.zelos.TopRow,t.blockRendering.TopRow),t.zelos.TopRow.prototype.endsWithElemSpacer=function(){return!1},t.zelos.TopRow.prototype.hasLeftSquareCorner=function(t){var e=(t.hat?"cap"===t.hat:this.constants_.ADD_START_HATS)&&!t.outputConnection&&!t.previousConnection;return!!t.outputConnection||e},t.zelos.TopRow.prototype.hasRightSquareCorner=function(t){return!!t.outputConnection&&!t.statementInputCount&&!t.nextConnection},t.zelos.BottomRow=function(e){t.zelos.BottomRow.superClass_.constructor.call(this,e)},t.utils.object.inherits(t.zelos.BottomRow,t.blockRendering.BottomRow),t.zelos.BottomRow.prototype.endsWithElemSpacer=function(){return!1},t.zelos.BottomRow.prototype.hasLeftSquareCorner=function(t){return!!t.outputConnection},t.zelos.BottomRow.prototype.hasRightSquareCorner=function(t){return!!t.outputConnection&&!t.statementInputCount&&!t.nextConnection},t.zelos.RightConnectionShape=function(e){t.zelos.RightConnectionShape.superClass_.constructor.call(this,e),this.type|=t.blockRendering.Types.getType("RIGHT_CONNECTION"),this.width=this.height=0},t.utils.object.inherits(t.zelos.RightConnectionShape,t.blockRendering.Measurable),t.zelos.StatementInput=function(e,o){if(t.zelos.StatementInput.superClass_.constructor.call(this,e,o),this.connectedBlock){for(e=this.connectedBlock;e.getNextBlock();)e=e.getNextBlock();e.nextConnection||(this.height=this.connectedBlockHeight,this.connectedBottomNextConnection=!0)}},t.utils.object.inherits(t.zelos.StatementInput,t.blockRendering.StatementInput),t.zelos.RenderInfo=function(e,o){t.zelos.RenderInfo.superClass_.constructor.call(this,e,o),this.topRow=new t.zelos.TopRow(this.constants_),this.bottomRow=new t.zelos.BottomRow(this.constants_),this.isInline=!0,this.isMultiRow=!o.getInputsInline()||o.isCollapsed(),this.hasStatementInput=0=this.rows.length-1?!!this.bottomRow.hasNextConnection:!!r.precedesStatement,t.blockRendering.Types.isInputRow(s)&&s.hasStatement)s.measure(),o=s.width-s.getLastInput().width+e;else if(n&&(2==i||r)&&t.blockRendering.Types.isInputRow(s)&&!s.hasStatement){r=s.xPos,n=null;for(var a,l=0;a=s.elements[l];l++)t.blockRendering.Types.isSpacer(a)&&(n=a),!(n&&(t.blockRendering.Types.isField(a)||t.blockRendering.Types.isInput(a))&&ri?i:this.height/2)*(1-Math.sin(Math.acos((i-this.constants_.SMALL_PADDING)/i)));default:return 0}if(t.blockRendering.Types.isInlineInput(e)){var s=e.connectedBlock;return e=s?s.pathObject.outputShapeType:e.shape.type,s&&s.outputConnection&&(s.statementInputCount||s.nextConnection)||i==n.SHAPES.HEXAGONAL&&i!=e?0:o-this.constants_.SHAPE_IN_SHAPE_PADDING[i][e]}return t.blockRendering.Types.isField(e)?i==n.SHAPES.ROUND&&e.field instanceof t.FieldTextInput?o-2.75*n.GRID_UNIT:o-this.constants_.SHAPE_IN_SHAPE_PADDING[i][0]:t.blockRendering.Types.isIcon(e)?this.constants_.SMALL_PADDING:0},t.zelos.RenderInfo.prototype.finalizeVerticalAlignment_=function(){if(!this.outputConnection)for(var e=2;e=this.rows.length-1?!!this.bottomRow.hasNextConnection:!!n.precedesStatement;if(s?this.topRow.hasPreviousConnection:o.followsStatement){var a=3==i.elements.length&&(i.elements[1].field instanceof t.FieldLabel||i.elements[1].field instanceof t.FieldImage);if(!s&&a)o.height-=this.constants_.SMALL_PADDING,n.height-=this.constants_.SMALL_PADDING,i.height-=this.constants_.MEDIUM_PADDING;else if(s||r){if(r){for(s=!1,r=0;a=i.elements[r];r++)if(t.blockRendering.Types.isInlineInput(a)&&a.connectedBlock&&!a.connectedBlock.isShadow()&&40<=a.connectedBlock.getHeightWidth().height){s=!0;break}s&&(o.height-=this.constants_.SMALL_PADDING,n.height-=this.constants_.SMALL_PADDING)}}else o.height+=this.constants_.SMALL_PADDING}}},t.zelos.RenderInfo.prototype.finalize_=function(){this.finalizeOutputConnection_(),this.finalizeHorizontalAlignment_(),this.finalizeVerticalAlignment_(),t.zelos.RenderInfo.superClass_.finalize_.call(this),this.rightSide&&(this.widthWithChildren+=this.rightSide.width)},t.zelos.Drawer=function(e,o){t.zelos.Drawer.superClass_.constructor.call(this,e,o)},t.utils.object.inherits(t.zelos.Drawer,t.blockRendering.Drawer),t.zelos.Drawer.prototype.draw=function(){var e=this.block_.pathObject;e.beginDrawing(),this.hideHiddenIcons_(),this.drawOutline_(),this.drawInternals_(),e.setPath(this.outlinePath_+"\n"+this.inlinePath_),this.info_.RTL&&e.flipRTL(),t.blockRendering.useDebugger&&this.block_.renderingDebugger.drawDebug(this.block_,this.info_),this.recordSizeOnBlock_(),this.info_.outputConnection&&(e.outputShapeType=this.info_.outputConnection.shape.type),e.endDrawing()},t.zelos.Drawer.prototype.drawOutline_=function(){this.info_.outputConnection&&this.info_.outputConnection.isDynamicShape&&!this.info_.hasStatementInput&&!this.info_.bottomRow.hasNextConnection?(this.drawFlatTop_(),this.drawRightDynamicConnection_(),this.drawFlatBottom_(),this.drawLeftDynamicConnection_()):t.zelos.Drawer.superClass_.drawOutline_.call(this)},t.zelos.Drawer.prototype.drawLeft_=function(){this.info_.outputConnection&&this.info_.outputConnection.isDynamicShape?this.drawLeftDynamicConnection_():t.zelos.Drawer.superClass_.drawLeft_.call(this)},t.zelos.Drawer.prototype.drawRightSideRow_=function(e){if(!(0>=e.height))if(e.precedesStatement||e.followsStatement){var o=this.constants_.INSIDE_CORNERS.rightHeight;o=e.height-(e.precedesStatement?o:0),this.outlinePath_+=(e.followsStatement?this.constants_.INSIDE_CORNERS.pathBottomRight:"")+(0","GT"],["‏≥","GTE"]]},{type:"input_value",name:"B"}],inputsInline:!0,output:"Boolean",style:"logic_blocks",helpUrl:"%{BKY_LOGIC_COMPARE_HELPURL}",extensions:["logic_compare","logic_op_tooltip"]},{type:"logic_operation",message0:"%1 %2 %3",args0:[{type:"input_value",name:"A",check:"Boolean"},{type:"field_dropdown",name:"OP",options:[["%{BKY_LOGIC_OPERATION_AND}","AND"],["%{BKY_LOGIC_OPERATION_OR}","OR"]]},{type:"input_value",name:"B",check:"Boolean"}],inputsInline:!0,output:"Boolean",style:"logic_blocks",helpUrl:"%{BKY_LOGIC_OPERATION_HELPURL}",extensions:["logic_op_tooltip"]},{type:"logic_negate",message0:"%{BKY_LOGIC_NEGATE_TITLE}",args0:[{type:"input_value",name:"BOOL",check:"Boolean"}],output:"Boolean",style:"logic_blocks",tooltip:"%{BKY_LOGIC_NEGATE_TOOLTIP}",helpUrl:"%{BKY_LOGIC_NEGATE_HELPURL}"},{type:"logic_null",message0:"%{BKY_LOGIC_NULL}",output:null,style:"logic_blocks",tooltip:"%{BKY_LOGIC_NULL_TOOLTIP}",helpUrl:"%{BKY_LOGIC_NULL_HELPURL}"},{type:"logic_ternary",message0:"%{BKY_LOGIC_TERNARY_CONDITION} %1",args0:[{type:"input_value",name:"IF",check:"Boolean"}],message1:"%{BKY_LOGIC_TERNARY_IF_TRUE} %1",args1:[{type:"input_value",name:"THEN"}],message2:"%{BKY_LOGIC_TERNARY_IF_FALSE} %1",args2:[{type:"input_value",name:"ELSE"}],output:null,style:"logic_blocks",tooltip:"%{BKY_LOGIC_TERNARY_TOOLTIP}",helpUrl:"%{BKY_LOGIC_TERNARY_HELPURL}",extensions:["logic_ternary"]}]),t.defineBlocksWithJsonArray([{type:"controls_if_if",message0:"%{BKY_CONTROLS_IF_IF_TITLE_IF}",nextStatement:null,enableContextMenu:!1,style:"logic_blocks",tooltip:"%{BKY_CONTROLS_IF_IF_TOOLTIP}"},{type:"controls_if_elseif",message0:"%{BKY_CONTROLS_IF_ELSEIF_TITLE_ELSEIF}",previousStatement:null,nextStatement:null,enableContextMenu:!1,style:"logic_blocks",tooltip:"%{BKY_CONTROLS_IF_ELSEIF_TOOLTIP}"},{type:"controls_if_else",message0:"%{BKY_CONTROLS_IF_ELSE_TITLE_ELSE}",previousStatement:null,enableContextMenu:!1,style:"logic_blocks",tooltip:"%{BKY_CONTROLS_IF_ELSE_TOOLTIP}"}]),t.Constants.Logic.TOOLTIPS_BY_OP={EQ:"%{BKY_LOGIC_COMPARE_TOOLTIP_EQ}",NEQ:"%{BKY_LOGIC_COMPARE_TOOLTIP_NEQ}",LT:"%{BKY_LOGIC_COMPARE_TOOLTIP_LT}",LTE:"%{BKY_LOGIC_COMPARE_TOOLTIP_LTE}",GT:"%{BKY_LOGIC_COMPARE_TOOLTIP_GT}",GTE:"%{BKY_LOGIC_COMPARE_TOOLTIP_GTE}",AND:"%{BKY_LOGIC_OPERATION_TOOLTIP_AND}",OR:"%{BKY_LOGIC_OPERATION_TOOLTIP_OR}"},t.Extensions.register("logic_op_tooltip",t.Extensions.buildTooltipForDropdown("OP",t.Constants.Logic.TOOLTIPS_BY_OP)),t.Constants.Logic.CONTROLS_IF_MUTATOR_MIXIN={elseifCount_:0,elseCount_:0,suppressPrefixSuffix:!0,mutationToDom:function(){if(!this.elseifCount_&&!this.elseCount_)return null;var e=t.utils.xml.createElement("mutation");return this.elseifCount_&&e.setAttribute("elseif",this.elseifCount_),this.elseCount_&&e.setAttribute("else",1),e},domToMutation:function(t){this.elseifCount_=parseInt(t.getAttribute("elseif"),10)||0,this.elseCount_=parseInt(t.getAttribute("else"),10)||0,this.rebuildShape_()},decompose:function(t){var e=t.newBlock("controls_if_if");e.initSvg();for(var o=e.nextConnection,i=1;i<=this.elseifCount_;i++){var n=t.newBlock("controls_if_elseif");n.initSvg(),o.connect(n.previousConnection),o=n.nextConnection}return this.elseCount_&&((t=t.newBlock("controls_if_else")).initSvg(),o.connect(t.previousConnection)),e},compose:function(t){t=t.nextConnection.targetBlock(),this.elseCount_=this.elseifCount_=0;for(var e=[null],o=[null],i=null;t;){switch(t.type){case"controls_if_elseif":this.elseifCount_++,e.push(t.valueConnection_),o.push(t.statementConnection_);break;case"controls_if_else":this.elseCount_++,i=t.statementConnection_;break;default:throw TypeError("Unknown block type: "+t.type)}t=t.nextConnection&&t.nextConnection.targetBlock()}this.updateShape_(),this.reconnectChildBlocks_(e,o,i)},saveConnections:function(t){t=t.nextConnection.targetBlock();for(var e=1;t;){switch(t.type){case"controls_if_elseif":var o=this.getInput("IF"+e),i=this.getInput("DO"+e);t.valueConnection_=o&&o.connection.targetConnection,t.statementConnection_=i&&i.connection.targetConnection,e++;break;case"controls_if_else":i=this.getInput("ELSE"),t.statementConnection_=i&&i.connection.targetConnection;break;default:throw TypeError("Unknown block type: "+t.type)}t=t.nextConnection&&t.nextConnection.targetBlock()}},rebuildShape_:function(){var t=[null],e=[null],o=null;this.getInput("ELSE")&&(o=this.getInput("ELSE").connection.targetConnection);for(var i=1;this.getInput("IF"+i);){var n=this.getInput("IF"+i),s=this.getInput("DO"+i);t.push(n.connection.targetConnection),e.push(s.connection.targetConnection),i++}this.updateShape_(),this.reconnectChildBlocks_(t,e,o)},updateShape_:function(){this.getInput("ELSE")&&this.removeInput("ELSE");for(var e=1;this.getInput("IF"+e);)this.removeInput("IF"+e),this.removeInput("DO"+e),e++;for(e=1;e<=this.elseifCount_;e++)this.appendValueInput("IF"+e).setCheck("Boolean").appendField(t.Msg.CONTROLS_IF_MSG_ELSEIF),this.appendStatementInput("DO"+e).appendField(t.Msg.CONTROLS_IF_MSG_THEN);this.elseCount_&&this.appendStatementInput("ELSE").appendField(t.Msg.CONTROLS_IF_MSG_ELSE)},reconnectChildBlocks_:function(e,o,i){for(var n=1;n<=this.elseifCount_;n++)t.Mutator.reconnect(e[n],this,"IF"+n),t.Mutator.reconnect(o[n],this,"DO"+n);t.Mutator.reconnect(i,this,"ELSE")}},t.Extensions.registerMutator("controls_if_mutator",t.Constants.Logic.CONTROLS_IF_MUTATOR_MIXIN,null,["controls_if_elseif","controls_if_else"]),t.Constants.Logic.CONTROLS_IF_TOOLTIP_EXTENSION=function(){this.setTooltip(function(){return this.elseifCount_||this.elseCount_?!this.elseifCount_&&this.elseCount_?t.Msg.CONTROLS_IF_TOOLTIP_2:this.elseifCount_&&!this.elseCount_?t.Msg.CONTROLS_IF_TOOLTIP_3:this.elseifCount_&&this.elseCount_?t.Msg.CONTROLS_IF_TOOLTIP_4:"":t.Msg.CONTROLS_IF_TOOLTIP_1}.bind(this))},t.Extensions.register("controls_if_tooltip",t.Constants.Logic.CONTROLS_IF_TOOLTIP_EXTENSION),t.Constants.Logic.LOGIC_COMPARE_ONCHANGE_MIXIN={onchange:function(e){this.prevBlocks_||(this.prevBlocks_=[null,null]);var o=this.getInputTargetBlock("A"),i=this.getInputTargetBlock("B");o&&i&&!o.outputConnection.checkType(i.outputConnection)&&(t.Events.setGroup(e.group),(e=this.prevBlocks_[0])!==o&&(o.unplug(),!e||e.isDisposed()||e.isShadow()||this.getInput("A").connection.connect(e.outputConnection)),(o=this.prevBlocks_[1])!==i&&(i.unplug(),!o||o.isDisposed()||o.isShadow()||this.getInput("B").connection.connect(o.outputConnection)),this.bumpNeighbours(),t.Events.setGroup(!1)),this.prevBlocks_[0]=this.getInputTargetBlock("A"),this.prevBlocks_[1]=this.getInputTargetBlock("B")}},t.Constants.Logic.LOGIC_COMPARE_EXTENSION=function(){this.mixin(t.Constants.Logic.LOGIC_COMPARE_ONCHANGE_MIXIN)},t.Extensions.register("logic_compare",t.Constants.Logic.LOGIC_COMPARE_EXTENSION),t.Constants.Logic.LOGIC_TERNARY_ONCHANGE_MIXIN={prevParentConnection_:null,onchange:function(e){var o=this.getInputTargetBlock("THEN"),i=this.getInputTargetBlock("ELSE"),n=this.outputConnection.targetConnection;if((o||i)&&n)for(var s=0;2>s;s++){var r=1==s?o:i;r&&!r.outputConnection.checkType(n)&&(t.Events.setGroup(e.group),n===this.prevParentConnection_?(this.unplug(),n.getSourceBlock().bumpNeighbours()):(r.unplug(),r.bumpNeighbours()),t.Events.setGroup(!1))}this.prevParentConnection_=n}},t.Extensions.registerMixin("logic_ternary",t.Constants.Logic.LOGIC_TERNARY_ONCHANGE_MIXIN),t.Blocks.loops={},t.Constants.Loops={},t.Constants.Loops.HUE=120,t.defineBlocksWithJsonArray([{type:"controls_repeat_ext",message0:"%{BKY_CONTROLS_REPEAT_TITLE}",args0:[{type:"input_value",name:"TIMES",check:"Number"}],message1:"%{BKY_CONTROLS_REPEAT_INPUT_DO} %1",args1:[{type:"input_statement",name:"DO"}],previousStatement:null,nextStatement:null,style:"loop_blocks",tooltip:"%{BKY_CONTROLS_REPEAT_TOOLTIP}",helpUrl:"%{BKY_CONTROLS_REPEAT_HELPURL}"},{type:"controls_repeat",message0:"%{BKY_CONTROLS_REPEAT_TITLE}",args0:[{type:"field_number",name:"TIMES",value:10,min:0,precision:1}],message1:"%{BKY_CONTROLS_REPEAT_INPUT_DO} %1",args1:[{type:"input_statement",name:"DO"}],previousStatement:null,nextStatement:null,style:"loop_blocks",tooltip:"%{BKY_CONTROLS_REPEAT_TOOLTIP}",helpUrl:"%{BKY_CONTROLS_REPEAT_HELPURL}"},{type:"controls_whileUntil",message0:"%1 %2",args0:[{type:"field_dropdown",name:"MODE",options:[["%{BKY_CONTROLS_WHILEUNTIL_OPERATOR_WHILE}","WHILE"],["%{BKY_CONTROLS_WHILEUNTIL_OPERATOR_UNTIL}","UNTIL"]]},{type:"input_value",name:"BOOL",check:"Boolean"}],message1:"%{BKY_CONTROLS_REPEAT_INPUT_DO} %1",args1:[{type:"input_statement",name:"DO"}],previousStatement:null,nextStatement:null,style:"loop_blocks",helpUrl:"%{BKY_CONTROLS_WHILEUNTIL_HELPURL}",extensions:["controls_whileUntil_tooltip"]},{type:"controls_for",message0:"%{BKY_CONTROLS_FOR_TITLE}",args0:[{type:"field_variable",name:"VAR",variable:null},{type:"input_value",name:"FROM",check:"Number",align:"RIGHT"},{type:"input_value",name:"TO",check:"Number",align:"RIGHT"},{type:"input_value",name:"BY",check:"Number",align:"RIGHT"}],message1:"%{BKY_CONTROLS_REPEAT_INPUT_DO} %1",args1:[{type:"input_statement",name:"DO"}],inputsInline:!0,previousStatement:null,nextStatement:null,style:"loop_blocks",helpUrl:"%{BKY_CONTROLS_FOR_HELPURL}",extensions:["contextMenu_newGetVariableBlock","controls_for_tooltip"]},{type:"controls_forEach",message0:"%{BKY_CONTROLS_FOREACH_TITLE}",args0:[{type:"field_variable",name:"VAR",variable:null},{type:"input_value",name:"LIST",check:"Array"}],message1:"%{BKY_CONTROLS_REPEAT_INPUT_DO} %1",args1:[{type:"input_statement",name:"DO"}],previousStatement:null,nextStatement:null,style:"loop_blocks",helpUrl:"%{BKY_CONTROLS_FOREACH_HELPURL}",extensions:["contextMenu_newGetVariableBlock","controls_forEach_tooltip"]},{type:"controls_flow_statements",message0:"%1",args0:[{type:"field_dropdown",name:"FLOW",options:[["%{BKY_CONTROLS_FLOW_STATEMENTS_OPERATOR_BREAK}","BREAK"],["%{BKY_CONTROLS_FLOW_STATEMENTS_OPERATOR_CONTINUE}","CONTINUE"]]}],previousStatement:null,style:"loop_blocks",helpUrl:"%{BKY_CONTROLS_FLOW_STATEMENTS_HELPURL}",extensions:["controls_flow_tooltip","controls_flow_in_loop_check"]}]),t.Constants.Loops.WHILE_UNTIL_TOOLTIPS={WHILE:"%{BKY_CONTROLS_WHILEUNTIL_TOOLTIP_WHILE}",UNTIL:"%{BKY_CONTROLS_WHILEUNTIL_TOOLTIP_UNTIL}"},t.Extensions.register("controls_whileUntil_tooltip",t.Extensions.buildTooltipForDropdown("MODE",t.Constants.Loops.WHILE_UNTIL_TOOLTIPS)),t.Constants.Loops.BREAK_CONTINUE_TOOLTIPS={BREAK:"%{BKY_CONTROLS_FLOW_STATEMENTS_TOOLTIP_BREAK}",CONTINUE:"%{BKY_CONTROLS_FLOW_STATEMENTS_TOOLTIP_CONTINUE}"},t.Extensions.register("controls_flow_tooltip",t.Extensions.buildTooltipForDropdown("FLOW",t.Constants.Loops.BREAK_CONTINUE_TOOLTIPS)),t.Constants.Loops.CUSTOM_CONTEXT_MENU_CREATE_VARIABLES_GET_MIXIN={customContextMenu:function(e){if(!this.isInFlyout){var o=this.getField("VAR").getVariable(),i=o.name;if(!this.isCollapsed()&&null!=i){var n={enabled:!0};n.text=t.Msg.VARIABLES_SET_CREATE_GET.replace("%1",i),o=t.Variables.generateVariableFieldDom(o),(i=t.utils.xml.createElement("block")).setAttribute("type","variables_get"),i.appendChild(o),n.callback=t.ContextMenu.callbackFactory(this,i),e.push(n)}}}},t.Extensions.registerMixin("contextMenu_newGetVariableBlock",t.Constants.Loops.CUSTOM_CONTEXT_MENU_CREATE_VARIABLES_GET_MIXIN),t.Extensions.register("controls_for_tooltip",t.Extensions.buildTooltipWithFieldText("%{BKY_CONTROLS_FOR_TOOLTIP}","VAR")),t.Extensions.register("controls_forEach_tooltip",t.Extensions.buildTooltipWithFieldText("%{BKY_CONTROLS_FOREACH_TOOLTIP}","VAR")),t.Constants.Loops.CONTROL_FLOW_IN_LOOP_CHECK_MIXIN={LOOP_TYPES:["controls_repeat","controls_repeat_ext","controls_forEach","controls_for","controls_whileUntil"],suppressPrefixSuffix:!0,getSurroundLoop:function(e){do{if(-1!=t.Constants.Loops.CONTROL_FLOW_IN_LOOP_CHECK_MIXIN.LOOP_TYPES.indexOf(e.type))return e;e=e.getSurroundParent()}while(e);return null},onchange:function(e){if(this.workspace.isDragging&&!this.workspace.isDragging()&&e.type==t.Events.BLOCK_MOVE&&e.blockId==this.id){var o=t.Constants.Loops.CONTROL_FLOW_IN_LOOP_CHECK_MIXIN.getSurroundLoop(this);if(this.setWarningText(o?null:t.Msg.CONTROLS_FLOW_STATEMENTS_WARNING),!this.isInFlyout){var i=t.Events.getGroup();t.Events.setGroup(e.group),this.setEnabled(o),t.Events.setGroup(i)}}}},t.Extensions.registerMixin("controls_flow_in_loop_check",t.Constants.Loops.CONTROL_FLOW_IN_LOOP_CHECK_MIXIN),t.Blocks.math={},t.Constants.Math={},t.Constants.Math.HUE=230,t.defineBlocksWithJsonArray([{type:"math_number",message0:"%1",args0:[{type:"field_number",name:"NUM",value:0}],output:"Number",helpUrl:"%{BKY_MATH_NUMBER_HELPURL}",style:"math_blocks",tooltip:"%{BKY_MATH_NUMBER_TOOLTIP}",extensions:["parent_tooltip_when_inline"]},{type:"math_arithmetic",message0:"%1 %2 %3",args0:[{type:"input_value",name:"A",check:"Number"},{type:"field_dropdown",name:"OP",options:[["%{BKY_MATH_ADDITION_SYMBOL}","ADD"],["%{BKY_MATH_SUBTRACTION_SYMBOL}","MINUS"],["%{BKY_MATH_MULTIPLICATION_SYMBOL}","MULTIPLY"],["%{BKY_MATH_DIVISION_SYMBOL}","DIVIDE"],["%{BKY_MATH_POWER_SYMBOL}","POWER"]]},{type:"input_value",name:"B",check:"Number"}],inputsInline:!0,output:"Number",style:"math_blocks",helpUrl:"%{BKY_MATH_ARITHMETIC_HELPURL}",extensions:["math_op_tooltip"]},{type:"math_single",message0:"%1 %2",args0:[{type:"field_dropdown",name:"OP",options:[["%{BKY_MATH_SINGLE_OP_ROOT}","ROOT"],["%{BKY_MATH_SINGLE_OP_ABSOLUTE}","ABS"],["-","NEG"],["ln","LN"],["log10","LOG10"],["e^","EXP"],["10^","POW10"]]},{type:"input_value",name:"NUM",check:"Number"}],output:"Number",style:"math_blocks",helpUrl:"%{BKY_MATH_SINGLE_HELPURL}",extensions:["math_op_tooltip"]},{type:"math_trig",message0:"%1 %2",args0:[{type:"field_dropdown",name:"OP",options:[["%{BKY_MATH_TRIG_SIN}","SIN"],["%{BKY_MATH_TRIG_COS}","COS"],["%{BKY_MATH_TRIG_TAN}","TAN"],["%{BKY_MATH_TRIG_ASIN}","ASIN"],["%{BKY_MATH_TRIG_ACOS}","ACOS"],["%{BKY_MATH_TRIG_ATAN}","ATAN"]]},{type:"input_value",name:"NUM",check:"Number"}],output:"Number",style:"math_blocks",helpUrl:"%{BKY_MATH_TRIG_HELPURL}",extensions:["math_op_tooltip"]},{type:"math_constant",message0:"%1",args0:[{type:"field_dropdown",name:"CONSTANT",options:[["π","PI"],["e","E"],["φ","GOLDEN_RATIO"],["sqrt(2)","SQRT2"],["sqrt(½)","SQRT1_2"],["∞","INFINITY"]]}],output:"Number",style:"math_blocks",tooltip:"%{BKY_MATH_CONSTANT_TOOLTIP}",helpUrl:"%{BKY_MATH_CONSTANT_HELPURL}"},{type:"math_number_property",message0:"%1 %2",args0:[{type:"input_value",name:"NUMBER_TO_CHECK",check:"Number"},{type:"field_dropdown",name:"PROPERTY",options:[["%{BKY_MATH_IS_EVEN}","EVEN"],["%{BKY_MATH_IS_ODD}","ODD"],["%{BKY_MATH_IS_PRIME}","PRIME"],["%{BKY_MATH_IS_WHOLE}","WHOLE"],["%{BKY_MATH_IS_POSITIVE}","POSITIVE"],["%{BKY_MATH_IS_NEGATIVE}","NEGATIVE"],["%{BKY_MATH_IS_DIVISIBLE_BY}","DIVISIBLE_BY"]]}],inputsInline:!0,output:"Boolean",style:"math_blocks",tooltip:"%{BKY_MATH_IS_TOOLTIP}",mutator:"math_is_divisibleby_mutator"},{type:"math_change",message0:"%{BKY_MATH_CHANGE_TITLE}",args0:[{type:"field_variable",name:"VAR",variable:"%{BKY_MATH_CHANGE_TITLE_ITEM}"},{type:"input_value",name:"DELTA",check:"Number"}],previousStatement:null,nextStatement:null,style:"variable_blocks",helpUrl:"%{BKY_MATH_CHANGE_HELPURL}",extensions:["math_change_tooltip"]},{type:"math_round",message0:"%1 %2",args0:[{type:"field_dropdown",name:"OP",options:[["%{BKY_MATH_ROUND_OPERATOR_ROUND}","ROUND"],["%{BKY_MATH_ROUND_OPERATOR_ROUNDUP}","ROUNDUP"],["%{BKY_MATH_ROUND_OPERATOR_ROUNDDOWN}","ROUNDDOWN"]]},{type:"input_value",name:"NUM",check:"Number"}],output:"Number",style:"math_blocks",helpUrl:"%{BKY_MATH_ROUND_HELPURL}",tooltip:"%{BKY_MATH_ROUND_TOOLTIP}"},{type:"math_on_list",message0:"%1 %2",args0:[{type:"field_dropdown",name:"OP",options:[["%{BKY_MATH_ONLIST_OPERATOR_SUM}","SUM"],["%{BKY_MATH_ONLIST_OPERATOR_MIN}","MIN"],["%{BKY_MATH_ONLIST_OPERATOR_MAX}","MAX"],["%{BKY_MATH_ONLIST_OPERATOR_AVERAGE}","AVERAGE"],["%{BKY_MATH_ONLIST_OPERATOR_MEDIAN}","MEDIAN"],["%{BKY_MATH_ONLIST_OPERATOR_MODE}","MODE"],["%{BKY_MATH_ONLIST_OPERATOR_STD_DEV}","STD_DEV"],["%{BKY_MATH_ONLIST_OPERATOR_RANDOM}","RANDOM"]]},{type:"input_value",name:"LIST",check:"Array"}],output:"Number",style:"math_blocks",helpUrl:"%{BKY_MATH_ONLIST_HELPURL}",mutator:"math_modes_of_list_mutator",extensions:["math_op_tooltip"]},{type:"math_modulo",message0:"%{BKY_MATH_MODULO_TITLE}",args0:[{type:"input_value",name:"DIVIDEND",check:"Number"},{type:"input_value",name:"DIVISOR",check:"Number"}],inputsInline:!0,output:"Number",style:"math_blocks",tooltip:"%{BKY_MATH_MODULO_TOOLTIP}",helpUrl:"%{BKY_MATH_MODULO_HELPURL}"},{type:"math_constrain",message0:"%{BKY_MATH_CONSTRAIN_TITLE}",args0:[{type:"input_value",name:"VALUE",check:"Number"},{type:"input_value",name:"LOW",check:"Number"},{type:"input_value",name:"HIGH",check:"Number"}],inputsInline:!0,output:"Number",style:"math_blocks",tooltip:"%{BKY_MATH_CONSTRAIN_TOOLTIP}",helpUrl:"%{BKY_MATH_CONSTRAIN_HELPURL}"},{type:"math_random_int",message0:"%{BKY_MATH_RANDOM_INT_TITLE}",args0:[{type:"input_value",name:"FROM",check:"Number"},{type:"input_value",name:"TO",check:"Number"}],inputsInline:!0,output:"Number",style:"math_blocks",tooltip:"%{BKY_MATH_RANDOM_INT_TOOLTIP}",helpUrl:"%{BKY_MATH_RANDOM_INT_HELPURL}"},{type:"math_random_float",message0:"%{BKY_MATH_RANDOM_FLOAT_TITLE_RANDOM}",output:"Number",style:"math_blocks",tooltip:"%{BKY_MATH_RANDOM_FLOAT_TOOLTIP}",helpUrl:"%{BKY_MATH_RANDOM_FLOAT_HELPURL}"},{type:"math_atan2",message0:"%{BKY_MATH_ATAN2_TITLE}",args0:[{type:"input_value",name:"X",check:"Number"},{type:"input_value",name:"Y",check:"Number"}],inputsInline:!0,output:"Number",style:"math_blocks",tooltip:"%{BKY_MATH_ATAN2_TOOLTIP}",helpUrl:"%{BKY_MATH_ATAN2_HELPURL}"}]),t.Constants.Math.TOOLTIPS_BY_OP={ADD:"%{BKY_MATH_ARITHMETIC_TOOLTIP_ADD}",MINUS:"%{BKY_MATH_ARITHMETIC_TOOLTIP_MINUS}",MULTIPLY:"%{BKY_MATH_ARITHMETIC_TOOLTIP_MULTIPLY}",DIVIDE:"%{BKY_MATH_ARITHMETIC_TOOLTIP_DIVIDE}",POWER:"%{BKY_MATH_ARITHMETIC_TOOLTIP_POWER}",ROOT:"%{BKY_MATH_SINGLE_TOOLTIP_ROOT}",ABS:"%{BKY_MATH_SINGLE_TOOLTIP_ABS}",NEG:"%{BKY_MATH_SINGLE_TOOLTIP_NEG}",LN:"%{BKY_MATH_SINGLE_TOOLTIP_LN}",LOG10:"%{BKY_MATH_SINGLE_TOOLTIP_LOG10}",EXP:"%{BKY_MATH_SINGLE_TOOLTIP_EXP}",POW10:"%{BKY_MATH_SINGLE_TOOLTIP_POW10}",SIN:"%{BKY_MATH_TRIG_TOOLTIP_SIN}",COS:"%{BKY_MATH_TRIG_TOOLTIP_COS}",TAN:"%{BKY_MATH_TRIG_TOOLTIP_TAN}",ASIN:"%{BKY_MATH_TRIG_TOOLTIP_ASIN}",ACOS:"%{BKY_MATH_TRIG_TOOLTIP_ACOS}",ATAN:"%{BKY_MATH_TRIG_TOOLTIP_ATAN}",SUM:"%{BKY_MATH_ONLIST_TOOLTIP_SUM}",MIN:"%{BKY_MATH_ONLIST_TOOLTIP_MIN}",MAX:"%{BKY_MATH_ONLIST_TOOLTIP_MAX}",AVERAGE:"%{BKY_MATH_ONLIST_TOOLTIP_AVERAGE}",MEDIAN:"%{BKY_MATH_ONLIST_TOOLTIP_MEDIAN}",MODE:"%{BKY_MATH_ONLIST_TOOLTIP_MODE}",STD_DEV:"%{BKY_MATH_ONLIST_TOOLTIP_STD_DEV}",RANDOM:"%{BKY_MATH_ONLIST_TOOLTIP_RANDOM}"},t.Extensions.register("math_op_tooltip",t.Extensions.buildTooltipForDropdown("OP",t.Constants.Math.TOOLTIPS_BY_OP)),t.Constants.Math.IS_DIVISIBLEBY_MUTATOR_MIXIN={mutationToDom:function(){var e=t.utils.xml.createElement("mutation"),o="DIVISIBLE_BY"==this.getFieldValue("PROPERTY");return e.setAttribute("divisor_input",o),e},domToMutation:function(t){t="true"==t.getAttribute("divisor_input"),this.updateShape_(t)},updateShape_:function(t){var e=this.getInput("DIVISOR");t?e||this.appendValueInput("DIVISOR").setCheck("Number"):e&&this.removeInput("DIVISOR")}},t.Constants.Math.IS_DIVISIBLE_MUTATOR_EXTENSION=function(){this.getField("PROPERTY").setValidator((function(t){t="DIVISIBLE_BY"==t,this.getSourceBlock().updateShape_(t)}))},t.Extensions.registerMutator("math_is_divisibleby_mutator",t.Constants.Math.IS_DIVISIBLEBY_MUTATOR_MIXIN,t.Constants.Math.IS_DIVISIBLE_MUTATOR_EXTENSION),t.Extensions.register("math_change_tooltip",t.Extensions.buildTooltipWithFieldText("%{BKY_MATH_CHANGE_TOOLTIP}","VAR")),t.Constants.Math.LIST_MODES_MUTATOR_MIXIN={updateType_:function(t){"MODE"==t?this.outputConnection.setCheck("Array"):this.outputConnection.setCheck("Number")},mutationToDom:function(){var e=t.utils.xml.createElement("mutation");return e.setAttribute("op",this.getFieldValue("OP")),e},domToMutation:function(t){this.updateType_(t.getAttribute("op"))}},t.Constants.Math.LIST_MODES_MUTATOR_EXTENSION=function(){this.getField("OP").setValidator(function(t){this.updateType_(t)}.bind(this))},t.Extensions.registerMutator("math_modes_of_list_mutator",t.Constants.Math.LIST_MODES_MUTATOR_MIXIN,t.Constants.Math.LIST_MODES_MUTATOR_EXTENSION),t.Blocks.procedures={},t.Blocks.procedures_defnoreturn={init:function(){var e=new t.FieldTextInput("",t.Procedures.rename);e.setSpellcheck(!1),this.appendDummyInput().appendField(t.Msg.PROCEDURES_DEFNORETURN_TITLE).appendField(e,"NAME").appendField("","PARAMS"),this.setMutator(new t.Mutator(["procedures_mutatorarg"])),(this.workspace.options.comments||this.workspace.options.parentWorkspace&&this.workspace.options.parentWorkspace.options.comments)&&t.Msg.PROCEDURES_DEFNORETURN_COMMENT&&this.setCommentText(t.Msg.PROCEDURES_DEFNORETURN_COMMENT),this.setStyle("procedure_blocks"),this.setTooltip(t.Msg.PROCEDURES_DEFNORETURN_TOOLTIP),this.setHelpUrl(t.Msg.PROCEDURES_DEFNORETURN_HELPURL),this.arguments_=[],this.argumentVarModels_=[],this.setStatements_(!0),this.statementConnection_=null},setStatements_:function(e){this.hasStatements_!==e&&(e?(this.appendStatementInput("STACK").appendField(t.Msg.PROCEDURES_DEFNORETURN_DO),this.getInput("RETURN")&&this.moveInputBefore("STACK","RETURN")):this.removeInput("STACK",!0),this.hasStatements_=e)},updateParams_:function(){var e="";this.arguments_.length&&(e=t.Msg.PROCEDURES_BEFORE_PARAMS+" "+this.arguments_.join(", ")),t.Events.disable();try{this.setFieldValue(e,"PARAMS")}finally{t.Events.enable()}},mutationToDom:function(e){var o=t.utils.xml.createElement("mutation");e&&o.setAttribute("name",this.getFieldValue("NAME"));for(var i=0;ii?t.JavaScript.valueToCode(e,o,t.JavaScript.ORDER_SUBTRACTION)||r:n?t.JavaScript.valueToCode(e,o,t.JavaScript.ORDER_UNARY_NEGATION)||r:t.JavaScript.valueToCode(e,o,s)||r,t.isNumber(e))e=Number(e)+i,n&&(e=-e);else{if(0i&&(e=e+" - "+-i,a=t.JavaScript.ORDER_SUBTRACTION);n&&(e=i?"-("+e+")":"-"+e,a=t.JavaScript.ORDER_UNARY_NEGATION),a=Math.floor(a),s=Math.floor(s),a&&s>=a&&(e="("+e+")")}return e},t.JavaScript.colour={},t.JavaScript.colour_picker=function(e){return[t.JavaScript.quote_(e.getFieldValue("COLOUR")),t.JavaScript.ORDER_ATOMIC]},t.JavaScript.colour_random=function(e){return[t.JavaScript.provideFunction_("colourRandom",["function "+t.JavaScript.FUNCTION_NAME_PLACEHOLDER_+"() {"," var num = Math.floor(Math.random() * Math.pow(2, 24));"," return '#' + ('00000' + num.toString(16)).substr(-6);","}"])+"()",t.JavaScript.ORDER_FUNCTION_CALL]},t.JavaScript.colour_rgb=function(e){var o=t.JavaScript.valueToCode(e,"RED",t.JavaScript.ORDER_COMMA)||0,i=t.JavaScript.valueToCode(e,"GREEN",t.JavaScript.ORDER_COMMA)||0;return e=t.JavaScript.valueToCode(e,"BLUE",t.JavaScript.ORDER_COMMA)||0,[t.JavaScript.provideFunction_("colourRgb",["function "+t.JavaScript.FUNCTION_NAME_PLACEHOLDER_+"(r, g, b) {"," r = Math.max(Math.min(Number(r), 100), 0) * 2.55;"," g = Math.max(Math.min(Number(g), 100), 0) * 2.55;"," b = Math.max(Math.min(Number(b), 100), 0) * 2.55;"," r = ('0' + (Math.round(r) || 0).toString(16)).slice(-2);"," g = ('0' + (Math.round(g) || 0).toString(16)).slice(-2);"," b = ('0' + (Math.round(b) || 0).toString(16)).slice(-2);"," return '#' + r + g + b;","}"])+"("+o+", "+i+", "+e+")",t.JavaScript.ORDER_FUNCTION_CALL]},t.JavaScript.colour_blend=function(e){var o=t.JavaScript.valueToCode(e,"COLOUR1",t.JavaScript.ORDER_COMMA)||"'#000000'",i=t.JavaScript.valueToCode(e,"COLOUR2",t.JavaScript.ORDER_COMMA)||"'#000000'";return e=t.JavaScript.valueToCode(e,"RATIO",t.JavaScript.ORDER_COMMA)||.5,[t.JavaScript.provideFunction_("colourBlend",["function "+t.JavaScript.FUNCTION_NAME_PLACEHOLDER_+"(c1, c2, ratio) {"," ratio = Math.max(Math.min(Number(ratio), 1), 0);"," var r1 = parseInt(c1.substring(1, 3), 16);"," var g1 = parseInt(c1.substring(3, 5), 16);"," var b1 = parseInt(c1.substring(5, 7), 16);"," var r2 = parseInt(c2.substring(1, 3), 16);"," var g2 = parseInt(c2.substring(3, 5), 16);"," var b2 = parseInt(c2.substring(5, 7), 16);"," var r = Math.round(r1 * (1 - ratio) + r2 * ratio);"," var g = Math.round(g1 * (1 - ratio) + g2 * ratio);"," var b = Math.round(b1 * (1 - ratio) + b2 * ratio);"," r = ('0' + (r || 0).toString(16)).slice(-2);"," g = ('0' + (g || 0).toString(16)).slice(-2);"," b = ('0' + (b || 0).toString(16)).slice(-2);"," return '#' + r + g + b;","}"])+"("+o+", "+i+", "+e+")",t.JavaScript.ORDER_FUNCTION_CALL]},t.JavaScript.lists={},t.JavaScript.lists_create_empty=function(e){return["[]",t.JavaScript.ORDER_ATOMIC]},t.JavaScript.lists_create_with=function(e){for(var o=Array(e.itemCount_),i=0;i b.toString() ? 1 : -1; },",' "IGNORE_CASE": function(a, b) {'," return a.toString().toLowerCase() > b.toString().toLowerCase() ? 1 : -1; },"," };"," var compare = compareFuncs[type];"," return function(a, b) { return compare(a, b) * direction; }","}"])+'("'+e+'", '+i+"))",t.JavaScript.ORDER_FUNCTION_CALL]},t.JavaScript.lists_split=function(e){var o=t.JavaScript.valueToCode(e,"INPUT",t.JavaScript.ORDER_MEMBER),i=t.JavaScript.valueToCode(e,"DELIM",t.JavaScript.ORDER_NONE)||"''";if("SPLIT"==(e=e.getFieldValue("MODE")))o||(o="''"),e="split";else{if("JOIN"!=e)throw Error("Unknown mode: "+e);o||(o="[]"),e="join"}return[o+"."+e+"("+i+")",t.JavaScript.ORDER_FUNCTION_CALL]},t.JavaScript.lists_reverse=function(e){return[(t.JavaScript.valueToCode(e,"LIST",t.JavaScript.ORDER_FUNCTION_CALL)||"[]")+".slice().reverse()",t.JavaScript.ORDER_FUNCTION_CALL]},t.JavaScript.logic={},t.JavaScript.controls_if=function(e){var o=0,i="";t.JavaScript.STATEMENT_PREFIX&&(i+=t.JavaScript.injectId(t.JavaScript.STATEMENT_PREFIX,e));do{var n=t.JavaScript.valueToCode(e,"IF"+o,t.JavaScript.ORDER_NONE)||"false",s=t.JavaScript.statementToCode(e,"DO"+o);t.JavaScript.STATEMENT_SUFFIX&&(s=t.JavaScript.prefixLines(t.JavaScript.injectId(t.JavaScript.STATEMENT_SUFFIX,e),t.JavaScript.INDENT)+s),i+=(0",GTE:">="}[e.getFieldValue("OP")],i="=="==o||"!="==o?t.JavaScript.ORDER_EQUALITY:t.JavaScript.ORDER_RELATIONAL;return[(t.JavaScript.valueToCode(e,"A",i)||"0")+" "+o+" "+(e=t.JavaScript.valueToCode(e,"B",i)||"0"),i]},t.JavaScript.logic_operation=function(e){var o="AND"==e.getFieldValue("OP")?"&&":"||",i="&&"==o?t.JavaScript.ORDER_LOGICAL_AND:t.JavaScript.ORDER_LOGICAL_OR,n=t.JavaScript.valueToCode(e,"A",i);if(e=t.JavaScript.valueToCode(e,"B",i),n||e){var s="&&"==o?"true":"false";n||(n=s),e||(e=s)}else e=n="false";return[n+" "+o+" "+e,i]},t.JavaScript.logic_negate=function(e){var o=t.JavaScript.ORDER_LOGICAL_NOT;return["!"+(t.JavaScript.valueToCode(e,"BOOL",o)||"true"),o]},t.JavaScript.logic_boolean=function(e){return["TRUE"==e.getFieldValue("BOOL")?"true":"false",t.JavaScript.ORDER_ATOMIC]},t.JavaScript.logic_null=function(e){return["null",t.JavaScript.ORDER_ATOMIC]},t.JavaScript.logic_ternary=function(e){return[(t.JavaScript.valueToCode(e,"IF",t.JavaScript.ORDER_CONDITIONAL)||"false")+" ? "+(t.JavaScript.valueToCode(e,"THEN",t.JavaScript.ORDER_CONDITIONAL)||"null")+" : "+(e=t.JavaScript.valueToCode(e,"ELSE",t.JavaScript.ORDER_CONDITIONAL)||"null"),t.JavaScript.ORDER_CONDITIONAL]},t.JavaScript.loops={},t.JavaScript.controls_repeat_ext=function(e){var o=e.getField("TIMES")?String(Number(e.getFieldValue("TIMES"))):t.JavaScript.valueToCode(e,"TIMES",t.JavaScript.ORDER_ASSIGNMENT)||"0",i=t.JavaScript.statementToCode(e,"DO");i=t.JavaScript.addLoopTrap(i,e),e="";var n=t.JavaScript.variableDB_.getDistinctName("count",t.VARIABLE_CATEGORY_NAME),s=o;return o.match(/^\w+$/)||t.isNumber(o)||(e+="var "+(s=t.JavaScript.variableDB_.getDistinctName("repeat_end",t.VARIABLE_CATEGORY_NAME))+" = "+o+";\n"),e+"for (var "+n+" = 0; "+n+" < "+s+"; "+n+"++) {\n"+i+"}\n"},t.JavaScript.controls_repeat=t.JavaScript.controls_repeat_ext,t.JavaScript.controls_whileUntil=function(e){var o="UNTIL"==e.getFieldValue("MODE"),i=t.JavaScript.valueToCode(e,"BOOL",o?t.JavaScript.ORDER_LOGICAL_NOT:t.JavaScript.ORDER_NONE)||"false",n=t.JavaScript.statementToCode(e,"DO");return o&&(i="!"+i),"while ("+i+") {\n"+(n=t.JavaScript.addLoopTrap(n,e))+"}\n"},t.JavaScript.controls_for=function(e){var o=t.JavaScript.variableDB_.getName(e.getFieldValue("VAR"),t.VARIABLE_CATEGORY_NAME),i=t.JavaScript.valueToCode(e,"FROM",t.JavaScript.ORDER_ASSIGNMENT)||"0",n=t.JavaScript.valueToCode(e,"TO",t.JavaScript.ORDER_ASSIGNMENT)||"0",s=t.JavaScript.valueToCode(e,"BY",t.JavaScript.ORDER_ASSIGNMENT)||"1",r=t.JavaScript.statementToCode(e,"DO");if(r=t.JavaScript.addLoopTrap(r,e),t.isNumber(i)&&t.isNumber(n)&&t.isNumber(s)){var a=Number(i)<=Number(n);e="for ("+o+" = "+i+"; "+o+(a?" <= ":" >= ")+n+"; "+o,e=(1==(o=Math.abs(Number(s)))?e+(a?"++":"--"):e+(a?" += ":" -= ")+o)+") {\n"+r+"}\n"}else e="",a=i,i.match(/^\w+$/)||t.isNumber(i)||(e+="var "+(a=t.JavaScript.variableDB_.getDistinctName(o+"_start",t.VARIABLE_CATEGORY_NAME))+" = "+i+";\n"),i=n,n.match(/^\w+$/)||t.isNumber(n)||(e+="var "+(i=t.JavaScript.variableDB_.getDistinctName(o+"_end",t.VARIABLE_CATEGORY_NAME))+" = "+n+";\n"),e+="var "+(n=t.JavaScript.variableDB_.getDistinctName(o+"_inc",t.VARIABLE_CATEGORY_NAME))+" = ",e=(e=t.isNumber(s)?e+(Math.abs(s)+";\n"):e+"Math.abs("+s+");\n")+"if ("+a+" > "+i+") {\n"+(t.JavaScript.INDENT+n)+" = -"+n+";\n",e+="}\n",e+="for ("+o+" = "+a+"; "+n+" >= 0 ? "+o+" <= "+i+" : "+o+" >= "+i+"; "+o+" += "+n+") {\n"+r+"}\n";return e},t.JavaScript.controls_forEach=function(e){var o=t.JavaScript.variableDB_.getName(e.getFieldValue("VAR"),t.VARIABLE_CATEGORY_NAME),i=t.JavaScript.valueToCode(e,"LIST",t.JavaScript.ORDER_ASSIGNMENT)||"[]",n=t.JavaScript.statementToCode(e,"DO");n=t.JavaScript.addLoopTrap(n,e),e="";var s=i;return i.match(/^\w+$/)||(e+="var "+(s=t.JavaScript.variableDB_.getDistinctName(o+"_list",t.VARIABLE_CATEGORY_NAME))+" = "+i+";\n"),e+"for (var "+(i=t.JavaScript.variableDB_.getDistinctName(o+"_index",t.VARIABLE_CATEGORY_NAME))+" in "+s+") {\n"+(n=t.JavaScript.INDENT+o+" = "+s+"["+i+"];\n"+n)+"}\n"},t.JavaScript.controls_flow_statements=function(e){var o="";if(t.JavaScript.STATEMENT_PREFIX&&(o+=t.JavaScript.injectId(t.JavaScript.STATEMENT_PREFIX,e)),t.JavaScript.STATEMENT_SUFFIX&&(o+=t.JavaScript.injectId(t.JavaScript.STATEMENT_SUFFIX,e)),t.JavaScript.STATEMENT_PREFIX){var i=t.Constants.Loops.CONTROL_FLOW_IN_LOOP_CHECK_MIXIN.getSurroundLoop(e);i&&!i.suppressPrefixSuffix&&(o+=t.JavaScript.injectId(t.JavaScript.STATEMENT_PREFIX,i))}switch(e.getFieldValue("FLOW")){case"BREAK":return o+"break;\n";case"CONTINUE":return o+"continue;\n"}throw Error("Unknown flow statement.")},t.JavaScript.math={},t.JavaScript.math_number=function(e){return[e=Number(e.getFieldValue("NUM")),0<=e?t.JavaScript.ORDER_ATOMIC:t.JavaScript.ORDER_UNARY_NEGATION]},t.JavaScript.math_arithmetic=function(e){var o={ADD:[" + ",t.JavaScript.ORDER_ADDITION],MINUS:[" - ",t.JavaScript.ORDER_SUBTRACTION],MULTIPLY:[" * ",t.JavaScript.ORDER_MULTIPLICATION],DIVIDE:[" / ",t.JavaScript.ORDER_DIVISION],POWER:[null,t.JavaScript.ORDER_COMMA]}[e.getFieldValue("OP")],i=o[0];o=o[1];var n=t.JavaScript.valueToCode(e,"A",o)||"0";return e=t.JavaScript.valueToCode(e,"B",o)||"0",i?[n+i+e,o]:["Math.pow("+n+", "+e+")",t.JavaScript.ORDER_FUNCTION_CALL]},t.JavaScript.math_single=function(e){var o=e.getFieldValue("OP");if("NEG"==o)return"-"==(e=t.JavaScript.valueToCode(e,"NUM",t.JavaScript.ORDER_UNARY_NEGATION)||"0")[0]&&(e=" "+e),["-"+e,t.JavaScript.ORDER_UNARY_NEGATION];switch(e="SIN"==o||"COS"==o||"TAN"==o?t.JavaScript.valueToCode(e,"NUM",t.JavaScript.ORDER_DIVISION)||"0":t.JavaScript.valueToCode(e,"NUM",t.JavaScript.ORDER_NONE)||"0",o){case"ABS":var i="Math.abs("+e+")";break;case"ROOT":i="Math.sqrt("+e+")";break;case"LN":i="Math.log("+e+")";break;case"EXP":i="Math.exp("+e+")";break;case"POW10":i="Math.pow(10,"+e+")";break;case"ROUND":i="Math.round("+e+")";break;case"ROUNDUP":i="Math.ceil("+e+")";break;case"ROUNDDOWN":i="Math.floor("+e+")";break;case"SIN":i="Math.sin("+e+" / 180 * Math.PI)";break;case"COS":i="Math.cos("+e+" / 180 * Math.PI)";break;case"TAN":i="Math.tan("+e+" / 180 * Math.PI)"}if(i)return[i,t.JavaScript.ORDER_FUNCTION_CALL];switch(o){case"LOG10":i="Math.log("+e+") / Math.log(10)";break;case"ASIN":i="Math.asin("+e+") / Math.PI * 180";break;case"ACOS":i="Math.acos("+e+") / Math.PI * 180";break;case"ATAN":i="Math.atan("+e+") / Math.PI * 180";break;default:throw Error("Unknown math operator: "+o)}return[i,t.JavaScript.ORDER_DIVISION]},t.JavaScript.math_constant=function(e){return{PI:["Math.PI",t.JavaScript.ORDER_MEMBER],E:["Math.E",t.JavaScript.ORDER_MEMBER],GOLDEN_RATIO:["(1 + Math.sqrt(5)) / 2",t.JavaScript.ORDER_DIVISION],SQRT2:["Math.SQRT2",t.JavaScript.ORDER_MEMBER],SQRT1_2:["Math.SQRT1_2",t.JavaScript.ORDER_MEMBER],INFINITY:["Infinity",t.JavaScript.ORDER_ATOMIC]}[e.getFieldValue("CONSTANT")]},t.JavaScript.math_number_property=function(e){var o=t.JavaScript.valueToCode(e,"NUMBER_TO_CHECK",t.JavaScript.ORDER_MODULUS)||"0",i=e.getFieldValue("PROPERTY");if("PRIME"==i)return[t.JavaScript.provideFunction_("mathIsPrime",["function "+t.JavaScript.FUNCTION_NAME_PLACEHOLDER_+"(n) {"," // https://en.wikipedia.org/wiki/Primality_test#Naive_methods"," if (n == 2 || n == 3) {"," return true;"," }"," // False if n is NaN, negative, is 1, or not whole."," // And false if n is divisible by 2 or 3."," if (isNaN(n) || n <= 1 || n % 1 != 0 || n % 2 == 0 || n % 3 == 0) {"," return false;"," }"," // Check all the numbers of form 6k +/- 1, up to sqrt(n)."," for (var x = 6; x <= Math.sqrt(n) + 1; x += 6) {"," if (n % (x - 1) == 0 || n % (x + 1) == 0) {"," return false;"," }"," }"," return true;","}"])+"("+o+")",t.JavaScript.ORDER_FUNCTION_CALL];switch(i){case"EVEN":var n=o+" % 2 == 0";break;case"ODD":n=o+" % 2 == 1";break;case"WHOLE":n=o+" % 1 == 0";break;case"POSITIVE":n=o+" > 0";break;case"NEGATIVE":n=o+" < 0";break;case"DIVISIBLE_BY":n=o+" % "+(e=t.JavaScript.valueToCode(e,"DIVISOR",t.JavaScript.ORDER_MODULUS)||"0")+" == 0"}return[n,t.JavaScript.ORDER_EQUALITY]},t.JavaScript.math_change=function(e){var o=t.JavaScript.valueToCode(e,"DELTA",t.JavaScript.ORDER_ADDITION)||"0";return(e=t.JavaScript.variableDB_.getName(e.getFieldValue("VAR"),t.VARIABLE_CATEGORY_NAME))+" = (typeof "+e+" == 'number' ? "+e+" : 0) + "+o+";\n"},t.JavaScript.math_round=t.JavaScript.math_single,t.JavaScript.math_trig=t.JavaScript.math_single,t.JavaScript.math_on_list=function(e){var o=e.getFieldValue("OP");switch(o){case"SUM":e=t.JavaScript.valueToCode(e,"LIST",t.JavaScript.ORDER_MEMBER)||"[]",e+=".reduce(function(x, y) {return x + y;})";break;case"MIN":e="Math.min.apply(null, "+(e=t.JavaScript.valueToCode(e,"LIST",t.JavaScript.ORDER_COMMA)||"[]")+")";break;case"MAX":e="Math.max.apply(null, "+(e=t.JavaScript.valueToCode(e,"LIST",t.JavaScript.ORDER_COMMA)||"[]")+")";break;case"AVERAGE":e=(o=t.JavaScript.provideFunction_("mathMean",["function "+t.JavaScript.FUNCTION_NAME_PLACEHOLDER_+"(myList) {"," return myList.reduce(function(x, y) {return x + y;}) / myList.length;","}"]))+"("+(e=t.JavaScript.valueToCode(e,"LIST",t.JavaScript.ORDER_NONE)||"[]")+")";break;case"MEDIAN":e=(o=t.JavaScript.provideFunction_("mathMedian",["function "+t.JavaScript.FUNCTION_NAME_PLACEHOLDER_+"(myList) {"," var localList = myList.filter(function (x) {return typeof x == 'number';});"," if (!localList.length) return null;"," localList.sort(function(a, b) {return b - a;});"," if (localList.length % 2 == 0) {"," return (localList[localList.length / 2 - 1] + localList[localList.length / 2]) / 2;"," } else {"," return localList[(localList.length - 1) / 2];"," }","}"]))+"("+(e=t.JavaScript.valueToCode(e,"LIST",t.JavaScript.ORDER_NONE)||"[]")+")";break;case"MODE":e=(o=t.JavaScript.provideFunction_("mathModes",["function "+t.JavaScript.FUNCTION_NAME_PLACEHOLDER_+"(values) {"," var modes = [];"," var counts = [];"," var maxCount = 0;"," for (var i = 0; i < values.length; i++) {"," var value = values[i];"," var found = false;"," var thisCount;"," for (var j = 0; j < counts.length; j++) {"," if (counts[j][0] === value) {"," thisCount = ++counts[j][1];"," found = true;"," break;"," }"," }"," if (!found) {"," counts.push([value, 1]);"," thisCount = 1;"," }"," maxCount = Math.max(thisCount, maxCount);"," }"," for (var j = 0; j < counts.length; j++) {"," if (counts[j][1] == maxCount) {"," modes.push(counts[j][0]);"," }"," }"," return modes;","}"]))+"("+(e=t.JavaScript.valueToCode(e,"LIST",t.JavaScript.ORDER_NONE)||"[]")+")";break;case"STD_DEV":e=(o=t.JavaScript.provideFunction_("mathStandardDeviation",["function "+t.JavaScript.FUNCTION_NAME_PLACEHOLDER_+"(numbers) {"," var n = numbers.length;"," if (!n) return null;"," var mean = numbers.reduce(function(x, y) {return x + y;}) / n;"," var variance = 0;"," for (var j = 0; j < n; j++) {"," variance += Math.pow(numbers[j] - mean, 2);"," }"," variance = variance / n;"," return Math.sqrt(variance);","}"]))+"("+(e=t.JavaScript.valueToCode(e,"LIST",t.JavaScript.ORDER_NONE)||"[]")+")";break;case"RANDOM":e=(o=t.JavaScript.provideFunction_("mathRandomList",["function "+t.JavaScript.FUNCTION_NAME_PLACEHOLDER_+"(list) {"," var x = Math.floor(Math.random() * list.length);"," return list[x];","}"]))+"("+(e=t.JavaScript.valueToCode(e,"LIST",t.JavaScript.ORDER_NONE)||"[]")+")";break;default:throw Error("Unknown operator: "+o)}return[e,t.JavaScript.ORDER_FUNCTION_CALL]},t.JavaScript.math_modulo=function(e){return[(t.JavaScript.valueToCode(e,"DIVIDEND",t.JavaScript.ORDER_MODULUS)||"0")+" % "+(e=t.JavaScript.valueToCode(e,"DIVISOR",t.JavaScript.ORDER_MODULUS)||"0"),t.JavaScript.ORDER_MODULUS]},t.JavaScript.math_constrain=function(e){return["Math.min(Math.max("+(t.JavaScript.valueToCode(e,"VALUE",t.JavaScript.ORDER_COMMA)||"0")+", "+(t.JavaScript.valueToCode(e,"LOW",t.JavaScript.ORDER_COMMA)||"0")+"), "+(e=t.JavaScript.valueToCode(e,"HIGH",t.JavaScript.ORDER_COMMA)||"Infinity")+")",t.JavaScript.ORDER_FUNCTION_CALL]},t.JavaScript.math_random_int=function(e){var o=t.JavaScript.valueToCode(e,"FROM",t.JavaScript.ORDER_COMMA)||"0";return e=t.JavaScript.valueToCode(e,"TO",t.JavaScript.ORDER_COMMA)||"0",[t.JavaScript.provideFunction_("mathRandomInt",["function "+t.JavaScript.FUNCTION_NAME_PLACEHOLDER_+"(a, b) {"," if (a > b) {"," // Swap a and b to ensure a is smaller."," var c = a;"," a = b;"," b = c;"," }"," return Math.floor(Math.random() * (b - a + 1) + a);","}"])+"("+o+", "+e+")",t.JavaScript.ORDER_FUNCTION_CALL]},t.JavaScript.math_random_float=function(e){return["Math.random()",t.JavaScript.ORDER_FUNCTION_CALL]},t.JavaScript.math_atan2=function(e){var o=t.JavaScript.valueToCode(e,"X",t.JavaScript.ORDER_COMMA)||"0";return["Math.atan2("+(t.JavaScript.valueToCode(e,"Y",t.JavaScript.ORDER_COMMA)||"0")+", "+o+") / Math.PI * 180",t.JavaScript.ORDER_DIVISION]},t.JavaScript.procedures={},t.JavaScript.procedures_defreturn=function(e){var o=t.JavaScript.variableDB_.getName(e.getFieldValue("NAME"),t.PROCEDURE_CATEGORY_NAME),i="";t.JavaScript.STATEMENT_PREFIX&&(i+=t.JavaScript.injectId(t.JavaScript.STATEMENT_PREFIX,e)),t.JavaScript.STATEMENT_SUFFIX&&(i+=t.JavaScript.injectId(t.JavaScript.STATEMENT_SUFFIX,e)),i&&(i=t.JavaScript.prefixLines(i,t.JavaScript.INDENT));var n="";t.JavaScript.INFINITE_LOOP_TRAP&&(n=t.JavaScript.prefixLines(t.JavaScript.injectId(t.JavaScript.INFINITE_LOOP_TRAP,e),t.JavaScript.INDENT));var s=t.JavaScript.statementToCode(e,"STACK"),r=t.JavaScript.valueToCode(e,"RETURN",t.JavaScript.ORDER_NONE)||"",a="";s&&r&&(a=i),r&&(r=t.JavaScript.INDENT+"return "+r+";\n");for(var l=[],c=0;c\n \n \n \n 1\n 1\n \n \n 1\n \n \n 1\n \n \n \n \n 1\n \n \n Alias\n name\n \n \n Existing Key\n tpub, WIF, hex...\n \n \n \n \n \n \n Alias\n Alice\n \n \n \n \n 1\n 1\n \n \n \n \n Alias\n Alice\n \n \n \n \n \n \n \n \n Alias\n Bob\n \n \n \n \n \n \n 99\n 1\n \n \n \n \n Alias\n KeyLikely\n \n \n \n \n \n \n \n \n Alias\n Likely\n \n \n \n \n \n \n \n \n \n \n Alias\n User\n \n \n \n \n \n \n 99\n 1\n \n \n \n \n Alias\n Service\n \n \n \n \n \n \n 12960\n \n \n \n \n \n \n 3\n \n \n \n \n \n \n Alias\n Alice\n \n \n \n \n \n \n \n \n \n \n Alias\n Bob\n \n \n \n \n \n \n \n \n \n \n Alias\n Carol\n \n \n \n \n \n \n \n \n 12960\n \n \n \n \n \n \n \n \n \n \n \n \n',collapse:!0,comments:!0,disable:!0,maxBlocks:1/0,trashcan:!0,horizontalLayout:!0,toolboxPosition:"start",css:!0,media:"https://blockly-demo.appspot.com/static/media/",rtl:!1,scrollbars:!0,sounds:!0,oneBasedIndex:!0,grid:{spacing:20,length:1,colour:"#888",snap:!0}};r.a.Blocks.pk={init:function(){this.appendValueInput("pk").setCheck("key").appendField("Key"),this.setPreviousStatement(!0,"policy"),this.setColour(260),this.setTooltip("Requires a signature with a given public key"),this.setHelpUrl("")}},r.a.Blocks.begin={init:function(){this.appendDummyInput().appendField("Begin"),this.setNextStatement(!0,"policy"),this.setColour(160),this.setTooltip("Sets the beginning of the policy"),this.setHelpUrl("")}},r.a.Blocks.existing_key={init:function(){this.appendDummyInput().appendField(new r.a.FieldLabelSerializable("Existing Key"),"NAME").appendField(new r.a.FieldTextInput("tpub, WIF, hex..."),"key"),this.setOutput(!0,"key"),this.setColour(120),this.setTooltip("Sets the value of a key to an existing WIF key, xpub or hex public key"),this.setHelpUrl("")}},r.a.Blocks.alias_key={init:function(){this.appendDummyInput().appendField(new r.a.FieldLabelSerializable("Alias"),"label").appendField(new r.a.FieldTextInput("name"),"name"),this.setOutput(!0,"key"),this.setColour(120),this.setTooltip("Sets the value of a key to an alias"),this.setHelpUrl("")}},r.a.Blocks.thresh={init:function(){this.appendDummyInput().appendField("Threshold").appendField(new r.a.FieldNumber(1,1,1/0,1),"Threshold"),this.appendStatementInput("A").setCheck("thresh").appendField("Policies"),this.setPreviousStatement(!0,"policy"),this.setColour(230),this.setTooltip("Creates a threshold element (m-of-n), where the 'm' field is manually set and 'n' is implied by the number of sub-policies added. Requies all of its children to be wrapped in the 'Entry' block"),this.setHelpUrl("")}},r.a.Blocks.older={init:function(){this.appendDummyInput().appendField("Older").appendField(new r.a.FieldNumber(1,1,1/0,1),"NAME"),this.setPreviousStatement(!0,"policy"),this.setColour(20),this.setTooltip("Requires waiting a number of blocks from the confirmation height of a UTXO before it becomes spendable"),this.setHelpUrl("")}},r.a.Blocks.after={init:function(){this.appendDummyInput().appendField("After").appendField(new r.a.FieldNumber(1,1,1/0,1),"NAME"),this.setPreviousStatement(!0,"policy"),this.setColour(20),this.setTooltip("Requires the blockchain to reach a specific block height before the UTXO becomes spendable"),this.setHelpUrl("")}},r.a.Blocks.adapter={init:function(){this.appendStatementInput("NAME").setCheck("policy").appendField("Entry"),this.setPreviousStatement(!0,"thresh"),this.setNextStatement(!0,"thresh"),this.setColour(290),this.setTooltip("Adapter used to stack policies into 'Threshold' blocks"),this.setHelpUrl("")}},r.a.Blocks.and={init:function(){this.appendStatementInput("A").setCheck("policy"),this.appendDummyInput().appendField("AND"),this.appendStatementInput("B").setCheck("policy"),this.setPreviousStatement(!0,"policy"),this.setColour(230),this.setTooltip("Requires both sub-policies to be satisfied"),this.setHelpUrl("")}},r.a.Blocks.or={init:function(){this.appendStatementInput("A").setCheck("policy").appendField("Weight").appendField(new r.a.FieldNumber(1,1),"A_weight"),this.appendDummyInput().appendField("OR"),this.appendStatementInput("B").setCheck("policy").appendField("Weight").appendField(new r.a.FieldNumber(1,1),"B_weight"),this.setPreviousStatement(!0,"policy"),this.setColour(230),this.setTooltip("Requires either one of the two sub-policies to be satisfied. Weights can be used to indicate the relative probability of each sub-policy"),this.setHelpUrl("")}},r.a.JavaScript.begin=function(e){return""},r.a.JavaScript.pk=function(e){if(!e.getParent())return"";var n=r.a.JavaScript.valueToCode(e,"pk",r.a.JavaScript.ORDER_ATOMIC);return""==n&&(n="()"),"pk"+n},r.a.JavaScript.existing_key=function(e){return e.getParent()?[e.getFieldValue("key"),r.a.JavaScript.ORDER_NONE]:["",r.a.JavaScript.ORDER_NONE]},r.a.JavaScript.alias_key=function(e){return e.getParent()?[e.getFieldValue("name"),r.a.JavaScript.ORDER_NONE]:["",r.a.JavaScript.ORDER_NONE]},r.a.JavaScript.thresh=function(e){return"thresh("+e.getFieldValue("Threshold")+","+r.a.JavaScript.statementToCode(e,"A")+")"},r.a.JavaScript.older=function(e){return e.getParent()?"older("+e.getFieldValue("NAME")+")":""},r.a.JavaScript.after=function(e){return e.getParent()?"after("+e.getFieldValue("NAME")+")":""},r.a.JavaScript.adapter=function(e){return e.getParent()?r.a.JavaScript.statementToCode(e,"NAME")+(e.getNextBlock()?",":""):""},r.a.JavaScript.and=function(e){return e.getParent()?"and("+r.a.JavaScript.statementToCode(e,"A")+","+r.a.JavaScript.statementToCode(e,"B")+")":""},r.a.JavaScript.or=function(e){if(!e.getParent())return"";var n=e.getFieldValue("A_weight");"1"==n?n="":n+="@";var t=r.a.JavaScript.statementToCode(e,"A"),i=e.getFieldValue("B_weight");return"1"==i?i="":i+="@","or("+n+t+","+i+r.a.JavaScript.statementToCode(e,"B")+")"};var o=r.a.inject(e,i);o.addChangeListener((function(e){t.value=r.a.JavaScript.workspaceToCode(o)})),o.addChangeListener(r.a.Events.disableOrphans),setTimeout(()=>{if(l.restoreBlocks(),0==o.getTopBlocks().length){var e=o.newBlock("begin");e.setDeletable(!1),e.setEditable(!1),e.moveBy(20,20),e.initSvg(),e.render()}const n=document.createElement("span");n.innerHTML='',n.style.float="right",n.style["margin-right"]="10px";let t=!1;n.onclick=function(){t?document.exitFullscreen():document.getElementById("blocklyDiv").requestFullscreen(),t=!t},document.getElementsByClassName("blocklyToolboxDiv")[0].appendChild(n)},0),l.backupOnUnload()}("blocklyDiv","policy");let e=null;document.getElementById("stdin").disabled=!0;const n=document.getElementById("start_button"),t=document.getElementById("stop_button"),o=document.getElementById("start_message");n.disabled=!1,t.disabled=!0;const a=document.getElementById("descriptor"),u=document.getElementById("change_descriptor");n.onclick=r=>{0!=a.value.length&&(r.preventDefault(),async function(e,n){const t=document.getElementById("stdout"),o=document.getElementById("stdin");o.disabled=!1;const r=[];let a=0;const l=await new i.a("testnet",e,n,"https://blockstream.info/testnet/api"),u=e=>{if("clear"!=e)return o.disabled=!0,t.innerHTML.length>0&&(t.innerHTML+="\n"),t.innerHTML+=`> ${e}\n`,a=r.push(e),l.run(e).then(e=>{e&&(t.innerHTML+=`${e}\n`)}).catch(e=>t.innerHTML+=`${e}\n`).finally(()=>{o.disabled=!1,t.scrollTop=t.scrollHeight-t.clientHeight});t.innerHTML=""};return o.onkeydown=e=>{if("Enter"==e.key){if(0==o.value.length)return;u(o.value),o.value="",e.preventDefault()}else"ArrowUp"==e.key?a>0&&(o.value=r[--a]):"ArrowDown"==e.key&&a0?u.value:null).then(i=>{n.disabled=!0,a.disabled=!0,u.disabled=!0,o.innerHTML="Wallet created, running `sync`...",i.run("sync").then(()=>o.innerHTML="Ready!"),e=i,t.disabled=!1}).catch(e=>o.innerHTML=`${e}`))},t.onclick=i=>{null!=e&&(i.preventDefault(),e.free(),o.innerHTML="Wallet instance destroyed",n.disabled=!1,t.disabled=!0,a.disabled=!1,u.disabled=!1)};const c=document.getElementById("policy"),s=document.getElementById("compiler_script_type"),d=document.getElementById("compiler_output");document.getElementById("compile_button").onclick=e=>{if(0==c.value.length)return;e.preventDefault();const n=!e.target.form.elements.namedItem("alias").length;let t=e.target.form.elements.namedItem("alias"),o=e.target.form.elements.namedItem("type"),r=e.target.form.elements.namedItem("extra");n?(t=[t],o=[o],r=[r]):(t=Array.from(t),o=Array.from(o),r=Array.from(r));const a={};t.forEach(e=>{const n=o.filter(n=>n.attributes["data-index"].value==e.attributes["data-index"].value)[0].value,t=r.filter(n=>n.attributes["data-index"].value==e.attributes["data-index"].value)[0].value,i=e.value;a[i]={type:n,extra:t}}),Object(i.nb)(c.value,JSON.stringify(a),s.value).then(e=>d.innerHTML=e).catch(e=>d.innerHTML=`${e}`)}}()},12:function(e,n,t){"use strict";var i=t.w[e.i];e.exports=i;t(2);i.n()},2:function(e,n,t){"use strict";(function(e){t.d(n,"ob",(function(){return w})),t.d(n,"nb",(function(){return _})),t.d(n,"a",(function(){return S})),t.d(n,"jb",(function(){return E})),t.d(n,"Y",(function(){return R})),t.d(n,"lb",(function(){return x})),t.d(n,"A",(function(){return B})),t.d(n,"Q",(function(){return I})),t.d(n,"l",(function(){return F})),t.d(n,"gb",(function(){return q})),t.d(n,"N",(function(){return C})),t.d(n,"L",(function(){return N})),t.d(n,"i",(function(){return M})),t.d(n,"x",(function(){return D})),t.d(n,"fb",(function(){return O})),t.d(n,"o",(function(){return H})),t.d(n,"p",(function(){return J})),t.d(n,"K",(function(){return L})),t.d(n,"R",(function(){return P})),t.d(n,"n",(function(){return U})),t.d(n,"ib",(function(){return X})),t.d(n,"j",(function(){return j})),t.d(n,"m",(function(){return W})),t.d(n,"s",(function(){return V})),t.d(n,"w",(function(){return $})),t.d(n,"Z",(function(){return K})),t.d(n,"G",(function(){return z})),t.d(n,"t",(function(){return Q})),t.d(n,"W",(function(){return G})),t.d(n,"S",(function(){return Y})),t.d(n,"r",(function(){return Z})),t.d(n,"e",(function(){return ee})),t.d(n,"T",(function(){return ne})),t.d(n,"F",(function(){return te})),t.d(n,"z",(function(){return ie})),t.d(n,"d",(function(){return oe})),t.d(n,"c",(function(){return re})),t.d(n,"B",(function(){return ae})),t.d(n,"b",(function(){return le})),t.d(n,"ab",(function(){return ue})),t.d(n,"db",(function(){return ce})),t.d(n,"eb",(function(){return se})),t.d(n,"I",(function(){return de})),t.d(n,"k",(function(){return fe})),t.d(n,"X",(function(){return pe})),t.d(n,"u",(function(){return me})),t.d(n,"g",(function(){return be})),t.d(n,"h",(function(){return he})),t.d(n,"H",(function(){return ke})),t.d(n,"J",(function(){return ye})),t.d(n,"y",(function(){return ge})),t.d(n,"D",(function(){return ve})),t.d(n,"M",(function(){return we})),t.d(n,"V",(function(){return _e})),t.d(n,"U",(function(){return Te})),t.d(n,"f",(function(){return Ae})),t.d(n,"E",(function(){return Se})),t.d(n,"C",(function(){return Ee})),t.d(n,"P",(function(){return Re})),t.d(n,"v",(function(){return xe})),t.d(n,"q",(function(){return Be})),t.d(n,"O",(function(){return Ie})),t.d(n,"kb",(function(){return Fe})),t.d(n,"cb",(function(){return qe})),t.d(n,"mb",(function(){return Ce})),t.d(n,"hb",(function(){return Ne})),t.d(n,"bb",(function(){return Me}));var i=t(12);const o=new Array(32).fill(void 0);function r(e){return o[e]}o.push(void 0,null,!0,!1);let a=o.length;function l(e){const n=r(e);return function(e){e<36||(o[e]=a,a=e)}(e),n}let u=new("undefined"==typeof TextDecoder?(0,e.require)("util").TextDecoder:TextDecoder)("utf-8",{ignoreBOM:!0,fatal:!0});u.decode();let c=null;function s(){return null!==c&&c.buffer===i.j.buffer||(c=new Uint8Array(i.j.buffer)),c}function d(e,n){return u.decode(s().subarray(e,e+n))}function f(e){a===o.length&&o.push(o.length+1);const n=a;return a=o[n],o[n]=e,n}let p=0;let m=new("undefined"==typeof TextEncoder?(0,e.require)("util").TextEncoder:TextEncoder)("utf-8");const b="function"==typeof m.encodeInto?function(e,n){return m.encodeInto(e,n)}:function(e,n){const t=m.encode(e);return n.set(t),{read:e.length,written:t.length}};function h(e,n,t){if(void 0===t){const t=m.encode(e),i=n(t.length);return s().subarray(i,i+t.length).set(t),p=t.length,i}let i=e.length,o=n(i);const r=s();let a=0;for(;a127)break;r[o+a]=n}if(a!==i){0!==a&&(e=e.slice(a)),o=t(o,i,i=a+3*e.length);const n=s().subarray(o+a,o+i);a+=b(e,n).written}return p=a,o}let k=null;function y(){return null!==k&&k.buffer===i.j.buffer||(k=new Int32Array(i.j.buffer)),k}function g(e){return null==e}function v(e,n,t){i.g(e,n,f(t))}function w(){i.i()}function _(e,n,t){var o=h(e,i.e,i.f),r=p,a=h(n,i.e,i.f),u=p,c=h(t,i.e,i.f),s=p;return l(i.h(o,r,a,u,c,s))}function T(e){return function(){try{return e.apply(this,arguments)}catch(e){i.b(f(e))}}}function A(e,n){return s().subarray(e/1,e/1+n)}class S{static __wrap(e){const n=Object.create(S.prototype);return n.ptr=e,n}free(){const e=this.ptr;this.ptr=0,i.a(e)}constructor(e,n,t,o){var r=h(e,i.e,i.f),a=p,u=h(n,i.e,i.f),c=p,s=g(t)?0:h(t,i.e,i.f),d=p,f=h(o,i.e,i.f),m=p;return l(i.k(r,a,u,c,s,d,f,m))}run(e){var n=h(e,i.e,i.f),t=p;return l(i.l(this.ptr,n,t))}}const E=function(e){l(e)},R=function(e){return f(S.__wrap(e))},x=function(e,n){return f(d(e,n))},B=function(){return f(new Error)},I=function(e,n){var t=h(r(n).stack,i.e,i.f),o=p;y()[e/4+1]=o,y()[e/4+0]=t},F=function(e,n){try{console.error(d(e,n))}finally{i.d(e,n)}},q=function(e,n){const t=r(n);var o=h(JSON.stringify(void 0===t?null:t),i.e,i.f),a=p;y()[e/4+1]=a,y()[e/4+0]=o},C=T((function(){return f(self.self)})),N=function(e,n,t){return f(r(e).require(d(n,t)))},M=function(e){return f(r(e).crypto)},D=function(e){return f(r(e).msCrypto)},O=function(e){return void 0===r(e)},H=function(e){return f(r(e).getRandomValues)},J=function(e,n,t){r(e).getRandomValues(A(n,t))},L=function(e,n,t){r(e).randomFillSync(A(n,t))},P=function(){return f(e)},U=function(e){return f(fetch(r(e)))},X=function(e){return f(r(e))},j=function(e){console.debug(r(e))},W=function(e){console.error(r(e))},V=function(e){console.info(r(e))},$=function(e){console.log(r(e))},K=function(e){console.warn(r(e))},z=T((function(e,n){return f(new Blob(r(e),r(n)))})),Q=function(e){return r(e)instanceof Response},G=function(e,n){var t=h(r(n).url,i.e,i.f),o=p;y()[e/4+1]=o,y()[e/4+0]=t},Y=function(e){return r(e).status},Z=function(e){return f(r(e).headers)},ee=T((function(e){return f(r(e).arrayBuffer())})),ne=T((function(e){return f(r(e).text())})),te=T((function(e,n,t){return f(new Request(d(e,n),r(t)))})),ie=T((function(){return f(new FormData)})),oe=T((function(e,n,t,i){r(e).append(d(n,t),r(i))})),re=T((function(e,n,t,i,o,a){r(e).append(d(n,t),r(i),d(o,a))})),ae=T((function(){return f(new Headers)})),le=T((function(e,n,t,i,o){r(e).append(d(n,t),d(i,o))})),ue=function(e){const n=l(e).original;if(1==n.cnt--)return n.a=0,!0;return!1},ce=function(e){return"function"==typeof r(e)},se=function(e){const n=r(e);return"object"==typeof n&&null!==n},de=function(e){return f(r(e).next)},fe=function(e){return r(e).done},pe=function(e){return f(r(e).value)},me=function(){return f(Symbol.iterator)},be=T((function(e,n){return f(r(e).call(r(n)))})),he=T((function(e,n,t){return f(r(e).call(r(n),r(t)))})),ke=T((function(e){return f(r(e).next())})),ye=function(){return Date.now()},ge=function(){return f(new Object)},ve=function(e,n){try{var t={a:e,b:n},o=new Promise((e,n)=>{const o=t.a;t.a=0;try{return function(e,n,t,o){i.m(e,n,f(t),f(o))}(o,t.b,e,n)}finally{t.a=o}});return f(o)}finally{t.a=t.b=0}},we=function(e){return f(Promise.resolve(r(e)))},_e=function(e,n){return f(r(e).then(r(n)))},Te=function(e,n,t){return f(r(e).then(r(n),r(t)))},Ae=function(e){return f(r(e).buffer)},Se=function(e,n,t){return f(new Uint8Array(r(e),n>>>0,t>>>0))},Ee=function(e){return f(new Uint8Array(r(e)))},Re=function(e,n,t){r(e).set(r(n),t>>>0)},xe=function(e){return r(e).length},Be=T((function(e,n){return f(Reflect.get(r(e),r(n)))})),Ie=T((function(e,n,t){return Reflect.set(r(e),r(n),r(t))})),Fe=function(e,n){const t=r(n);var o="string"==typeof t?t:void 0,a=g(o)?0:h(o,i.e,i.f),l=p;y()[e/4+1]=l,y()[e/4+0]=a},qe=function(e,n){var t=h(function e(n){const t=typeof n;if("number"==t||"boolean"==t||null==n)return""+n;if("string"==t)return`"${n}"`;if("symbol"==t){const e=n.description;return null==e?"Symbol":`Symbol(${e})`}if("function"==t){const e=n.name;return"string"==typeof e&&e.length>0?`Function(${e})`:"Function"}if(Array.isArray(n)){const t=n.length;let i="[";t>0&&(i+=e(n[0]));for(let o=1;o1))return toString.call(n);if(o=i[1],"Object"==o)try{return"Object("+JSON.stringify(n)+")"}catch(e){return"Object"}return n instanceof Error?`${n.name}: ${n.message}\n${n.stack}`:o}(r(n)),i.e,i.f),o=p;y()[e/4+1]=o,y()[e/4+0]=t},Ce=function(e,n){throw new Error(d(e,n))},Ne=function(){return f(i.j)},Me=function(e,n,t){return f(function(e,n,t,o){const r={a:e,b:n,cnt:1,dtor:t},a=(...e)=>{r.cnt++;const n=r.a;r.a=0;try{return o(n,r.b,...e)}finally{0==--r.cnt?i.c.get(r.dtor)(n,r.b):r.a=n}};return a.original=r,a}(e,n,1080,v))}}).call(this,t(11)(e))}}]); \ No newline at end of file diff --git a/static/repl/playground/25cafba91a92f4b8098c.module.wasm b/static/repl/playground/25cafba91a92f4b8098c.module.wasm deleted file mode 100644 index cdcd1360e7..0000000000 Binary files a/static/repl/playground/25cafba91a92f4b8098c.module.wasm and /dev/null differ diff --git a/static/repl/playground/playground.js b/static/repl/playground/playground.js deleted file mode 100644 index 5c4764d9b5..0000000000 --- a/static/repl/playground/playground.js +++ /dev/null @@ -1 +0,0 @@ -!function(e){function n(n){for(var t,o,_=n[0],u=n[1],c=0,f=[];c<_.length;c++)o=_[c],Object.prototype.hasOwnProperty.call(r,o)&&r[o]&&f.push(r[o][0]),r[o]=0;for(t in u)Object.prototype.hasOwnProperty.call(u,t)&&(e[t]=u[t]);for(b&&b(n);f.length;)f.shift()()}var t={},r={0:0};var o={};var _={12:function(){return{"./bdk_playground_bg.js":{__wbindgen_object_drop_ref:function(e){return t[2].exports.jb(e)},__wbg_walletwrapper_new:function(e){return t[2].exports.Y(e)},__wbindgen_string_new:function(e,n){return t[2].exports.lb(e,n)},__wbg_new_59cb74e423758ede:function(){return t[2].exports.A()},__wbg_stack_558ba5917b466edd:function(e,n){return t[2].exports.Q(e,n)},__wbg_error_4bb6c2a97407129a:function(e,n){return t[2].exports.l(e,n)},__wbindgen_json_serialize:function(e,n){return t[2].exports.gb(e,n)},__wbg_self_1c83eb4471d9eb9b:function(){return t[2].exports.N()},__wbg_require_5b2b5b594d809d9f:function(e,n,r){return t[2].exports.L(e,n,r)},__wbg_crypto_c12f14e810edcaa2:function(e){return t[2].exports.i(e)},__wbg_msCrypto_679be765111ba775:function(e){return t[2].exports.x(e)},__wbindgen_is_undefined:function(e){return t[2].exports.fb(e)},__wbg_getRandomValues_05a60bf171bfc2be:function(e){return t[2].exports.o(e)},__wbg_getRandomValues_3ac1b33c90b52596:function(e,n,r){return t[2].exports.p(e,n,r)},__wbg_randomFillSync_6f956029658662ec:function(e,n,r){return t[2].exports.K(e,n,r)},__wbg_static_accessor_MODULE_abf5ae284bffdf45:function(){return t[2].exports.R()},__wbg_fetch_f5b2195afedb6a6b:function(e){return t[2].exports.n(e)},__wbindgen_object_clone_ref:function(e){return t[2].exports.ib(e)},__wbg_debug_b443de592faba09f:function(e){return t[2].exports.j(e)},__wbg_error_7f083efc6bc6752c:function(e){return t[2].exports.m(e)},__wbg_info_6d4a86f0fd590270:function(e){return t[2].exports.s(e)},__wbg_log_3bafd82835c6de6d:function(e){return t[2].exports.w(e)},__wbg_warn_d05e82888b7fad05:function(e){return t[2].exports.Z(e)},__wbg_newwithu8arraysequenceandoptions_ae6479c676bebdcf:function(e,n){return t[2].exports.G(e,n)},__wbg_instanceof_Response_328c03967a8e8902:function(e){return t[2].exports.t(e)},__wbg_url_67bbdafba8ff6e85:function(e,n){return t[2].exports.W(e,n)},__wbg_status_eb6dbb31556c329f:function(e){return t[2].exports.S(e)},__wbg_headers_c736e1fe38752cff:function(e){return t[2].exports.r(e)},__wbg_arrayBuffer_dc33ab7b8cdf0d63:function(e){return t[2].exports.e(e)},__wbg_text_966d07536ca6ccdc:function(e){return t[2].exports.T(e)},__wbg_newwithstrandinit_d1de1bfcd175e38a:function(e,n,r){return t[2].exports.F(e,n,r)},__wbg_new_43d9cb1835f877ad:function(){return t[2].exports.z()},__wbg_append_f76809690e4b2f3a:function(e,n,r,o){return t[2].exports.d(e,n,r,o)},__wbg_append_eaa42b75460769af:function(e,n,r,o,_,u){return t[2].exports.c(e,n,r,o,_,u)},__wbg_new_8469604d5504c189:function(){return t[2].exports.B()},__wbg_append_cc6fe0273163a31b:function(e,n,r,o,_){return t[2].exports.b(e,n,r,o,_)},__wbindgen_cb_drop:function(e){return t[2].exports.ab(e)},__wbindgen_is_function:function(e){return t[2].exports.db(e)},__wbindgen_is_object:function(e){return t[2].exports.eb(e)},__wbg_next_edda7e0003e5daf9:function(e){return t[2].exports.I(e)},__wbg_done_037d0a173aef1834:function(e){return t[2].exports.k(e)},__wbg_value_e60bbfb7d52af62f:function(e){return t[2].exports.X(e)},__wbg_iterator_09191f8878ea9877:function(){return t[2].exports.u()},__wbg_call_8e95613cc6524977:function(e,n){return t[2].exports.g(e,n)},__wbg_call_d713ea0274dfc6d2:function(e,n,r){return t[2].exports.h(e,n,r)},__wbg_next_2966fa909601a075:function(e){return t[2].exports.H(e)},__wbg_now_4de5b53a19e45567:function(){return t[2].exports.J()},__wbg_new_3e06d4f36713e4cb:function(){return t[2].exports.y()},__wbg_new_d0c63652ab4d825c:function(e,n){return t[2].exports.D(e,n)},__wbg_resolve_2529512c3bb73938:function(e){return t[2].exports.M(e)},__wbg_then_4a7a614abbbe6d81:function(e,n){return t[2].exports.V(e,n)},__wbg_then_3b7ac098cfda2fa5:function(e,n,r){return t[2].exports.U(e,n,r)},__wbg_buffer_49131c283a06686f:function(e){return t[2].exports.f(e)},__wbg_newwithbyteoffsetandlength_c0f38401daad5a22:function(e,n,r){return t[2].exports.E(e,n,r)},__wbg_new_9b295d24cf1d706f:function(e){return t[2].exports.C(e)},__wbg_set_3bb960a9975f3cd2:function(e,n,r){return t[2].exports.P(e,n,r)},__wbg_length_2b13641a9d906653:function(e){return t[2].exports.v(e)},__wbg_get_0e3f2950cdf758ae:function(e,n){return t[2].exports.q(e,n)},__wbg_set_304f2ec1a3ab3b79:function(e,n,r){return t[2].exports.O(e,n,r)},__wbindgen_string_get:function(e,n){return t[2].exports.kb(e,n)},__wbindgen_debug_string:function(e,n){return t[2].exports.cb(e,n)},__wbindgen_throw:function(e,n){return t[2].exports.mb(e,n)},__wbindgen_memory:function(){return t[2].exports.hb()},__wbindgen_closure_wrapper7033:function(e,n,r){return t[2].exports.bb(e,n,r)}}}}};function u(n){if(t[n])return t[n].exports;var r=t[n]={i:n,l:!1,exports:{}};return e[n].call(r.exports,r,r.exports,u),r.l=!0,r.exports}u.e=function(e){var n=[],t=r[e];if(0!==t)if(t)n.push(t[2]);else{var c=new Promise((function(n,o){t=r[e]=[n,o]}));n.push(t[2]=c);var f,i=document.createElement("script");i.charset="utf-8",i.timeout=120,u.nc&&i.setAttribute("nonce",u.nc),i.src=function(e){return u.p+""+e+".playground.js"}(e);var b=new Error;f=function(n){i.onerror=i.onload=null,clearTimeout(a);var t=r[e];if(0!==t){if(t){var o=n&&("load"===n.type?"missing":n.type),_=n&&n.target&&n.target.src;b.message="Loading chunk "+e+" failed.\n("+o+": "+_+")",b.name="ChunkLoadError",b.type=o,b.request=_,t[1](b)}r[e]=void 0}};var a=setTimeout((function(){f({type:"timeout",target:i})}),12e4);i.onerror=i.onload=f,document.head.appendChild(i)}return({2:[12]}[e]||[]).forEach((function(e){var t=o[e];if(t)n.push(t);else{var r,c=_[e](),f=fetch(u.p+""+{12:"25cafba91a92f4b8098c"}[e]+".module.wasm");if(c instanceof Promise&&"function"==typeof WebAssembly.compileStreaming)r=Promise.all([WebAssembly.compileStreaming(f),c]).then((function(e){return WebAssembly.instantiate(e[0],e[1])}));else if("function"==typeof WebAssembly.instantiateStreaming)r=WebAssembly.instantiateStreaming(f,c);else{r=f.then((function(e){return e.arrayBuffer()})).then((function(e){return WebAssembly.instantiate(e,c)}))}n.push(o[e]=r.then((function(n){return u.w[e]=(n.instance||n).exports})))}})),Promise.all(n)},u.m=e,u.c=t,u.d=function(e,n,t){u.o(e,n)||Object.defineProperty(e,n,{enumerable:!0,get:t})},u.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},u.t=function(e,n){if(1&n&&(e=u(e)),8&n)return e;if(4&n&&"object"==typeof e&&e&&e.__esModule)return e;var t=Object.create(null);if(u.r(t),Object.defineProperty(t,"default",{enumerable:!0,value:e}),2&n&&"string"!=typeof e)for(var r in e)u.d(t,r,function(n){return e[n]}.bind(null,r));return t},u.n=function(e){var n=e&&e.__esModule?function(){return e.default}:function(){return e};return u.d(n,"a",n),n},u.o=function(e,n){return Object.prototype.hasOwnProperty.call(e,n)},u.p="/repl/playground/",u.oe=function(e){throw console.error(e),e},u.w={};var c=window.webpackJsonp=window.webpackJsonp||[],f=c.push.bind(c);c.push=n,c=c.slice();for(var i=0;iconsole.error("Error importing `index.js`:",e))}]); \ No newline at end of file