]> Untitled Git - bitcoindevkit.org/commitdiff
Rename repl to bdk-cli and update related docs
authorSteve Myers <steve@notmandatory.org>
Thu, 7 Jan 2021 04:50:24 +0000 (20:50 -0800)
committerSteve Myers <steve@notmandatory.org>
Tue, 12 Jan 2021 18:13:01 +0000 (10:13 -0800)
26 files changed:
config.toml
content/_index.md
content/bdk-cli/_index.md [new file with mode: 0644]
content/bdk-cli/compiler.md [new file with mode: 0644]
content/bdk-cli/concept.md [new file with mode: 0644]
content/bdk-cli/installation.md [new file with mode: 0644]
content/bdk-cli/interface.md [new file with mode: 0644]
content/bdk-cli/playground.md [new file with mode: 0644]
content/bdk-cli/regtest.md [new file with mode: 0644]
content/repl/_index.md [deleted file]
content/repl/compiler.md [deleted file]
content/repl/concept.md [deleted file]
content/repl/installation.md [deleted file]
content/repl/interface.md [deleted file]
content/repl/playground.md [deleted file]
content/repl/regtest.md [deleted file]
playground/www/index.html
playground/www/webpack.config.js
static/bdk-cli/playground/1.playground.js [new file with mode: 0644]
static/bdk-cli/playground/2.playground.js [new file with mode: 0644]
static/bdk-cli/playground/25cafba91a92f4b8098c.module.wasm [new file with mode: 0644]
static/bdk-cli/playground/playground.js [new file with mode: 0644]
static/repl/playground/1.playground.js [deleted file]
static/repl/playground/2.playground.js [deleted file]
static/repl/playground/25cafba91a92f4b8098c.module.wasm [deleted file]
static/repl/playground/playground.js [deleted file]

index a670f79e164408db8b13e4d6d3038aefc7f59b16..60e9bb6ab21eeb3e1661b90b89e01b468d0b7956 100644 (file)
@@ -58,7 +58,7 @@ weight = 5
 
 [[Languages.en.menu.shortcuts]]
 name = "<i class='fas fa-magic'></i> Playground"
-url = "/repl/playground"
+url = "/bdk-cli/playground"
 weight = 10
 
 [[Languages.en.menu.shortcuts]]
index f256540f9954c8236635b8a3bd72cfb582f5ed9f..90fbd26b7fedf733a503d04336405f895775a320 100644 (file)
@@ -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 (file)
index 0000000..92b80b0
--- /dev/null
@@ -0,0 +1,13 @@
++++
+title = "BDK CLI"
+date = 2020-04-28T17:03:00+02:00
+weight = 1
+chapter = true
+pre = '<i class="fas fa-terminal"></i> '
++++
+
+# 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 (file)
index 0000000..39ebea0
--- /dev/null
@@ -0,0 +1,151 @@
+---
+title: "Compiler"
+date: 2020-04-29T12:06:50+02:00
+draft: false
+weight: 5
+pre: "<b>5. </b>"
+---
+
+## 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 (file)
index 0000000..96078ea
--- /dev/null
@@ -0,0 +1,26 @@
+---
+title: "Concept"
+date: 2020-04-28T17:38:20+02:00
+draft: false
+weight: 2
+pre: "<b>2. </b>"
+---
+
+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 (file)
index 0000000..4fa8b00
--- /dev/null
@@ -0,0 +1,92 @@
+---
+title: "Installation"
+date: 2020-04-28T17:11:29+02:00
+draft: false
+weight: 1
+pre: "<b>1. </b>"
+---
+
+## 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 <alekos.filini@gmail.com>:Riccardo Casatta <riccardo@casatta.it>
+A modern, lightweight, descriptor-based wallet
+
+USAGE:
+    bdk-cli [OPTIONS] --descriptor <DESCRIPTOR> <SUBCOMMAND>
+
+FLAGS:
+    -h, --help       Prints help information
+    -V, --version    Prints version information
+
+OPTIONS:
+    -c, --change_descriptor <CHANGE_DESCRIPTOR>        Sets the descriptor to use for internal addresses
+    -d, --descriptor <DESCRIPTOR>                      Sets the descriptor to use for the external addresses
+        --esplora_concurrency <ESPLORA_CONCURRENCY>    Concurrency of requests made to the esplora server [default: 4]
+    -e, --esplora <ESPLORA_URL>                        Use the esplora server if given as parameter
+    -n, --network <NETWORK>                            Sets the network [default: testnet]
+    -p, --proxy <PROXY_SERVER:PORT>                    Sets the SOCKS5 proxy for the Electrum client
+    -s, --server <SERVER:PORT>
+            Sets the Electrum server to use [default: ssl://electrum.blockstream.info:60002]
+
+    -w, --wallet <WALLET_NAME>                         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 (file)
index 0000000..83f9666
--- /dev/null
@@ -0,0 +1,531 @@
+---
+title: "Interface"
+date: 2020-04-28T18:20:28+02:00
+draft: false
+weight: 3
+pre: "<b>3. </b>"
+---
+
+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 <CHANGE_DESCRIPTOR>        Sets the descriptor to use for internal addresses
+    -d, --descriptor <DESCRIPTOR>                      Sets the descriptor to use for the external addresses
+        --esplora_concurrency <ESPLORA_CONCURRENCY>    Concurrency of requests made to the esplora server [default: 4]
+    -e, --esplora <ESPLORA_URL>                        Use the esplora server if given as parameter
+    -n, --network <NETWORK>                            Sets the network [default: testnet]
+    -p, --proxy <PROXY_SERVER:PORT>                    Sets the SOCKS5 proxy for the Electrum client
+    -s, --server <SERVER:PORT>
+            Sets the Electrum server to use [default: ssl://electrum.blockstream.info:60002]
+
+    -w, --wallet <WALLET_NAME>                         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 <subcommand> --help`.
+
+### broadcast
+
+```text
+OPTIONS:
+        --psbt <BASE64_PSBT>    Sets the PSBT to extract and broadcast
+        --tx <RAWTX>            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 <SATS_VBYTE>         The new targeted fee rate in sat/vbyte
+    -t, --txid <txid>                   TXID of the transaction to update
+        --unspendable <TXID:VOUT>...    Marks an utxo as unspendable, in case more inputs are needed to cover the extra
+                                        fees
+        --utxos <TXID:VOUT>...          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 <BASE64_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 <ADDRESS:SAT>...                      Adds a recipient to the transaction
+        --unspendable <CANT_SPEND_TXID:VOUT>...    Marks a utxo as unspendable
+        --external_policy <EXT_POLICY>
+            Selects which policy should be used to satisfy the external descriptor
+
+        --internal_policy <INT_POLICY>
+            Selects which policy should be used to satisfy the internal descriptor
+
+        --utxos <MUST_SPEND_TXID:VOUT>...          Selects which utxos *must* be spent
+    -f, --fee_rate <SATS_VBYTE>                    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.
+
+{{<mermaid align="center">}}
+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 <BASE64_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 <BASE64_PSBT>        Sets the PSBT to finalize
+        --assume_height <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 <BASE64_PSBT>        Sets the PSBT to sign
+          --assume_height <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 (file)
index 0000000..f135f93
--- /dev/null
@@ -0,0 +1,9 @@
+---
+title: "Playground"
+date: 2020-05-08T15:42:22+02:00
+draft: false
+weight: 6
+pre: "<b>6. </b>"
+---
+
+{{< playground >}}
diff --git a/content/bdk-cli/regtest.md b/content/bdk-cli/regtest.md
new file mode 100644 (file)
index 0000000..c7ef600
--- /dev/null
@@ -0,0 +1,52 @@
+---
+title: "Regtest"
+date: 2020-04-29T00:19:34+02:00
+draft: false
+weight: 4
+pre: "<b>4. </b>"
+---
+
+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 <address>`
+
+## 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 (file)
index fd9d9c7..0000000
+++ /dev/null
@@ -1,12 +0,0 @@
-+++
-title = "REPL"
-date = 2020-04-28T17:03:00+02:00
-weight = 5
-chapter = true
-pre = '<i class="fas fa-terminal"></i> '
-+++
-
-# 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 (file)
index 9b717a3..0000000
+++ /dev/null
@@ -1,151 +0,0 @@
----
-title: "Compiler"
-date: 2020-04-29T12:06:50+02:00
-draft: false
-weight: 5
-pre: "<b>5. </b>"
----
-
-## 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 (file)
index 9c9989f..0000000
+++ /dev/null
@@ -1,26 +0,0 @@
----
-title: "Concept"
-date: 2020-04-28T17:38:20+02:00
-draft: false
-weight: 2
-pre: "<b>2. </b>"
----
-
-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 (file)
index 9d0130c..0000000
+++ /dev/null
@@ -1,71 +0,0 @@
----
-title: "Installation"
-date: 2020-04-28T17:11:29+02:00
-draft: false
-weight: 1
-pre: "<b>1. </b>"
----
-
-## 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 <riccardo@casatta.it>:Alekos Filini <alekos.filini@gmail.com>
-A modern, lightweight, descriptor-based wallet
-
-USAGE:
-    repl [FLAGS] [OPTIONS] --descriptor <DESCRIPTOR> [SUBCOMMAND]
-
-FLAGS:
-    -h, --help       Prints help information
-    -v               Sets the level of verbosity
-    -V, --version    Prints version information
-
-OPTIONS:
-    -c, --change_descriptor <DESCRIPTOR>    Sets the descriptor to use for internal addresses
-    -d, --descriptor <DESCRIPTOR>           Sets the descriptor to use for the external addresses
-    -n, --network <NETWORK>                 Sets the network [default: testnet]  [possible values: testnet, regtest]
-    -s, --server <SERVER:PORT>              Sets the Electrum server to use [default: tn.not.fyi:55001]
-    -w, --wallet <WALLET_NAME>              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 (file)
index 0de6b50..0000000
+++ /dev/null
@@ -1,524 +0,0 @@
----
-title: "Interface"
-date: 2020-04-28T18:20:28+02:00
-draft: false
-weight: 3
-pre: "<b>3. </b>"
----
-
-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 <DESCRIPTOR>    Sets the descriptor to use for internal addresses
-    -d, --descriptor <DESCRIPTOR>           Sets the descriptor to use for the external addresses
-    -e, --esplora <ESPLORA>                 Use the esplora server if given as parameter
-    -n, --network <NETWORK>                 Sets the network [default: testnet]  [possible values: testnet, regtest]
-    -s, --server <SERVER:PORT>              Sets the Electrum server to use [default:
-                                            ssl://electrum.blockstream.info:60002]
-    -w, --wallet <WALLET_NAME>              Selects the wallet to use [default: main]
-    -p, --proxy <SERVER:PORT>               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 <subcommand> --help`.
-
-### broadcast
-
-```text
-OPTIONS:
-        --psbt <BASE64_PSBT>    Sets the PSBT to extract and broadcast
-        --tx <RAWTX>            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 <SATS_VBYTE>         The new targeted fee rate in sat/vbyte
-    -t, --txid <txid>                   TXID of the transaction to update
-        --unspendable <TXID:VOUT>...    Marks an utxo as unspendable, in case more inputs are needed to cover the extra
-                                        fees
-        --utxos <TXID:VOUT>...          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 <BASE64_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 <POLICY>      Selects which policy should be used to satisfy the external descriptor
-    -f, --fee_rate <SATS_VBYTE>         Fee rate to use in sat/vbyte
-        --internal_policy <POLICY>      Selects which policy should be used to satisfy the internal descriptor
-        --to <ADDRESS:SAT>...           Adds an addressee to the transaction
-        --unspendable <TXID:VOUT>...    Marks an utxo as unspendable
-        --utxos <TXID:VOUT>...          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.
-
-{{<mermaid align="center">}}
-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 <BASE64_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 <HEIGHT>    Assume the blockchain has reached a specific height
-        --psbt <BASE64_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 <HEIGHT>    Assume the blockchain has reached a specific height. This affects the transaction
-                                    finalization, if there are timelocks in the descriptor
-        --psbt <BASE64_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 (file)
index f135f93..0000000
+++ /dev/null
@@ -1,9 +0,0 @@
----
-title: "Playground"
-date: 2020-05-08T15:42:22+02:00
-draft: false
-weight: 6
-pre: "<b>6. </b>"
----
-
-{{< playground >}}
diff --git a/content/repl/regtest.md b/content/repl/regtest.md
deleted file mode 100644 (file)
index b626c9d..0000000
+++ /dev/null
@@ -1,52 +0,0 @@
----
-title: "Regtest"
-date: 2020-04-29T00:19:34+02:00
-draft: false
-weight: 4
-pre: "<b>4. </b>"
----
-
-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 <address>`
-
-## 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.
index 20a22dc8bccd826ad79197f8df4eb1dd25548506..6f032210dec150e7df4cb2f42a26143d1469312a 100644 (file)
@@ -3,4 +3,4 @@
 
 <button onclick="javascript:document.getElementById('blocklyDiv').requestFullscreen()">FS</button>
 
-<script src="/repl/playground/playground.js"></script>
+<script src="/bdk-cli/playground/playground.js"></script>
index a84f692a35a82cc881db7c5571063e3d035f230e..26a6652bee2a1f3d957fba74f3132131fba21aa6 100644 (file)
@@ -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 (file)
index 0000000..87e47df
--- /dev/null
@@ -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.length<e.length?t:e})).length:0},t.utils.string.commonWordPrefix=function(e,o){if(!e.length)return 0;if(1==e.length)return e[0].length;var i=0;o=o||t.utils.string.shortestStringLength(e);for(var n=0;n<o;n++){for(var s=e[0][n],r=1;r<e.length;r++)if(s!=e[r][n])return i;" "==s&&(i=n+1)}for(r=1;r<e.length;r++)if((s=e[r][n])&&" "!=s)return i;return o},t.utils.string.commonWordSuffix=function(e,o){if(!e.length)return 0;if(1==e.length)return e[0].length;var i=0;o=o||t.utils.string.shortestStringLength(e);for(var n=0;n<o;n++){for(var s=e[0].substr(-n-1,1),r=1;r<e.length;r++)if(s!=e[r].substr(-n-1,1))return i;" "==s&&(i=n+1)}for(r=1;r<e.length;r++)if((s=e[r].charAt(e[r].length-n-1))&&" "!=s)return i;return o},t.utils.string.wrap=function(e,o){e=e.split("\n");for(var i=0;i<e.length;i++)e[i]=t.utils.string.wrapLine_(e[i],o);return e.join("\n")},t.utils.string.wrapLine_=function(e,o){if(e.length<=o)return e;for(var i=e.trim().split(/\s+/),n=0;n<i.length;n++)i[n].length>o&&(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;n<i.length-1;n++)c<(n+1.5)/l?(c++,e[n]=!0):e[n]=!1;e=t.utils.string.wrapMutate_(i,e,o),n=t.utils.string.wrapScore_(i,e,o),e=t.utils.string.wrapToText_(i,e),s++}while(n>r);return a},t.utils.string.wrapScore_=function(t,e,o){for(var i=[0],n=[],s=0;s<t.length;s++)i[i.length-1]+=t[s].length,!0===e[s]?(i.push(0),n.push(t[s].charAt(t[s].length-1))):!1===e[s]&&i[i.length-1]++;for(t=Math.max.apply(Math,i),s=e=0;s<i.length;s++)e-=2*Math.pow(Math.abs(o-i[s]),1.5),e-=Math.pow(t-i[s],1.5),-1!=".?!".indexOf(n[s])?e+=o/3:-1!=",;)]}".indexOf(n[s])&&(e+=o/4);return 1<i.length&&i[i.length-1]<=i[i.length-2]&&(e+=.5),e},t.utils.string.wrapMutate_=function(e,o,i){for(var n,s=t.utils.string.wrapScore_(e,o,i),r=0;r<o.length-1;r++)if(o[r]!=o[r+1]){var a=[].concat(o);a[r]=!a[r],a[r+1]=!a[r+1];var l=t.utils.string.wrapScore_(e,a,i);l>s&&(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<t.length;i++)o.push(t[i]),void 0!==e[i]&&o.push(e[i]?"\n":" ");return o.join("")},t.utils.Size=function(t,e){this.width=t,this.height=e},t.utils.Size.equals=function(t,e){return t==e||!(!t||!e)&&t.width==e.width&&t.height==e.height},t.utils.style={},t.utils.style.getSize=function(e){if("none"!=t.utils.style.getStyle_(e,"display"))return t.utils.style.getSizeWithDisplay_(e);var o=e.style,i=o.display,n=o.visibility,s=o.position;o.visibility="hidden",o.position="absolute",o.display="inline";var r=e.offsetWidth;return e=e.offsetHeight,o.display=i,o.position=s,o.visibility=n,new t.utils.Size(r,e)},t.utils.style.getSizeWithDisplay_=function(e){return new t.utils.Size(e.offsetWidth,e.offsetHeight)},t.utils.style.getStyle_=function(e,o){return t.utils.style.getComputedStyle(e,o)||t.utils.style.getCascadedStyle(e,o)||e.style&&e.style[o]},t.utils.style.getComputedStyle=function(t,e){return document.defaultView&&document.defaultView.getComputedStyle&&(t=document.defaultView.getComputedStyle(t,null))&&(t[e]||t.getPropertyValue(e))||""},t.utils.style.getCascadedStyle=function(t,e){return t.currentStyle?t.currentStyle[e]:null},t.utils.style.getPageOffset=function(e){var o=new t.utils.Coordinate(0,0);e=e.getBoundingClientRect();var i=document.documentElement;return i=new t.utils.Coordinate(window.pageXOffset||i.scrollLeft,window.pageYOffset||i.scrollTop),o.x=e.left+i.x,o.y=e.top+i.y,o},t.utils.style.getViewportPageOffset=function(){var e=document.body,o=document.documentElement;return new t.utils.Coordinate(e.scrollLeft||o.scrollLeft,e.scrollTop||o.scrollTop)},t.utils.style.setElementShown=function(t,e){t.style.display=e?"":"none"},t.utils.style.isRightToLeft=function(e){return"rtl"==t.utils.style.getStyle_(e,"direction")},t.utils.style.getBorderBox=function(e){var o=t.utils.style.getComputedStyle(e,"borderLeftWidth"),i=t.utils.style.getComputedStyle(e,"borderRightWidth"),n=t.utils.style.getComputedStyle(e,"borderTopWidth");return e=t.utils.style.getComputedStyle(e,"borderBottomWidth"),{top:parseFloat(n),right:parseFloat(i),bottom:parseFloat(e),left:parseFloat(o)}},t.utils.style.scrollIntoContainerView=function(e,o,i){e=t.utils.style.getContainerOffsetToScrollInto(e,o,i),o.scrollLeft=e.x,o.scrollTop=e.y},t.utils.style.getContainerOffsetToScrollInto=function(e,o,i){var n=t.utils.style.getPageOffset(e),s=t.utils.style.getPageOffset(o),r=t.utils.style.getBorderBox(o),a=n.x-s.x-r.left;return n=n.y-s.y-r.top,s=t.utils.style.getSizeWithDisplay_(e),e=o.clientWidth-s.width,s=o.clientHeight-s.height,r=o.scrollLeft,o=o.scrollTop,i?(r+=a-e/2,o+=n-s/2):(r+=Math.min(a,Math.max(a-e,0)),o+=Math.min(n,Math.max(n-s,0))),new t.utils.Coordinate(r,o)},t.utils.userAgent={},function(e){function o(t){return-1!=i.indexOf(t.toUpperCase())}t.utils.userAgent.raw=e;var i=t.utils.userAgent.raw.toUpperCase();t.utils.userAgent.IE=o("Trident")||o("MSIE"),t.utils.userAgent.EDGE=o("Edge"),t.utils.userAgent.JAVA_FX=o("JavaFX"),t.utils.userAgent.CHROME=(o("Chrome")||o("CriOS"))&&!t.utils.userAgent.EDGE,t.utils.userAgent.WEBKIT=o("WebKit")&&!t.utils.userAgent.EDGE,t.utils.userAgent.GECKO=o("Gecko")&&!t.utils.userAgent.WEBKIT&&!t.utils.userAgent.IE&&!t.utils.userAgent.EDGE,t.utils.userAgent.ANDROID=o("Android"),t.utils.userAgent.IPAD=o("iPad"),t.utils.userAgent.IPOD=o("iPod"),t.utils.userAgent.IPHONE=o("iPhone")&&!t.utils.userAgent.IPAD&&!t.utils.userAgent.IPOD,t.utils.userAgent.MAC=o("Macintosh"),t.utils.userAgent.TABLET=t.utils.userAgent.IPAD||t.utils.userAgent.ANDROID&&!o("Mobile")||o("Silk"),t.utils.userAgent.MOBILE=!t.utils.userAgent.TABLET&&(t.utils.userAgent.IPOD||t.utils.userAgent.IPHONE||t.utils.userAgent.ANDROID||o("IEMobile"))}(t.utils.global.navigator&&t.utils.global.navigator.userAgent||""),t.utils.noEvent=function(t){t.preventDefault(),t.stopPropagation()},t.utils.isTargetInput=function(t){return"textarea"==t.target.type||"text"==t.target.type||"number"==t.target.type||"email"==t.target.type||"password"==t.target.type||"search"==t.target.type||"tel"==t.target.type||"url"==t.target.type||t.target.isContentEditable},t.utils.getRelativeXY=function(e){var o=new t.utils.Coordinate(0,0),i=e.getAttribute("x");return i&&(o.x=parseInt(i,10)),(i=e.getAttribute("y"))&&(o.y=parseInt(i,10)),(i=(i=e.getAttribute("transform"))&&i.match(t.utils.getRelativeXY.XY_REGEX_))&&(o.x+=Number(i[1]),i[3]&&(o.y+=Number(i[3]))),(e=e.getAttribute("style"))&&-1<e.indexOf("translate")&&(e=e.match(t.utils.getRelativeXY.XY_STYLE_REGEX_))&&(o.x+=Number(e[1]),e[3]&&(o.y+=Number(e[3]))),o},t.utils.getInjectionDivXY_=function(e){for(var o=0,i=0;e;){var n=t.utils.getRelativeXY(e);if(o+=n.x,i+=n.y,-1!=(" "+(e.getAttribute("class")||"")+" ").indexOf(" injectionDiv "))break;e=e.parentNode}return new t.utils.Coordinate(o,i)},t.utils.getRelativeXY.XY_REGEX_=/translate\(\s*([-+\d.e]+)([ ,]\s*([-+\d.e]+)\s*)?/,t.utils.getRelativeXY.XY_STYLE_REGEX_=/transform:\s*translate(?:3d)?\(\s*([-+\d.e]+)\s*px([ ,]\s*([-+\d.e]+)\s*px)?/,t.utils.isRightButton=function(e){return!(!e.ctrlKey||!t.utils.userAgent.MAC)||2==e.button},t.utils.mouseToSvg=function(t,e,o){var i=e.createSVGPoint();return i.x=t.clientX,i.y=t.clientY,o||(o=e.getScreenCTM().inverse()),i.matrixTransform(o)},t.utils.getScrollDeltaPixels=function(e){switch(e.deltaMode){default:return{x:e.deltaX,y:e.deltaY};case 1:return{x:e.deltaX*t.LINE_MODE_MULTIPLIER,y:e.deltaY*t.LINE_MODE_MULTIPLIER};case 2:return{x:e.deltaX*t.PAGE_MODE_MULTIPLIER,y:e.deltaY*t.PAGE_MODE_MULTIPLIER}}},t.utils.tokenizeInterpolation=function(e){return t.utils.tokenizeInterpolation_(e,!0)},t.utils.replaceMessageReferences=function(e){return"string"!=typeof e?e:(e=t.utils.tokenizeInterpolation_(e,!1)).length?String(e[0]):""},t.utils.checkMessageReferences=function(e){for(var o=!0,i=t.Msg,n=e.match(/%{BKY_[A-Z]\w*}/gi),s=0;s<n.length;s++)null==i[n[s].toUpperCase().slice(6,-1)]&&(console.log("WARNING: No message string for "+n[s]+" in "+e),o=!1);return o},t.utils.tokenizeInterpolation_=function(e,o){var i=[],n=e.split("");n.push("");var s=0;e=[];for(var r=null,a=0;a<n.length;a++){var l=n[a];0==s?"%"==l?((l=e.join(""))&&i.push(l),e.length=0,s=1):e.push(l):1==s?"%"==l?(e.push(l),s=0):o&&"0"<=l&&"9">=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;a<i.length;++a)"string"==typeof i[a]?e.push(i[a]):((l=e.join(""))&&o.push(l),e.length=0,o.push(i[a]));return(l=e.join(""))&&o.push(l),e.length=0,o},t.utils.genUid=function(){for(var e=t.utils.genUid.soup_.length,o=[],i=0;20>i;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;i<o.length;i++)o[i]&&o[i]!=e||(o.splice(i,1),i--);return o.length?t.setAttribute("class",o.join(" ")):t.removeAttribute("class"),!0},t.utils.dom.hasClass=function(t,e){return-1!=(" "+t.getAttribute("class")+" ").indexOf(" "+e+" ")},t.utils.dom.removeNode=function(t){return t&&t.parentNode?t.parentNode.removeChild(t):null},t.utils.dom.insertAfter=function(t,e){var o=e.nextSibling;if(!(e=e.parentNode))throw Error("Reference node has no parent.");o?e.insertBefore(t,o):e.appendChild(t)},t.utils.dom.containsNode=function(e,o){return!!(e.compareDocumentPosition(o)&t.utils.dom.Node.DOCUMENT_POSITION_CONTAINED_BY)},t.utils.dom.setCssTransform=function(t,e){t.style.transform=e,t.style["-webkit-transform"]=e},t.utils.dom.startTextWidthCache=function(){t.utils.dom.cacheReference_++,t.utils.dom.cacheWidths_||(t.utils.dom.cacheWidths_={})},t.utils.dom.stopTextWidthCache=function(){t.utils.dom.cacheReference_--,t.utils.dom.cacheReference_||(t.utils.dom.cacheWidths_=null)},t.utils.dom.getTextWidth=function(e){var o,i=e.textContent+"\n"+e.className.baseVal;if(t.utils.dom.cacheWidths_&&(o=t.utils.dom.cacheWidths_[i]))return o;try{o=t.utils.userAgent.IE||t.utils.userAgent.EDGE?e.getBBox().width:e.getComputedTextLength()}catch(t){return 8*e.textContent.length}return t.utils.dom.cacheWidths_&&(t.utils.dom.cacheWidths_[i]=o),o},t.utils.dom.getFastTextWidth=function(e,o,i,n){return t.utils.dom.getFastTextWidthWithSizeString(e,o+"pt",i,n)},t.utils.dom.getFastTextWidthWithSizeString=function(e,o,i,n){var s,r=e.textContent;return e=r+"\n"+e.className.baseVal,t.utils.dom.cacheWidths_&&(s=t.utils.dom.cacheWidths_[e])||(t.utils.dom.canvasContext_||((s=document.createElement("canvas")).className="blocklyComputeCanvas",document.body.appendChild(s),t.utils.dom.canvasContext_=s.getContext("2d")),t.utils.dom.canvasContext_.font=i+" "+o+" "+n,s=t.utils.dom.canvasContext_.measureText(r).width,t.utils.dom.cacheWidths_&&(t.utils.dom.cacheWidths_[e]=s)),s},t.utils.dom.measureFontMetrics=function(t,e,o,i){var n=document.createElement("span");n.style.font=o+" "+e+" "+i,n.textContent=t,(t=document.createElement("div")).style.width="1px",t.style.height="0px",(e=document.createElement("div")).setAttribute("style","position: fixed; top: 0; left: 0; display: flex;"),e.appendChild(n),e.appendChild(t),document.body.appendChild(e);try{o={},e.style.alignItems="baseline",o.baseline=t.offsetTop-n.offsetTop,e.style.alignItems="flex-end",o.height=t.offsetTop-n.offsetTop}finally{document.body.removeChild(e)}return o},t.BlockDragSurfaceSvg=function(t){this.container_=t,this.createDom()},t.BlockDragSurfaceSvg.prototype.SVG_=null,t.BlockDragSurfaceSvg.prototype.dragGroup_=null,t.BlockDragSurfaceSvg.prototype.container_=null,t.BlockDragSurfaceSvg.prototype.scale_=1,t.BlockDragSurfaceSvg.prototype.surfaceXY_=null,t.BlockDragSurfaceSvg.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:"blocklyBlockDragSurface"},this.container_),this.dragGroup_=t.utils.dom.createSvgElement("g",{},this.SVG_))},t.BlockDragSurfaceSvg.prototype.setBlocksAndShow=function(e){if(this.dragGroup_.childNodes.length)throw Error("Already dragging a block.");this.dragGroup_.appendChild(e),this.SVG_.style.display="block",this.surfaceXY_=new t.utils.Coordinate(0,0)},t.BlockDragSurfaceSvg.prototype.translateAndScaleGroup=function(t,e,o){this.scale_=o,t=t.toFixed(0),e=e.toFixed(0),this.dragGroup_.setAttribute("transform","translate("+t+","+e+") scale("+o+")")},t.BlockDragSurfaceSvg.prototype.translateSurfaceInternal_=function(){var e=this.surfaceXY_.x,o=this.surfaceXY_.y;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.BlockDragSurfaceSvg.prototype.translateSurface=function(e,o){this.surfaceXY_=new t.utils.Coordinate(e*this.scale_,o*this.scale_),this.translateSurfaceInternal_()},t.BlockDragSurfaceSvg.prototype.getSurfaceTranslation=function(){var e=t.utils.getRelativeXY(this.SVG_);return new t.utils.Coordinate(e.x/this.scale_,e.y/this.scale_)},t.BlockDragSurfaceSvg.prototype.getGroup=function(){return this.dragGroup_},t.BlockDragSurfaceSvg.prototype.getCurrentBlock=function(){return this.dragGroup_.firstChild},t.BlockDragSurfaceSvg.prototype.clearAndHide=function(t){if(t?t.appendChild(this.getCurrentBlock()):this.dragGroup_.removeChild(this.getCurrentBlock()),this.SVG_.style.display="none",this.dragGroup_.childNodes.length)throw Error("Drag group was not cleared.");this.surfaceXY_=null},t.utils.IdGenerator={},t.utils.IdGenerator.nextId_=0,t.utils.IdGenerator.getNextUniqueId=function(){return"blockly:"+(t.utils.IdGenerator.nextId_++).toString(36)},t.Component=function(){this.rightToLeft_=t.Component.defaultRightToLeft,this.id_=null,this.inDocument_=!1,this.parent_=this.element_=null,this.children_=[],this.childIndex_={}},t.Component.defaultRightToLeft=!1,t.Component.Error={ALREADY_RENDERED:"Component already rendered",PARENT_UNABLE_TO_BE_SET:"Unable to set parent component",CHILD_INDEX_OUT_OF_BOUNDS:"Child component index out of bounds"},t.Component.prototype.getId=function(){return this.id_||(this.id_=t.utils.IdGenerator.getNextUniqueId())},t.Component.prototype.getElement=function(){return this.element_},t.Component.prototype.setElementInternal=function(t){this.element_=t},t.Component.prototype.setParent=function(e){if(this==e)throw Error(t.Component.Error.PARENT_UNABLE_TO_BE_SET);if(e&&this.parent_&&this.id_&&this.parent_.getChild(this.id_)&&this.parent_!=e)throw Error(t.Component.Error.PARENT_UNABLE_TO_BE_SET);this.parent_=e},t.Component.prototype.getParent=function(){return this.parent_},t.Component.prototype.isInDocument=function(){return this.inDocument_},t.Component.prototype.createDom=function(){this.element_=document.createElement("div")},t.Component.prototype.render=function(t){this.render_(t)},t.Component.prototype.renderBefore=function(t){this.render_(t.parentNode,t)},t.Component.prototype.render_=function(e,o){if(this.inDocument_)throw Error(t.Component.Error.ALREADY_RENDERED);this.element_||this.createDom(),e?e.insertBefore(this.element_,o||null):document.body.appendChild(this.element_),this.parent_&&!this.parent_.isInDocument()||this.enterDocument()},t.Component.prototype.enterDocument=function(){this.inDocument_=!0,this.forEachChild((function(t){!t.isInDocument()&&t.getElement()&&t.enterDocument()}))},t.Component.prototype.exitDocument=function(){this.forEachChild((function(t){t.isInDocument()&&t.exitDocument()})),this.inDocument_=!1},t.Component.prototype.dispose=function(){this.disposed_||(this.disposed_=!0,this.disposeInternal())},t.Component.prototype.disposeInternal=function(){this.inDocument_&&this.exitDocument(),this.forEachChild((function(t){t.dispose()})),this.element_&&t.utils.dom.removeNode(this.element_),this.parent_=this.element_=this.childIndex_=this.children_=null},t.Component.prototype.addChild=function(t,e){this.addChildAt(t,this.getChildCount(),e)},t.Component.prototype.addChildAt=function(e,o,i){if(e.inDocument_&&(i||!this.inDocument_))throw Error(t.Component.Error.ALREADY_RENDERED);if(0>o||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<n&&this.children_.splice(n,1)}e.setParent(this),this.children_.splice(o,0,e),e.inDocument_&&this.inDocument_&&e.getParent()==this?(o=(i=this.getContentElement()).childNodes[o]||null)!=e.getElement()&&i.insertBefore(e.getElement(),o):i?(this.element_||this.createDom(),o=this.getChildAt(o+1),e.render_(this.getContentElement(),o?o.element_:null)):this.inDocument_&&!e.inDocument_&&e.element_&&e.element_.parentNode&&e.element_.parentNode.nodeType==t.utils.dom.Node.ELEMENT_NODE&&e.enterDocument()},t.Component.prototype.getContentElement=function(){return this.element_},t.Component.prototype.setRightToLeft=function(e){if(this.inDocument_)throw Error(t.Component.Error.ALREADY_RENDERED);this.rightToLeft_=e},t.Component.prototype.hasChildren=function(){return 0!=this.children_.length},t.Component.prototype.getChildCount=function(){return this.children_.length},t.Component.prototype.getChild=function(t){return t&&this.childIndex_[t]||null},t.Component.prototype.getChildAt=function(t){return this.children_[t]||null},t.Component.prototype.forEachChild=function(t,e){for(var o=0;o<this.children_.length;o++)t.call(e,this.children_[o],o)},t.Component.prototype.indexOfChild=function(t){return this.children_.indexOf(t)},t.Css={},t.Css.injected_=!1,t.Css.register=function(e){if(t.Css.injected_)throw Error("CSS already injected");Array.prototype.push.apply(t.Css.CONTENT,e),e.length=0},t.Css.inject=function(e,o){if(!t.Css.injected_){t.Css.injected_=!0;var i=t.Css.CONTENT.join("\n");t.Css.CONTENT.length=0,e&&(e=o.replace(/[\\/]$/,""),i=i.replace(/<<<PATH>>>/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("<<<PATH>>>/handopen.cur"), auto;',"cursor: grab;","cursor: -webkit-grab;","}",".blocklyDragging {",'cursor: url("<<<PATH>>>/handclosed.cur"), auto;',"cursor: grabbing;","cursor: -webkit-grabbing;","}",".blocklyDraggable:active {",'cursor: url("<<<PATH>>>/handclosed.cur"), auto;',"cursor: grabbing;","cursor: -webkit-grabbing;","}",".blocklyBlockDragSurface .blocklyDraggable {",'cursor: url("<<<PATH>>>/handclosed.cur"), auto;',"cursor: grabbing;","cursor: -webkit-grabbing;","}",".blocklyDragging.blocklyDraggingDelete {",'cursor: url("<<<PATH>>>/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(<<<PATH>>>/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(o<t){var i=o;o=t,t=i}return Math.max(t,Math.min(e,o))},t.DropDownDiv=function(){},t.DropDownDiv.boundsElement_=null,t.DropDownDiv.owner_=null,t.DropDownDiv.positionToField_=null,t.DropDownDiv.ARROW_SIZE=16,t.DropDownDiv.BORDER_SIZE=1,t.DropDownDiv.ARROW_HORIZONTAL_PADDING=12,t.DropDownDiv.PADDING_Y=16,t.DropDownDiv.ANIMATION_TIME=.25,t.DropDownDiv.animateOutTimer_=null,t.DropDownDiv.onHide_=null,t.DropDownDiv.rendererClassName_="",t.DropDownDiv.themeClassName_="",t.DropDownDiv.createDom=function(){if(!t.DropDownDiv.DIV_){var e=document.createElement("div");e.className="blocklyDropDownDiv",(t.parentContainer||document.body).appendChild(e),t.DropDownDiv.DIV_=e;var o=document.createElement("div");o.className="blocklyDropDownContent",e.appendChild(o),t.DropDownDiv.content_=o,(o=document.createElement("div")).className="blocklyDropDownArrow",e.appendChild(o),t.DropDownDiv.arrow_=o,t.DropDownDiv.DIV_.style.opacity=0,t.DropDownDiv.DIV_.style.transition="transform "+t.DropDownDiv.ANIMATION_TIME+"s, opacity "+t.DropDownDiv.ANIMATION_TIME+"s",e.addEventListener("focusin",(function(){t.utils.dom.addClass(e,"focused")})),e.addEventListener("focusout",(function(){t.utils.dom.removeClass(e,"focused")}))}},t.DropDownDiv.setBoundsElement=function(e){t.DropDownDiv.boundsElement_=e},t.DropDownDiv.getContentDiv=function(){return t.DropDownDiv.content_},t.DropDownDiv.clearContent=function(){t.DropDownDiv.content_.textContent="",t.DropDownDiv.content_.style.width=""},t.DropDownDiv.setColour=function(e,o){t.DropDownDiv.DIV_.style.backgroundColor=e,t.DropDownDiv.DIV_.style.borderColor=o},t.DropDownDiv.showPositionedByBlock=function(e,o,i,n){return t.DropDownDiv.showPositionedByRect_(t.DropDownDiv.getScaledBboxOfBlock_(o),e,i,n)},t.DropDownDiv.showPositionedByField=function(e,o,i){return t.DropDownDiv.positionToField_=!0,t.DropDownDiv.showPositionedByRect_(t.DropDownDiv.getScaledBboxOfField_(e),e,o,i)},t.DropDownDiv.getScaledBboxOfBlock_=function(e){var o=e.getSvgRoot(),i=o.getBBox(),n=e.workspace.scale;return e=i.height*n,i=i.width*n,o=t.utils.style.getPageOffset(o),new t.utils.Rect(o.y,o.y+e,o.x,o.x+i)},t.DropDownDiv.getScaledBboxOfField_=function(e){return e=e.getScaledBBox(),new t.utils.Rect(e.top,e.bottom,e.left,e.right)},t.DropDownDiv.showPositionedByRect_=function(e,o,i,n){var s=e.left+(e.right-e.left)/2,r=e.bottom;return e=e.top,n&&(e+=n),n=o.getSourceBlock(),t.DropDownDiv.setBoundsElement(n.workspace.getParentSvg().parentNode),t.DropDownDiv.show(o,n.RTL,s,r,s,e,i)},t.DropDownDiv.show=function(e,o,i,n,s,r,a){return t.DropDownDiv.owner_=e,t.DropDownDiv.onHide_=a||null,(e=t.DropDownDiv.DIV_).style.direction=o?"rtl":"ltr",t.DropDownDiv.rendererClassName_=t.getMainWorkspace().getRenderer().getClassName(),t.DropDownDiv.themeClassName_=t.getMainWorkspace().getTheme().getClassName(),t.utils.dom.addClass(e,t.DropDownDiv.rendererClassName_),t.utils.dom.addClass(e,t.DropDownDiv.themeClassName_),t.DropDownDiv.positionInternal_(i,n,s,r)},t.DropDownDiv.getBoundsInfo_=function(){var e=t.utils.style.getPageOffset(t.DropDownDiv.boundsElement_),o=t.utils.style.getSize(t.DropDownDiv.boundsElement_);return{left:e.x,right:e.x+o.width,top:e.y,bottom:e.y+o.height,width:o.width,height:o.height}},t.DropDownDiv.getPositionMetrics_=function(e,o,i,n){var s=t.DropDownDiv.getBoundsInfo_(),r=t.utils.style.getSize(t.DropDownDiv.DIV_);return o+r.height<s.bottom?t.DropDownDiv.getPositionBelowMetrics_(e,o,s,r):n-r.height>s.top?t.DropDownDiv.getPositionAboveMetrics_(i,n,s,r):o+r.height<document.documentElement.clientHeight?t.DropDownDiv.getPositionBelowMetrics_(e,o,s,r):n-r.height>document.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),0<o.length&&0<o.spacing?(t.utils.dom.createSvgElement("line",{stroke:o.colour},e),1<o.length&&t.utils.dom.createSvgElement("line",{stroke:o.colour},e)):t.utils.dom.createSvgElement("line",{},e),e},t.Theme=function(t,e,o,i){this.name=t,this.blockStyles=e||Object.create(null),this.categoryStyles=o||Object.create(null),this.componentStyles=i||Object.create(null),this.fontStyle=Object.create(null),this.startHats=null},t.Theme.prototype.getClassName=function(){return this.name+"-theme"},t.Theme.prototype.setBlockStyle=function(t,e){this.blockStyles[t]=e},t.Theme.prototype.setCategoryStyle=function(t,e){this.categoryStyles[t]=e},t.Theme.prototype.getComponentStyle=function(t){return(t=this.componentStyles[t])&&"string"==typeof propertyValue&&this.getComponentStyle(t)?this.getComponentStyle(t):t?String(t):null},t.Theme.prototype.setComponentStyle=function(t,e){this.componentStyles[t]=e},t.Theme.prototype.setFontStyle=function(t){this.fontStyle=t},t.Theme.prototype.setStartHats=function(t){this.startHats=t},t.Theme.defineTheme=function(e,o){var i=new t.Theme(e),n=o.base;return n&&n instanceof t.Theme&&(t.utils.object.deepMerge(i,n),i.name=e),t.utils.object.deepMerge(i.blockStyles,o.blockStyles),t.utils.object.deepMerge(i.categoryStyles,o.categoryStyles),t.utils.object.deepMerge(i.componentStyles,o.componentStyles),t.utils.object.deepMerge(i.fontStyle,o.fontStyle),null!=o.startHats&&(i.startHats=o.startHats),i},t.Themes={},t.Themes.Classic={},t.Themes.Classic.defaultBlockStyles={colour_blocks:{colourPrimary:"20"},list_blocks:{colourPrimary:"260"},logic_blocks:{colourPrimary:"210"},loop_blocks:{colourPrimary:"120"},math_blocks:{colourPrimary:"230"},procedure_blocks:{colourPrimary:"290"},text_blocks:{colourPrimary:"160"},variable_blocks:{colourPrimary:"330"},variable_dynamic_blocks:{colourPrimary:"310"},hat_blocks:{colourPrimary:"330",hat:"cap"}},t.Themes.Classic.categoryStyles={colour_category:{colour:"20"},list_category:{colour:"260"},logic_category:{colour:"210"},loop_category:{colour:"120"},math_category:{colour:"230"},procedure_category:{colour:"290"},text_category:{colour:"160"},variable_category:{colour:"330"},variable_dynamic_category:{colour:"310"}},t.Themes.Classic=new t.Theme("classic",t.Themes.Classic.defaultBlockStyles,t.Themes.Classic.categoryStyles),t.utils.KeyCodes={WIN_KEY_FF_LINUX:0,MAC_ENTER:3,BACKSPACE:8,TAB:9,NUM_CENTER:12,ENTER:13,SHIFT:16,CTRL:17,ALT:18,PAUSE:19,CAPS_LOCK:20,ESC:27,SPACE:32,PAGE_UP:33,PAGE_DOWN:34,END:35,HOME:36,LEFT:37,UP:38,RIGHT:39,DOWN:40,PLUS_SIGN:43,PRINT_SCREEN:44,INSERT:45,DELETE:46,ZERO:48,ONE:49,TWO:50,THREE:51,FOUR:52,FIVE:53,SIX:54,SEVEN:55,EIGHT:56,NINE:57,FF_SEMICOLON:59,FF_EQUALS:61,FF_DASH:173,FF_HASH:163,QUESTION_MARK:63,AT_SIGN:64,A:65,B:66,C:67,D:68,E:69,F:70,G:71,H:72,I:73,J:74,K:75,L:76,M:77,N:78,O:79,P:80,Q:81,R:82,S:83,T:84,U:85,V:86,W:87,X:88,Y:89,Z:90,META:91,WIN_KEY_RIGHT:92,CONTEXT_MENU:93,NUM_ZERO:96,NUM_ONE:97,NUM_TWO:98,NUM_THREE:99,NUM_FOUR:100,NUM_FIVE:101,NUM_SIX:102,NUM_SEVEN:103,NUM_EIGHT:104,NUM_NINE:105,NUM_MULTIPLY:106,NUM_PLUS:107,NUM_MINUS:109,NUM_PERIOD:110,NUM_DIVISION:111,F1:112,F2:113,F3:114,F4:115,F5:116,F6:117,F7:118,F8:119,F9:120,F10:121,F11:122,F12:123,NUMLOCK:144,SCROLL_LOCK:145,FIRST_MEDIA_KEY:166,LAST_MEDIA_KEY:183,SEMICOLON:186,DASH:189,EQUALS:187,COMMA:188,PERIOD:190,SLASH:191,APOSTROPHE:192,TILDE:192,SINGLE_QUOTE:222,OPEN_SQUARE_BRACKET:219,BACKSLASH:220,CLOSE_SQUARE_BRACKET:221,WIN_KEY:224,MAC_FF_META:224,MAC_WK_CMD_LEFT:91,MAC_WK_CMD_RIGHT:93,WIN_IME:229,VK_NONAME:252,PHANTOM:255},t.user={},t.user.keyMap={},t.user.keyMap.map_={},t.user.keyMap.modifierKeys={SHIFT:"Shift",CONTROL:"Control",ALT:"Alt",META:"Meta"},t.user.keyMap.setActionForKey=function(e,o){var i=t.user.keyMap.getKeyByAction(o);i&&delete t.user.keyMap.map_[i],t.user.keyMap.map_[e]=o},t.user.keyMap.setKeyMap=function(e){t.user.keyMap.map_=e},t.user.keyMap.getKeyMap=function(){var e={};return t.utils.object.mixin(e,t.user.keyMap.map_),e},t.user.keyMap.getActionByKeyCode=function(e){return t.user.keyMap.map_[e]},t.user.keyMap.getKeyByAction=function(e){for(var o,i=Object.keys(t.user.keyMap.map_),n=0;o=i[n];n++)if(t.user.keyMap.map_[o].name===e.name)return o;return null},t.user.keyMap.serializeKeyEvent=function(e){for(var o,i=t.utils.object.values(t.user.keyMap.modifierKeys),n="",s=0;o=i[s];s++)e.getModifierState(o)&&(n+=o);return n+e.keyCode},t.user.keyMap.checkModifiers_=function(t,e){for(var o,i=0;o=t[i];i++)if(0>e.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.indexOf(s)&&(i+=s);return i+e},t.user.keyMap.createDefaultKeyMap=function(){var e={},o=t.user.keyMap.createSerializedKey(t.utils.KeyCodes.K,[t.user.keyMap.modifierKeys.CONTROL,t.user.keyMap.modifierKeys.SHIFT]),i=t.user.keyMap.createSerializedKey(t.utils.KeyCodes.W,[t.user.keyMap.modifierKeys.SHIFT]),n=t.user.keyMap.createSerializedKey(t.utils.KeyCodes.A,[t.user.keyMap.modifierKeys.SHIFT]),s=t.user.keyMap.createSerializedKey(t.utils.KeyCodes.S,[t.user.keyMap.modifierKeys.SHIFT]),r=t.user.keyMap.createSerializedKey(t.utils.KeyCodes.D,[t.user.keyMap.modifierKeys.SHIFT]);return e[t.utils.KeyCodes.W]=t.navigation.ACTION_PREVIOUS,e[t.utils.KeyCodes.A]=t.navigation.ACTION_OUT,e[t.utils.KeyCodes.S]=t.navigation.ACTION_NEXT,e[t.utils.KeyCodes.D]=t.navigation.ACTION_IN,e[t.utils.KeyCodes.I]=t.navigation.ACTION_INSERT,e[t.utils.KeyCodes.ENTER]=t.navigation.ACTION_MARK,e[t.utils.KeyCodes.X]=t.navigation.ACTION_DISCONNECT,e[t.utils.KeyCodes.T]=t.navigation.ACTION_TOOLBOX,e[t.utils.KeyCodes.E]=t.navigation.ACTION_EXIT,e[t.utils.KeyCodes.ESC]=t.navigation.ACTION_EXIT,e[o]=t.navigation.ACTION_TOGGLE_KEYBOARD_NAV,e[i]=t.navigation.ACTION_MOVE_WS_CURSOR_UP,e[n]=t.navigation.ACTION_MOVE_WS_CURSOR_LEFT,e[s]=t.navigation.ACTION_MOVE_WS_CURSOR_DOWN,e[r]=t.navigation.ACTION_MOVE_WS_CURSOR_RIGHT,e},t.utils.xml={},t.utils.xml.NAME_SPACE="https://developers.google.com/blockly/xml",t.utils.xml.document=function(){return document},t.utils.xml.createElement=function(e){return t.utils.xml.document().createElementNS(t.utils.xml.NAME_SPACE,e)},t.utils.xml.createTextNode=function(e){return t.utils.xml.document().createTextNode(e)},t.utils.xml.textToDomDocument=function(t){return(new DOMParser).parseFromString(t,"text/xml")},t.utils.xml.domToText=function(t){return(new XMLSerializer).serializeToString(t)},t.Events.BlockBase=function(e){t.Events.BlockBase.superClass_.constructor.call(this),this.blockId=e.id,this.workspaceId=e.workspace.id},t.utils.object.inherits(t.Events.BlockBase,t.Events.Abstract),t.Events.BlockBase.prototype.toJson=function(){var e=t.Events.BlockBase.superClass_.toJson.call(this);return e.blockId=this.blockId,e},t.Events.BlockBase.prototype.fromJson=function(e){t.Events.BlockBase.superClass_.fromJson.call(this,e),this.blockId=e.blockId},t.Events.Change=function(e,o,i,n,s){e&&(t.Events.Change.superClass_.constructor.call(this,e),this.element=o,this.name=i,this.oldValue=n,this.newValue=s)},t.utils.object.inherits(t.Events.Change,t.Events.BlockBase),t.Events.BlockChange=t.Events.Change,t.Events.Change.prototype.type=t.Events.CHANGE,t.Events.Change.prototype.toJson=function(){var e=t.Events.Change.superClass_.toJson.call(this);return e.element=this.element,this.name&&(e.name=this.name),e.newValue=this.newValue,e},t.Events.Change.prototype.fromJson=function(e){t.Events.Change.superClass_.fromJson.call(this,e),this.element=e.element,this.name=e.name,this.newValue=e.newValue},t.Events.Change.prototype.isNull=function(){return this.oldValue==this.newValue},t.Events.Change.prototype.run=function(e){var o=this.getEventWorkspace_().getBlockById(this.blockId);if(o)switch(o.mutator&&o.mutator.setVisible(!1),e=e?this.newValue:this.oldValue,this.element){case"field":(o=o.getField(this.name))?o.setValue(e):console.warn("Can't set non-existent field: "+this.name);break;case"comment":o.setCommentText(e||null);break;case"collapsed":o.setCollapsed(!!e);break;case"disabled":o.setEnabled(!e);break;case"inline":o.setInputsInline(!!e);break;case"mutation":var i="";if(o.mutationToDom&&(i=(i=o.mutationToDom())&&t.Xml.domToText(i)),o.domToMutation){var n=t.Xml.textToDom(e||"<mutation/>");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&#10;$2")}while(e!=i);return e.replace(/<(\w+)([^<]*)\/>/g,"<$1$2></$1>")},t.Xml.domToPrettyText=function(e){e=t.Xml.domToText(e).split("<");for(var o="",i=1;i<e.length;i++){var n=e[i];"/"==n[0]&&(o=o.substring(2)),e[i]=o+"<"+n,"/"!=n[0]&&"/>"!=n.slice(-2)&&(o+="  ")}return(e=(e=e.join("\n")).replace(/(<(\w+)\b[^>]*>[^\n]*)\n *<\/\2>/g,"$1</$2>")).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;i<e.length;i++){var c=o.getBlockById(e[i]).getRelativeToSurfaceXY();c.y<l&&(l=c.y),c.x<r&&(r=c.x),c.x>a&&(a=c.x)}for(n=n-l+10,s=o.RTL?s-a:s-r,i=0;i<e.length;i++)o.getBlockById(e[i]).moveBy(s,n)}return e},t.Xml.domToBlock=function(e,o){if(e instanceof t.Workspace){var i=e;e=o,o=i,console.warn("Deprecated call to Blockly.Xml.domToBlock, swap the arguments.")}t.Events.disable(),i=o.getAllVariables();try{var n=t.Xml.domToBlockHeadless_(e,o),s=n.getDescendants(!1);if(o.rendered){n.setConnectionTracking(!1);for(var r=s.length-1;0<=r;r--)s[r].initSvg();for(r=s.length-1;0<=r;r--)s[r].render(!1);setTimeout((function(){n.disposed||n.setConnectionTracking(!0)}),1),n.updateDisabled(),o.resizeContents()}else for(r=s.length-1;0<=r;r--)s[r].initModel()}finally{t.Events.enable()}if(t.Events.isEnabled()){for(e=t.Variables.getAddedVariables(o,i),r=0;r<e.length;r++)t.Events.fire(new t.Events.VarCreate(e[r]));t.Events.fire(new t.Events.BlockCreate(n))}return n},t.Xml.domToVariables=function(e,o){for(var i,n=0;i=e.childNodes[n];n++)if(i.nodeType==t.utils.dom.Node.ELEMENT_NODE){var s=i.getAttribute("type"),r=i.getAttribute("id");o.createVariable(i.textContent,s,r)}},t.Xml.domToBlockHeadless_=function(e,o){var i=null,n=e.getAttribute("type");if(!n)throw TypeError("Block type unspecified: "+e.outerHTML);var s=e.getAttribute("id");i=o.newBlock(n,s);var r,a=null;for(s=0;r=e.childNodes[s];s++)if(r.nodeType!=t.utils.dom.Node.TEXT_NODE){for(var l,c=a=null,h=0;l=r.childNodes[h];h++)l.nodeType==t.utils.dom.Node.ELEMENT_NODE&&("block"==l.nodeName.toLowerCase()?a=l:"shadow"==l.nodeName.toLowerCase()&&(c=l));switch(!a&&c&&(a=c),l=r.getAttribute("name"),h=r,r.nodeName.toLowerCase()){case"mutation":i.domToMutation&&(i.domToMutation(h),i.initSvg&&i.initSvg());break;case"comment":if(!t.Comment){console.warn("Missing require for Blockly.Comment, ignoring block comment.");break}a=h.textContent,c="true"==h.getAttribute("pinned"),r=parseInt(h.getAttribute("w"),10),h=parseInt(h.getAttribute("h"),10),i.setCommentText(a),i.commentModel.pinned=c,isNaN(r)||isNaN(h)||(i.commentModel.size=new t.utils.Size(r,h)),c&&i.getCommentIcon&&!i.isInFlyout&&setTimeout((function(){i.getCommentIcon().setVisible(!0)}),1);break;case"data":i.data=r.textContent;break;case"title":case"field":t.Xml.domToField_(i,l,h);break;case"value":case"statement":if(!(h=i.getInput(l))){console.warn("Ignoring non-existent input "+l+" in block "+n);break}if(c&&h.connection.setShadowDom(c),a)if((a=t.Xml.domToBlockHeadless_(a,o)).outputConnection)h.connection.connect(a.outputConnection);else{if(!a.previousConnection)throw TypeError("Child block does not have output or previous statement.");h.connection.connect(a.previousConnection)}break;case"next":if(c&&i.nextConnection&&i.nextConnection.setShadowDom(c),a){if(!i.nextConnection)throw TypeError("Next statement does not exist.");if(i.nextConnection.isConnected())throw TypeError("Next statement is already connected.");if(!(a=t.Xml.domToBlockHeadless_(a,o)).previousConnection)throw TypeError("Next block does not have previous statement.");i.nextConnection.connect(a.previousConnection)}break;default:console.warn("Ignoring unknown tag: "+r.nodeName)}}if((s=e.getAttribute("inline"))&&i.setInputsInline("true"==s),(s=e.getAttribute("disabled"))&&i.setEnabled("true"!=s&&"disabled"!=s),(s=e.getAttribute("deletable"))&&i.setDeletable("true"==s),(s=e.getAttribute("movable"))&&i.setMovable("true"==s),(s=e.getAttribute("editable"))&&i.setEditable("true"==s),(s=e.getAttribute("collapsed"))&&i.setCollapsed("true"==s),"shadow"==e.nodeName.toLowerCase()){for(e=i.getChildren(!1),s=0;o=e[s];s++)if(!o.isShadow())throw TypeError("Shadow block not allowed non-shadow child.");if(i.getVarModels().length)throw TypeError("Shadow blocks cannot have variable references.");i.setShadow(!0)}return i},t.Xml.domToField_=function(t,e,o){var i=t.getField(e);i?i.fromXml(o):console.warn("Ignoring non-existent field "+e+" in block "+t.type)},t.Xml.deleteNext=function(t){for(var e,o=0;e=t.childNodes[o];o++)if("next"==e.nodeName.toLowerCase()){t.removeChild(e);break}},t.Options=function(e){var o=!!e.readOnly;if(o)var i=null,n=!1,s=!1,r=!1,a=!1,l=!1,c=!1;else{n=!(!(i=t.Options.parseToolboxTree(e.toolbox||null))||!i.getElementsByTagName("category").length),void 0===(s=e.trashcan)&&(s=n);var h=e.maxTrashcanContents;s?void 0===h&&(h=32):h=0,void 0===(r=e.collapse)&&(r=n),void 0===(a=e.comments)&&(a=n),void 0===(l=e.disable)&&(l=n),void 0===(c=e.sounds)&&(c=!0)}var u=!!e.rtl,p=e.horizontalLayout;void 0===p&&(p=!1);var _=e.toolboxPosition;_="end"!==_,_=p?_?t.TOOLBOX_AT_TOP:t.TOOLBOX_AT_BOTTOM:_==u?t.TOOLBOX_AT_RIGHT:t.TOOLBOX_AT_LEFT;var d=e.css;void 0===d&&(d=!0);var g="https://blockly-demo.appspot.com/static/media/";e.media?g=e.media:e.path&&(g=e.path+"media/");var T=void 0===e.oneBasedIndex||!!e.oneBasedIndex,E=e.keyMap||t.user.keyMap.createDefaultKeyMap(),f=e.renderer||"geras";this.RTL=u,this.oneBasedIndex=T,this.collapse=r,this.comments=a,this.disable=l,this.readOnly=o,this.maxBlocks=e.maxBlocks||1/0,this.maxInstances=e.maxInstances,this.pathToMedia=g,this.hasCategories=n,this.moveOptions=t.Options.parseMoveOptions(e,n),this.hasScrollbars=this.moveOptions.scrollbars,this.hasTrashcan=s,this.maxTrashcanContents=h,this.hasSounds=c,this.hasCss=d,this.horizontalLayout=p,this.languageTree=i,this.gridOptions=t.Options.parseGridOptions_(e),this.zoomOptions=t.Options.parseZoomOptions_(e),this.toolboxPosition=_,this.theme=t.Options.parseThemeOptions_(e),this.keyMap=E,this.renderer=f,this.rendererOverrides=e.rendererOverrides,this.gridPattern=void 0,this.parentWorkspace=e.parentWorkspace},t.BlocklyOptions=function(){},t.Options.parseMoveOptions=function(t,e){var o=t.move||{},i={};return i.scrollbars=void 0===o.scrollbars&&void 0===t.scrollbars?e:!!o.scrollbars||!!t.scrollbars,i.wheel=!(!i.scrollbars||void 0===o.wheel||!o.wheel),i.drag=!(!i.scrollbars||void 0!==o.drag&&!o.drag),i},t.Options.parseZoomOptions_=function(t){t=t.zoom||{};var e={};return e.controls=void 0!==t.controls&&!!t.controls,e.wheel=void 0!==t.wheel&&!!t.wheel,e.startScale=void 0===t.startScale?1:Number(t.startScale),e.maxScale=void 0===t.maxScale?3:Number(t.maxScale),e.minScale=void 0===t.minScale?.3:Number(t.minScale),e.scaleSpeed=void 0===t.scaleSpeed?1.2:Number(t.scaleSpeed),e.pinch=void 0===t.pinch?e.wheel||e.controls:!!t.pinch,e},t.Options.parseGridOptions_=function(t){t=t.grid||{};var e={};return e.spacing=Number(t.spacing)||0,e.colour=t.colour||"#888",e.length=void 0===t.length?1:Number(t.length),e.snap=0<e.spacing&&!!t.snap,e},t.Options.parseThemeOptions_=function(e){return(e=e.theme||t.Themes.Classic)instanceof t.Theme?e:t.Theme.defineTheme("builtin",e)},t.Options.parseToolboxTree=function(e){if(e){if("string"!=typeof e&&(t.utils.userAgent.IE&&e.outerHTML?e=e.outerHTML:e instanceof Element||(e=null)),"string"==typeof e&&"xml"!=(e=t.Xml.textToDom(e)).nodeName.toLowerCase())throw TypeError("Toolbox should be an <xml> 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<t.changedTouches.length;o++)e[o]={type:t.type,changedTouches:[t.changedTouches[o]],target:t.target,stopPropagation:function(){t.stopPropagation()},preventDefault:function(){t.preventDefault()}};else e.push(t);return e},t.ScrollbarPair=function(e){this.workspace_=e,this.hScroll=new t.Scrollbar(e,!0,!0,"blocklyMainWorkspaceScrollbar"),this.vScroll=new t.Scrollbar(e,!1,!0,"blocklyMainWorkspaceScrollbar"),this.corner_=t.utils.dom.createSvgElement("rect",{height:t.Scrollbar.scrollbarThickness,width:t.Scrollbar.scrollbarThickness,class:"blocklyScrollbarBackground"},null),t.utils.dom.insertAfter(this.corner_,e.getBubbleCanvas())},t.ScrollbarPair.prototype.oldHostMetrics_=null,t.ScrollbarPair.prototype.dispose=function(){t.utils.dom.removeNode(this.corner_),this.oldHostMetrics_=this.workspace_=this.corner_=null,this.hScroll.dispose(),this.hScroll=null,this.vScroll.dispose(),this.vScroll=null},t.ScrollbarPair.prototype.resize=function(){var t=this.workspace_.getMetrics();if(t){var e=!1,o=!1;this.oldHostMetrics_&&this.oldHostMetrics_.viewWidth==t.viewWidth&&this.oldHostMetrics_.viewHeight==t.viewHeight&&this.oldHostMetrics_.absoluteTop==t.absoluteTop&&this.oldHostMetrics_.absoluteLeft==t.absoluteLeft?(this.oldHostMetrics_&&this.oldHostMetrics_.contentWidth==t.contentWidth&&this.oldHostMetrics_.viewLeft==t.viewLeft&&this.oldHostMetrics_.contentLeft==t.contentLeft||(e=!0),this.oldHostMetrics_&&this.oldHostMetrics_.contentHeight==t.contentHeight&&this.oldHostMetrics_.viewTop==t.viewTop&&this.oldHostMetrics_.contentTop==t.contentTop||(o=!0)):o=e=!0,e&&this.hScroll.resize(t),o&&this.vScroll.resize(t),this.oldHostMetrics_&&this.oldHostMetrics_.viewWidth==t.viewWidth&&this.oldHostMetrics_.absoluteLeft==t.absoluteLeft||this.corner_.setAttribute("x",this.vScroll.position_.x),this.oldHostMetrics_&&this.oldHostMetrics_.viewHeight==t.viewHeight&&this.oldHostMetrics_.absoluteTop==t.absoluteTop||this.corner_.setAttribute("y",this.hScroll.position_.y),this.oldHostMetrics_=t}},t.ScrollbarPair.prototype.set=function(t,e){var o={};t*=this.hScroll.ratio_,e*=this.vScroll.ratio_;var i=this.vScroll.scrollViewSize_;o.x=this.getRatio_(t,this.hScroll.scrollViewSize_),o.y=this.getRatio_(e,i),this.workspace_.setMetrics(o),this.hScroll.setHandlePosition(t),this.vScroll.setHandlePosition(e)},t.ScrollbarPair.prototype.getRatio_=function(t,e){return t/=e,isNaN(t)?0:t},t.Scrollbar=function(e,o,i,n){this.workspace_=e,this.pair_=i||!1,this.horizontal_=o,this.oldHostMetrics_=null,this.createDom_(n),this.position_=new t.utils.Coordinate(0,0),e=t.Scrollbar.scrollbarThickness,o?(this.svgBackground_.setAttribute("height",e),this.outerSvg_.setAttribute("height",e),this.svgHandle_.setAttribute("height",e-5),this.svgHandle_.setAttribute("y",2.5),this.lengthAttribute_="width",this.positionAttribute_="x"):(this.svgBackground_.setAttribute("width",e),this.outerSvg_.setAttribute("width",e),this.svgHandle_.setAttribute("width",e-5),this.svgHandle_.setAttribute("x",2.5),this.lengthAttribute_="height",this.positionAttribute_="y"),this.onMouseDownBarWrapper_=t.bindEventWithChecks_(this.svgBackground_,"mousedown",this,this.onMouseDownBar_),this.onMouseDownHandleWrapper_=t.bindEventWithChecks_(this.svgHandle_,"mousedown",this,this.onMouseDownHandle_)},t.Scrollbar.prototype.origin_=new t.utils.Coordinate(0,0),t.Scrollbar.prototype.startDragMouse_=0,t.Scrollbar.prototype.scrollViewSize_=0,t.Scrollbar.prototype.handleLength_=0,t.Scrollbar.prototype.handlePosition_=0,t.Scrollbar.prototype.isVisible_=!0,t.Scrollbar.prototype.containerVisible_=!0,t.Scrollbar.scrollbarThickness=15,t.Touch.TOUCH_ENABLED&&(t.Scrollbar.scrollbarThickness=25),t.Scrollbar.metricsAreEquivalent_=function(t,e){return!(!t||!e||t.viewWidth!=e.viewWidth||t.viewHeight!=e.viewHeight||t.viewLeft!=e.viewLeft||t.viewTop!=e.viewTop||t.absoluteTop!=e.absoluteTop||t.absoluteLeft!=e.absoluteLeft||t.contentWidth!=e.contentWidth||t.contentHeight!=e.contentHeight||t.contentLeft!=e.contentLeft||t.contentTop!=e.contentTop)},t.Scrollbar.prototype.dispose=function(){this.cleanUp_(),t.unbindEvent_(this.onMouseDownBarWrapper_),this.onMouseDownBarWrapper_=null,t.unbindEvent_(this.onMouseDownHandleWrapper_),this.onMouseDownHandleWrapper_=null,t.utils.dom.removeNode(this.outerSvg_),this.svgBackground_=this.svgGroup_=this.outerSvg_=null,this.svgHandle_&&(this.workspace_.getThemeManager().unsubscribe(this.svgHandle_),this.svgHandle_=null),this.workspace_=null},t.Scrollbar.prototype.setHandleLength_=function(t){this.handleLength_=t,this.svgHandle_.setAttribute(this.lengthAttribute_,this.handleLength_)},t.Scrollbar.prototype.setHandlePosition=function(t){this.handlePosition_=t,this.svgHandle_.setAttribute(this.positionAttribute_,this.handlePosition_)},t.Scrollbar.prototype.setScrollViewSize_=function(t){this.scrollViewSize_=t,this.outerSvg_.setAttribute(this.lengthAttribute_,this.scrollViewSize_),this.svgBackground_.setAttribute(this.lengthAttribute_,this.scrollViewSize_)},t.ScrollbarPair.prototype.setContainerVisible=function(t){this.hScroll.setContainerVisible(t),this.vScroll.setContainerVisible(t)},t.Scrollbar.prototype.setPosition_=function(e,o){this.position_.x=e,this.position_.y=o,t.utils.dom.setCssTransform(this.outerSvg_,"translate("+(this.position_.x+this.origin_.x)+"px,"+(this.position_.y+this.origin_.y)+"px)")},t.Scrollbar.prototype.resize=function(e){(e||(e=this.workspace_.getMetrics()))&&(t.Scrollbar.metricsAreEquivalent_(e,this.oldHostMetrics_)||(this.oldHostMetrics_=e,this.horizontal_?this.resizeHorizontal_(e):this.resizeVertical_(e),this.onScroll_()))},t.Scrollbar.prototype.resizeHorizontal_=function(t){this.resizeViewHorizontal(t)},t.Scrollbar.prototype.resizeViewHorizontal=function(e){var o=e.viewWidth-1;this.pair_&&(o-=t.Scrollbar.scrollbarThickness),this.setScrollViewSize_(Math.max(0,o)),o=e.absoluteLeft+.5,this.pair_&&this.workspace_.RTL&&(o+=t.Scrollbar.scrollbarThickness),this.setPosition_(o,e.absoluteTop+e.viewHeight-t.Scrollbar.scrollbarThickness-.5),this.resizeContentHorizontal(e)},t.Scrollbar.prototype.resizeContentHorizontal=function(t){this.pair_||this.setVisible(this.scrollViewSize_<t.contentWidth),this.ratio_=this.scrollViewSize_/t.contentWidth,(-1/0==this.ratio_||1/0==this.ratio_||isNaN(this.ratio_))&&(this.ratio_=0),this.setHandleLength_(Math.max(0,t.viewWidth*this.ratio_)),this.setHandlePosition(this.constrainHandle_((t.viewLeft-t.contentLeft)*this.ratio_))},t.Scrollbar.prototype.resizeVertical_=function(t){this.resizeViewVertical(t)},t.Scrollbar.prototype.resizeViewVertical=function(e){var o=e.viewHeight-1;this.pair_&&(o-=t.Scrollbar.scrollbarThickness),this.setScrollViewSize_(Math.max(0,o)),o=e.absoluteLeft+.5,this.workspace_.RTL||(o+=e.viewWidth-t.Scrollbar.scrollbarThickness-1),this.setPosition_(o,e.absoluteTop+.5),this.resizeContentVertical(e)},t.Scrollbar.prototype.resizeContentVertical=function(t){this.pair_||this.setVisible(this.scrollViewSize_<t.contentHeight),this.ratio_=this.scrollViewSize_/t.contentHeight,(-1/0==this.ratio_||1/0==this.ratio_||isNaN(this.ratio_))&&(this.ratio_=0),this.setHandleLength_(Math.max(0,t.viewHeight*this.ratio_)),this.setHandlePosition(this.constrainHandle_((t.viewTop-t.contentTop)*this.ratio_))},t.Scrollbar.prototype.createDom_=function(e){var o="blocklyScrollbar"+(this.horizontal_?"Horizontal":"Vertical");e&&(o+=" "+e),this.outerSvg_=t.utils.dom.createSvgElement("svg",{class:o},null),this.svgGroup_=t.utils.dom.createSvgElement("g",{},this.outerSvg_),this.svgBackground_=t.utils.dom.createSvgElement("rect",{class:"blocklyScrollbarBackground"},this.svgGroup_),e=Math.floor((t.Scrollbar.scrollbarThickness-5)/2),this.svgHandle_=t.utils.dom.createSvgElement("rect",{class:"blocklyScrollbarHandle",rx:e,ry:e},this.svgGroup_),this.workspace_.getThemeManager().subscribe(this.svgHandle_,"scrollbarColour","fill"),this.workspace_.getThemeManager().subscribe(this.svgHandle_,"scrollbarOpacity","fill-opacity"),t.utils.dom.insertAfter(this.outerSvg_,this.workspace_.getParentSvg())},t.Scrollbar.prototype.isVisible=function(){return this.isVisible_},t.Scrollbar.prototype.setContainerVisible=function(t){var e=t!=this.containerVisible_;this.containerVisible_=t,e&&this.updateDisplay_()},t.Scrollbar.prototype.setVisible=function(t){var e=t!=this.isVisible();if(this.pair_)throw Error("Unable to toggle visibility of paired scrollbars.");this.isVisible_=t,e&&this.updateDisplay_()},t.Scrollbar.prototype.updateDisplay_=function(){this.containerVisible_&&this.isVisible()?this.outerSvg_.setAttribute("display","block"):this.outerSvg_.setAttribute("display","none")},t.Scrollbar.prototype.onMouseDownBar_=function(e){if(this.workspace_.markFocused(),t.Touch.clearTouchIdentifier(),this.cleanUp_(),t.utils.isRightButton(e))e.stopPropagation();else{var o=t.utils.mouseToSvg(e,this.workspace_.getParentSvg(),this.workspace_.getInverseScreenCTM());o=this.horizontal_?o.x:o.y;var i=t.utils.getInjectionDivXY_(this.svgHandle_);i=this.horizontal_?i.x:i.y;var n=this.handlePosition_,s=.95*this.handleLength_;o<=i?n-=s: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_<this.handleLength_?0:Math.min(t,this.scrollViewSize_-this.handleLength_)},t.Scrollbar.prototype.onScroll_=function(){var t=this.handlePosition_/this.scrollViewSize_;isNaN(t)&&(t=0);var e={};this.horizontal_?e.x=t:e.y=t,this.workspace_.setMetrics(e)},t.Scrollbar.prototype.set=function(t){this.setHandlePosition(this.constrainHandle_(t*this.ratio_)),this.onScroll_()},t.Scrollbar.prototype.setOrigin=function(e,o){this.origin_=new t.utils.Coordinate(e,o)},t.Tooltip={},t.Tooltip.visible=!1,t.Tooltip.blocked_=!1,t.Tooltip.LIMIT=50,t.Tooltip.mouseOutPid_=0,t.Tooltip.showPid_=0,t.Tooltip.lastX_=0,t.Tooltip.lastY_=0,t.Tooltip.element_=null,t.Tooltip.poisonedElement_=null,t.Tooltip.OFFSET_X=0,t.Tooltip.OFFSET_Y=10,t.Tooltip.RADIUS_OK=10,t.Tooltip.HOVER_MS=750,t.Tooltip.MARGINS=5,t.Tooltip.DIV=null,t.Tooltip.createDom=function(){t.Tooltip.DIV||(t.Tooltip.DIV=document.createElement("div"),t.Tooltip.DIV.className="blocklyTooltipDiv",(t.parentContainer||document.body).appendChild(t.Tooltip.DIV))},t.Tooltip.bindMouseEvents=function(e){e.mouseOverWrapper_=t.bindEvent_(e,"mouseover",null,t.Tooltip.onMouseOver_),e.mouseOutWrapper_=t.bindEvent_(e,"mouseout",null,t.Tooltip.onMouseOut_),e.addEventListener("mousemove",t.Tooltip.onMouseMove_,!1)},t.Tooltip.unbindMouseEvents=function(e){e&&(t.unbindEvent_(e.mouseOverWrapper_),t.unbindEvent_(e.mouseOutWrapper_),e.removeEventListener("mousemove",t.Tooltip.onMouseMove_))},t.Tooltip.onMouseOver_=function(e){if(!t.Tooltip.blocked_){for(e=e.currentTarget;"string"!=typeof e.tooltip&&"function"!=typeof e.tooltip;)e=e.tooltip;t.Tooltip.element_!=e&&(t.Tooltip.hide(),t.Tooltip.poisonedElement_=null,t.Tooltip.element_=e),clearTimeout(t.Tooltip.mouseOutPid_)}},t.Tooltip.onMouseOut_=function(e){t.Tooltip.blocked_||(t.Tooltip.mouseOutPid_=setTimeout((function(){t.Tooltip.element_=null,t.Tooltip.poisonedElement_=null,t.Tooltip.hide()}),1),clearTimeout(t.Tooltip.showPid_))},t.Tooltip.onMouseMove_=function(e){if(t.Tooltip.element_&&t.Tooltip.element_.tooltip&&!t.Tooltip.blocked_)if(t.Tooltip.visible){var o=t.Tooltip.lastX_-e.pageX;e=t.Tooltip.lastY_-e.pageY,Math.sqrt(o*o+e*e)>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;o<e.length;o++){var i=document.createElement("div");i.appendChild(document.createTextNode(e[o])),t.Tooltip.DIV.appendChild(i)}e=t.Tooltip.element_.RTL,o=document.documentElement.clientWidth,i=document.documentElement.clientHeight,t.Tooltip.DIV.style.direction=e?"rtl":"ltr",t.Tooltip.DIV.style.display="block",t.Tooltip.visible=!0;var n=t.Tooltip.lastX_;n=e?n-(t.Tooltip.OFFSET_X+t.Tooltip.DIV.offsetWidth):n+t.Tooltip.OFFSET_X;var s=t.Tooltip.lastY_+t.Tooltip.OFFSET_Y;s+t.Tooltip.DIV.offsetHeight>i+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;e<s.length;){if(s[e].isClickable()||t.ASTNode.NAVIGATE_ALL_FIELDS)return t.ASTNode.createFieldNode(s[e]);e++}if(e=0,o.connection)return t.ASTNode.createInputNode(o)}return null},t.ASTNode.prototype.findPrevForInput_=function(){for(var e,o=this.location_.getParentInput(),i=o.getSourceBlock(),n=i.inputList.indexOf(o);e=i.inputList[n];n--){if(e.connection&&e!==o)return t.ASTNode.createInputNode(e);for(var s,r=(e=e.fieldRow).length-1;s=e[r];r--)if(s.isClickable()||t.ASTNode.NAVIGATE_ALL_FIELDS)return t.ASTNode.createFieldNode(s)}return null},t.ASTNode.prototype.findPrevForField_=function(){var e,o=this.location_,i=o.getParentInput(),n=o.getSourceBlock(),s=n.inputList.indexOf(i);for(o=i.fieldRow.indexOf(o)-1;e=n.inputList[s];s--){if(e.connection&&e!==i)return t.ASTNode.createInputNode(e);for(e=e.fieldRow;-1<o;){if(e[o].isClickable()||t.ASTNode.NAVIGATE_ALL_FIELDS)return t.ASTNode.createFieldNode(e[o]);o--}0<=s-1&&(o=n.inputList[s-1].fieldRow.length-1)}return null},t.ASTNode.prototype.navigateBetweenStacks_=function(e){var o=this.getLocation();if(o instanceof t.Block||(o=o.getSourceBlock()),!o||!o.workspace)return null;var i=o.getRootBlock();o=i.workspace.getTopBlocks(!0);for(var n,s=0;n=o[s];s++)if(i.id==n.id)return-1==(e=s+(e?1:-1))||e==o.length?null:t.ASTNode.createStackNode(o[e]);throw Error("Couldn't find "+(e?"next":"previous")+" stack?!")},t.ASTNode.prototype.findTopASTNodeForBlock_=function(e){var o=e.previousConnection||e.outputConnection;return o?t.ASTNode.createConnectionNode(o):t.ASTNode.createBlockNode(e)},t.ASTNode.prototype.getOutAstNodeForBlock_=function(e){if(!e)return null;var o=(e=e.getTopStackBlock()).previousConnection||e.outputConnection;return o&&o.targetConnection&&o.targetConnection.getParentInput()?t.ASTNode.createInputNode(o.targetConnection.getParentInput()):t.ASTNode.createStackNode(e)},t.ASTNode.prototype.findFirstFieldOrInput_=function(e){e=e.inputList;for(var o,i=0;o=e[i];i++){for(var n,s=o.fieldRow,r=0;n=s[r];r++)if(n.isClickable()||t.ASTNode.NAVIGATE_ALL_FIELDS)return t.ASTNode.createFieldNode(n);if(o.connection)return t.ASTNode.createInputNode(o)}return null},t.ASTNode.prototype.getSourceBlock=function(){return this.getType()===t.ASTNode.types.BLOCK||this.getType()===t.ASTNode.types.STACK?this.getLocation():this.getType()===t.ASTNode.types.WORKSPACE?null:this.getLocation().getSourceBlock()},t.ASTNode.prototype.next=function(){switch(this.type_){case t.ASTNode.types.STACK:return this.navigateBetweenStacks_(!0);case t.ASTNode.types.OUTPUT:return t.ASTNode.createBlockNode(this.location_.getSourceBlock());case t.ASTNode.types.FIELD:return this.findNextForField_();case t.ASTNode.types.INPUT:return this.findNextForInput_();case t.ASTNode.types.BLOCK:return t.ASTNode.createConnectionNode(this.location_.nextConnection);case t.ASTNode.types.PREVIOUS:return t.ASTNode.createBlockNode(this.location_.getSourceBlock());case t.ASTNode.types.NEXT:return t.ASTNode.createConnectionNode(this.location_.targetConnection)}return null},t.ASTNode.prototype.in=function(){switch(this.type_){case t.ASTNode.types.WORKSPACE:var e=this.location_.getTopBlocks(!0);if(0<e.length)return t.ASTNode.createStackNode(e[0]);break;case t.ASTNode.types.STACK:return e=this.location_,this.findTopASTNodeForBlock_(e);case t.ASTNode.types.BLOCK:return e=this.location_,this.findFirstFieldOrInput_(e);case t.ASTNode.types.INPUT:return t.ASTNode.createConnectionNode(this.location_.targetConnection)}return null},t.ASTNode.prototype.prev=function(){switch(this.type_){case t.ASTNode.types.STACK:return this.navigateBetweenStacks_(!1);case t.ASTNode.types.FIELD:return this.findPrevForField_();case t.ASTNode.types.INPUT:return this.findPrevForInput_();case t.ASTNode.types.BLOCK:var e=this.location_;return t.ASTNode.createConnectionNode(e.previousConnection||e.outputConnection);case t.ASTNode.types.PREVIOUS:if((e=this.location_.targetConnection)&&!e.getParentInput())return t.ASTNode.createConnectionNode(e);break;case t.ASTNode.types.NEXT:return t.ASTNode.createBlockNode(this.location_.getSourceBlock())}return null},t.ASTNode.prototype.out=function(){switch(this.type_){case t.ASTNode.types.STACK:var e=this.location_.getRelativeToSurfaceXY();return e=new t.utils.Coordinate(e.x,e.y+t.ASTNode.DEFAULT_OFFSET_Y),t.ASTNode.createWorkspaceNode(this.location_.workspace,e);case t.ASTNode.types.OUTPUT:return(e=this.location_.targetConnection)?t.ASTNode.createConnectionNode(e):t.ASTNode.createStackNode(this.location_.getSourceBlock());case t.ASTNode.types.FIELD:case t.ASTNode.types.INPUT:return t.ASTNode.createBlockNode(this.location_.getSourceBlock());case t.ASTNode.types.BLOCK:return this.getOutAstNodeForBlock_(this.location_);case t.ASTNode.types.PREVIOUS:case t.ASTNode.types.NEXT:return this.getOutAstNodeForBlock_(this.location_.getSourceBlock())}return null},t.Blocks=Object.create(null),t.Connection=function(t,e){this.sourceBlock_=t,this.type=e},t.Connection.CAN_CONNECT=0,t.Connection.REASON_SELF_CONNECTION=1,t.Connection.REASON_WRONG_TYPE=2,t.Connection.REASON_TARGET_NULL=3,t.Connection.REASON_CHECKS_FAILED=4,t.Connection.REASON_DIFFERENT_WORKSPACES=5,t.Connection.REASON_SHADOW_PARENT=6,t.Connection.prototype.targetConnection=null,t.Connection.prototype.disposed=!1,t.Connection.prototype.check_=null,t.Connection.prototype.shadowDom_=null,t.Connection.prototype.x=0,t.Connection.prototype.y=0,t.Connection.prototype.connect_=function(e){var o,i=this,n=i.getSourceBlock(),s=e.getSourceBlock();if(e.isConnected()&&e.disconnect(),i.isConnected()){var r=i.targetBlock(),a=i.getShadowDom();if(i.setShadowDom(null),r.isShadow())a=t.Xml.blockToDom(r),r.dispose(!1),r=null;else if(i.type==t.INPUT_VALUE){if(!r.outputConnection)throw Error("Orphan block does not have an output connection.");var l=t.Connection.lastConnectionInRow(s,r);l&&(r.outputConnection.connect(l),r=null)}else if(i.type==t.NEXT_STATEMENT){if(!r.previousConnection)throw Error("Orphan block does not have a previous connection.");for(l=s;l.nextConnection;){var c=l.getNextBlock();if(!c||c.isShadow()){r.previousConnection.checkType(l.nextConnection)&&(l.nextConnection.connect(r.previousConnection),r=null);break}l=c}}if(r&&(i.disconnect(),t.Events.recordUndo)){var h=t.Events.getGroup();setTimeout((function(){r.workspace&&!r.getParent()&&(t.Events.setGroup(h),r.outputConnection?r.outputConnection.onFailedConnect(i):r.previousConnection&&r.previousConnection.onFailedConnect(i),t.Events.setGroup(!1))}),t.BUMP_DELAY)}i.setShadowDom(a)}t.Events.isEnabled()&&(o=new t.Events.BlockMove(s)),t.Connection.connectReciprocally_(i,e),s.setParent(n),o&&(o.recordNew(),t.Events.fire(o))},t.Connection.prototype.dispose=function(){if(this.isConnected()){this.setShadowDom(null);var t=this.targetBlock();t.isShadow()?t.dispose(!1):t.unplug()}this.disposed=!0},t.Connection.prototype.getSourceBlock=function(){return this.sourceBlock_},t.Connection.prototype.isSuperior=function(){return this.type==t.INPUT_VALUE||this.type==t.NEXT_STATEMENT},t.Connection.prototype.isConnected=function(){return!!this.targetConnection},t.Connection.prototype.canConnectWithReason=function(e){if(!e)return t.Connection.REASON_TARGET_NULL;if(this.isSuperior())var o=this.sourceBlock_,i=e.getSourceBlock();else i=this.sourceBlock_,o=e.getSourceBlock();return o&&o==i?t.Connection.REASON_SELF_CONNECTION:e.type!=t.OPPOSITE_TYPE[this.type]?t.Connection.REASON_WRONG_TYPE:o&&i&&o.workspace!==i.workspace?t.Connection.REASON_DIFFERENT_WORKSPACES:this.checkType(e)?o.isShadow()&&!i.isShadow()?t.Connection.REASON_SHADOW_PARENT:t.Connection.CAN_CONNECT:t.Connection.REASON_CHECKS_FAILED},t.Connection.prototype.checkConnection=function(e){switch(this.canConnectWithReason(e)){case t.Connection.CAN_CONNECT:break;case t.Connection.REASON_SELF_CONNECTION:throw Error("Attempted to connect a block to itself.");case t.Connection.REASON_DIFFERENT_WORKSPACES:throw Error("Blocks not on same workspace.");case t.Connection.REASON_WRONG_TYPE:throw Error("Attempt to connect incompatible types.");case t.Connection.REASON_TARGET_NULL:throw Error("Target connection is null.");case t.Connection.REASON_CHECKS_FAILED:throw Error("Connection checks failed. "+this+" expected "+this.check_+", found "+e.check_);case t.Connection.REASON_SHADOW_PARENT:throw Error("Connecting non-shadow to shadow block.");default:throw Error("Unknown connection failure: this should never happen!")}},t.Connection.prototype.canConnectToPrevious_=function(e){return!(this.targetConnection||-1!=t.draggingConnections.indexOf(e)||e.targetConnection&&(!(e=e.targetBlock()).isInsertionMarker()||e.getPreviousBlock()))},t.Connection.prototype.isConnectionAllowed=function(e){if(e.sourceBlock_.isInsertionMarker()||this.canConnectWithReason(e)!=t.Connection.CAN_CONNECT)return!1;switch(e.type){case t.PREVIOUS_STATEMENT:return this.canConnectToPrevious_(e);case t.OUTPUT_VALUE:if(e.isConnected()&&!e.targetBlock().isInsertionMarker()||this.isConnected())return!1;break;case t.INPUT_VALUE:if(e.isConnected()&&!e.targetBlock().isMovable()&&!e.targetBlock().isShadow())return!1;break;case t.NEXT_STATEMENT:if(e.isConnected()&&!this.sourceBlock_.nextConnection&&!e.targetBlock().isShadow()&&e.targetBlock().nextConnection)return!1;break;default:throw Error("Unknown connection type in isConnectionAllowed")}return-1==t.draggingConnections.indexOf(e)},t.Connection.prototype.onFailedConnect=function(t){},t.Connection.prototype.connect=function(e){if(this.targetConnection!=e){this.checkConnection(e);var o=t.Events.getGroup();o||t.Events.setGroup(!0),this.isSuperior()?this.connect_(e):e.connect_(this),o||t.Events.setGroup(!1)}},t.Connection.connectReciprocally_=function(t,e){if(!t||!e)throw Error("Cannot connect null connections.");t.targetConnection=e,e.targetConnection=t},t.Connection.singleConnection_=function(e,o){for(var i=null,n=0;n<e.inputList.length;n++){var s=e.inputList[n].connection;if(s&&s.type==t.INPUT_VALUE&&o.outputConnection.checkType(s)){if(i)return null;i=s}}return i},t.Connection.lastConnectionInRow=function(e,o){for(var i;i=t.Connection.singleConnection_(e,o);)if(!(e=i.targetBlock())||e.isShadow())return i;return null},t.Connection.prototype.disconnect=function(){var e=this.targetConnection;if(!e)throw Error("Source connection not connected.");if(e.targetConnection!=this)throw Error("Target connection not connected to source connection.");if(this.isSuperior()){var o=this.sourceBlock_,i=e.getSourceBlock();e=this}else o=e.getSourceBlock(),i=this.sourceBlock_;var n=t.Events.getGroup();n||t.Events.setGroup(!0),this.disconnectInternal_(o,i),e.respawnShadow_(),n||t.Events.setGroup(!1)},t.Connection.prototype.disconnectInternal_=function(e,o){var i;t.Events.isEnabled()&&(i=new t.Events.BlockMove(o)),this.targetConnection=this.targetConnection.targetConnection=null,o.setParent(null),i&&(i.recordNew(),t.Events.fire(i))},t.Connection.prototype.respawnShadow_=function(){var e=this.getSourceBlock(),o=this.getShadowDom();if(e.workspace&&o&&t.Events.recordUndo)if((e=t.Xml.domToBlock(o,e.workspace)).outputConnection)this.connect(e.outputConnection);else{if(!e.previousConnection)throw Error("Child block does not have output or previous statement.");this.connect(e.previousConnection)}},t.Connection.prototype.targetBlock=function(){return this.isConnected()?this.targetConnection.getSourceBlock():null},t.Connection.prototype.checkType=function(t){if(!this.check_||!t.check_)return!0;for(var e=0;e<this.check_.length;e++)if(-1!=t.check_.indexOf(this.check_[e]))return!0;return!1},t.Connection.prototype.checkType_=function(t){return console.warn("Deprecated call to Blockly.Connection.prototype.checkType_, use Blockly.Connection.prototype.checkType instead."),this.checkType(t)},t.Connection.prototype.onCheckChanged_=function(){!this.isConnected()||this.targetConnection&&this.checkType(this.targetConnection)||(this.isSuperior()?this.targetBlock():this.sourceBlock_).unplug()},t.Connection.prototype.setCheck=function(t){return t?(Array.isArray(t)||(t=[t]),this.check_=t,this.onCheckChanged_()):this.check_=null,this},t.Connection.prototype.getCheck=function(){return this.check_},t.Connection.prototype.setShadowDom=function(t){this.shadowDom_=t},t.Connection.prototype.getShadowDom=function(){return this.shadowDom_},t.Connection.prototype.neighbours=function(t){return[]},t.Connection.prototype.getParentInput=function(){for(var t=null,e=this.sourceBlock_,o=e.inputList,i=0;i<e.inputList.length;i++)if(o[i].connection===this){t=o[i];break}return t},t.Connection.prototype.toString=function(){var t=this.sourceBlock_;if(!t)return"Orphan Connection";if(t.outputConnection==this)var e="Output Connection of ";else if(t.previousConnection==this)e="Previous Connection of ";else if(t.nextConnection==this)e="Next Connection of ";else{e=null;for(var o,i=0;o=t.inputList[i];i++)if(o.connection==this){e=o;break}if(!e)return console.warn("Connection not actually connected to sourceBlock_"),"Orphan Connection";e='Input "'+e.name+'" connection on '}return e+t.toDevString()},t.Extensions={},t.Extensions.ALL_={},t.Extensions.register=function(e,o){if("string"!=typeof e||""==e.trim())throw Error('Error: Invalid extension name "'+e+'"');if(t.Extensions.ALL_[e])throw Error('Error: Extension "'+e+'" is already registered.');if("function"!=typeof o)throw Error('Error: Extension "'+e+'" must be a function');t.Extensions.ALL_[e]=o},t.Extensions.registerMixin=function(e,o){if(!o||"object"!=typeof o)throw Error('Error: Mixin "'+e+'" must be a object');t.Extensions.register(e,(function(){this.mixin(o)}))},t.Extensions.registerMutator=function(e,o,i,n){var s='Error when registering mutator "'+e+'": ';t.Extensions.checkHasFunction_(s,o.domToMutation,"domToMutation"),t.Extensions.checkHasFunction_(s,o.mutationToDom,"mutationToDom");var r=t.Extensions.checkMutatorDialog_(o,s);if(i&&"function"!=typeof i)throw Error('Extension "'+e+'" is not a function');t.Extensions.register(e,(function(){if(r){if(!t.Mutator)throw Error(s+"Missing require for Blockly.Mutator");this.setMutator(new t.Mutator(n||[]))}this.mixin(o),i&&i.apply(this)}))},t.Extensions.unregister=function(e){t.Extensions.ALL_[e]?delete t.Extensions.ALL_[e]:console.warn('No extension mapping for name "'+e+'" found to unregister')},t.Extensions.apply=function(e,o,i){var n=t.Extensions.ALL_[e];if("function"!=typeof n)throw Error('Error: Extension "'+e+'" not found.');if(i)t.Extensions.checkNoMutatorProperties_(e,o);else var s=t.Extensions.getMutatorProperties_(o);if(n.apply(o),i)t.Extensions.checkBlockHasMutatorProperties_('Error after applying mutator "'+e+'": ',o);else if(!t.Extensions.mutatorPropertiesMatch_(s,o))throw Error('Error when applying extension "'+e+'": mutation properties changed when applying a non-mutator extension.')},t.Extensions.checkHasFunction_=function(t,e,o){if(!e)throw Error(t+'missing required property "'+o+'"');if("function"!=typeof e)throw Error(t+'" required property "'+o+'" must be a function')},t.Extensions.checkNoMutatorProperties_=function(e,o){if(t.Extensions.getMutatorProperties_(o).length)throw Error('Error: tried to apply mutation "'+e+'" to a block that already has mutator functions.  Block id: '+o.id)},t.Extensions.checkMutatorDialog_=function(t,e){var o=void 0!==t.compose,i=void 0!==t.decompose;if(o&&i){if("function"!=typeof t.compose)throw Error(e+"compose must be a function.");if("function"!=typeof t.decompose)throw Error(e+"decompose must be a function.");return!0}if(o||i)throw Error(e+'Must have both or neither of "compose" and "decompose"');return!1},t.Extensions.checkBlockHasMutatorProperties_=function(e,o){if("function"!=typeof o.domToMutation)throw Error(e+'Applying a mutator didn\'t add "domToMutation"');if("function"!=typeof o.mutationToDom)throw Error(e+'Applying a mutator didn\'t add "mutationToDom"');t.Extensions.checkMutatorDialog_(o,e)},t.Extensions.getMutatorProperties_=function(t){var e=[];return void 0!==t.domToMutation&&e.push(t.domToMutation),void 0!==t.mutationToDom&&e.push(t.mutationToDom),void 0!==t.compose&&e.push(t.compose),void 0!==t.decompose&&e.push(t.decompose),e},t.Extensions.mutatorPropertiesMatch_=function(e,o){if((o=t.Extensions.getMutatorProperties_(o)).length!=e.length)return!1;for(var i=0;i<o.length;i++)if(e[i]!=o[i])return!1;return!0},t.Extensions.buildTooltipForDropdown=function(e,o){var i=[];return"object"==typeof document&&t.utils.runAfterPageLoad((function(){for(var e in o)t.utils.checkMessageReferences(o[e])})),function(){this.type&&-1==i.indexOf(this.type)&&(t.Extensions.checkDropdownOptionsInTable_(this,e,o),i.push(this.type)),this.setTooltip(function(){var n=String(this.getFieldValue(e)),s=o[n];return null==s?-1==i.indexOf(this.type)&&(n="No tooltip mapping for value "+n+" of field "+e,null!=this.type&&(n+=" of block type "+this.type),console.warn(n+".")):s=t.utils.replaceMessageReferences(s),s}.bind(this))}},t.Extensions.checkDropdownOptionsInTable_=function(t,e,o){var i=t.getField(e);if(!i.isOptionListDynamic()){i=i.getOptions();for(var n=0;n<i.length;++n){var s=i[n][1];null==o[s]&&console.warn("No tooltip mapping for value "+s+" of field "+e+" of block type "+t.type)}}},t.Extensions.buildTooltipWithFieldText=function(e,o){return"object"==typeof document&&t.utils.runAfterPageLoad((function(){t.utils.checkMessageReferences(e)})),function(){this.setTooltip(function(){var i=this.getField(o);return t.utils.replaceMessageReferences(e).replace("%1",i?i.getText():"")}.bind(this))}},t.Extensions.extensionParentTooltip_=function(){this.tooltipWhenNotConnected_=this.tooltip,this.setTooltip(function(){var t=this.getParent();return t&&t.getInputsInline()&&t.tooltip||this.tooltipWhenNotConnected_}.bind(this))},t.Extensions.register("parent_tooltip_when_inline",t.Extensions.extensionParentTooltip_),t.fieldRegistry={},t.fieldRegistry.typeMap_={},t.fieldRegistry.register=function(e,o){if("string"!=typeof e||""==e.trim())throw Error('Invalid field type "'+e+'". The type must be a non-empty string.');if(t.fieldRegistry.typeMap_[e])throw Error('Error: Field "'+e+'" is already registered.');if(!o||"function"!=typeof o.fromJson)throw Error('Field "'+o+'" must have a fromJson function');e=e.toLowerCase(),t.fieldRegistry.typeMap_[e]=o},t.fieldRegistry.unregister=function(e){t.fieldRegistry.typeMap_[e]?delete t.fieldRegistry.typeMap_[e]:console.warn('No field mapping for type "'+e+'" found to unregister')},t.fieldRegistry.fromJson=function(e){var o=e.type.toLowerCase();return(o=t.fieldRegistry.typeMap_[o])?o.fromJson(e):(console.warn("Blockly could not create a field of type "+e.type+". The field is probably not being registered. This could be because the file is not loaded, the field does not register itself (Issue #1584), or the registration is not being reached."),null)},t.blockAnimations={},t.blockAnimations.disconnectPid_=0,t.blockAnimations.disconnectGroup_=null,t.blockAnimations.disposeUiEffect=function(e){var o=e.workspace,i=e.getSvgRoot();o.getAudioManager().play("delete"),e=o.getSvgXY(i),(i=i.cloneNode(!0)).translateX_=e.x,i.translateY_=e.y,i.setAttribute("transform","translate("+e.x+","+e.y+")"),o.getParentSvg().appendChild(i),i.bBox_=i.getBBox(),t.blockAnimations.disposeUiStep_(i,o.RTL,new Date,o.scale)},t.blockAnimations.disposeUiStep_=function(e,o,i,n){var s=(new Date-i)/150;1<s?t.utils.dom.removeNode(e):(e.setAttribute("transform","translate("+(e.translateX_+(o?-1:1)*e.bBox_.width*n/2*s)+","+(e.translateY_+e.bBox_.height*n*s)+") scale("+(1-s)*n+")"),setTimeout(t.blockAnimations.disposeUiStep_,10,e,o,i,n))},t.blockAnimations.connectionUiEffect=function(e){var o=e.workspace,i=o.scale;if(o.getAudioManager().play("click"),!(1>i)){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;1<n?t.utils.dom.removeNode(e):(e.setAttribute("r",25*n*i),e.style.opacity=1-n,t.blockAnimations.disconnectPid_=setTimeout(t.blockAnimations.connectionUiStep_,10,e,o,i))},t.blockAnimations.disconnectUiEffect=function(e){if(e.workspace.getAudioManager().play("disconnect"),!(1>e.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;1<n?e.skew_="":(e.skew_="skewX("+Math.round(Math.sin(n*Math.PI*3)*(1-n)*o)+")",t.blockAnimations.disconnectGroup_=e,t.blockAnimations.disconnectPid_=setTimeout(t.blockAnimations.disconnectUiStep_,10,e,o,i)),e.setAttribute("transform",e.translate_+e.skew_)},t.blockAnimations.disconnectUiStop=function(){if(t.blockAnimations.disconnectGroup_){clearTimeout(t.blockAnimations.disconnectPid_);var e=t.blockAnimations.disconnectGroup_;e.skew_="",e.setAttribute("transform",e.translate_),t.blockAnimations.disconnectGroup_=null}},t.InsertionMarkerManager=function(e){this.topBlock_=t.selected=e,this.workspace_=e.workspace,this.lastMarker_=this.lastOnStack_=null,this.firstMarker_=this.createMarkerBlock_(this.topBlock_),this.localConnection_=this.closestConnection_=null,this.wouldDeleteBlock_=!1,this.fadedBlock_=this.highlightedBlock_=this.markerConnection_=null,this.availableConnections_=this.initAvailableConnections_()},t.InsertionMarkerManager.PREVIEW_TYPE={INSERTION_MARKER:0,INPUT_OUTLINE:1,REPLACEMENT_FADE:2},t.InsertionMarkerManager.prototype.dispose=function(){this.availableConnections_.length=0,t.Events.disable();try{this.firstMarker_&&this.firstMarker_.dispose(),this.lastMarker_&&this.lastMarker_.dispose()}finally{t.Events.enable()}},t.InsertionMarkerManager.prototype.wouldDeleteBlock=function(){return this.wouldDeleteBlock_},t.InsertionMarkerManager.prototype.wouldConnectBlock=function(){return!!this.closestConnection_},t.InsertionMarkerManager.prototype.applyConnections=function(){if(this.closestConnection_&&(t.Events.disable(),this.hidePreview_(),t.Events.enable(),this.localConnection_.connect(this.closestConnection_),this.topBlock_.rendered)){var e=this.localConnection_.isSuperior()?this.closestConnection_:this.localConnection_;t.blockAnimations.connectionUiEffect(e.getSourceBlock()),this.topBlock_.getRootBlock().bringToFront()}},t.InsertionMarkerManager.prototype.update=function(e,o){var i=this.getCandidate_(e);((this.wouldDeleteBlock_=this.shouldDelete_(i,o))||this.shouldUpdatePreviews_(i,e))&&(t.Events.disable(),this.maybeHidePreview_(i),this.maybeShowPreview_(i),t.Events.enable())},t.InsertionMarkerManager.prototype.createMarkerBlock_=function(e){var o=e.type;t.Events.disable();try{var i=this.workspace_.newBlock(o);if(i.setInsertionMarker(!0),e.mutationToDom){var n=e.mutationToDom();n&&i.domToMutation(n)}for(i.setCollapsed(e.isCollapsed()),i.setInputsInline(e.getInputsInline()),o=0;o<e.inputList.length;o++){var s=e.inputList[o];if(s.isVisible()){var r=i.inputList[o];for(n=0;n<s.fieldRow.length;n++)r.fieldRow[n].setValue(s.fieldRow[n].getValue())}}i.initSvg(),i.getSvgRoot().setAttribute("visibility","hidden")}finally{t.Events.enable()}return i},t.InsertionMarkerManager.prototype.initAvailableConnections_=function(){var t=this.topBlock_.getConnections_(!1),e=this.topBlock_.lastConnectionInStack();return e&&e!=this.topBlock_.nextConnection&&(t.push(e),this.lastOnStack_=e,this.lastMarker_=this.createMarkerBlock_(e.getSourceBlock())),t},t.InsertionMarkerManager.prototype.shouldUpdatePreviews_=function(e,o){var i=e.local,n=e.closest;return e=e.radius,i&&n?this.localConnection_&&this.closestConnection_?!(this.closestConnection_==n&&this.localConnection_==i||(i=this.localConnection_.x+o.x-this.closestConnection_.x,o=this.localConnection_.y+o.y-this.closestConnection_.y,o=Math.sqrt(i*i+o*o),n&&e>o-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;n<this.availableConnections_.length;n++){var s=this.availableConnections_[n],r=s.closest(e,t);r.connection&&(o=r.connection,i=s,e=r.radius)}return{closest:o,local:i,radius:e}},t.InsertionMarkerManager.prototype.getStartRadius_=function(){return this.closestConnection_&&this.localConnection_?t.CONNECTING_SNAP_RADIUS:t.SNAP_RADIUS},t.InsertionMarkerManager.prototype.shouldDelete_=function(e,o){return e=e&&!!e.closest&&o!=t.DELETE_AREA_TOOLBOX,!!o&&!this.topBlock_.getParent()&&this.topBlock_.isDeletable()&&!e},t.InsertionMarkerManager.prototype.maybeShowPreview_=function(t){if(!this.wouldDeleteBlock_){var e=t.closest;t=t.local,e&&(e==this.closestConnection_||e.getSourceBlock().isInsertionMarker()?console.log("Trying to connect to an insertion marker"):(this.closestConnection_=e,this.localConnection_=t,this.showPreview_()))}},t.InsertionMarkerManager.prototype.showPreview_=function(){var e=this.closestConnection_,o=this.workspace_.getRenderer();switch(o.getConnectionPreviewMethod(e,this.localConnection_,this.topBlock_)){case t.InsertionMarkerManager.PREVIEW_TYPE.INPUT_OUTLINE:this.showInsertionInputOutline_();break;case t.InsertionMarkerManager.PREVIEW_TYPE.INSERTION_MARKER:this.showInsertionMarker_();break;case t.InsertionMarkerManager.PREVIEW_TYPE.REPLACEMENT_FADE:this.showReplacementFade_()}e&&o.shouldHighlightConnection(e)&&e.highlight()},t.InsertionMarkerManager.prototype.maybeHidePreview_=function(t){if(t.closest){var e=this.closestConnection_!=t.closest;t=this.localConnection_!=t.local,this.closestConnection_&&this.localConnection_&&(e||t||this.wouldDeleteBlock_)&&this.hidePreview_()}else this.hidePreview_();this.localConnection_=this.closestConnection_=this.markerConnection_=null},t.InsertionMarkerManager.prototype.hidePreview_=function(){this.closestConnection_&&this.closestConnection_.targetBlock()&&this.workspace_.getRenderer().shouldHighlightConnection(this.closestConnection_)&&this.closestConnection_.unhighlight(),this.fadedBlock_?this.hideReplacementFade_():this.highlightedBlock_?this.hideInsertionInputOutline_():this.markerConnection_&&this.hideInsertionMarker_()},t.InsertionMarkerManager.prototype.showInsertionMarker_=function(){var t=this.localConnection_,e=this.closestConnection_,o=this.lastOnStack_&&t==this.lastOnStack_?this.lastMarker_:this.firstMarker_;if((t=o.getMatchingConnection(t.getSourceBlock(),t))==this.markerConnection_)throw Error("Made it to showInsertionMarker_ even though the marker isn't changing");o.render(),o.rendered=!0,o.getSvgRoot().setAttribute("visibility","visible"),t&&e&&o.positionNearConnection(t,e),e&&t.connect(e),this.markerConnection_=t},t.InsertionMarkerManager.prototype.hideInsertionMarker_=function(){if(this.markerConnection_){var e=this.markerConnection_,o=e.getSourceBlock(),i=o.nextConnection,n=o.previousConnection,s=o.outputConnection;if(s=e.type==t.INPUT_VALUE&&!(s&&s.targetConnection),!(e!=i||n&&n.targetConnection)||s?e.targetBlock().unplug(!1):e.type==t.NEXT_STATEMENT&&e!=i?((i=e.targetConnection).getSourceBlock().unplug(!1),n=n?n.targetConnection:null,o.unplug(!0),n&&n.connect(i)):o.unplug(!0),e.targetConnection)throw Error("markerConnection_ still connected at the end of disconnectInsertionMarker");this.markerConnection_=null,o.getSvgRoot().setAttribute("visibility","hidden")}else console.log("No insertion marker connection to disconnect")},t.InsertionMarkerManager.prototype.showInsertionInputOutline_=function(){var t=this.closestConnection_;this.highlightedBlock_=t.getSourceBlock(),this.highlightedBlock_.highlightShapeForInput(t,!0)},t.InsertionMarkerManager.prototype.hideInsertionInputOutline_=function(){this.highlightedBlock_.highlightShapeForInput(this.closestConnection_,!1),this.highlightedBlock_=null},t.InsertionMarkerManager.prototype.showReplacementFade_=function(){this.fadedBlock_=this.closestConnection_.targetBlock(),this.fadedBlock_.fadeForReplacement(!0)},t.InsertionMarkerManager.prototype.hideReplacementFade_=function(){this.fadedBlock_.fadeForReplacement(!1),this.fadedBlock_=null},t.InsertionMarkerManager.prototype.getInsertionMarkers=function(){var t=[];return this.firstMarker_&&t.push(this.firstMarker_),this.lastMarker_&&t.push(this.lastMarker_),t},t.BlockDragger=function(e,o){this.draggingBlock_=e,this.workspace_=o,this.draggedConnectionManager_=new t.InsertionMarkerManager(this.draggingBlock_),this.deleteArea_=null,this.wouldDeleteBlock_=!1,this.startXY_=this.draggingBlock_.getRelativeToSurfaceXY(),this.dragIconData_=t.BlockDragger.initIconData_(e)},t.BlockDragger.prototype.dispose=function(){this.dragIconData_.length=0,this.draggedConnectionManager_&&this.draggedConnectionManager_.dispose()},t.BlockDragger.initIconData_=function(t){var e=[];t=t.getDescendants(!1);for(var o,i=0;o=t[i];i++){o=o.getIcons();for(var n=0;n<o.length;n++){var s={location:o[n].getIconLocation(),icon:o[n]};e.push(s)}}return e},t.BlockDragger.prototype.startBlockDrag=function(e,o){t.Events.getGroup()||t.Events.setGroup(!0),this.fireDragStartEvent_(),this.workspace_.isMutator&&this.draggingBlock_.bringToFront(),t.utils.dom.startTextWidthCache(),this.workspace_.setResizesEnabled(!1),t.blockAnimations.disconnectUiStop(),(this.draggingBlock_.getParent()||o&&this.draggingBlock_.nextConnection&&this.draggingBlock_.nextConnection.targetBlock())&&(this.draggingBlock_.unplug(o),e=this.pixelsToWorkspaceUnits_(e),e=t.utils.Coordinate.sum(this.startXY_,e),this.draggingBlock_.translate(e.x,e.y),t.blockAnimations.disconnectUiEffect(this.draggingBlock_)),this.draggingBlock_.setDragging(!0),this.draggingBlock_.moveToDragSurface(),(e=this.workspace_.getToolbox())&&(o=this.draggingBlock_.isDeletable()?"blocklyToolboxDelete":"blocklyToolboxGrab",e.addStyle(o))},t.BlockDragger.prototype.fireDragStartEvent_=function(){var e=new t.Events.Ui(this.draggingBlock_,"dragStart",null,this.draggingBlock_.getDescendants(!1));t.Events.fire(e)},t.BlockDragger.prototype.dragBlock=function(e,o){o=this.pixelsToWorkspaceUnits_(o);var i=t.utils.Coordinate.sum(this.startXY_,o);this.draggingBlock_.moveDuringDrag(i),this.dragIcons_(o),this.deleteArea_=this.workspace_.isDeleteArea(e),this.draggedConnectionManager_.update(o,this.deleteArea_),this.updateCursorDuringBlockDrag_()},t.BlockDragger.prototype.endBlockDrag=function(e,o){this.dragBlock(e,o),this.dragIconData_=[],this.fireDragEndEvent_(),t.utils.dom.stopTextWidthCache(),t.blockAnimations.disconnectUiStop(),e=this.pixelsToWorkspaceUnits_(o),o=t.utils.Coordinate.sum(this.startXY_,e),this.draggingBlock_.moveOffDragSurface(o),this.maybeDeleteBlock_()||(this.draggingBlock_.moveConnections(e.x,e.y),this.draggingBlock_.setDragging(!1),this.fireMoveEvent_(),this.draggedConnectionManager_.wouldConnectBlock()?this.draggedConnectionManager_.applyConnections():this.draggingBlock_.render(),this.draggingBlock_.scheduleSnapAndBump()),this.workspace_.setResizesEnabled(!0),(e=this.workspace_.getToolbox())&&(o=this.draggingBlock_.isDeletable()?"blocklyToolboxDelete":"blocklyToolboxGrab",e.removeStyle(o)),t.Events.setGroup(!1)},t.BlockDragger.prototype.fireDragEndEvent_=function(){var e=new t.Events.Ui(this.draggingBlock_,"dragStop",this.draggingBlock_.getDescendants(!1),null);t.Events.fire(e)},t.BlockDragger.prototype.fireMoveEvent_=function(){var e=new t.Events.BlockMove(this.draggingBlock_);e.oldCoordinate=this.startXY_,e.recordNew(),t.Events.fire(e)},t.BlockDragger.prototype.maybeDeleteBlock_=function(){var e=this.workspace_.trashcan;return this.wouldDeleteBlock_?(e&&setTimeout(e.close.bind(e),100),this.fireMoveEvent_(),this.draggingBlock_.dispose(!1,!0),t.draggingConnections=[]):e&&e.close(),this.wouldDeleteBlock_},t.BlockDragger.prototype.updateCursorDuringBlockDrag_=function(){this.wouldDeleteBlock_=this.draggedConnectionManager_.wouldDeleteBlock();var e=this.workspace_.trashcan;this.wouldDeleteBlock_?(this.draggingBlock_.setDeleteStyle(!0),this.deleteArea_==t.DELETE_AREA_TRASH&&e&&e.setOpen(!0)):(this.draggingBlock_.setDeleteStyle(!1),e&&e.setOpen(!1))},t.BlockDragger.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.BlockDragger.prototype.dragIcons_=function(e){for(var o=0;o<this.dragIconData_.length;o++){var i=this.dragIconData_[o];i.icon.setIconLocation(t.utils.Coordinate.sum(i.location,e))}},t.BlockDragger.prototype.getInsertionMarkers=function(){return this.draggedConnectionManager_&&this.draggedConnectionManager_.getInsertionMarkers?this.draggedConnectionManager_.getInsertionMarkers():[]},t.VariableMap=function(t){this.variableMap_=Object.create(null),this.workspace=t},t.VariableMap.prototype.clear=function(){this.variableMap_=Object.create(null)},t.VariableMap.prototype.renameVariable=function(e,o){var i=this.getVariable(o,e.type),n=this.workspace.getAllBlocks(!1);t.Events.setGroup(!0);try{i&&i.getId()!=e.getId()?this.renameVariableWithConflict_(e,o,i,n):this.renameVariableAndUses_(e,o,n)}finally{t.Events.setGroup(!1)}},t.VariableMap.prototype.renameVariableById=function(t,e){var o=this.getVariableById(t);if(!o)throw Error("Tried to rename a variable that didn't exist. ID: "+t);this.renameVariable(o,e)},t.VariableMap.prototype.renameVariableAndUses_=function(e,o,i){for(t.Events.fire(new t.Events.VarRename(e,o)),e.name=o,o=0;o<i.length;o++)i[o].updateVarName(e)},t.VariableMap.prototype.renameVariableWithConflict_=function(e,o,i,n){var s=e.type;for(o!=i.name&&this.renameVariableAndUses_(i,o,n),o=0;o<n.length;o++)n[o].renameVarById(e.getId(),i.getId());t.Events.fire(new t.Events.VarDelete(e)),e=this.getVariablesOfType(s).indexOf(e),this.variableMap_[s].splice(e,1)},t.VariableMap.prototype.createVariable=function(e,o,i){var n=this.getVariable(e,o);if(n){if(i&&n.getId()!=i)throw Error('Variable "'+e+'" is already in use and its id is "'+n.getId()+'" which conflicts with the passed in id, "'+i+'".');return n}if(i&&this.getVariableById(i))throw Error('Variable id, "'+i+'", is already in use.');return n=i||t.utils.genUid(),o=o||"",n=new t.VariableModel(this.workspace,e,o,n),(e=this.variableMap_[o]||[]).push(n),delete this.variableMap_[o],this.variableMap_[o]=e,n},t.VariableMap.prototype.deleteVariable=function(e){for(var o,i=this.variableMap_[e.type],n=0;o=i[n];n++)if(o.getId()==e.getId()){i.splice(n,1),t.Events.fire(new t.Events.VarDelete(e));break}},t.VariableMap.prototype.deleteVariableById=function(e){var o=this.getVariableById(e);if(o){var i,n=o.name,s=this.getVariableUsesById(e);for(e=0;i=s[e];e++)if("procedures_defnoreturn"==i.type||"procedures_defreturn"==i.type)return e=i.getFieldValue("NAME"),n=t.Msg.CANNOT_DELETE_VARIABLE_PROCEDURE.replace("%1",n).replace("%2",e),void t.alert(n);var r=this;1<s.length?(n=t.Msg.DELETE_VARIABLE_CONFIRMATION.replace("%1",String(s.length)).replace("%2",n),t.confirm(n,(function(t){t&&o&&r.deleteVariableInternal(o,s)}))):r.deleteVariableInternal(o,s)}else console.warn("Can't delete non-existent variable: "+e)},t.VariableMap.prototype.deleteVariableInternal=function(e,o){var i=t.Events.getGroup();i||t.Events.setGroup(!0);try{for(var n=0;n<o.length;n++)o[n].dispose(!0);this.deleteVariable(e)}finally{i||t.Events.setGroup(!1)}},t.VariableMap.prototype.getVariable=function(e,o){if(o=this.variableMap_[o||""])for(var i,n=0;i=o[n];n++)if(t.Names.equals(i.name,e))return i;return null},t.VariableMap.prototype.getVariableById=function(t){for(var e=Object.keys(this.variableMap_),o=0;o<e.length;o++)for(var i,n=e[o],s=0;i=this.variableMap_[n][s];s++)if(i.getId()==t)return i;return null},t.VariableMap.prototype.getVariablesOfType=function(t){return(t=this.variableMap_[t||""])?t.slice():[]},t.VariableMap.prototype.getVariableTypes=function(e){var o={};t.utils.object.mixin(o,this.variableMap_),e&&e.getPotentialVariableMap()&&t.utils.object.mixin(o,e.getPotentialVariableMap().variableMap_),e=Object.keys(o),o=!1;for(var i=0;i<e.length;i++)""==e[i]&&(o=!0);return o||e.push(""),e},t.VariableMap.prototype.getAllVariables=function(){var t,e=[];for(t in this.variableMap_)e=e.concat(this.variableMap_[t]);return e},t.VariableMap.prototype.getAllVariableNames=function(){var t,e=[];for(t in this.variableMap_)for(var o,i=this.variableMap_[t],n=0;o=i[n];n++)e.push(o.name);return e},t.VariableMap.prototype.getVariableUsesById=function(t){for(var e=[],o=this.workspace.getAllBlocks(!1),i=0;i<o.length;i++){var n=o[i].getVarModels();if(n)for(var s=0;s<n.length;s++)n[s].getId()==t&&e.push(o[i])}return e},t.Workspace=function(e){this.id=t.utils.genUid(),t.Workspace.WorkspaceDB_[this.id]=this,this.options=e||new t.Options({}),this.RTL=!!this.options.RTL,this.horizontalLayout=!!this.options.horizontalLayout,this.toolboxPosition=this.options.toolboxPosition,this.topBlocks_=[],this.topComments_=[],this.commentDB_=Object.create(null),this.listeners_=[],this.undoStack_=[],this.redoStack_=[],this.blockDB_=Object.create(null),this.typedBlocksDB_=Object.create(null),this.variableMap_=new t.VariableMap(this),this.potentialVariableMap_=null},t.Workspace.prototype.rendered=!1,t.Workspace.prototype.isClearing=!1,t.Workspace.prototype.MAX_UNDO=1024,t.Workspace.prototype.connectionDBList=null,t.Workspace.prototype.dispose=function(){this.listeners_.length=0,this.clear(),delete t.Workspace.WorkspaceDB_[this.id]},t.Workspace.SCAN_ANGLE=3,t.Workspace.prototype.sortObjects_=function(e,o){return e=e.getRelativeToSurfaceXY(),o=o.getRelativeToSurfaceXY(),e.y+t.Workspace.prototype.sortObjects_.offset*e.x-(o.y+t.Workspace.prototype.sortObjects_.offset*o.x)},t.Workspace.prototype.addTopBlock=function(t){this.topBlocks_.push(t)},t.Workspace.prototype.removeTopBlock=function(e){if(!t.utils.arrayRemove(this.topBlocks_,e))throw Error("Block not present in workspace's list of top-most blocks.")},t.Workspace.prototype.getTopBlocks=function(e){var o=[].concat(this.topBlocks_);return e&&1<o.length&&(this.sortObjects_.offset=Math.sin(t.utils.math.toRadians(t.Workspace.SCAN_ANGLE)),this.RTL&&(this.sortObjects_.offset*=-1),o.sort(this.sortObjects_)),o},t.Workspace.prototype.addTypedBlock=function(t){this.typedBlocksDB_[t.type]||(this.typedBlocksDB_[t.type]=[]),this.typedBlocksDB_[t.type].push(t)},t.Workspace.prototype.removeTypedBlock=function(t){this.typedBlocksDB_[t.type].splice(this.typedBlocksDB_[t.type].indexOf(t),1),this.typedBlocksDB_[t.type].length||delete this.typedBlocksDB_[t.type]},t.Workspace.prototype.getBlocksByType=function(e,o){return this.typedBlocksDB_[e]?(e=this.typedBlocksDB_[e].slice(0),o&&1<e.length&&(this.sortObjects_.offset=Math.sin(t.utils.math.toRadians(t.Workspace.SCAN_ANGLE)),this.RTL&&(this.sortObjects_.offset*=-1),e.sort(this.sortObjects_)),e):[]},t.Workspace.prototype.addTopComment=function(t){this.topComments_.push(t),this.commentDB_[t.id]&&console.warn('Overriding an existing comment on this workspace, with id "'+t.id+'"'),this.commentDB_[t.id]=t},t.Workspace.prototype.removeTopComment=function(e){if(!t.utils.arrayRemove(this.topComments_,e))throw Error("Comment not present in workspace's list of top-most comments.");delete this.commentDB_[e.id]},t.Workspace.prototype.getTopComments=function(e){var o=[].concat(this.topComments_);return e&&1<o.length&&(this.sortObjects_.offset=Math.sin(t.utils.math.toRadians(t.Workspace.SCAN_ANGLE)),this.RTL&&(this.sortObjects_.offset*=-1),o.sort(this.sortObjects_)),o},t.Workspace.prototype.getAllBlocks=function(t){if(t){t=this.getTopBlocks(!0);for(var e=[],o=0;o<t.length;o++)e.push.apply(e,t[o].getDescendants(!0))}else for(e=this.getTopBlocks(!1),o=0;o<e.length;o++)e.push.apply(e,e[o].getChildren(!1));return e.filter((function(t){return!t.isInsertionMarker()}))},t.Workspace.prototype.clear=function(){this.isClearing=!0;try{var e=t.Events.getGroup();for(e||t.Events.setGroup(!0);this.topBlocks_.length;)this.topBlocks_[0].dispose(!1);for(;this.topComments_.length;)this.topComments_[this.topComments_.length-1].dispose(!1);e||t.Events.setGroup(!1),this.variableMap_.clear(),this.potentialVariableMap_&&this.potentialVariableMap_.clear()}finally{this.isClearing=!1}},t.Workspace.prototype.renameVariableById=function(t,e){this.variableMap_.renameVariableById(t,e)},t.Workspace.prototype.createVariable=function(t,e,o){return this.variableMap_.createVariable(t,e,o)},t.Workspace.prototype.getVariableUsesById=function(t){return this.variableMap_.getVariableUsesById(t)},t.Workspace.prototype.deleteVariableById=function(t){this.variableMap_.deleteVariableById(t)},t.Workspace.prototype.deleteVariableInternal_=function(t,e){this.variableMap_.deleteVariableInternal(t,e)},t.Workspace.prototype.variableIndexOf=function(t){return console.warn("Deprecated call to Blockly.Workspace.prototype.variableIndexOf"),-1},t.Workspace.prototype.getVariable=function(t,e){return this.variableMap_.getVariable(t,e)},t.Workspace.prototype.getVariableById=function(t){return this.variableMap_.getVariableById(t)},t.Workspace.prototype.getVariablesOfType=function(t){return this.variableMap_.getVariablesOfType(t)},t.Workspace.prototype.getVariableTypes=function(){return this.variableMap_.getVariableTypes(this)},t.Workspace.prototype.getAllVariables=function(){return this.variableMap_.getAllVariables()},t.Workspace.prototype.getAllVariableNames=function(){return this.variableMap_.getAllVariableNames()},t.Workspace.prototype.getWidth=function(){return 0},t.Workspace.prototype.newBlock=function(e,o){return new t.Block(this,e,o)},t.Workspace.prototype.remainingCapacity=function(){return isNaN(this.options.maxBlocks)?1/0:this.options.maxBlocks-this.getAllBlocks(!1).length},t.Workspace.prototype.remainingCapacityOfType=function(t){return this.options.maxInstances?(this.options.maxInstances[t]||1/0)-this.getBlocksByType(t,!1).length:1/0},t.Workspace.prototype.isCapacityAvailable=function(t){if(!this.hasBlockLimits())return!0;var e,o=0;for(e in t){if(t[e]>this.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.width<i.height?o:r,i=i.width<i.height?r:o,o=this.getOverlap_(n,t),r=this.getOverlap_(s,t);var a=this.getOverlap_(e,t);t=this.getOverlap_(i,t),o==(t=Math.max(o,r,a,t))?(this.relativeLeft_=n.x,this.relativeTop_=n.y):r==t?(this.relativeLeft_=s.x,this.relativeTop_=s.y):a==t?(this.relativeLeft_=e.x,this.relativeTop_=e.y):(this.relativeLeft_=i.x,this.relativeTop_=i.y)},t.Bubble.prototype.getOverlap_=function(t,e){var o=this.workspace_.RTL?this.anchorXY_.x-t.x-this.width_:t.x+this.anchorXY_.x;return t=t.y+this.anchorXY_.y,Math.max(0,Math.min(1,(Math.min(o+this.width_,e.viewLeft+e.viewWidth)-Math.max(o,e.viewLeft))*(Math.min(t+this.height_,e.viewTop+e.viewHeight)-Math.max(t,e.viewTop))/(this.width_*this.height_)))},t.Bubble.prototype.getOptimalRelativeLeft_=function(e){var o=-this.width_/4;if(this.width_>e.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?n<r?o=-(r-this.anchorXY_.x+this.width_):i>s&&(o=-(s-this.anchorXY_.x)):n<r?o=r-this.anchorXY_.x:i>s&&(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 i<s?o=s-r:n>e&&(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<n.length?o.setCurNode(t.navigation.getTopNode(n[0])):(i=new t.utils.Coordinate(100,100),e=t.ASTNode.createWorkspaceNode(e,i),o.setCurNode(e))},t.navigation.getFlyoutCursor_=function(){var e=t.getMainWorkspace(),o=null;return e.rendered&&(o=(e=(o=e.getToolbox())?o.flyout_:e.getFlyout())?e.workspace_.getCursor():null),o},t.navigation.insertFromFlyout=function(){var e=t.getMainWorkspace(),o=e.getFlyout();if(o&&o.isVisible()){var i=t.navigation.getFlyoutCursor_().getCurNode().getLocation();i.isEnabled()?((o=o.createBlock(i)).render(),o.setConnectionTracking(!0),e.getCursor().setCurNode(t.ASTNode.createBlockNode(o)),t.navigation.modify_()||t.navigation.warn_("Something went wrong while inserting a block from the flyout."),t.navigation.focusWorkspace_(),e.getCursor().setCurNode(t.navigation.getTopNode(o)),t.navigation.removeMark_()):t.navigation.warn_("Can't insert a disabled block.")}else t.navigation.warn_("Trying to insert from the flyout when the flyout does not  exist or is not visible")},t.navigation.resetFlyout_=function(e){t.navigation.getFlyoutCursor_()&&(t.navigation.getFlyoutCursor_().hide(),e&&t.getMainWorkspace().getFlyout().hide())},t.navigation.modifyWarn_=function(){var e=t.navigation.getMarker().getCurNode(),o=t.getMainWorkspace().getCursor().getCurNode();return e?o?(e=e.getType(),o=o.getType(),e==t.ASTNode.types.FIELD?(t.navigation.warn_("Should not have been able to mark a field."),!1):e==t.ASTNode.types.BLOCK?(t.navigation.warn_("Should not have been able to mark a block."),!1):e==t.ASTNode.types.STACK?(t.navigation.warn_("Should not have been able to mark a stack."),!1):o==t.ASTNode.types.FIELD?(t.navigation.warn_("Cannot attach a field to anything else."),!1):o!=t.ASTNode.types.WORKSPACE||(t.navigation.warn_("Cannot attach a workspace to anything else."),!1)):(t.navigation.warn_("Cannot insert with no cursor node."),!1):(t.navigation.warn_("Cannot insert with no marked node."),!1)},t.navigation.moveBlockToWorkspace_=function(e,o){return!!e&&(e.isShadow()?(t.navigation.warn_("Cannot move a shadow block to the workspace."),!1):(e.getParent()&&e.unplug(!1),e.moveTo(o.getWsCoordinate()),!0))},t.navigation.modify_=function(){var e=t.navigation.getMarker().getCurNode(),o=t.getMainWorkspace().getCursor().getCurNode();if(!t.navigation.modifyWarn_())return!1;var i=e.getType(),n=o.getType(),s=o.getLocation(),r=e.getLocation();return e.isConnection()&&o.isConnection()?t.navigation.connect_(s,r):!e.isConnection()||n!=t.ASTNode.types.BLOCK&&n!=t.ASTNode.types.STACK?i==t.ASTNode.types.WORKSPACE?(o=o?o.getSourceBlock():null,t.navigation.moveBlockToWorkspace_(o,e)):(t.navigation.warn_("Unexpected state in Blockly.navigation.modify_."),!1):t.navigation.insertBlock(s,r)},t.navigation.disconnectChild_=function(e,o){var i=e.getSourceBlock(),n=o.getSourceBlock();i.getRootBlock()==n.getRootBlock()&&(-1<i.getDescendants(!1).indexOf(n)?t.navigation.getInferiorConnection_(o).disconnect():t.navigation.getInferiorConnection_(e).disconnect())},t.navigation.moveAndConnect_=function(e,o){if(!e||!o)return!1;var i=e.getSourceBlock();return o.canConnectWithReason(e)==t.Connection.CAN_CONNECT&&(t.navigation.disconnectChild_(e,o),o.isSuperior()||i.getRootBlock().positionNearConnection(e,o),o.connect(e),!0)},t.navigation.getInferiorConnection_=function(t){var e=t.getSourceBlock();return t.isSuperior()?e.previousConnection?e.previousConnection:e.outputConnection?e.outputConnection:null:t},t.navigation.getSuperiorConnection_=function(t){return t.isSuperior()?t:t.targetConnection?t.targetConnection:null},t.navigation.connect_=function(e,o){if(!e||!o)return!1;var i=t.navigation.getInferiorConnection_(e),n=t.navigation.getSuperiorConnection_(o),s=t.navigation.getSuperiorConnection_(e),r=t.navigation.getInferiorConnection_(o);if(i&&n&&t.navigation.moveAndConnect_(i,n)||s&&r&&t.navigation.moveAndConnect_(s,r)||t.navigation.moveAndConnect_(e,o))return!0;try{o.checkConnection(e)}catch(e){t.navigation.warn_("Connection failed with error: "+e)}return!1},t.navigation.insertBlock=function(e,o){switch(o.type){case t.PREVIOUS_STATEMENT:if(t.navigation.connect_(e.nextConnection,o))return!0;break;case t.NEXT_STATEMENT:if(t.navigation.connect_(e.previousConnection,o))return!0;break;case t.INPUT_VALUE:if(t.navigation.connect_(e.outputConnection,o))return!0;break;case t.OUTPUT_VALUE:for(var i=0;i<e.inputList.length;i++){var n=e.inputList[i].connection;if(n&&n.type===t.INPUT_VALUE&&t.navigation.connect_(n,o))return!0}if(e.outputConnection&&t.navigation.connect_(e.outputConnection,o))return!0}return t.navigation.warn_("This block can not be inserted at the marked location."),!1},t.navigation.disconnectBlocks_=function(){var e=t.getMainWorkspace(),o=e.getCursor().getCurNode();if(o.isConnection()){var i=o.getLocation();i.isConnected()?(o=i.isSuperior()?i:i.targetConnection,(i=i.isSuperior()?i.targetConnection:i).getSourceBlock().isShadow()?t.navigation.log_("Cannot disconnect a shadow block"):(o.disconnect(),i.bumpAwayFrom(o),o.getSourceBlock().getRootBlock().bringToFront(),o=t.ASTNode.createConnectionNode(o),e.getCursor().setCurNode(o))):t.navigation.log_("Cannot disconnect unconnected connection")}else t.navigation.log_("Cannot disconnect blocks when the cursor is not on a connection")},t.navigation.markAtCursor_=function(){t.navigation.getMarker().setCurNode(t.getMainWorkspace().getCursor().getCurNode())},t.navigation.removeMark_=function(){var e=t.navigation.getMarker();e.setCurNode(null),e.hide()},t.navigation.setState=function(e){t.navigation.currentState_=e},t.navigation.getTopNode=function(e){var o=e.previousConnection||e.outputConnection;return o?t.ASTNode.createConnectionNode(o):t.ASTNode.createBlockNode(e)},t.navigation.moveCursorOnBlockDelete=function(e){var o=t.getMainWorkspace();if(o&&(o=o.getCursor())){var i=o.getCurNode();(i=i?i.getSourceBlock():null)===e?i.getParent()?(e=i.previousConnection||i.outputConnection)&&o.setCurNode(t.ASTNode.createConnectionNode(e.targetConnection)):o.setCurNode(t.ASTNode.createWorkspaceNode(i.workspace,i.getRelativeToSurfaceXY())):i&&-1<e.getChildren(!1).indexOf(i)&&o.setCurNode(t.ASTNode.createWorkspaceNode(i.workspace,i.getRelativeToSurfaceXY()))}},t.navigation.moveCursorOnBlockMutation=function(e){var o=t.getMainWorkspace().getCursor();if(o){var i=o.getCurNode();(i=i?i.getSourceBlock():null)===e&&o.setCurNode(t.ASTNode.createBlockNode(i))}},t.navigation.enableKeyboardAccessibility=function(){t.getMainWorkspace().keyboardAccessibilityMode||(t.getMainWorkspace().keyboardAccessibilityMode=!0,t.navigation.focusWorkspace_())},t.navigation.disableKeyboardAccessibility=function(){if(t.getMainWorkspace().keyboardAccessibilityMode){var e=t.getMainWorkspace();t.getMainWorkspace().keyboardAccessibilityMode=!1,e.getCursor().hide(),t.navigation.getMarker().hide(),t.navigation.getFlyoutCursor_()&&t.navigation.getFlyoutCursor_().hide()}},t.navigation.log_=function(e){t.navigation.loggingCallback?t.navigation.loggingCallback("log",e):console.log(e)},t.navigation.warn_=function(e){t.navigation.loggingCallback?t.navigation.loggingCallback("warn",e):console.warn(e)},t.navigation.error_=function(e){t.navigation.loggingCallback?t.navigation.loggingCallback("error",e):console.error(e)},t.navigation.onKeyPress=function(e){return e=t.user.keyMap.serializeKeyEvent(e),!!(e=t.user.keyMap.getActionByKeyCode(e))&&t.navigation.onBlocklyAction(e)},t.navigation.onBlocklyAction=function(e){var o=t.getMainWorkspace().options.readOnly,i=!1;return t.getMainWorkspace().keyboardAccessibilityMode?o?-1<t.navigation.READONLY_ACTION_LIST.indexOf(e)&&(i=t.navigation.handleActions_(e)):i=t.navigation.handleActions_(e):e.name===t.navigation.actionNames.TOGGLE_KEYBOARD_NAV&&(t.navigation.enableKeyboardAccessibility(),i=!0),i},t.navigation.handleActions_=function(e){return e.name==t.navigation.actionNames.TOOLBOX||t.navigation.currentState_==t.navigation.STATE_TOOLBOX?t.navigation.toolboxOnAction_(e):e.name==t.navigation.actionNames.TOGGLE_KEYBOARD_NAV?(t.navigation.disableKeyboardAccessibility(),!0):t.navigation.currentState_==t.navigation.STATE_WS?t.navigation.workspaceOnAction_(e):t.navigation.currentState_==t.navigation.STATE_FLYOUT&&t.navigation.flyoutOnAction_(e)},t.navigation.flyoutOnAction_=function(e){var o=t.getMainWorkspace(),i=o.getToolbox();if((o=i?i.flyout_:o.getFlyout())&&o.onBlocklyAction(e))return!0;switch(e.name){case t.navigation.actionNames.OUT:return t.navigation.focusToolbox_(),!0;case t.navigation.actionNames.MARK:return t.navigation.insertFromFlyout(),!0;case t.navigation.actionNames.EXIT:return t.navigation.focusWorkspace_(),!0;default:return!1}},t.navigation.toolboxOnAction_=function(e){var o=t.getMainWorkspace(),i=o.getToolbox();return!((!i||!i.onBlocklyAction(e))&&(e.name===t.navigation.actionNames.TOOLBOX?(o.getToolbox()?t.navigation.focusToolbox_():t.navigation.focusFlyout_(),0):e.name===t.navigation.actionNames.IN?(t.navigation.focusFlyout_(),0):e.name!==t.navigation.actionNames.EXIT||(t.navigation.focusWorkspace_(),0)))},t.navigation.moveWSCursor_=function(e,o){var i=t.getMainWorkspace().getCursor(),n=t.getMainWorkspace().getCursor().getCurNode();return n.getType()===t.ASTNode.types.WORKSPACE&&(n=n.getWsCoordinate(),e=e*t.navigation.WS_MOVE_DISTANCE+n.x,o=o*t.navigation.WS_MOVE_DISTANCE+n.y,i.setCurNode(t.ASTNode.createWorkspaceNode(t.getMainWorkspace(),new t.utils.Coordinate(e,o))),!0)},t.navigation.workspaceOnAction_=function(e){if(t.getMainWorkspace().getCursor().onBlocklyAction(e))return!0;switch(e.name){case t.navigation.actionNames.INSERT:return t.navigation.modify_(),!0;case t.navigation.actionNames.MARK:return t.navigation.handleEnterForWS_(),!0;case t.navigation.actionNames.DISCONNECT:return t.navigation.disconnectBlocks_(),!0;case t.navigation.actionNames.MOVE_WS_CURSOR_UP:return t.navigation.moveWSCursor_(0,-1);case t.navigation.actionNames.MOVE_WS_CURSOR_DOWN:return t.navigation.moveWSCursor_(0,1);case t.navigation.actionNames.MOVE_WS_CURSOR_LEFT:return t.navigation.moveWSCursor_(-1,0);case t.navigation.actionNames.MOVE_WS_CURSOR_RIGHT:return t.navigation.moveWSCursor_(1,0);default:return!1}},t.navigation.handleEnterForWS_=function(){var e=t.getMainWorkspace().getCursor().getCurNode(),o=e.getType();o==t.ASTNode.types.FIELD?e.getLocation().showEditor():e.isConnection()||o==t.ASTNode.types.WORKSPACE?t.navigation.markAtCursor_():o==t.ASTNode.types.BLOCK?t.navigation.warn_("Cannot mark a block."):o==t.ASTNode.types.STACK&&t.navigation.warn_("Cannot mark a stack.")},t.navigation.ACTION_PREVIOUS=new t.Action(t.navigation.actionNames.PREVIOUS,"Go to the previous location."),t.navigation.ACTION_OUT=new t.Action(t.navigation.actionNames.OUT,"Go to the parent of the current location."),t.navigation.ACTION_NEXT=new t.Action(t.navigation.actionNames.NEXT,"Go to the next location."),t.navigation.ACTION_IN=new t.Action(t.navigation.actionNames.IN,"Go to the first child of the current location."),t.navigation.ACTION_INSERT=new t.Action(t.navigation.actionNames.INSERT,"Connect the current location to the marked location."),t.navigation.ACTION_MARK=new t.Action(t.navigation.actionNames.MARK,"Mark the current location."),t.navigation.ACTION_DISCONNECT=new t.Action(t.navigation.actionNames.DISCONNECT,"Disconnect the block at the current location from its parent."),t.navigation.ACTION_TOOLBOX=new t.Action(t.navigation.actionNames.TOOLBOX,"Open the toolbox."),t.navigation.ACTION_EXIT=new t.Action(t.navigation.actionNames.EXIT,"Close the current modal, such as a toolbox or field editor."),t.navigation.ACTION_TOGGLE_KEYBOARD_NAV=new t.Action(t.navigation.actionNames.TOGGLE_KEYBOARD_NAV,"Turns on and off keyboard navigation."),t.navigation.ACTION_MOVE_WS_CURSOR_LEFT=new t.Action(t.navigation.actionNames.MOVE_WS_CURSOR_LEFT,"Move the workspace cursor to the lefts."),t.navigation.ACTION_MOVE_WS_CURSOR_RIGHT=new t.Action(t.navigation.actionNames.MOVE_WS_CURSOR_RIGHT,"Move the workspace cursor to the right."),t.navigation.ACTION_MOVE_WS_CURSOR_UP=new t.Action(t.navigation.actionNames.MOVE_WS_CURSOR_UP,"Move the workspace cursor up."),t.navigation.ACTION_MOVE_WS_CURSOR_DOWN=new t.Action(t.navigation.actionNames.MOVE_WS_CURSOR_DOWN,"Move the workspace cursor down."),t.navigation.READONLY_ACTION_LIST=[t.navigation.ACTION_PREVIOUS,t.navigation.ACTION_OUT,t.navigation.ACTION_IN,t.navigation.ACTION_NEXT,t.navigation.ACTION_TOGGLE_KEYBOARD_NAV],t.Gesture=function(e,o){this.mouseDownXY_=null,this.currentDragDeltaXY_=new t.utils.Coordinate(0,0),this.startWorkspace_=this.targetBlock_=this.startBlock_=this.startField_=this.startBubble_=null,this.creatorWorkspace_=o,this.isDraggingBubble_=this.isDraggingBlock_=this.isDraggingWorkspace_=this.hasExceededDragRadius_=!1,this.mostRecentEvent_=e,this.flyout_=this.workspaceDragger_=this.blockDragger_=this.bubbleDragger_=this.onUpWrapper_=this.onMoveWrapper_=null,this.isEnding_=this.hasStarted_=this.calledUpdateIsDragging_=!1,this.healStack_=!t.DRAG_STACK},t.Gesture.prototype.dispose=function(){t.Touch.clearTouchIdentifier(),t.Tooltip.unblock(),this.creatorWorkspace_.clearGesture(),this.onMoveWrapper_&&t.unbindEvent_(this.onMoveWrapper_),this.onUpWrapper_&&t.unbindEvent_(this.onUpWrapper_),this.blockDragger_&&this.blockDragger_.dispose(),this.workspaceDragger_&&this.workspaceDragger_.dispose(),this.bubbleDragger_&&this.bubbleDragger_.dispose()},t.Gesture.prototype.updateFromEvent_=function(e){var o=new t.utils.Coordinate(e.clientX,e.clientY);this.updateDragDelta_(o)&&(this.updateIsDragging_(),t.longStop_()),this.mostRecentEvent_=e},t.Gesture.prototype.updateDragDelta_=function(e){return this.currentDragDeltaXY_=t.utils.Coordinate.difference(e,this.mouseDownXY_),!this.hasExceededDragRadius_&&(this.hasExceededDragRadius_=t.utils.Coordinate.magnitude(this.currentDragDeltaXY_)>(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;i<e.inputList.length;i++)for(var n=o[i],s=n.fieldRow,r=0;r<s.length;r++)if(s[r]===this){t=n;break}return t},t.Field.prototype.getFlipRtl=function(){return!1},t.Field.prototype.isTabNavigable=function(){return!1},t.Field.prototype.onBlocklyAction=function(t){return!1},t.Field.prototype.setCursorSvg=function(t){t?(this.fieldGroup_.appendChild(t),this.cursorSvg_=t):this.cursorSvg_=null},t.Field.prototype.setMarkerSvg=function(t){t?(this.fieldGroup_.appendChild(t),this.markerSvg_=t):this.markerSvg_=null},t.Field.prototype.updateMarkers_=function(){var e=this.sourceBlock_.workspace;e.keyboardAccessibilityMode&&this.cursorSvg_&&e.getCursor().draw(),e.keyboardAccessibilityMode&&this.markerSvg_&&e.getMarker(t.navigation.MARKER_NAME).draw()},t.FieldLabel=function(e,o,i){this.class_=null,null==e&&(e=""),t.FieldLabel.superClass_.constructor.call(this,e,null,i),i||(this.class_=o||null)},t.utils.object.inherits(t.FieldLabel,t.Field),t.FieldLabel.fromJson=function(e){var o=t.utils.replaceMessageReferences(e.text);return new t.FieldLabel(o,void 0,e)},t.FieldLabel.prototype.EDITABLE=!1,t.FieldLabel.prototype.configure_=function(e){t.FieldLabel.superClass_.configure_.call(this,e),this.class_=e.class},t.FieldLabel.prototype.initView=function(){this.createTextElement_(),this.class_&&t.utils.dom.addClass(this.textElement_,this.class_)},t.FieldLabel.prototype.doClassValidation_=function(t){return null==t?null:String(t)},t.FieldLabel.prototype.setClass=function(e){this.textElement_&&(this.class_&&t.utils.dom.removeClass(this.textElement_,this.class_),e&&t.utils.dom.addClass(this.textElement_,e)),this.class_=e},t.fieldRegistry.register("field_label",t.FieldLabel),t.Input=function(e,o,i,n){if(e!=t.DUMMY_INPUT&&!o)throw Error("Value inputs and statement inputs must have non-empty name.");this.type=e,this.name=o,this.sourceBlock_=i,this.connection=n,this.fieldRow=[]},t.Input.prototype.align=t.ALIGN_LEFT,t.Input.prototype.visible_=!0,t.Input.prototype.getSourceBlock=function(){return this.sourceBlock_},t.Input.prototype.appendField=function(t,e){return this.insertFieldAt(this.fieldRow.length,t,e),this},t.Input.prototype.insertFieldAt=function(e,o,i){if(0>e||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;t<this.fieldRow.length;t++)this.fieldRow[t].init()},t.Input.prototype.dispose=function(){for(var t,e=0;t=this.fieldRow[e];e++)t.dispose();this.connection&&this.connection.dispose(),this.sourceBlock_=null},t.Block=function(e,o,i){if(t.Generator&&void 0!==t.Generator.prototype[o])throw Error('Block prototypeName "'+o+'" conflicts with Blockly.Generator members.');if(this.id=i&&!e.getBlockById(i)?i:t.utils.genUid(),e.setBlockById(this.id,this),this.previousConnection=this.nextConnection=this.outputConnection=null,this.inputList=[],this.inputsInline=void 0,this.disabled=!1,this.tooltip="",this.contextMenu=!0,this.parentBlock_=null,this.childBlocks_=[],this.editable_=this.movable_=this.deletable_=!0,this.collapsed_=this.isShadow_=!1,this.comment=this.outputShape_=null,this.commentModel={text:null,pinned:!1,size:new t.utils.Size(160,80)},this.xy_=new t.utils.Coordinate(0,0),this.workspace=e,this.isInFlyout=e.isFlyout,this.isInMutator=e.isMutator,this.RTL=e.RTL,this.isInsertionMarker_=!1,this.hat=void 0,this.statementInputCount=0,o){if(this.type=o,!(i=t.Blocks[o])||"object"!=typeof i)throw TypeError("Unknown block type: "+o);t.utils.object.mixin(this,i)}if(e.addTopBlock(this),e.addTypedBlock(this),"function"==typeof this.init&&this.init(),this.inputsInlineDefault=this.inputsInline,t.Events.isEnabled()){(e=t.Events.getGroup())||t.Events.setGroup(!0);try{t.Events.fire(new t.Events.BlockCreate(this))}finally{e||t.Events.setGroup(!1)}}"function"==typeof this.onchange&&this.setOnChange(this.onchange)},t.Block.prototype.data=null,t.Block.prototype.disposed=!1,t.Block.prototype.hue_=null,t.Block.prototype.colour_="#000000",t.Block.prototype.styleName_=null,t.Block.prototype.dispose=function(e){if(this.workspace){this.onchangeWrapper_&&this.workspace.removeChangeListener(this.onchangeWrapper_),this.unplug(e),t.Events.isEnabled()&&t.Events.fire(new t.Events.BlockDelete(this)),t.Events.disable();try{this.workspace&&(this.workspace.removeTopBlock(this),this.workspace.removeTypedBlock(this),this.workspace.removeBlockById(this.id),this.workspace=null),t.selected==this&&(t.selected=null);for(var o=this.childBlocks_.length-1;0<=o;o--)this.childBlocks_[o].dispose(!1);o=0;for(var i;i=this.inputList[o];o++)i.dispose();this.inputList.length=0;var n,s=this.getConnections_(!0);for(o=0;n=s[o];o++)n.dispose()}finally{t.Events.enable(),this.disposed=!0}}},t.Block.prototype.initModel=function(){for(var t,e=0;t=this.inputList[e];e++)for(var o,i=0;o=t.fieldRow[i];i++)o.initModel&&o.initModel()},t.Block.prototype.unplug=function(t){this.outputConnection?this.unplugFromRow_(t):this.previousConnection&&this.unplugFromStack_(t)},t.Block.prototype.unplugFromRow_=function(t){var e=null;this.outputConnection.isConnected()&&(e=this.outputConnection.targetConnection,this.outputConnection.disconnect()),e&&t&&(t=this.getOnlyValueConnection_())&&t.isConnected()&&!t.targetBlock().isShadow()&&((t=t.targetConnection).disconnect(),t.checkType(e)?e.connect(t):t.onFailedConnect(e))},t.Block.prototype.getOnlyValueConnection_=function(){for(var e=null,o=0;o<this.inputList.length;o++){var i=this.inputList[o].connection;if(i&&i.type==t.INPUT_VALUE&&i.targetConnection){if(e)return null;e=i}}return e},t.Block.prototype.unplugFromStack_=function(t){var e=null;this.previousConnection.isConnected()&&(e=this.previousConnection.targetConnection,this.previousConnection.disconnect());var o=this.getNextBlock();t&&o&&!o.isShadow()&&((t=this.nextConnection.targetConnection).disconnect(),e&&e.checkType(t)&&e.connect(t))},t.Block.prototype.getConnections_=function(t){t=[],this.outputConnection&&t.push(this.outputConnection),this.previousConnection&&t.push(this.previousConnection),this.nextConnection&&t.push(this.nextConnection);for(var e,o=0;e=this.inputList[o];o++)e.connection&&t.push(e.connection);return t},t.Block.prototype.lastConnectionInStack=function(){for(var t=this.nextConnection;t;){var e=t.targetBlock();if(!e)return t;t=e.nextConnection}return null},t.Block.prototype.bumpNeighbours=function(){console.warn("Not expected to reach Block.bumpNeighbours function. BlockSvg.bumpNeighbours was expected to be called instead.")},t.Block.prototype.getParent=function(){return this.parentBlock_},t.Block.prototype.getInputWithBlock=function(t){for(var e,o=0;e=this.inputList[o];o++)if(e.connection&&e.connection.targetBlock()==t)return e;return null},t.Block.prototype.getSurroundParent=function(){var t=this;do{var e=t;if(!(t=t.getParent()))return null}while(t.getNextBlock()==e);return t},t.Block.prototype.getNextBlock=function(){return this.nextConnection&&this.nextConnection.targetBlock()},t.Block.prototype.getPreviousBlock=function(){return this.previousConnection&&this.previousConnection.targetBlock()},t.Block.prototype.getFirstStatementConnection=function(){for(var e,o=0;e=this.inputList[o];o++)if(e.connection&&e.connection.type==t.NEXT_STATEMENT)return e.connection;return null},t.Block.prototype.getRootBlock=function(){var t=this;do{var e=t;t=e.parentBlock_}while(t);return e},t.Block.prototype.getTopStackBlock=function(){var t=this;do{var e=t.getPreviousBlock()}while(e&&e.getNextBlock()==t&&(t=e));return t},t.Block.prototype.getChildren=function(t){if(!t)return this.childBlocks_;t=[];for(var e,o=0;e=this.inputList[o];o++)e.connection&&(e=e.connection.targetBlock())&&t.push(e);return(o=this.getNextBlock())&&t.push(o),t},t.Block.prototype.setParent=function(e){if(e!=this.parentBlock_){if(this.parentBlock_){if(t.utils.arrayRemove(this.parentBlock_.childBlocks_,this),this.previousConnection&&this.previousConnection.isConnected())throw Error("Still connected to previous block.");if(this.outputConnection&&this.outputConnection.isConnected())throw Error("Still connected to parent block.");this.parentBlock_=null}else this.workspace.removeTopBlock(this);(this.parentBlock_=e)?e.childBlocks_.push(this):this.workspace.addTopBlock(this)}},t.Block.prototype.getDescendants=function(t){for(var e,o=[this],i=this.getChildren(t),n=0;e=i[n];n++)o.push.apply(o,e.getDescendants(t));return o},t.Block.prototype.isDeletable=function(){return this.deletable_&&!this.isShadow_&&!(this.workspace&&this.workspace.options.readOnly)},t.Block.prototype.setDeletable=function(t){this.deletable_=t},t.Block.prototype.isMovable=function(){return this.movable_&&!this.isShadow_&&!(this.workspace&&this.workspace.options.readOnly)},t.Block.prototype.setMovable=function(t){this.movable_=t},t.Block.prototype.isDuplicatable=function(){return!this.workspace.hasBlockLimits()||this.workspace.isCapacityAvailable(t.utils.getBlockTypeCounts(this,!0))},t.Block.prototype.isShadow=function(){return this.isShadow_},t.Block.prototype.setShadow=function(t){this.isShadow_=t},t.Block.prototype.isInsertionMarker=function(){return this.isInsertionMarker_},t.Block.prototype.setInsertionMarker=function(t){this.isInsertionMarker_=t},t.Block.prototype.isEditable=function(){return this.editable_&&!(this.workspace&&this.workspace.options.readOnly)},t.Block.prototype.setEditable=function(t){this.editable_=t,t=0;for(var e;e=this.inputList[t];t++)for(var o,i=0;o=e.fieldRow[i];i++)o.updateEditable()},t.Block.prototype.isDisposed=function(){return this.disposed},t.Block.prototype.getMatchingConnection=function(t,e){var o=this.getConnections_(!0);if(t=t.getConnections_(!0),o.length!=t.length)throw Error("Connection lists did not match in length.");for(var i=0;i<t.length;i++)if(t[i]==e)return o[i];return null},t.Block.prototype.setHelpUrl=function(t){this.helpUrl=t},t.Block.prototype.setTooltip=function(t){this.tooltip=t},t.Block.prototype.getColour=function(){return this.colour_},t.Block.prototype.getStyleName=function(){return this.styleName_},t.Block.prototype.getHue=function(){return this.hue_},t.Block.prototype.setColour=function(e){e=t.utils.parseBlockColour(e),this.hue_=e.hue,this.colour_=e.hex},t.Block.prototype.setStyle=function(t){this.styleName_=t},t.Block.prototype.setOnChange=function(t){if(t&&"function"!=typeof t)throw Error("onchange must be a function.");this.onchangeWrapper_&&this.workspace.removeChangeListener(this.onchangeWrapper_),(this.onchange=t)&&(this.onchangeWrapper_=t.bind(this),this.workspace.addChangeListener(this.onchangeWrapper_))},t.Block.prototype.getField=function(t){for(var e,o=0;e=this.inputList[o];o++)for(var i,n=0;i=e.fieldRow[n];n++)if(i.name==t)return i;return null},t.Block.prototype.getVars=function(){for(var t,e=[],o=0;t=this.inputList[o];o++)for(var i,n=0;i=t.fieldRow[n];n++)i.referencesVariables()&&e.push(i.getValue());return e},t.Block.prototype.getVarModels=function(){for(var t,e=[],o=0;t=this.inputList[o];o++)for(var i,n=0;i=t.fieldRow[n];n++)i.referencesVariables()&&(i=this.workspace.getVariableById(i.getValue()))&&e.push(i);return e},t.Block.prototype.updateVarName=function(t){for(var e,o=0;e=this.inputList[o];o++)for(var i,n=0;i=e.fieldRow[n];n++)i.referencesVariables()&&t.getId()==i.getValue()&&i.refreshVariableName()},t.Block.prototype.renameVarById=function(t,e){for(var o,i=0;o=this.inputList[i];i++)for(var n,s=0;n=o.fieldRow[s];s++)n.referencesVariables()&&t==n.getValue()&&n.setValue(e)},t.Block.prototype.getFieldValue=function(t){return(t=this.getField(t))?t.getValue():null},t.Block.prototype.setFieldValue=function(t,e){var o=this.getField(e);if(!o)throw Error('Field "'+e+'" not found.');o.setValue(t)},t.Block.prototype.setPreviousStatement=function(e,o){if(e){if(void 0===o&&(o=null),!this.previousConnection){if(this.outputConnection)throw Error("Remove output connection prior to adding previous connection.");this.previousConnection=this.makeConnection_(t.PREVIOUS_STATEMENT)}this.previousConnection.setCheck(o)}else if(this.previousConnection){if(this.previousConnection.isConnected())throw Error("Must disconnect previous statement before removing connection.");this.previousConnection.dispose(),this.previousConnection=null}},t.Block.prototype.setNextStatement=function(e,o){if(e)void 0===o&&(o=null),this.nextConnection||(this.nextConnection=this.makeConnection_(t.NEXT_STATEMENT)),this.nextConnection.setCheck(o);else if(this.nextConnection){if(this.nextConnection.isConnected())throw Error("Must disconnect next statement before removing connection.");this.nextConnection.dispose(),this.nextConnection=null}},t.Block.prototype.setOutput=function(e,o){if(e){if(void 0===o&&(o=null),!this.outputConnection){if(this.previousConnection)throw Error("Remove previous connection prior to adding output connection.");this.outputConnection=this.makeConnection_(t.OUTPUT_VALUE)}this.outputConnection.setCheck(o)}else if(this.outputConnection){if(this.outputConnection.isConnected())throw Error("Must disconnect output value before removing connection.");this.outputConnection.dispose(),this.outputConnection=null}},t.Block.prototype.setInputsInline=function(e){this.inputsInline!=e&&(t.Events.fire(new t.Events.BlockChange(this,"inline",null,this.inputsInline,e)),this.inputsInline=e)},t.Block.prototype.getInputsInline=function(){if(null!=this.inputsInline)return this.inputsInline;for(var e=1;e<this.inputList.length;e++)if(this.inputList[e-1].type==t.DUMMY_INPUT&&this.inputList[e].type==t.DUMMY_INPUT)return!1;for(e=1;e<this.inputList.length;e++)if(this.inputList[e-1].type==t.INPUT_VALUE&&this.inputList[e].type==t.DUMMY_INPUT)return!0;return!1},t.Block.prototype.setOutputShape=function(t){this.outputShape_=t},t.Block.prototype.getOutputShape=function(){return this.outputShape_},t.Block.prototype.setDisabled=function(t){console.warn("Deprecated call to Blockly.Block.prototype.setDisabled, use Blockly.Block.prototype.setEnabled instead."),this.setEnabled(!t)},t.Block.prototype.isEnabled=function(){return!this.disabled},t.Block.prototype.setEnabled=function(e){this.isEnabled()!=e&&(t.Events.fire(new t.Events.BlockChange(this,"disabled",null,this.disabled,!e)),this.disabled=!e)},t.Block.prototype.getInheritedDisabled=function(){for(var t=this.getSurroundParent();t;){if(t.disabled)return!0;t=t.getSurroundParent()}return!1},t.Block.prototype.isCollapsed=function(){return this.collapsed_},t.Block.prototype.setCollapsed=function(e){this.collapsed_!=e&&(t.Events.fire(new t.Events.BlockChange(this,"collapsed",null,this.collapsed_,e)),this.collapsed_=e)},t.Block.prototype.toString=function(t,e){var o=[],i=e||"?";if(this.collapsed_)o.push(this.getInput("_TEMP_COLLAPSED_INPUT").fieldRow[0].getText());else for(var n,s=0;n=this.inputList[s];s++){for(var r,a=0;r=n.fieldRow[a];a++)o.push(r.getText());n.connection&&((n=n.connection.targetBlock())?o.push(n.toString(void 0,e)):o.push(i))}return o=o.join(" ").trim()||"???",t&&o.length>t&&(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<e.length;++o)t.Extensions.apply(e[o],this,!1)},t.Block.prototype.jsonInitColour_=function(t,e){if("colour"in t)if(void 0===t.colour)console.warn(e+"Undefined colour value.");else{t=t.colour;try{this.setColour(t)}catch(o){console.warn(e+"Illegal colour value: ",t)}}},t.Block.prototype.jsonInitStyle_=function(t,e){t=t.style;try{this.setStyle(t)}catch(o){console.warn(e+"Style does not exist: ",t)}},t.Block.prototype.mixin=function(e,o){if(void 0!==o&&"boolean"!=typeof o)throw Error("opt_disableCheck must be a boolean if provided");if(!o){for(var i in o=[],e)void 0!==this[i]&&o.push(i);if(o.length)throw Error("Mixin will overwrite block members: "+JSON.stringify(o))}t.utils.object.mixin(this,e)},t.Block.prototype.interpolate_=function(e,o,i,n){var s=t.utils.tokenizeInterpolation(e),r=[],a=0;e=[];for(var l=0;l<s.length;l++){var c=s[l];if("number"==typeof c){if(0>=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<e.length;l++)if("string"==typeof(r=e[l]))o.push([r,void 0]);else{s=a=null;do{if(c=!1,"string"==typeof r)a=new t.FieldLabel(r);else switch(r.type){case"input_value":s=this.appendValueInput(r.name);break;case"input_statement":s=this.appendStatementInput(r.name);break;case"input_dummy":s=this.appendDummyInput(r.name);break;default:!(a=t.fieldRegistry.fromJson(r))&&r.alt&&(r=r.alt,c=!0)}}while(c);if(a)o.push([a,r.name]);else if(s){for(r.check&&s.setCheck(r.check),r.align&&(void 0===(a=i[r.align.toUpperCase()])?console.warn(n+"Illegal align value: ",r.align):s.setAlign(a)),r=0;r<o.length;r++)s.appendField(o[r][0],o[r][1]);o.length=0}}},t.Block.prototype.appendInput_=function(e,o){var i=null;return e!=t.INPUT_VALUE&&e!=t.NEXT_STATEMENT||(i=this.makeConnection_(e)),e==t.NEXT_STATEMENT&&this.statementInputCount++,e=new t.Input(e,o,this,i),this.inputList.push(e),e},t.Block.prototype.moveInputBefore=function(t,e){if(t!=e){for(var o,i=-1,n=e?-1:this.inputList.length,s=0;o=this.inputList[s];s++)if(o.name==t){if(i=s,-1!=n)break}else if(e&&o.name==e&&(n=s,-1!=i))break;if(-1==i)throw Error('Named input "'+t+'" not found.');if(-1==n)throw Error('Reference input "'+e+'" not found.');this.moveNumberedInputBefore(i,n)}},t.Block.prototype.moveNumberedInputBefore=function(t,e){if(t==e)throw Error("Can't move input to itself.");if(t>=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<e&&e--,this.inputList.splice(e,0,o)},t.Block.prototype.removeInput=function(e,o){for(var i,n=0;i=this.inputList[n];n++)if(i.name==e)return i.type==t.NEXT_STATEMENT&&this.statementInputCount--,i.dispose(),void this.inputList.splice(n,1);if(!o)throw Error("Input not found: "+e)},t.Block.prototype.getInput=function(t){for(var e,o=0;e=this.inputList[o];o++)if(e.name==t)return e;return null},t.Block.prototype.getInputTargetBlock=function(t){return(t=this.getInput(t))&&t.connection&&t.connection.targetBlock()},t.Block.prototype.getCommentText=function(){return this.commentModel.text},t.Block.prototype.setCommentText=function(e){this.commentModel.text!=e&&(t.Events.fire(new t.Events.BlockChange(this,"comment",null,this.commentModel.text,e)),this.comment=this.commentModel.text=e)},t.Block.prototype.setWarningText=function(t,e){},t.Block.prototype.setMutator=function(t){},t.Block.prototype.getRelativeToSurfaceXY=function(){return this.xy_},t.Block.prototype.moveBy=function(e,o){if(this.parentBlock_)throw Error("Block has parent.");var i=new t.Events.BlockMove(this);this.xy_.translate(e,o),i.recordNew(),t.Events.fire(i)},t.Block.prototype.makeConnection_=function(e){return new t.Connection(this,e)},t.Block.prototype.allInputsFilled=function(t){if(void 0===t&&(t=!0),!t&&this.isShadow())return!1;for(var e,o=0;e=this.inputList[o];o++)if(e.connection&&(!(e=e.connection.targetBlock())||!e.allInputsFilled(t)))return!1;return!(o=this.getNextBlock())||o.allInputsFilled(t)},t.Block.prototype.toDevString=function(){var t=this.type?'"'+this.type+'" block':"Block";return this.id&&(t+=' (id="'+this.id+'")'),t},t.blockRendering={},t.blockRendering.IPathObject=function(t,e){},t.utils.aria={},t.utils.aria.ARIA_PREFIX_="aria-",t.utils.aria.ROLE_ATTRIBUTE_="role",t.utils.aria.Role={GRID:"grid",GRIDCELL:"gridcell",GROUP:"group",LISTBOX:"listbox",MENU:"menu",MENUITEM:"menuitem",MENUITEMCHECKBOX:"menuitemcheckbox",OPTION:"option",PRESENTATION:"presentation",ROW:"row",TREE:"tree",TREEITEM:"treeitem"},t.utils.aria.State={ACTIVEDESCENDANT:"activedescendant",COLCOUNT:"colcount",EXPANDED:"expanded",INVALID:"invalid",LABEL:"label",LABELLEDBY:"labelledby",LEVEL:"level",ORIENTATION:"orientation",POSINSET:"posinset",ROWCOUNT:"rowcount",SELECTED:"selected",SETSIZE:"setsize",VALUEMAX:"valuemax",VALUEMIN:"valuemin"},t.utils.aria.setRole=function(e,o){e.setAttribute(t.utils.aria.ROLE_ATTRIBUTE_,o)},t.utils.aria.setState=function(e,o,i){Array.isArray(i)&&(i=i.join(" ")),e.setAttribute(t.utils.aria.ARIA_PREFIX_+o,i)},t.Menu=function(){t.Component.call(this),this.openingCoords=null,this.highlightedIndex_=-1,this.onKeyDownWrapper_=this.mouseLeaveHandler_=this.mouseEnterHandler_=this.clickHandler_=this.mouseOverHandler_=null},t.utils.object.inherits(t.Menu,t.Component),t.Menu.prototype.createDom=function(){var e=document.createElement("div");e.id=this.getId(),this.setElementInternal(e),e.className="goog-menu goog-menu-vertical blocklyNonSelectable",e.tabIndex=0,t.utils.aria.setRole(e,this.roleName_||t.utils.aria.Role.MENU)},t.Menu.prototype.focus=function(){var e=this.getElement();e&&(e.focus({preventScroll:!0}),t.utils.dom.addClass(e,"focused"))},t.Menu.prototype.blur=function(){var e=this.getElement();e&&(e.blur(),t.utils.dom.removeClass(e,"focused"))},t.Menu.prototype.setRole=function(t){this.roleName_=t},t.Menu.prototype.enterDocument=function(){t.Menu.superClass_.enterDocument.call(this),this.forEachChild((function(t){t.isInDocument()&&this.registerChildId_(t)}),this),this.attachEvents_()},t.Menu.prototype.exitDocument=function(){this.setHighlightedIndex(-1),t.Menu.superClass_.exitDocument.call(this)},t.Menu.prototype.disposeInternal=function(){t.Menu.superClass_.disposeInternal.call(this),this.detachEvents_()},t.Menu.prototype.attachEvents_=function(){var e=this.getElement();this.mouseOverHandler_=t.bindEventWithChecks_(e,"mouseover",this,this.handleMouseOver_,!0),this.clickHandler_=t.bindEventWithChecks_(e,"click",this,this.handleClick_,!0),this.mouseEnterHandler_=t.bindEventWithChecks_(e,"mouseenter",this,this.handleMouseEnter_,!0),this.mouseLeaveHandler_=t.bindEventWithChecks_(e,"mouseleave",this,this.handleMouseLeave_,!0),this.onKeyDownWrapper_=t.bindEventWithChecks_(e,"keydown",this,this.handleKeyEvent)},t.Menu.prototype.detachEvents_=function(){this.mouseOverHandler_&&(t.unbindEvent_(this.mouseOverHandler_),this.mouseOverHandler_=null),this.clickHandler_&&(t.unbindEvent_(this.clickHandler_),this.clickHandler_=null),this.mouseEnterHandler_&&(t.unbindEvent_(this.mouseEnterHandler_),this.mouseEnterHandler_=null),this.mouseLeaveHandler_&&(t.unbindEvent_(this.mouseLeaveHandler_),this.mouseLeaveHandler_=null),this.onKeyDownWrapper_&&(t.unbindEvent_(this.onKeyDownWrapper_),this.onKeyDownWrapper_=null)},t.Menu.prototype.childElementIdMap_=null,t.Menu.prototype.registerChildId_=function(t){var e=t.getElement();e=e.id||(e.id=t.getId()),this.childElementIdMap_||(this.childElementIdMap_={}),this.childElementIdMap_[e]=t},t.Menu.prototype.getMenuItem=function(t){if(this.childElementIdMap_)for(var e=this.getElement();t&&t!==e;){var o=t.id;if(o in this.childElementIdMap_)return this.childElementIdMap_[o];t=t.parentNode}return null},t.Menu.prototype.unhighlightCurrent=function(){var t=this.getHighlighted();t&&t.setHighlighted(!1)},t.Menu.prototype.clearHighlighted=function(){this.unhighlightCurrent(),this.setHighlightedIndex(-1)},t.Menu.prototype.getHighlighted=function(){return this.getChildAt(this.highlightedIndex_)},t.Menu.prototype.setHighlightedIndex=function(e){var o=this.getChildAt(e);o?(o.setHighlighted(!0),this.highlightedIndex_=e):-1<this.highlightedIndex_&&(this.getHighlighted().setHighlighted(!1),this.highlightedIndex_=-1),o&&t.utils.style.scrollIntoContainerView(o.getElement(),this.getElement())},t.Menu.prototype.setHighlighted=function(t){this.setHighlightedIndex(this.indexOfChild(t))},t.Menu.prototype.highlightNext=function(){this.unhighlightCurrent(),this.highlightHelper((function(t,e){return(t+1)%e}),this.highlightedIndex_)},t.Menu.prototype.highlightPrevious=function(){this.unhighlightCurrent(),this.highlightHelper((function(t,e){return 0>--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;e<t.length;e++){for(var o=t[e],i=o.getConnections_(!0),n=0;n<i.length;n++)i[n].setTracking(!1);for(o=o.getIcons(),n=0;n<o.length;n++)o[n].setVisible(!1)}},t.RenderedConnection.prototype.startTrackingAll=function(){this.setTracking(!0);var e=[];if(this.type!=t.INPUT_VALUE&&this.type!=t.NEXT_STATEMENT)return e;var o=this.targetBlock();if(o){if(o.isCollapsed()){var i=[];o.outputConnection&&i.push(o.outputConnection),o.nextConnection&&i.push(o.nextConnection),o.previousConnection&&i.push(o.previousConnection)}else i=o.getConnections_(!0);for(var n=0;n<i.length;n++)e.push.apply(e,i[n].startTrackingAll());e.length||(e[0]=o)}return e},t.RenderedConnection.prototype.isConnectionAllowed=function(e,o){return!(this.distanceFrom(e)>o)&&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<e.length;o++)e[o].createIcon();this.applyColour(),this.pathObject.updateMovable(this.isMovable()),o=this.getSvgRoot(),this.workspace.options.readOnly||this.eventsInit_||!o||t.bindEventWithChecks_(o,"mousedown",this,this.onMouseDown_),this.eventsInit_=!0,o.parentNode||this.workspace.getCanvas().appendChild(o)},t.BlockSvg.prototype.getColourSecondary=function(){return this.style.colourSecondary},t.BlockSvg.prototype.getColourTertiary=function(){return this.style.colourTertiary},t.BlockSvg.prototype.getColourShadow=function(){return this.getColourSecondary()},t.BlockSvg.prototype.getColourBorder=function(){return{colourBorder:this.getColourTertiary(),colourLight:null,colourDark:null}},t.BlockSvg.prototype.select=function(){if(this.isShadow()&&this.getParent())this.getParent().select();else if(t.selected!=this){var e=null;if(t.selected){e=t.selected.id,t.Events.disable();try{t.selected.unselect()}finally{t.Events.enable()}}(e=new t.Events.Ui(null,"selected",e,this.id)).workspaceId=this.workspace.id,t.Events.fire(e),t.selected=this,this.addSelect()}},t.BlockSvg.prototype.unselect=function(){if(t.selected==this){var e=new t.Events.Ui(null,"selected",this.id,null);e.workspaceId=this.workspace.id,t.Events.fire(e),t.selected=null,this.removeSelect()}},t.BlockSvg.prototype.mutator=null,t.BlockSvg.prototype.comment=null,t.BlockSvg.prototype.commentIcon_=null,t.BlockSvg.prototype.warning=null,t.BlockSvg.prototype.getIcons=function(){var t=[];return this.mutator&&t.push(this.mutator),this.commentIcon_&&t.push(this.commentIcon_),this.warning&&t.push(this.warning),t},t.BlockSvg.prototype.setParent=function(e){var o=this.parentBlock_;if(e!=o){t.utils.dom.startTextWidthCache(),t.BlockSvg.superClass_.setParent.call(this,e),t.utils.dom.stopTextWidthCache();var i=this.getSvgRoot();if(!this.workspace.isClearing&&i){var n=this.getRelativeToSurfaceXY();e?(e.getSvgRoot().appendChild(i),e=this.getRelativeToSurfaceXY(),this.moveConnections(e.x-n.x,e.y-n.y)):o&&(this.workspace.getCanvas().appendChild(i),this.translate(n.x,n.y)),this.applyColour()}}},t.BlockSvg.prototype.getRelativeToSurfaceXY=function(){var e=0,o=0,i=this.useDragSurface_?this.workspace.getBlockDragSurface().getGroup():null,n=this.getSvgRoot();if(n)do{var s=t.utils.getRelativeXY(n);e+=s.x,o+=s.y,this.useDragSurface_&&this.workspace.getBlockDragSurface().getCurrentBlock()==n&&(e+=(s=this.workspace.getBlockDragSurface().getSurfaceTranslation()).x,o+=s.y),n=n.parentNode}while(n&&n!=this.workspace.getCanvas()&&n!=i);return new t.utils.Coordinate(e,o)},t.BlockSvg.prototype.moveBy=function(e,o){if(this.parentBlock_)throw Error("Block has parent.");var i=t.Events.isEnabled();if(i)var n=new t.Events.BlockMove(this);var s=this.getRelativeToSurfaceXY();this.translate(s.x+e,s.y+o),this.moveConnections(e,o),i&&(n.recordNew(),t.Events.fire(n)),this.workspace.resizeContents()},t.BlockSvg.prototype.translate=function(t,e){this.getSvgRoot().setAttribute("transform","translate("+t+","+e+")")},t.BlockSvg.prototype.moveToDragSurface=function(){if(this.useDragSurface_){var t=this.getRelativeToSurfaceXY();this.clearTransformAttributes_(),this.workspace.getBlockDragSurface().translateSurface(t.x,t.y),(t=this.getSvgRoot())&&this.workspace.getBlockDragSurface().setBlocksAndShow(t)}},t.BlockSvg.prototype.moveTo=function(t){var e=this.getRelativeToSurfaceXY();this.moveBy(t.x-e.x,t.y-e.y)},t.BlockSvg.prototype.moveOffDragSurface=function(t){this.useDragSurface_&&(this.translate(t.x,t.y),this.workspace.getBlockDragSurface().clearAndHide(this.workspace.getCanvas()))},t.BlockSvg.prototype.moveDuringDrag=function(t){this.useDragSurface_?this.workspace.getBlockDragSurface().translateSurface(t.x,t.y):(this.svgGroup_.translate_="translate("+t.x+","+t.y+")",this.svgGroup_.setAttribute("transform",this.svgGroup_.translate_+this.svgGroup_.skew_))},t.BlockSvg.prototype.clearTransformAttributes_=function(){this.getSvgRoot().removeAttribute("transform")},t.BlockSvg.prototype.snapToGrid=function(){if(this.workspace&&!this.workspace.isDragging()&&!this.getParent()&&!this.isInFlyout){var t=this.workspace.getGrid();if(t&&t.shouldSnap()){var e=t.getSpacing(),o=e/2,i=this.getRelativeToSurfaceXY();t=Math.round((i.x-o)/e)*e+o-i.x,e=Math.round((i.y-o)/e)*e+o-i.y,t=Math.round(t),e=Math.round(e),0==t&&0==e||this.moveBy(t,e)}}},t.BlockSvg.prototype.getBoundingRectangle=function(){var e=this.getRelativeToSurfaceXY(),o=this.getHeightWidth();if(this.RTL)var i=e.x-o.width,n=e.x;else i=e.x,n=e.x+o.width;return new t.utils.Rect(e.y,e.y+o.height,i,n)},t.BlockSvg.prototype.markDirty=function(){this.pathObject.constants=this.workspace.getRenderer().getConstants();for(var t,e=0;t=this.inputList[e];e++)t.markDirty()},t.BlockSvg.prototype.setCollapsed=function(e){if(this.collapsed_!=e){for(var o,i=[],n=0;o=this.inputList[n];n++)i.push.apply(i,o.setVisible(!e));if(e){for(o=this.getIcons(),n=0;n<o.length;n++)o[n].setVisible(!1);n=this.toString(t.COLLAPSE_CHARS),this.appendDummyInput("_TEMP_COLLAPSED_INPUT").appendField(n).init(),o=this.getDescendants(!0),(n=this.getNextBlock())&&(n=o.indexOf(n),o.splice(n,o.length-n)),n=1;for(var s;s=o[n];n++)if(s.warning){this.setWarningText(t.Msg.COLLAPSED_WARNINGS_WARNING,t.BlockSvg.COLLAPSED_WARNING_ID);break}}else this.removeInput("_TEMP_COLLAPSED_INPUT"),this.warning&&(this.warning.setText("",t.BlockSvg.COLLAPSED_WARNING_ID),Object.keys(this.warning.text_).length||this.setWarningText(null));if(t.BlockSvg.superClass_.setCollapsed.call(this,e),i.length||(i[0]=this),this.rendered)for(n=0;s=i[n];n++)s.render()}},t.BlockSvg.prototype.tab=function(e,o){var i=new t.TabNavigateCursor;i.setCurNode(t.ASTNode.createFieldNode(e)),e=i.getCurNode(),i.onBlocklyAction(o?t.navigation.ACTION_NEXT:t.navigation.ACTION_PREVIOUS),(o=i.getCurNode())&&o!==e&&(o.getLocation().showEditor(),this.workspace.keyboardAccessibilityMode&&this.workspace.getCursor().setCurNode(o))},t.BlockSvg.prototype.onMouseDown_=function(t){var e=this.workspace&&this.workspace.getGesture(t);e&&e.handleBlockStart(t,this)},t.BlockSvg.prototype.showHelp=function(){var t="function"==typeof this.helpUrl?this.helpUrl():this.helpUrl;t&&window.open(t)},t.BlockSvg.prototype.generateContextMenu=function(){if(this.workspace.options.readOnly||!this.contextMenu)return null;var e=this,o=[];if(!this.isInFlyout){if(this.isDeletable()&&this.isMovable()&&o.push(t.ContextMenu.blockDuplicateOption(e)),this.workspace.options.comments&&!this.collapsed_&&this.isEditable()&&o.push(t.ContextMenu.blockCommentOption(e)),this.isMovable())if(this.collapsed_)this.workspace.options.collapse&&((i={enabled:!0}).text=t.Msg.EXPAND_BLOCK,i.callback=function(){e.setCollapsed(!1)},o.push(i));else{for(var i=1;i<this.inputList.length;i++)if(this.inputList[i-1].type!=t.NEXT_STATEMENT&&this.inputList[i].type!=t.NEXT_STATEMENT){i={enabled:!0};var n=this.getInputsInline();i.text=n?t.Msg.EXTERNAL_INPUTS:t.Msg.INLINE_INPUTS,i.callback=function(){e.setInputsInline(!n)},o.push(i);break}this.workspace.options.collapse&&((i={enabled:!0}).text=t.Msg.COLLAPSE_BLOCK,i.callback=function(){e.setCollapsed(!0)},o.push(i))}this.workspace.options.disable&&this.isEditable()&&(i={text:this.isEnabled()?t.Msg.DISABLE_BLOCK:t.Msg.ENABLE_BLOCK,enabled:!this.getInheritedDisabled(),callback:function(){var o=t.Events.getGroup();o||t.Events.setGroup(!0),e.setEnabled(!e.isEnabled()),o||t.Events.setGroup(!1)}},o.push(i)),this.isDeletable()&&o.push(t.ContextMenu.blockDeleteOption(e))}return o.push(t.ContextMenu.blockHelpOption(e)),this.customContextMenu&&this.customContextMenu(o),o},t.BlockSvg.prototype.showContextMenu=function(e){var o=this.generateContextMenu();o&&o.length&&(t.ContextMenu.show(e,o,this.RTL),t.ContextMenu.currentBlock=this)},t.BlockSvg.prototype.moveConnections=function(t,e){if(this.rendered){for(var o=this.getConnections_(!1),i=0;i<o.length;i++)o[i].moveBy(t,e);for(o=this.getIcons(),i=0;i<o.length;i++)o[i].computeIconLocation();for(i=0;i<this.childBlocks_.length;i++)this.childBlocks_[i].moveConnections(t,e)}},t.BlockSvg.prototype.setDragging=function(e){if(e){var o=this.getSvgRoot();o.translate_="",o.skew_="",t.draggingConnections=t.draggingConnections.concat(this.getConnections_(!0)),t.utils.dom.addClass(this.svgGroup_,"blocklyDragging")}else t.draggingConnections=[],t.utils.dom.removeClass(this.svgGroup_,"blocklyDragging");for(o=0;o<this.childBlocks_.length;o++)this.childBlocks_[o].setDragging(e)},t.BlockSvg.prototype.setMovable=function(e){t.BlockSvg.superClass_.setMovable.call(this,e),this.pathObject.updateMovable(e)},t.BlockSvg.prototype.setEditable=function(e){t.BlockSvg.superClass_.setEditable.call(this,e),e=this.getIcons();for(var o=0;o<e.length;o++)e[o].updateEditable()},t.BlockSvg.prototype.setShadow=function(e){t.BlockSvg.superClass_.setShadow.call(this,e),this.applyColour()},t.BlockSvg.prototype.setInsertionMarker=function(t){this.isInsertionMarker_!=t&&(this.isInsertionMarker_=t)&&(this.setColour(this.workspace.getRenderer().getConstants().INSERTION_MARKER_COLOUR),this.pathObject.updateInsertionMarker(!0))},t.BlockSvg.prototype.getSvgRoot=function(){return this.svgGroup_},t.BlockSvg.prototype.dispose=function(e,o){if(this.workspace){t.Tooltip.dispose(),t.Tooltip.unbindMouseEvents(this.pathObject.svgPath),t.utils.dom.startTextWidthCache();var i=this.workspace;if(t.selected==this&&(this.unselect(),this.workspace.cancelCurrentGesture()),t.ContextMenu.currentBlock==this&&t.ContextMenu.hide(),this.workspace.keyboardAccessibilityMode&&t.navigation.moveCursorOnBlockDelete(this),o&&this.rendered&&(this.unplug(e),t.blockAnimations.disposeUiEffect(this)),this.rendered=!1,this.warningTextDb_){for(var n in this.warningTextDb_)clearTimeout(this.warningTextDb_[n]);this.warningTextDb_=null}for(o=this.getIcons(),n=0;n<o.length;n++)o[n].dispose();t.BlockSvg.superClass_.dispose.call(this,!!e),t.utils.dom.removeNode(this.svgGroup_),i.resizeContents(),this.svgGroup_=null,t.utils.dom.stopTextWidthCache()}},t.BlockSvg.prototype.applyColour=function(){this.pathObject.applyColour(this);for(var t=this.getIcons(),e=0;e<t.length;e++)t[e].applyColour();for(t=0;e=this.inputList[t];t++)for(var o,i=0;o=e.fieldRow[i];i++)o.applyColour()},t.BlockSvg.prototype.updateDisabled=function(){var t=this.getChildren(!1);this.applyColour();for(var e,o=0;e=t[o];o++)e.updateDisabled()},t.BlockSvg.prototype.getCommentIcon=function(){return this.commentIcon_},t.BlockSvg.prototype.setCommentText=function(e){if(!t.Comment)throw Error("Missing require for Blockly.Comment");this.commentModel.text!=e&&(t.BlockSvg.superClass_.setCommentText.call(this,e),e=null!=e,!!this.commentIcon_==e?this.commentIcon_.updateText():(e?this.comment=this.commentIcon_=new t.Comment(this):(this.commentIcon_.dispose(),this.comment=this.commentIcon_=null),this.rendered&&(this.render(),this.bumpNeighbours())))},t.BlockSvg.prototype.setWarningText=function(e,o){if(!t.Warning)throw Error("Missing require for Blockly.Warning");this.warningTextDb_||(this.warningTextDb_=Object.create(null));var i=o||"";if(i)this.warningTextDb_[i]&&(clearTimeout(this.warningTextDb_[i]),delete this.warningTextDb_[i]);else for(var n in this.warningTextDb_)clearTimeout(this.warningTextDb_[n]),delete this.warningTextDb_[n];if(this.workspace.isDragging()){var s=this;this.warningTextDb_[i]=setTimeout((function(){s.workspace&&(delete s.warningTextDb_[i],s.setWarningText(e,i))}),100)}else{for(this.isInFlyout&&(e=null),o=this.getSurroundParent(),n=null;o;)o.isCollapsed()&&(n=o),o=o.getSurroundParent();n&&n.setWarningText(t.Msg.COLLAPSED_WARNINGS_WARNING,t.BlockSvg.COLLAPSED_WARNING_ID),o=!1,"string"==typeof e?(this.warning||(this.warning=new t.Warning(this),o=!0),this.warning.setText(e,i)):this.warning&&!i?(this.warning.dispose(),o=!0):this.warning&&(o=this.warning.getText(),this.warning.setText("",i),(n=this.warning.getText())||this.warning.dispose(),o=o!=n),o&&this.rendered&&(this.render(),this.bumpNeighbours())}},t.BlockSvg.prototype.setMutator=function(t){this.mutator&&this.mutator!==t&&this.mutator.dispose(),t&&(t.setBlock(this),this.mutator=t,t.createIcon()),this.rendered&&(this.render(),this.bumpNeighbours())},t.BlockSvg.prototype.setDisabled=function(t){console.warn("Deprecated call to Blockly.BlockSvg.prototype.setDisabled, use Blockly.BlockSvg.prototype.setEnabled instead."),this.setEnabled(!t)},t.BlockSvg.prototype.setEnabled=function(e){this.isEnabled()!=e&&(t.BlockSvg.superClass_.setEnabled.call(this,e),this.rendered&&!this.getInheritedDisabled()&&this.updateDisabled())},t.BlockSvg.prototype.setHighlighted=function(t){this.rendered&&this.pathObject.updateHighlighted(t)},t.BlockSvg.prototype.addSelect=function(){this.pathObject.updateSelected(!0)},t.BlockSvg.prototype.removeSelect=function(){this.pathObject.updateSelected(!1)},t.BlockSvg.prototype.setDeleteStyle=function(t){this.pathObject.updateDraggingDelete(t)},t.BlockSvg.prototype.getColour=function(){return this.style.colourPrimary},t.BlockSvg.prototype.setColour=function(e){t.BlockSvg.superClass_.setColour.call(this,e),e=this.workspace.getRenderer().getConstants().getBlockStyleForColour(this.colour_),this.pathObject.setStyle(e.style),this.style=e.style,this.styleName_=e.name,this.applyColour()},t.BlockSvg.prototype.setStyle=function(t){var e=this.workspace.getRenderer().getConstants().getBlockStyle(t);if(this.styleName_=t,!e)throw Error("Invalid style name: "+t);this.hat=e.hat,this.pathObject.setStyle(e),this.colour_=e.colourPrimary,this.style=e,this.applyColour()},t.BlockSvg.prototype.bringToFront=function(){var t=this;do{var e=t.getSvgRoot(),o=e.parentNode,i=o.childNodes;i[i.length-1]!==e&&o.appendChild(e),t=t.getParent()}while(t)},t.BlockSvg.prototype.setPreviousStatement=function(e,o){t.BlockSvg.superClass_.setPreviousStatement.call(this,e,o),this.rendered&&(this.render(),this.bumpNeighbours())},t.BlockSvg.prototype.setNextStatement=function(e,o){t.BlockSvg.superClass_.setNextStatement.call(this,e,o),this.rendered&&(this.render(),this.bumpNeighbours())},t.BlockSvg.prototype.setOutput=function(e,o){t.BlockSvg.superClass_.setOutput.call(this,e,o),this.rendered&&(this.render(),this.bumpNeighbours())},t.BlockSvg.prototype.setInputsInline=function(e){t.BlockSvg.superClass_.setInputsInline.call(this,e),this.rendered&&(this.render(),this.bumpNeighbours())},t.BlockSvg.prototype.removeInput=function(e,o){t.BlockSvg.superClass_.removeInput.call(this,e,o),this.rendered&&(this.render(),this.bumpNeighbours())},t.BlockSvg.prototype.moveNumberedInputBefore=function(e,o){t.BlockSvg.superClass_.moveNumberedInputBefore.call(this,e,o),this.rendered&&(this.render(),this.bumpNeighbours())},t.BlockSvg.prototype.appendInput_=function(e,o){return e=t.BlockSvg.superClass_.appendInput_.call(this,e,o),this.rendered&&(this.render(),this.bumpNeighbours()),e},t.BlockSvg.prototype.setConnectionTracking=function(t){if(this.previousConnection&&this.previousConnection.setTracking(t),this.outputConnection&&this.outputConnection.setTracking(t),this.nextConnection){this.nextConnection.setTracking(t);var e=this.nextConnection.targetBlock();e&&e.setConnectionTracking(t)}if(!this.collapsed_)for(e=0;e<this.inputList.length;e++){var o=this.inputList[e].connection;o&&(o.setTracking(t),(o=o.targetBlock())&&o.setConnectionTracking(t))}},t.BlockSvg.prototype.getConnections_=function(t){var e=[];if((t||this.rendered)&&(this.outputConnection&&e.push(this.outputConnection),this.previousConnection&&e.push(this.previousConnection),this.nextConnection&&e.push(this.nextConnection),t||!this.collapsed_)){t=0;for(var o;o=this.inputList[t];t++)o.connection&&e.push(o.connection)}return e},t.BlockSvg.prototype.lastConnectionInStack=function(){return t.BlockSvg.superClass_.lastConnectionInStack.call(this)},t.BlockSvg.prototype.getMatchingConnection=function(e,o){return t.BlockSvg.superClass_.getMatchingConnection.call(this,e,o)},t.BlockSvg.prototype.makeConnection_=function(e){return new t.RenderedConnection(this,e)},t.BlockSvg.prototype.bumpNeighbours=function(){if(this.workspace&&!this.workspace.isDragging()){var e=this.getRootBlock();if(!e.isInFlyout)for(var o,i=this.getConnections_(!1),n=0;o=i[n];n++){o.isConnected()&&o.isSuperior()&&o.targetBlock().bumpNeighbours();for(var s,r=o.neighbours(t.SNAP_RADIUS),a=0;s=r[a];a++)o.isConnected()&&s.isConnected()||s.getSourceBlock().getRootBlock()!=e&&(o.isSuperior()?s.bumpAwayFrom(o):o.bumpAwayFrom(s))}}},t.BlockSvg.prototype.scheduleSnapAndBump=function(){var e=this,o=t.Events.getGroup();setTimeout((function(){t.Events.setGroup(o),e.snapToGrid(),t.Events.setGroup(!1)}),t.BUMP_DELAY/2),setTimeout((function(){t.Events.setGroup(o),e.bumpNeighbours(),t.Events.setGroup(!1)}),t.BUMP_DELAY)},t.BlockSvg.prototype.positionNearConnection=function(e,o){e.type!=t.NEXT_STATEMENT&&e.type!=t.INPUT_VALUE||this.moveBy(o.x-e.x,o.y-e.y)},t.BlockSvg.prototype.getParent=function(){return t.BlockSvg.superClass_.getParent.call(this)},t.BlockSvg.prototype.getRootBlock=function(){return t.BlockSvg.superClass_.getRootBlock.call(this)},t.BlockSvg.prototype.render=function(e){t.utils.dom.startTextWidthCache(),this.rendered=!0,this.workspace.getRenderer().render(this),this.updateConnectionLocations_(),!1!==e&&((e=this.getParent())?e.render(!0):this.workspace.resizeContents()),t.utils.dom.stopTextWidthCache(),this.updateMarkers_()},t.BlockSvg.prototype.updateMarkers_=function(){this.workspace.keyboardAccessibilityMode&&this.pathObject.cursorSvg&&this.workspace.getCursor().draw(),this.workspace.keyboardAccessibilityMode&&this.pathObject.markerSvg&&this.workspace.getMarker(t.navigation.MARKER_NAME).draw()},t.BlockSvg.prototype.updateConnectionLocations_=function(){var t=this.getRelativeToSurfaceXY();this.previousConnection&&this.previousConnection.moveToOffset(t),this.outputConnection&&this.outputConnection.moveToOffset(t);for(var e=0;e<this.inputList.length;e++){var o=this.inputList[e].connection;o&&(o.moveToOffset(t),o.isConnected()&&o.tighten())}this.nextConnection&&(this.nextConnection.moveToOffset(t),this.nextConnection.isConnected()&&this.nextConnection.tighten())},t.BlockSvg.prototype.setCursorSvg=function(t){this.pathObject.setCursorSvg(t)},t.BlockSvg.prototype.setMarkerSvg=function(t){this.pathObject.setMarkerSvg(t)},t.BlockSvg.prototype.getHeightWidth=function(){var t=this.height,e=this.width,o=this.getNextBlock();if(o){o=o.getHeightWidth();var i=this.workspace.getRenderer().getConstants().NOTCH_HEIGHT;t+=o.height-i,e=Math.max(e,o.width)}return{height:t,width:e}},t.BlockSvg.prototype.fadeForReplacement=function(t){this.pathObject.updateReplacementFade(t)},t.BlockSvg.prototype.highlightShapeForInput=function(t,e){this.pathObject.updateShapeForInputHighlight(t,e)},t.blockRendering.rendererMap_={},t.blockRendering.useDebugger=!1,t.blockRendering.register=function(e,o){if(t.blockRendering.rendererMap_[e])throw Error("Renderer has already been registered.");t.blockRendering.rendererMap_[e]=o},t.blockRendering.unregister=function(e){t.blockRendering.rendererMap_[e]?delete t.blockRendering.rendererMap_[e]:console.warn('No renderer mapping for name "'+e+'" found to unregister')},t.blockRendering.startDebugger=function(){t.blockRendering.useDebugger=!0},t.blockRendering.stopDebugger=function(){t.blockRendering.useDebugger=!1},t.blockRendering.init=function(e,o,i){if(!t.blockRendering.rendererMap_[e])throw Error("Renderer not registered: ",e);return(e=new t.blockRendering.rendererMap_[e](e)).init(o,i),e},t.ConnectionDB=function(){this.connections_=[]},t.ConnectionDB.prototype.addConnection=function(t,e){e=this.calculateIndexForYPos_(e),this.connections_.splice(e,0,t)},t.ConnectionDB.prototype.findIndexOfConnection_=function(t,e){if(!this.connections_.length)return-1;var o=this.calculateIndexForYPos_(e);if(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(;o<this.connections_.length&&this.connections_[o].y==e;){if(this.connections_[o]==t)return o;o++}return-1},t.ConnectionDB.prototype.calculateIndexForYPos_=function(t){if(!this.connections_.length)return 0;for(var e=0,o=this.connections_.length;e<o;){var i=Math.floor((e+o)/2);if(this.connections_[i].y<t)e=i+1;else{if(!(this.connections_[i].y>t)){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<e}var i=this.connections_,n=t.x,s=t.y;t=0;for(var r=i.length-2,a=r;t<a;)i[a].y<s?t=a:r=a,a=Math.floor((t+r)/2);var l=[];if(r=t=a,i.length){for(;0<=t&&o(t);)t--;do{r++}while(r<i.length&&o(r))}return l},t.ConnectionDB.prototype.isInYRange_=function(t,e,o){return Math.abs(this.connections_[t].y-e)<=o},t.ConnectionDB.prototype.searchForClosest=function(t,e,o){if(!this.connections_.length)return{connection:null,radius:e};var i=t.y,n=t.x;t.x=n+o.x,t.y=i+o.y;var s=this.calculateIndexForYPos_(t.y);o=null;for(var r,a=e,l=s-1;0<=l&&this.isInYRange_(l,t.y,e);)r=this.connections_[l],t.isConnectionAllowed(r,a)&&(o=r,a=r.distanceFrom(t)),l--;for(;s<this.connections_.length&&this.isInYRange_(s,t.y,e);)r=this.connections_[s],t.isConnectionAllowed(r,a)&&(o=r,a=r.distanceFrom(t)),s++;return t.x=n,t.y=i,{connection:o,radius:a}},t.ConnectionDB.init=function(){var e=[];return e[t.INPUT_VALUE]=new t.ConnectionDB,e[t.OUTPUT_VALUE]=new t.ConnectionDB,e[t.NEXT_STATEMENT]=new t.ConnectionDB,e[t.PREVIOUS_STATEMENT]=new t.ConnectionDB,e},t.MarkerManager=function(t){this.cursorSvg_=this.cursor_=null,this.markers_={},this.workspace_=t},t.MarkerManager.prototype.registerMarker=function(t,e){this.markers_[t]&&this.unregisterMarker(t),e.setDrawer(this.workspace_.getRenderer().makeMarkerDrawer(this.workspace_,e)),this.setMarkerSvg(e.getDrawer().createDom()),this.markers_[t]=e},t.MarkerManager.prototype.unregisterMarker=function(t){var e=this.markers_[t];if(!e)throw Error("Marker with id "+t+" does not exist. Can only unregistermarkers that exist.");e.dispose(),delete this.markers_[t]},t.MarkerManager.prototype.getCursor=function(){return this.cursor_},t.MarkerManager.prototype.getMarker=function(t){return this.markers_[t]},t.MarkerManager.prototype.setCursor=function(t){this.cursor_&&this.cursor_.getDrawer()&&this.cursor_.getDrawer().dispose(),(this.cursor_=t)&&(t=this.workspace_.getRenderer().makeMarkerDrawer(this.workspace_,this.cursor_),this.cursor_.setDrawer(t),this.setCursorSvg(this.cursor_.getDrawer().createDom()))},t.MarkerManager.prototype.setCursorSvg=function(t){t?(this.workspace_.getBlockCanvas().appendChild(t),this.cursorSvg_=t):this.cursorSvg_=null},t.MarkerManager.prototype.setMarkerSvg=function(t){t?this.workspace_.getBlockCanvas()&&(this.cursorSvg_?this.workspace_.getBlockCanvas().insertBefore(t,this.cursorSvg_):this.workspace_.getBlockCanvas().appendChild(t)):this.markerSvg_=null},t.MarkerManager.prototype.updateMarkers=function(){this.workspace_.keyboardAccessibilityMode&&this.cursorSvg_&&this.workspace_.getCursor().draw()},t.MarkerManager.prototype.dispose=function(){for(var t,e=Object.keys(this.markers_),o=0;t=e[o];o++)this.unregisterMarker(t);this.markers_=null,this.cursor_.dispose(),this.cursor_=null},t.ThemeManager=function(t,e){this.workspace_=t,this.theme_=e,this.subscribedWorkspaces_=[],this.componentDB_=Object.create(null)},t.ThemeManager.prototype.getTheme=function(){return this.theme_},t.ThemeManager.prototype.setTheme=function(e){var o,i=this.theme_;for(this.theme_=e,(e=this.workspace_.getInjectionDiv())&&(i&&t.utils.dom.removeClass(e,i.getClassName()),t.utils.dom.addClass(e,this.theme_.getClassName())),i=0;e=this.subscribedWorkspaces_[i];i++)e.refreshTheme();for(i=0,e=Object.keys(this.componentDB_);o=e[i];i++)for(var n,s=0;n=this.componentDB_[o][s];s++){var r=n.element;n=n.propertyName;var a=this.theme_&&this.theme_.getComponentStyle(o);r.style[n]=a||""}t.hideChaff()},t.ThemeManager.prototype.subscribeWorkspace=function(t){this.subscribedWorkspaces_.push(t)},t.ThemeManager.prototype.unsubscribeWorkspace=function(t){if(0>(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_,0<this.previousScale_&&1/0>this.previousScale_){var i=o-this.previousScale_;i=0<i?i*t.TouchGesture.ZOOM_IN_MULTIPLIER:i*t.TouchGesture.ZOOM_OUT_MULTIPLIER;var n=this.startWorkspace_,s=t.utils.mouseToSvg(e,n.getParentSvg(),n.getInverseScreenCTM());n.zoom(s.x,s.y,i)}this.previousScale_=o,e.preventDefault()},t.TouchGesture.prototype.handleTouchEnd=function(e){e=t.Touch.getTouchIdentifierFromEvent(e),this.cachedPoints_[e]&&delete this.cachedPoints_[e],2>Object.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<e.length;s++){var r=e[s],a=r.match(/\.(\w+)$/);if(a&&i.canPlayType("audio/"+a[1])){n=new t.utils.global.Audio(r);break}}n&&n.play&&(this.SOUNDS_[o]=n)}},t.WorkspaceAudio.prototype.preload=function(){for(var e in this.SOUNDS_){var o=this.SOUNDS_[e];o.volume=.01;var i=o.play();if(void 0!==i?i.then(o.pause).catch((function(){})):o.pause(),t.utils.userAgent.IPAD||t.utils.userAgent.IPHONE)break}},t.WorkspaceAudio.prototype.play=function(e,o){var i=this.SOUNDS_[e];i?(e=new Date,null!=this.lastSound_&&e-this.lastSound_<t.SOUND_LIMIT||(this.lastSound_=e,(i=t.utils.userAgent.IPAD||t.utils.userAgent.ANDROID?i:i.cloneNode()).volume=void 0===o?1:o,i.play())):this.parentWorkspace_&&this.parentWorkspace_.getAudioManager().play(e,o)},t.WorkspaceSvg=function(e,o,i){t.WorkspaceSvg.superClass_.constructor.call(this,e),this.getMetrics=e.getMetrics||t.WorkspaceSvg.getTopLevelWorkspaceMetrics_,this.setMetrics=e.setMetrics||t.WorkspaceSvg.setTopLevelWorkspaceMetrics_,this.connectionDBList=t.ConnectionDB.init(),o&&(this.blockDragSurface_=o),i&&(this.workspaceDragSurface_=i),this.useWorkspaceDragSurface_=!!this.workspaceDragSurface_&&t.utils.is3dSupported(),this.highlightedBlocks_=[],this.audioManager_=new t.WorkspaceAudio(e.parentWorkspace),this.grid_=this.options.gridPattern?new t.Grid(e.gridPattern,e.gridOptions):null,this.markerManager_=new t.MarkerManager(this),this.toolboxCategoryCallbacks_={},this.flyoutButtonCallbacks_={},t.Variables&&t.Variables.flyoutCategory&&this.registerToolboxCategoryCallback(t.VARIABLE_CATEGORY_NAME,t.Variables.flyoutCategory),t.VariablesDynamic&&t.VariablesDynamic.flyoutCategory&&this.registerToolboxCategoryCallback(t.VARIABLE_DYNAMIC_CATEGORY_NAME,t.VariablesDynamic.flyoutCategory),t.Procedures&&t.Procedures.flyoutCategory&&(this.registerToolboxCategoryCallback(t.PROCEDURE_CATEGORY_NAME,t.Procedures.flyoutCategory),this.addChangeListener(t.Procedures.mutatorOpenListener)),this.themeManager_=this.options.parentWorkspace?this.options.parentWorkspace.getThemeManager():new t.ThemeManager(this,this.options.theme||t.Themes.Classic),this.themeManager_.subscribeWorkspace(this),this.renderer_=t.blockRendering.init(this.options.renderer||"geras",this.getTheme(),this.options.rendererOverrides),this.cachedParentSvg_=null,this.keyboardAccessibilityMode=!1},t.utils.object.inherits(t.WorkspaceSvg,t.Workspace),t.WorkspaceSvg.prototype.resizeHandlerWrapper_=null,t.WorkspaceSvg.prototype.rendered=!0,t.WorkspaceSvg.prototype.isVisible_=!0,t.WorkspaceSvg.prototype.isFlyout=!1,t.WorkspaceSvg.prototype.isMutator=!1,t.WorkspaceSvg.prototype.resizesEnabled_=!0,t.WorkspaceSvg.prototype.scrollX=0,t.WorkspaceSvg.prototype.scrollY=0,t.WorkspaceSvg.prototype.startScrollX=0,t.WorkspaceSvg.prototype.startScrollY=0,t.WorkspaceSvg.prototype.dragDeltaXY_=null,t.WorkspaceSvg.prototype.scale=1,t.WorkspaceSvg.prototype.trashcan=null,t.WorkspaceSvg.prototype.scrollbar=null,t.WorkspaceSvg.prototype.flyout_=null,t.WorkspaceSvg.prototype.toolbox_=null,t.WorkspaceSvg.prototype.currentGesture_=null,t.WorkspaceSvg.prototype.blockDragSurface_=null,t.WorkspaceSvg.prototype.workspaceDragSurface_=null,t.WorkspaceSvg.prototype.useWorkspaceDragSurface_=!1,t.WorkspaceSvg.prototype.isDragSurfaceActive_=!1,t.WorkspaceSvg.prototype.injectionDiv_=null,t.WorkspaceSvg.prototype.lastRecordedPageScroll_=null,t.WorkspaceSvg.prototype.targetWorkspace=null,t.WorkspaceSvg.prototype.inverseScreenCTM_=null,t.WorkspaceSvg.prototype.inverseScreenCTMDirty_=!0,t.WorkspaceSvg.prototype.getMarkerManager=function(){return this.markerManager_},t.WorkspaceSvg.prototype.setCursorSvg=function(t){this.markerManager_.setCursorSvg(t)},t.WorkspaceSvg.prototype.setMarkerSvg=function(t){this.markerManager_.setMarkerSvg(t)},t.WorkspaceSvg.prototype.getMarker=function(t){return this.markerManager_?this.markerManager_.getMarker(t):null},t.WorkspaceSvg.prototype.getCursor=function(){return this.markerManager_?this.markerManager_.getCursor():null},t.WorkspaceSvg.prototype.getRenderer=function(){return this.renderer_},t.WorkspaceSvg.prototype.getThemeManager=function(){return this.themeManager_},t.WorkspaceSvg.prototype.getTheme=function(){return this.themeManager_.getTheme()},t.WorkspaceSvg.prototype.setTheme=function(e){e||(e=t.Themes.Classic),this.themeManager_.setTheme(e)},t.WorkspaceSvg.prototype.refreshTheme=function(){this.svgGroup_&&this.renderer_.refreshDom(this.svgGroup_,this.getTheme()),this.updateBlockStyles_(this.getAllBlocks(!1).filter((function(t){return void 0!==t.getStyleName()}))),this.refreshToolboxSelection(),this.toolbox_&&this.toolbox_.updateColourFromTheme(),this.isVisible()&&this.setVisible(!0);var e=new t.Events.Ui(null,"theme",null,null);e.workspaceId=this.id,t.Events.fire(e)},t.WorkspaceSvg.prototype.updateBlockStyles_=function(t){for(var e,o=0;e=t[o];o++){var i=e.getStyleName();i&&(e.setStyle(i),e.mutator&&e.mutator.updateBlockStyle())}},t.WorkspaceSvg.prototype.getInverseScreenCTM=function(){if(this.inverseScreenCTMDirty_){var t=this.getParentSvg().getScreenCTM();t&&(this.inverseScreenCTM_=t.inverse(),this.inverseScreenCTMDirty_=!1)}return this.inverseScreenCTM_},t.WorkspaceSvg.prototype.updateInverseScreenCTM=function(){this.inverseScreenCTMDirty_=!0},t.WorkspaceSvg.prototype.isVisible=function(){return this.isVisible_},t.WorkspaceSvg.prototype.getSvgXY=function(e){var o=0,i=0,n=1;(t.utils.dom.containsNode(this.getCanvas(),e)||t.utils.dom.containsNode(this.getBubbleCanvas(),e))&&(n=this.scale);do{var s=t.utils.getRelativeXY(e);e!=this.getCanvas()&&e!=this.getBubbleCanvas()||(n=1),o+=s.x*n,i+=s.y*n,e=e.parentNode}while(e&&e!=this.getParentSvg());return new t.utils.Coordinate(o,i)},t.WorkspaceSvg.prototype.getOriginOffsetInPixels=function(){return t.utils.getInjectionDivXY_(this.getCanvas())},t.WorkspaceSvg.prototype.getInjectionDiv=function(){if(!this.injectionDiv_)for(var t=this.svgGroup_;t;){if(-1!=(" "+(t.getAttribute("class")||"")+" ").indexOf(" injectionDiv ")){this.injectionDiv_=t;break}t=t.parentNode}return this.injectionDiv_},t.WorkspaceSvg.prototype.getBlockCanvas=function(){return this.svgBlockCanvas_},t.WorkspaceSvg.prototype.setResizeHandlerWrapper=function(t){this.resizeHandlerWrapper_=t},t.WorkspaceSvg.prototype.createDom=function(e){if(this.svgGroup_=t.utils.dom.createSvgElement("g",{class:"blocklyWorkspace"},null),e&&(this.svgBackground_=t.utils.dom.createSvgElement("rect",{height:"100%",width:"100%",class:e},this.svgGroup_),"blocklyMainBackground"==e&&this.grid_?this.svgBackground_.style.fill="url(#"+this.grid_.getPatternId()+")":this.themeManager_.subscribe(this.svgBackground_,"workspaceBackgroundColour","fill")),this.svgBlockCanvas_=t.utils.dom.createSvgElement("g",{class:"blocklyBlockCanvas"},this.svgGroup_),this.svgBubbleCanvas_=t.utils.dom.createSvgElement("g",{class:"blocklyBubbleCanvas"},this.svgGroup_),this.isFlyout||(t.bindEventWithChecks_(this.svgGroup_,"mousedown",this,this.onMouseDown_,!1,!0),t.bindEventWithChecks_(this.svgGroup_,"wheel",this,this.onMouseWheel_)),this.options.hasCategories){if(!t.Toolbox)throw Error("Missing require for Blockly.Toolbox");this.toolbox_=new t.Toolbox(this)}return this.grid_&&this.grid_.update(this.scale),this.recordDeleteAreas(),this.markerManager_.setCursor(new t.Cursor),this.markerManager_.registerMarker(t.navigation.MARKER_NAME,new t.Marker),this.renderer_.createDom(this.svgGroup_,this.getTheme()),this.svgGroup_},t.WorkspaceSvg.prototype.dispose=function(){if(this.rendered=!1,this.currentGesture_&&this.currentGesture_.cancel(),this.svgGroup_&&(t.utils.dom.removeNode(this.svgGroup_),this.svgGroup_=null),this.svgBubbleCanvas_=this.svgBlockCanvas_=null,this.toolbox_&&(this.toolbox_.dispose(),this.toolbox_=null),this.flyout_&&(this.flyout_.dispose(),this.flyout_=null),this.trashcan&&(this.trashcan.dispose(),this.trashcan=null),this.scrollbar&&(this.scrollbar.dispose(),this.scrollbar=null),this.zoomControls_&&(this.zoomControls_.dispose(),this.zoomControls_=null),this.audioManager_&&(this.audioManager_.dispose(),this.audioManager_=null),this.grid_&&(this.grid_.dispose(),this.grid_=null),this.renderer_.dispose(),this.themeManager_&&(this.themeManager_.unsubscribeWorkspace(this),this.themeManager_.unsubscribe(this.svgBackground_),this.options.parentWorkspace||(this.themeManager_.dispose(),this.themeManager_=null)),this.markerManager_&&(this.markerManager_.dispose(),this.markerManager_=null),t.WorkspaceSvg.superClass_.dispose.call(this),this.flyoutButtonCallbacks_=this.toolboxCategoryCallbacks_=this.connectionDBList=null,!this.options.parentWorkspace){var e=this.getParentSvg().parentNode;e&&t.utils.dom.removeNode(e)}this.resizeHandlerWrapper_&&(t.unbindEvent_(this.resizeHandlerWrapper_),this.resizeHandlerWrapper_=null)},t.WorkspaceSvg.prototype.newBlock=function(e,o){return new t.BlockSvg(this,e,o)},t.WorkspaceSvg.prototype.addTrashcan=function(){if(!t.Trashcan)throw Error("Missing require for Blockly.Trashcan");this.trashcan=new t.Trashcan(this);var e=this.trashcan.createDom();this.svgGroup_.insertBefore(e,this.svgBlockCanvas_)},t.WorkspaceSvg.prototype.addZoomControls=function(){if(!t.ZoomControls)throw Error("Missing require for Blockly.ZoomControls");this.zoomControls_=new t.ZoomControls(this);var e=this.zoomControls_.createDom();this.svgGroup_.appendChild(e)},t.WorkspaceSvg.prototype.addFlyout=function(e){var o=new t.Options({parentWorkspace:this,rtl:this.RTL,oneBasedIndex:this.options.oneBasedIndex,horizontalLayout:this.horizontalLayout,renderer:this.options.renderer,rendererOverrides:this.options.rendererOverrides});if(o.toolboxPosition=this.options.toolboxPosition,this.horizontalLayout){if(!t.HorizontalFlyout)throw Error("Missing require for Blockly.HorizontalFlyout");this.flyout_=new t.HorizontalFlyout(o)}else{if(!t.VerticalFlyout)throw Error("Missing require for Blockly.VerticalFlyout");this.flyout_=new t.VerticalFlyout(o)}return this.flyout_.autoClose=!1,this.flyout_.getWorkspace().setVisible(!0),this.flyout_.createDom(e)},t.WorkspaceSvg.prototype.getFlyout=function(t){return this.flyout_||t?this.flyout_:this.toolbox_?this.toolbox_.getFlyout():null},t.WorkspaceSvg.prototype.getToolbox=function(){return this.toolbox_},t.WorkspaceSvg.prototype.updateScreenCalculations_=function(){this.updateInverseScreenCTM(),this.recordDeleteAreas()},t.WorkspaceSvg.prototype.resizeContents=function(){this.resizesEnabled_&&this.rendered&&(this.scrollbar&&this.scrollbar.resize(),this.updateInverseScreenCTM())},t.WorkspaceSvg.prototype.resize=function(){this.toolbox_&&this.toolbox_.position(),this.flyout_&&this.flyout_.position(),this.trashcan&&this.trashcan.position(),this.zoomControls_&&this.zoomControls_.position(),this.scrollbar&&this.scrollbar.resize(),this.updateScreenCalculations_()},t.WorkspaceSvg.prototype.updateScreenCalculationsIfScrolled=function(){var e=t.utils.getDocumentScroll();t.utils.Coordinate.equals(this.lastRecordedPageScroll_,e)||(this.lastRecordedPageScroll_=e,this.updateScreenCalculations_())},t.WorkspaceSvg.prototype.getCanvas=function(){return this.svgBlockCanvas_},t.WorkspaceSvg.prototype.getBubbleCanvas=function(){return this.svgBubbleCanvas_},t.WorkspaceSvg.prototype.getParentSvg=function(){if(!this.cachedParentSvg_)for(var t=this.svgGroup_;t;){if("svg"==t.tagName){this.cachedParentSvg_=t;break}t=t.parentNode}return this.cachedParentSvg_},t.WorkspaceSvg.prototype.translate=function(t,e){if(this.useWorkspaceDragSurface_&&this.isDragSurfaceActive_)this.workspaceDragSurface_.translateSurface(t,e);else{var o="translate("+t+","+e+") scale("+this.scale+")";this.svgBlockCanvas_.setAttribute("transform",o),this.svgBubbleCanvas_.setAttribute("transform",o)}this.blockDragSurface_&&this.blockDragSurface_.translateAndScaleGroup(t,e,this.scale),this.grid_&&this.grid_.moveTo(t,e)},t.WorkspaceSvg.prototype.resetDragSurface=function(){if(this.useWorkspaceDragSurface_){this.isDragSurfaceActive_=!1;var t=this.workspaceDragSurface_.getSurfaceTranslation();this.workspaceDragSurface_.clearAndHide(this.svgGroup_),t="translate("+t.x+","+t.y+") scale("+this.scale+")",this.svgBlockCanvas_.setAttribute("transform",t),this.svgBubbleCanvas_.setAttribute("transform",t)}},t.WorkspaceSvg.prototype.setupDragSurface=function(){if(this.useWorkspaceDragSurface_&&!this.isDragSurfaceActive_){this.isDragSurfaceActive_=!0;var e=this.svgBlockCanvas_.previousSibling,o=parseInt(this.getParentSvg().getAttribute("width"),10),i=parseInt(this.getParentSvg().getAttribute("height"),10),n=t.utils.getRelativeXY(this.getCanvas());this.workspaceDragSurface_.setContentsAndShow(this.getCanvas(),this.getBubbleCanvas(),e,o,i,this.scale),this.workspaceDragSurface_.translateSurface(n.x,n.y)}},t.WorkspaceSvg.prototype.getBlockDragSurface=function(){return this.blockDragSurface_},t.WorkspaceSvg.prototype.getWidth=function(){var t=this.getMetrics();return t?t.viewWidth/this.scale:0},t.WorkspaceSvg.prototype.setVisible=function(e){if(this.isVisible_=e,this.svgGroup_)if(this.scrollbar&&this.scrollbar.setContainerVisible(e),this.getFlyout()&&this.getFlyout().setContainerVisible(e),this.getParentSvg().style.display=e?"block":"none",this.toolbox_&&(this.toolbox_.HtmlDiv.style.display=e?"block":"none"),e){for(var o=(e=this.getAllBlocks(!1)).length-1;0<=o;o--)e[o].markDirty();this.render(),this.toolbox_&&this.toolbox_.position()}else t.hideChaff(!0)},t.WorkspaceSvg.prototype.render=function(){for(var t=this.getAllBlocks(!1),e=t.length-1;0<=e;e--)t[e].render(!1);if(this.currentGesture_)for(t=this.currentGesture_.getInsertionMarkers(),e=0;e<t.length;e++)t[e].render(!1);this.markerManager_.updateMarkers()},t.WorkspaceSvg.prototype.traceOn=function(){console.warn("Deprecated call to traceOn, delete this.")},t.WorkspaceSvg.prototype.highlightBlock=function(e,o){if(void 0===o){for(var i,n=0;i=this.highlightedBlocks_[n];n++)i.setHighlighted(!1);this.highlightedBlocks_.length=0}(i=e?this.getBlockById(e):null)&&((e=void 0===o||o)?-1==this.highlightedBlocks_.indexOf(i)&&this.highlightedBlocks_.push(i):t.utils.arrayRemove(this.highlightedBlocks_,i),i.setHighlighted(e))},t.WorkspaceSvg.prototype.paste=function(t){!this.rendered||t.getElementsByTagName("block").length>=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;i<e.length;i++){var n=e[i].getBoundingRectangle();n.top<o.top&&(o.top=n.top),n.bottom>o.bottom&&(o.bottom=n.bottom),n.left<o.left&&(o.left=n.left),n.right>o.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<t.length;e++)o(t[e])}}function i(){t.Events.setGroup(r);var e=_.shift();e&&(e.workspace?(e.dispose(!1,!0),setTimeout(i,10)):i()),t.Events.setGroup(!1)}if(!this.options.readOnly&&!this.isFlyout){var n=[],s=this.getTopBlocks(!0),r=t.utils.genUid(),a=this,l={};if(l.text=t.Msg.UNDO,l.enabled=0<this.undoStack_.length,l.callback=this.undo.bind(this,!1),n.push(l),(l={}).text=t.Msg.REDO,l.enabled=0<this.redoStack_.length,l.callback=this.undo.bind(this,!0),n.push(l),this.isMovable()&&((l={}).text=t.Msg.CLEAN_UP,l.enabled=1<s.length,l.callback=this.cleanUp.bind(this),n.push(l)),this.options.collapse){for(var c=l=!1,h=0;h<s.length;h++)for(var u=s[h];u;)u.isCollapsed()?l=!0:c=!0,u=u.getNextBlock();var p=function(t){for(var e=0,o=0;o<s.length;o++)for(var i=s[o];i;)setTimeout(i.setCollapsed.bind(i,t),e),i=i.getNextBlock(),e+=10};(c={enabled:c}).text=t.Msg.COLLAPSE_ALL,c.callback=function(){p(!0)},n.push(c),(l={enabled:l}).text=t.Msg.EXPAND_ALL,l.callback=function(){p(!1)},n.push(l)}var _=[];for(h=0;h<s.length;h++)o(s[h]);l={text:1==_.length?t.Msg.DELETE_BLOCK:t.Msg.DELETE_X_BLOCKS.replace("%1",String(_.length)),enabled:0<_.length,callback:function(){a.currentGesture_&&a.currentGesture_.cancel(),2>_.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:i<this.options.zoomOptions.minScale&&(o=this.options.zoomOptions.minScale/this.scale);var n=this.getCanvas().getCTM(),s=this.getParentSvg().createSVGPoint();s.x=t,s.y=e,t=(s=s.matrixTransform(n.inverse())).x,e=s.y,n=n.translate(t*(1-o),e*(1-o)).scale(o),this.scrollX=n.e,this.scrollY=n.f,this.setScale(i)}},t.WorkspaceSvg.prototype.zoomCenter=function(t){var e=this.getMetrics();if(this.flyout_){var o=e.svgWidth/2;e=e.svgHeight/2}else o=e.viewWidth/2+e.absoluteLeft,e=e.viewHeight/2+e.absoluteTop;this.zoom(o,e,t)},t.WorkspaceSvg.prototype.zoomToFit=function(){if(this.isMovable()){var t=this.getMetrics(),e=t.viewWidth;t=t.viewHeight;var o=this.getBlocksBoundingBox(),i=o.right-o.left;o=o.bottom-o.top,i&&(this.flyout_&&(this.horizontalLayout?(t+=this.flyout_.getHeight(),o+=this.flyout_.getHeight()/this.scale):(e+=this.flyout_.getWidth(),i+=this.flyout_.getWidth()/this.scale)),this.setScale(Math.min(e/i,t/o)),this.scrollCenter())}else console.warn("Tried to move a non-movable workspace. This could result in blocks becoming inaccessible.")},t.WorkspaceSvg.prototype.beginCanvasTransition=function(){t.utils.dom.addClass(this.svgBlockCanvas_,"blocklyCanvasTransitioning"),t.utils.dom.addClass(this.svgBubbleCanvas_,"blocklyCanvasTransitioning")},t.WorkspaceSvg.prototype.endCanvasTransition=function(){t.utils.dom.removeClass(this.svgBlockCanvas_,"blocklyCanvasTransitioning"),t.utils.dom.removeClass(this.svgBubbleCanvas_,"blocklyCanvasTransitioning")},t.WorkspaceSvg.prototype.scrollCenter=function(){if(this.isMovable()){var t=this.getMetrics(),e=(t.contentWidth-t.viewWidth)/2,o=(t.contentHeight-t.viewHeight)/2;e=-e-t.contentLeft,o=-o-t.contentTop,this.scroll(e,o)}else console.warn("Tried to move a non-movable workspace. This could result in blocks becoming inaccessible.")},t.WorkspaceSvg.prototype.centerOnBlock=function(t){if(this.isMovable()){if(t=t?this.getBlockById(t):null){var e=t.getRelativeToSurfaceXY(),o=t.getHeightWidth(),i=this.scale;t=(e.x+(this.RTL?-1:1)*o.width/2)*i,e=(e.y+o.height/2)*i,o=this.getMetrics(),this.scroll(-(t-o.viewWidth/2),-(e-o.viewHeight/2))}}else console.warn("Tried to move a non-movable workspace. This could result in blocks becoming inaccessible.")},t.WorkspaceSvg.prototype.setScale=function(e){this.options.zoomOptions.maxScale&&e>this.options.zoomOptions.maxScale?e=this.options.zoomOptions.maxScale:this.options.zoomOptions.minScale&&e<this.options.zoomOptions.minScale&&(e=this.options.zoomOptions.minScale),this.scale=e,t.hideChaff(!1),this.flyout_&&(this.flyout_.reflow(),this.recordDeleteAreas()),this.grid_&&this.grid_.update(this.scale),e=this.getMetrics(),this.scrollX-=e.absoluteLeft,this.scrollY-=e.absoluteTop,e.viewLeft+=e.absoluteLeft,e.viewTop+=e.absoluteTop,this.scroll(this.scrollX,this.scrollY),this.scrollbar&&(this.flyout_?(this.scrollbar.hScroll.resizeViewHorizontal(e),this.scrollbar.vScroll.resizeViewVertical(e)):(this.scrollbar.hScroll.resizeContentHorizontal(e),this.scrollbar.vScroll.resizeContentVertical(e)))},t.WorkspaceSvg.prototype.getScale=function(){return this.options.parentWorkspace?this.options.parentWorkspace.getScale():this.scale},t.WorkspaceSvg.prototype.scroll=function(e,o){t.hideChaff(!0);var i=this.getMetrics(),n=i.contentWidth+i.contentLeft-i.viewWidth,s=i.contentHeight+i.contentTop-i.viewHeight;e=Math.min(e,-i.contentLeft),o=Math.min(o,-i.contentTop),e=Math.max(e,-n),o=Math.max(o,-s),this.scrollX=e,this.scrollY=o,this.scrollbar&&(this.scrollbar.hScroll.setHandlePosition(-(e+i.contentLeft)*this.scrollbar.hScroll.ratio_),this.scrollbar.vScroll.setHandlePosition(-(o+i.contentTop)*this.scrollbar.vScroll.ratio_)),e+=i.absoluteLeft,o+=i.absoluteTop,this.translate(e,o)},t.WorkspaceSvg.getDimensionsPx_=function(t){var e=0,o=0;return t&&(e=t.getWidth(),o=t.getHeight()),{width:e,height:o}},t.WorkspaceSvg.getContentDimensions_=function(e,o){return e.isContentBounded()?t.WorkspaceSvg.getContentDimensionsBounded_(e,o):t.WorkspaceSvg.getContentDimensionsExact_(e)},t.WorkspaceSvg.getContentDimensionsExact_=function(t){var e=t.getBlocksBoundingBox(),o=t.scale;t=e.top*o;var i=e.bottom*o,n=e.left*o;return{top:t,bottom:i,left:n,right:e=e.right*o,width:e-n,height:i-t}},t.WorkspaceSvg.getContentDimensionsBounded_=function(e,o){e=t.WorkspaceSvg.getContentDimensionsExact_(e);var i=o.width,n=i/2,s=(o=o.height)/2,r=Math.min(e.left-n,e.right-i),a=Math.min(e.top-s,e.bottom-o);return{left:r,top:a,height:Math.max(e.bottom+s,e.top+o)-a,width:Math.max(e.right+n,e.left+i)-r}},t.WorkspaceSvg.getTopLevelWorkspaceMetrics_=function(){var e=t.WorkspaceSvg.getDimensionsPx_(this.toolbox_),o=t.WorkspaceSvg.getDimensionsPx_(this.flyout_),i=t.svgSize(this.getParentSvg()),n={height:i.height,width:i.width};this.toolbox_?this.toolboxPosition==t.TOOLBOX_AT_TOP||this.toolboxPosition==t.TOOLBOX_AT_BOTTOM?n.height-=e.height:this.toolboxPosition!=t.TOOLBOX_AT_LEFT&&this.toolboxPosition!=t.TOOLBOX_AT_RIGHT||(n.width-=e.width):this.flyout_&&(this.toolboxPosition==t.TOOLBOX_AT_TOP||this.toolboxPosition==t.TOOLBOX_AT_BOTTOM?n.height-=o.height:this.toolboxPosition!=t.TOOLBOX_AT_LEFT&&this.toolboxPosition!=t.TOOLBOX_AT_RIGHT||(n.width-=o.width));var s=t.WorkspaceSvg.getContentDimensions_(this,n),r=0;this.toolbox_&&this.toolboxPosition==t.TOOLBOX_AT_LEFT?r=e.width:this.flyout_&&this.toolboxPosition==t.TOOLBOX_AT_LEFT&&(r=o.width);var a=0;return this.toolbox_&&this.toolboxPosition==t.TOOLBOX_AT_TOP?a=e.height:this.flyout_&&this.toolboxPosition==t.TOOLBOX_AT_TOP&&(a=o.height),{contentHeight:s.height,contentWidth:s.width,contentTop:s.top,contentLeft:s.left,viewHeight:n.height,viewWidth:n.width,viewTop:-this.scrollY,viewLeft:-this.scrollX,absoluteTop:a,absoluteLeft:r,svgHeight:i.height,svgWidth:i.width,toolboxWidth:e.width,toolboxHeight:e.height,flyoutWidth:o.width,flyoutHeight:o.height,toolboxPosition:this.toolboxPosition}},t.WorkspaceSvg.setTopLevelWorkspaceMetrics_=function(t){var e=this.getMetrics();"number"==typeof t.x&&(this.scrollX=-e.contentWidth*t.x-e.contentLeft),"number"==typeof t.y&&(this.scrollY=-e.contentHeight*t.y-e.contentTop),this.translate(this.scrollX+e.absoluteLeft,this.scrollY+e.absoluteTop)},t.WorkspaceSvg.prototype.getBlockById=function(e){return t.WorkspaceSvg.superClass_.getBlockById.call(this,e)},t.WorkspaceSvg.prototype.getTopBlocks=function(e){return t.WorkspaceSvg.superClass_.getTopBlocks.call(this,e)},t.WorkspaceSvg.prototype.setResizesEnabled=function(t){var e=!this.resizesEnabled_&&t;this.resizesEnabled_=t,e&&this.resizeContents()},t.WorkspaceSvg.prototype.clear=function(){this.setResizesEnabled(!1),t.WorkspaceSvg.superClass_.clear.call(this),this.setResizesEnabled(!0)},t.WorkspaceSvg.prototype.registerButtonCallback=function(t,e){if("function"!=typeof e)throw TypeError("Button callbacks must be functions.");this.flyoutButtonCallbacks_[t]=e},t.WorkspaceSvg.prototype.getButtonCallback=function(t){return(t=this.flyoutButtonCallbacks_[t])?t:null},t.WorkspaceSvg.prototype.removeButtonCallback=function(t){this.flyoutButtonCallbacks_[t]=null},t.WorkspaceSvg.prototype.registerToolboxCategoryCallback=function(t,e){if("function"!=typeof e)throw TypeError("Toolbox category callbacks must be functions.");this.toolboxCategoryCallbacks_[t]=e},t.WorkspaceSvg.prototype.getToolboxCategoryCallback=function(t){return this.toolboxCategoryCallbacks_[t]||null},t.WorkspaceSvg.prototype.removeToolboxCategoryCallback=function(t){this.toolboxCategoryCallbacks_[t]=null},t.WorkspaceSvg.prototype.getGesture=function(e){var o="mousedown"==e.type||"touchstart"==e.type||"pointerdown"==e.type,i=this.currentGesture_;return i?o&&i.hasStarted()?(console.warn("Tried to start the same gesture twice."),i.cancel(),null):i:o?this.currentGesture_=new t.TouchGesture(e,this):null},t.WorkspaceSvg.prototype.clearGesture=function(){this.currentGesture_=null},t.WorkspaceSvg.prototype.cancelCurrentGesture=function(){this.currentGesture_&&this.currentGesture_.cancel()},t.WorkspaceSvg.prototype.getAudioManager=function(){return this.audioManager_},t.WorkspaceSvg.prototype.getGrid=function(){return this.grid_},t.inject=function(e,o){if(t.checkBlockColourConstants(),"string"==typeof e&&(e=document.getElementById(e)||document.querySelector(e)),!e||!t.utils.dom.containsNode(document,e))throw Error("Error: container is not in current document.");o=new t.Options(o||{});var i=document.createElement("div");i.className="injectionDiv",i.tabIndex=0,t.utils.aria.setState(i,t.utils.aria.State.LABEL,t.Msg.WORKSPACE_ARIA_LABEL),e.appendChild(i),e=t.createDom_(i,o);var n=new t.BlockDragSurfaceSvg(i),s=new t.WorkspaceDragSurfaceSvg(i),r=t.createMainWorkspace_(e,o,n,s);return t.user.keyMap.setKeyMap(o.keyMap),t.init_(r),t.mainWorkspace=r,t.svgResize(r),i.addEventListener("focusin",(function(){t.mainWorkspace=r})),r},t.createDom_=function(e,o){e.setAttribute("dir","LTR"),t.Component.defaultRightToLeft=o.RTL,t.Css.inject(o.hasCss,o.pathToMedia),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",class:"blocklySvg",tabindex:"0"},e);var i=t.utils.dom.createSvgElement("defs",{},e),n=String(Math.random()).substring(2);return o.gridPattern=t.Grid.createDom(n,o.gridOptions,i),e},t.createMainWorkspace_=function(e,o,i,n){o.parentWorkspace=null;var s=new t.WorkspaceSvg(o,i,n);return o=s.options,s.scale=o.zoomOptions.startScale,e.appendChild(s.createDom("blocklyMainBackground")),t.utils.dom.addClass(s.getInjectionDiv(),s.getRenderer().getClassName()),t.utils.dom.addClass(s.getInjectionDiv(),s.getTheme().getClassName()),!o.hasCategories&&o.languageTree&&(i=s.addFlyout("svg"),t.utils.dom.insertAfter(i,e)),o.hasTrashcan&&s.addTrashcan(),o.zoomOptions&&o.zoomOptions.controls&&s.addZoomControls(),s.getThemeManager().subscribe(e,"workspaceBackgroundColour","background-color"),s.translate(0,0),o.readOnly||s.isMovable()||s.addChangeListener((function(e){if(!s.isDragging()&&!s.isMovable()&&-1!=t.Events.BUMP_EVENTS.indexOf(e.type)){var o=Object.create(null),i=s.getMetrics(),n=s.scale;if(o.RTL=s.RTL,o.viewLeft=i.viewLeft/n,o.viewTop=i.viewTop/n,o.viewRight=(i.viewLeft+i.viewWidth)/n,o.viewBottom=(i.viewTop+i.viewHeight)/n,s.isContentBounded()?(i=s.getBlocksBoundingBox(),o.contentLeft=i.left,o.contentTop=i.top,o.contentRight=i.right,o.contentBottom=i.bottom):(o.contentLeft=i.contentLeft/n,o.contentTop=i.contentTop/n,o.contentRight=(i.contentLeft+i.contentWidth)/n,o.contentBottom=(i.contentTop+i.contentHeight)/n),o.contentTop<o.viewTop||o.contentBottom>o.viewBottom||o.contentLeft<o.viewLeft||o.contentRight>o.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;e<t.length;e++)this.reservedDict_[t[e]]=!0;this.reset()},t.Names.DEVELOPER_VARIABLE_TYPE="DEVELOPER_VARIABLE",t.Names.prototype.reset=function(){this.db_=Object.create(null),this.dbReverse_=Object.create(null),this.variableMap_=null},t.Names.prototype.setVariableMap=function(t){this.variableMap_=t},t.Names.prototype.getNameForUserVariable_=function(t){return this.variableMap_?(t=this.variableMap_.getVariableById(t))?t.name:null:(console.log("Deprecated call to Blockly.Names.prototype.getName without defining a variable map. To fix, add the following code in your generator's init() function:\nBlockly.YourGeneratorName.variableDB_.setVariableMap(workspace.getVariableMap());"),null)},t.Names.prototype.getName=function(e,o){if(o==t.VARIABLE_CATEGORY_NAME){var i=this.getNameForUserVariable_(e);i&&(e=i)}i=e.toLowerCase()+"_"+o;var n=o==t.VARIABLE_CATEGORY_NAME||o==t.Names.DEVELOPER_VARIABLE_TYPE?this.variablePrefix_:"";return i in this.db_?n+this.db_[i]:(e=this.getDistinctName(e,o),this.db_[i]=e.substr(n.length),e)},t.Names.prototype.getDistinctName=function(e,o){e=this.safeName_(e);for(var i="";this.dbReverse_[e+i]||e+i in this.reservedDict_;)i=i?i+1:2;return e+=i,this.dbReverse_[e]=!0,(o==t.VARIABLE_CATEGORY_NAME||o==t.Names.DEVELOPER_VARIABLE_TYPE?this.variablePrefix_:"")+e},t.Names.prototype.safeName_=function(e){return e?(e=encodeURI(e.replace(/ /g,"_")).replace(/[^\w]/g,"_"),-1!="0123456789".indexOf(e[0])&&(e="my_"+e)):e=t.Msg.UNNAMED_KEY||"unnamed",e},t.Names.equals=function(t,e){return t.toLowerCase()==e.toLowerCase()},t.Procedures={},t.Procedures.NAME_TYPE=t.PROCEDURE_CATEGORY_NAME,t.Procedures.DEFAULT_ARG="x",t.Procedures.allProcedures=function(e){e=e.getAllBlocks(!1);for(var o=[],i=[],n=0;n<e.length;n++)if(e[n].getProcedureDef){var s=e[n].getProcedureDef();s&&(s[2]?o.push(s):i.push(s))}return i.sort(t.Procedures.procTupleComparator_),o.sort(t.Procedures.procTupleComparator_),[i,o]},t.Procedures.procTupleComparator_=function(t,e){return t[0].toLowerCase().localeCompare(e[0].toLowerCase())},t.Procedures.findLegalName=function(e,o){if(o.isInFlyout)return e;for(e=e||t.Msg.UNNAMED_KEY||"unnamed";!t.Procedures.isLegalName_(e,o.workspace,o);){var i=e.match(/^(.*?)(\d+)$/);e=i?i[1]+(parseInt(i[2],10)+1):e+"2"}return e},t.Procedures.isLegalName_=function(e,o,i){return!t.Procedures.isNameUsed(e,o,i)},t.Procedures.isNameUsed=function(e,o,i){o=o.getAllBlocks(!1);for(var n=0;n<o.length;n++)if(o[n]!=i&&o[n].getProcedureDef){var s=o[n].getProcedureDef();if(t.Names.equals(s[0],e))return!0}return!1},t.Procedures.rename=function(e){e=e.trim();var o=t.Procedures.findLegalName(e,this.getSourceBlock()),i=this.getValue();if(i!=e&&i!=o){e=this.getSourceBlock().workspace.getAllBlocks(!1);for(var n=0;n<e.length;n++)e[n].renameProcedure&&e[n].renameProcedure(i,o)}return o},t.Procedures.flyoutCategory=function(e){function o(e,o){for(var n=0;n<e.length;n++){var s=e[n][0],r=e[n][1],a=t.utils.xml.createElement("block");a.setAttribute("type",o),a.setAttribute("gap",16);var l=t.utils.xml.createElement("mutation");for(l.setAttribute("name",s),a.appendChild(l),s=0;s<r.length;s++){var c=t.utils.xml.createElement("arg");c.setAttribute("name",r[s]),l.appendChild(c)}i.push(a)}}var i=[];if(t.Blocks.procedures_defnoreturn){var n=t.utils.xml.createElement("block");n.setAttribute("type","procedures_defnoreturn"),n.setAttribute("gap",16);var s=t.utils.xml.createElement("field");s.setAttribute("name","NAME"),s.appendChild(t.utils.xml.createTextNode(t.Msg.PROCEDURES_DEFNORETURN_PROCEDURE)),n.appendChild(s),i.push(n)}return t.Blocks.procedures_defreturn&&((n=t.utils.xml.createElement("block")).setAttribute("type","procedures_defreturn"),n.setAttribute("gap",16),(s=t.utils.xml.createElement("field")).setAttribute("name","NAME"),s.appendChild(t.utils.xml.createTextNode(t.Msg.PROCEDURES_DEFRETURN_PROCEDURE)),n.appendChild(s),i.push(n)),t.Blocks.procedures_ifreturn&&((n=t.utils.xml.createElement("block")).setAttribute("type","procedures_ifreturn"),n.setAttribute("gap",16),i.push(n)),i.length&&i[i.length-1].setAttribute("gap",24),o((e=t.Procedures.allProcedures(e))[0],"procedures_callnoreturn"),o(e[1],"procedures_callreturn"),i},t.Procedures.updateMutatorFlyout_=function(e){for(var o,i=[],n=e.getBlocksByType("procedures_mutatorarg",!1),s=0;o=n[s];s++)i.push(o.getFieldValue("NAME"));n=t.utils.xml.createElement("xml"),(s=t.utils.xml.createElement("block")).setAttribute("type","procedures_mutatorarg"),(o=t.utils.xml.createElement("field")).setAttribute("name","NAME"),i=t.Variables.generateUniqueNameFromOptions(t.Procedures.DEFAULT_ARG,i),i=t.utils.xml.createTextNode(i),o.appendChild(i),s.appendChild(o),n.appendChild(s),e.updateToolbox(n)},t.Procedures.mutatorOpenListener=function(e){if(e.type==t.Events.UI&&"mutatorOpen"==e.element&&e.newValue){var o=(e=t.Workspace.getById(e.workspaceId).getBlockById(e.blockId)).type;"procedures_defnoreturn"!=o&&"procedures_defreturn"!=o||(e=e.mutator.getWorkspace(),t.Procedures.updateMutatorFlyout_(e),e.addChangeListener(t.Procedures.mutatorChangeListener_))}},t.Procedures.mutatorChangeListener_=function(e){e.type!=t.Events.BLOCK_CREATE&&e.type!=t.Events.BLOCK_DELETE&&e.type!=t.Events.BLOCK_CHANGE||(e=t.Workspace.getById(e.workspaceId),t.Procedures.updateMutatorFlyout_(e))},t.Procedures.getCallers=function(e,o){var i=[];o=o.getAllBlocks(!1);for(var n=0;n<o.length;n++)if(o[n].getProcedureCall){var s=o[n].getProcedureCall();s&&t.Names.equals(s,e)&&i.push(o[n])}return i},t.Procedures.mutateCallers=function(e){var o,i=t.Events.recordUndo,n=e.getProcedureDef()[0],s=e.mutationToDom(!0);for(e=t.Procedures.getCallers(n,e.workspace),n=0;o=e[n];n++){var r=o.mutationToDom();r=r&&t.Xml.domToText(r),o.domToMutation(s);var a=o.mutationToDom();r!=(a=a&&t.Xml.domToText(a))&&(t.Events.recordUndo=!1,t.Events.fire(new t.Events.BlockChange(o,"mutation",null,r,a)),t.Events.recordUndo=i)}},t.Procedures.getDefinition=function(e,o){o=o.getTopBlocks(!1);for(var i=0;i<o.length;i++)if(o[i].getProcedureDef){var n=o[i].getProcedureDef();if(n&&t.Names.equals(n[0],e))return o[i]}return null},t.VariableModel=function(e,o,i,n){this.workspace=e,this.name=o,this.type=i||"",this.id_=n||t.utils.genUid(),t.Events.fire(new t.Events.VarCreate(this))},t.VariableModel.prototype.getId=function(){return this.id_},t.VariableModel.compareByName=function(t,e){return(t=t.name.toLowerCase())<(e=e.name.toLowerCase())?-1:t==e?0:1},t.Variables={},t.Variables.NAME_TYPE=t.VARIABLE_CATEGORY_NAME,t.Variables.allUsedVarModels=function(t){var e=t.getAllBlocks(!1);t=Object.create(null);for(var o=0;o<e.length;o++){var i=e[o].getVarModels();if(i)for(var n=0;n<i.length;n++){var s=i[n],r=s.getId();r&&(t[r]=s)}}for(r in e=[],t)e.push(t[r]);return e},t.Variables.allUsedVariables=function(){console.warn("Deprecated call to Blockly.Variables.allUsedVariables. Use Blockly.Variables.allUsedVarModels instead.\nIf this is a major issue please file a bug on GitHub.")},t.Variables.ALL_DEVELOPER_VARS_WARNINGS_BY_BLOCK_TYPE_={},t.Variables.allDeveloperVariables=function(e){e=e.getAllBlocks(!1);for(var o,i=Object.create(null),n=0;o=e[n];n++){var s=o.getDeveloperVariables;if(!s&&o.getDeveloperVars&&(s=o.getDeveloperVars,t.Variables.ALL_DEVELOPER_VARS_WARNINGS_BY_BLOCK_TYPE_[o.type]||(console.warn("Function getDeveloperVars() deprecated. Use getDeveloperVariables() (block type '"+o.type+"')"),t.Variables.ALL_DEVELOPER_VARS_WARNINGS_BY_BLOCK_TYPE_[o.type]=!0)),s)for(o=s(),s=0;s<o.length;s++)i[o[s]]=!0}return Object.keys(i)},t.Variables.flyoutCategory=function(e){var o=[],i=document.createElement("button");return i.setAttribute("text","%{BKY_NEW_VARIABLE}"),i.setAttribute("callbackKey","CREATE_VARIABLE"),e.registerButtonCallback("CREATE_VARIABLE",(function(e){t.Variables.createVariableButtonHandler(e.getTargetWorkspace())})),o.push(i),e=t.Variables.flyoutCategoryBlocks(e),o.concat(e)},t.Variables.flyoutCategoryBlocks=function(e){var o=[];if(0<(e=e.getVariablesOfType("")).length){var i=e[e.length-1];if(t.Blocks.variables_set){var n=t.utils.xml.createElement("block");n.setAttribute("type","variables_set"),n.setAttribute("gap",t.Blocks.math_change?8:24),n.appendChild(t.Variables.generateVariableFieldDom(i)),o.push(n)}if(t.Blocks.math_change&&((n=t.utils.xml.createElement("block")).setAttribute("type","math_change"),n.setAttribute("gap",t.Blocks.variables_get?20:8),n.appendChild(t.Variables.generateVariableFieldDom(i)),i=t.Xml.textToDom('<value name="DELTA"><shadow type="math_number"><field name="NUM">1</field></shadow></value>'),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;a<o.length;a++)if(o[a].toLowerCase()==e){r=!0;break}if(!r)return e;++s==i.length&&(s=0,n=Number(n)+1),e=i.charAt(s)+n}},t.Variables.createVariableButtonHandler=function(e,o,i){var n=i||"",s=function(i){t.Variables.promptName(t.Msg.NEW_VARIABLE_TITLE,i,(function(i){if(i){var r=t.Variables.nameUsedWithAnyType_(i,e);if(r){if(r.type==n)var a=t.Msg.VARIABLE_ALREADY_EXISTS.replace("%1",r.name);else a=(a=t.Msg.VARIABLE_ALREADY_EXISTS_FOR_ANOTHER_TYPE).replace("%1",r.name).replace("%2",r.type);t.alert(a,(function(){s(i)}))}else e.createVariable(i,n),o&&o(i)}else o&&o(null)}))};s("")},t.Variables.createVariable=t.Variables.createVariableButtonHandler,t.Variables.renameVariable=function(e,o,i){var n=function(s){var r=t.Msg.RENAME_VARIABLE_TITLE.replace("%1",o.name);t.Variables.promptName(r,s,(function(s){if(s){var r=t.Variables.nameUsedWithOtherType_(s,o.type,e);r?(r=t.Msg.VARIABLE_ALREADY_EXISTS_FOR_ANOTHER_TYPE.replace("%1",r.name).replace("%2",r.type),t.alert(r,(function(){n(s)}))):(e.renameVariableById(o.getId(),s),i&&i(s))}else i&&i(null)}))};n("")},t.Variables.promptName=function(e,o,i){t.prompt(e,o,(function(e){e&&((e=e.replace(/[\s\xa0]+/g," ").trim())==t.Msg.RENAME_VARIABLE||e==t.Msg.NEW_VARIABLE)&&(e=null),i(e)}))},t.Variables.nameUsedWithOtherType_=function(t,e,o){o=o.getVariableMap().getAllVariables(),t=t.toLowerCase();for(var i,n=0;i=o[n];n++)if(i.name.toLowerCase()==t&&i.type!=e)return i;return null},t.Variables.nameUsedWithAnyType_=function(t,e){e=e.getVariableMap().getAllVariables(),t=t.toLowerCase();for(var o,i=0;o=e[i];i++)if(o.name.toLowerCase()==t)return o;return null},t.Variables.generateVariableFieldDom=function(e){var o=t.utils.xml.createElement("field");return o.setAttribute("name","VAR"),o.setAttribute("id",e.getId()),o.setAttribute("variabletype",e.type),e=t.utils.xml.createTextNode(e.name),o.appendChild(e),o},t.Variables.getOrCreateVariablePackage=function(e,o,i,n){var s=t.Variables.getVariable(e,o,i,n);return s||(s=t.Variables.createVariable_(e,o,i,n)),s},t.Variables.getVariable=function(t,e,o,i){var n=t.getPotentialVariableMap(),s=null;if(e&&(!(s=t.getVariableById(e))&&n&&(s=n.getVariableById(e)),s))return s;if(o){if(null==i)throw Error("Tried to look up a variable by name without a type");!(s=t.getVariable(o,i))&&n&&(s=n.getVariable(o,i))}return s},t.Variables.createVariable_=function(e,o,i,n){var s=e.getPotentialVariableMap();return i||(i=t.Variables.generateUniqueName(e.isFlyout?e.targetWorkspace:e)),s?s.createVariable(i,n,o):e.createVariable(i,n,o)},t.Variables.getAddedVariables=function(t,e){t=t.getAllVariables();var o=[];if(e.length!=t.length)for(var i=0;i<t.length;i++){var n=t[i];-1==e.indexOf(n)&&o.push(n)}return o},t.WidgetDiv={},t.WidgetDiv.owner_=null,t.WidgetDiv.dispose_=null,t.WidgetDiv.rendererClassName_="",t.WidgetDiv.themeClassName_="",t.WidgetDiv.createDom=function(){t.WidgetDiv.DIV||(t.WidgetDiv.DIV=document.createElement("div"),t.WidgetDiv.DIV.className="blocklyWidgetDiv",(t.parentContainer||document.body).appendChild(t.WidgetDiv.DIV))},t.WidgetDiv.show=function(e,o,i){t.WidgetDiv.hide(),t.WidgetDiv.owner_=e,t.WidgetDiv.dispose_=i,(e=t.WidgetDiv.DIV).style.direction=o?"rtl":"ltr",e.style.display="block",t.WidgetDiv.rendererClassName_=t.getMainWorkspace().getRenderer().getClassName(),t.WidgetDiv.themeClassName_=t.getMainWorkspace().getTheme().getClassName(),t.utils.dom.addClass(e,t.WidgetDiv.rendererClassName_),t.utils.dom.addClass(e,t.WidgetDiv.themeClassName_)},t.WidgetDiv.hide=function(){if(t.WidgetDiv.isVisible()){t.WidgetDiv.owner_=null;var e=t.WidgetDiv.DIV;e.style.display="none",e.style.left="",e.style.top="",t.WidgetDiv.dispose_&&t.WidgetDiv.dispose_(),t.WidgetDiv.dispose_=null,e.textContent="",t.WidgetDiv.rendererClassName_&&(t.utils.dom.removeClass(e,t.WidgetDiv.rendererClassName_),t.WidgetDiv.rendererClassName_=""),t.WidgetDiv.themeClassName_&&(t.utils.dom.removeClass(e,t.WidgetDiv.themeClassName_),t.WidgetDiv.themeClassName_=""),t.getMainWorkspace().markFocused()}},t.WidgetDiv.isVisible=function(){return!!t.WidgetDiv.owner_},t.WidgetDiv.hideIfOwner=function(e){t.WidgetDiv.owner_==e&&t.WidgetDiv.hide()},t.WidgetDiv.positionInternal_=function(e,o,i){t.WidgetDiv.DIV.style.left=e+"px",t.WidgetDiv.DIV.style.top=o+"px",t.WidgetDiv.DIV.style.height=i+"px"},t.WidgetDiv.positionWithAnchor=function(e,o,i,n){var s=t.WidgetDiv.calculateY_(e,o,i);e=t.WidgetDiv.calculateX_(e,o,i,n),0>s?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;o<e.length;o++){var i=e[o];if(i){var n=i.type;null==n||""===n?console.warn("Block definition #"+o+" in JSON array is missing a type attribute. Skipping."):(t.Blocks[n]&&console.warn("Block definition #"+o+' in JSON array overwrites prior definition of "'+n+'".'),t.Blocks[n]={init:t.jsonInitFactory_(i)})}else console.warn("Block definition #"+o+" in JSON array is "+i+". Skipping.")}},t.bindEventWithChecks_=function(e,o,i,n,s,r){var a=!1,l=function(e){var o=!s;e=t.Touch.splitEventByTouches(e);for(var r,l=0;r=e[l];l++)o&&!t.Touch.shouldHandleEvent(r)||(t.Touch.setClientFromTouch(r),i?n.call(i,r):n(r),a=!0)},c=[];if(t.utils.global.PointerEvent&&o in t.Touch.TOUCH_MAP)for(var h,u=0;h=t.Touch.TOUCH_MAP[o][u];u++)e.addEventListener(h,l,!1),c.push([e,h,l]);else if(e.addEventListener(o,l,!1),c.push([e,o,l]),o in t.Touch.TOUCH_MAP){var p=function(t){l(t),a&&!r&&t.preventDefault()};for(u=0;h=t.Touch.TOUCH_MAP[o][u];u++)e.addEventListener(h,p,!1),c.push([e,h,p])}return c},t.bindEvent_=function(e,o,i,n){var s=function(t){i?n.call(i,t):n(t)},r=[];if(t.utils.global.PointerEvent&&o in t.Touch.TOUCH_MAP)for(var a,l=0;a=t.Touch.TOUCH_MAP[o][l];l++)e.addEventListener(a,s,!1),r.push([e,a,s]);else if(e.addEventListener(o,s,!1),r.push([e,o,s]),o in t.Touch.TOUCH_MAP){var c=function(t){if(t.changedTouches&&1==t.changedTouches.length){var e=t.changedTouches[0];t.clientX=e.clientX,t.clientY=e.clientY}s(t),t.preventDefault()};for(l=0;a=t.Touch.TOUCH_MAP[o][l];l++)e.addEventListener(a,c,!1),r.push([e,a,c])}return r},t.unbindEvent_=function(t){for(;t.length;){var e=t.pop(),o=e[2];e[0].removeEventListener(e[1],o,!1)}return o},t.isNumber=function(t){return/^\s*-?\d+(\.\d+)?\s*$/.test(t)},t.hueToHex=function(e){return t.utils.colour.hsvToHex(e,t.HSV_SATURATION,255*t.HSV_VALUE)},t.checkBlockColourConstants=function(){t.checkBlockColourConstant_("LOGIC_HUE",["Blocks","logic","HUE"],void 0),t.checkBlockColourConstant_("LOGIC_HUE",["Constants","Logic","HUE"],210),t.checkBlockColourConstant_("LOOPS_HUE",["Blocks","loops","HUE"],void 0),t.checkBlockColourConstant_("LOOPS_HUE",["Constants","Loops","HUE"],120),t.checkBlockColourConstant_("MATH_HUE",["Blocks","math","HUE"],void 0),t.checkBlockColourConstant_("MATH_HUE",["Constants","Math","HUE"],230),t.checkBlockColourConstant_("TEXTS_HUE",["Blocks","texts","HUE"],void 0),t.checkBlockColourConstant_("TEXTS_HUE",["Constants","Text","HUE"],160),t.checkBlockColourConstant_("LISTS_HUE",["Blocks","lists","HUE"],void 0),t.checkBlockColourConstant_("LISTS_HUE",["Constants","Lists","HUE"],260),t.checkBlockColourConstant_("COLOUR_HUE",["Blocks","colour","HUE"],void 0),t.checkBlockColourConstant_("COLOUR_HUE",["Constants","Colour","HUE"],20),t.checkBlockColourConstant_("VARIABLES_HUE",["Blocks","variables","HUE"],void 0),t.checkBlockColourConstant_("VARIABLES_HUE",["Constants","Variables","HUE"],330),t.checkBlockColourConstant_("VARIABLES_DYNAMIC_HUE",["Constants","VariablesDynamic","HUE"],310),t.checkBlockColourConstant_("PROCEDURES_HUE",["Blocks","procedures","HUE"],void 0)},t.checkBlockColourConstant_=function(e,o,i){for(var n="Blockly",s=t,r=0;r<o.length;++r)n+="."+o[r],s&&(s=s[o[r]]);s&&s!==i&&(e=(void 0===i?'%1 has been removed. Use Blockly.Msg["%2"].':'%1 is deprecated and unused. Override Blockly.Msg["%2"].').replace("%1",n).replace("%2",e),console.warn(e))},t.setParentContainer=function(e){t.parentContainer=e},t.Icon=function(t){this.block_=t},t.Icon.prototype.collapseHidden=!0,t.Icon.prototype.SIZE=17,t.Icon.prototype.bubble_=null,t.Icon.prototype.iconXY_=null,t.Icon.prototype.createIcon=function(){this.iconGroup_||(this.iconGroup_=t.utils.dom.createSvgElement("g",{class:"blocklyIconGroup"},null),this.block_.isInFlyout&&t.utils.dom.addClass(this.iconGroup_,"blocklyIconGroupReadonly"),this.drawIcon_(this.iconGroup_),this.block_.getSvgRoot().appendChild(this.iconGroup_),t.bindEventWithChecks_(this.iconGroup_,"mouseup",this,this.iconClick_),this.updateEditable())},t.Icon.prototype.dispose=function(){t.utils.dom.removeNode(this.iconGroup_),this.iconGroup_=null,this.setVisible(!1),this.block_=null},t.Icon.prototype.updateEditable=function(){},t.Icon.prototype.isVisible=function(){return!!this.bubble_},t.Icon.prototype.iconClick_=function(e){this.block_.workspace.isDragging()||this.block_.isInFlyout||t.utils.isRightButton(e)||this.setVisible(!this.isVisible())},t.Icon.prototype.applyColour=function(){this.isVisible()&&this.bubble_.setColour(this.block_.style.colourPrimary)},t.Icon.prototype.setIconLocation=function(t){this.iconXY_=t,this.isVisible()&&this.bubble_.setAnchorLocation(t)},t.Icon.prototype.computeIconLocation=function(){var e=this.block_.getRelativeToSurfaceXY(),o=t.utils.getRelativeXY(this.iconGroup_);e=new t.utils.Coordinate(e.x+o.x+this.SIZE/2,e.y+o.y+this.SIZE/2),t.utils.Coordinate.equals(this.getIconLocation(),e)||this.setIconLocation(e)},t.Icon.prototype.getIconLocation=function(){return this.iconXY_},t.Icon.prototype.getCorrectedSize=function(){return new t.utils.Size(t.Icon.prototype.SIZE,t.Icon.prototype.SIZE-2)},t.Warning=function(e){t.Warning.superClass_.constructor.call(this,e),this.createIcon(),this.text_={}},t.utils.object.inherits(t.Warning,t.Icon),t.Warning.prototype.collapseHidden=!1,t.Warning.prototype.drawIcon_=function(e){t.utils.dom.createSvgElement("path",{class:"blocklyIconShape",d:"M2,15Q-1,15 0.5,12L6.5,1.7Q8,-1 9.5,1.7L15.5,12Q17,15 14,15z"},e),t.utils.dom.createSvgElement("path",{class:"blocklyIconSymbol",d:"m7,4.8v3.16l0.27,2.27h1.46l0.27,-2.27v-3.16z"},e),t.utils.dom.createSvgElement("rect",{class:"blocklyIconSymbol",x:"7",y:"11",height:"2",width:"2"},e)},t.Warning.textToDom_=function(e){var o=t.utils.dom.createSvgElement("text",{class:"blocklyText blocklyBubbleText blocklyNoPointerEvents",y:t.Bubble.BORDER_WIDTH},null);e=e.split("\n");for(var i=0;i<e.length;i++){var n=t.utils.dom.createSvgElement("tspan",{dy:"1em",x:t.Bubble.BORDER_WIDTH},o),s=document.createTextNode(e[i]);n.appendChild(s)}return o},t.Warning.prototype.setVisible=function(e){e!=this.isVisible()&&(t.Events.fire(new t.Events.Ui(this.block_,"warningOpen",!e,e)),e?this.createBubble():this.disposeBubble())},t.Warning.prototype.createBubble=function(){if(this.paragraphElement_=t.Warning.textToDom_(this.getText()),this.bubble_=new t.Bubble(this.block_.workspace,this.paragraphElement_,this.block_.pathObject.svgPath,this.iconXY_,null,null),this.bubble_.setSvgId(this.block_.id),this.block_.RTL)for(var e,o=this.paragraphElement_.getBBox().width,i=0;e=this.paragraphElement_.childNodes[i];i++)e.setAttribute("text-anchor","end"),e.setAttribute("x",o+t.Bubble.BORDER_WIDTH);this.applyColour()},t.Warning.prototype.disposeBubble=function(){this.bubble_.dispose(),this.paragraphElement_=this.body_=this.bubble_=null},t.Warning.prototype.bodyFocus_=function(t){this.bubble_.promote()},t.Warning.prototype.setText=function(t,e){this.text_[e]!=t&&(t?this.text_[e]=t:delete this.text_[e],this.isVisible()&&(this.setVisible(!1),this.setVisible(!0)))},t.Warning.prototype.getText=function(){var t,e=[];for(t in this.text_)e.push(this.text_[t]);return e.join("\n")},t.Warning.prototype.dispose=function(){this.block_.warning=null,t.Icon.prototype.dispose.call(this)},t.Comment=function(e){t.Comment.superClass_.constructor.call(this,e),this.model_=e.commentModel,this.model_.text=this.model_.text||"",this.cachedText_="",this.onInputWrapper_=this.onChangeWrapper_=this.onWheelWrapper_=this.onMouseUpWrapper_=null,this.createIcon()},t.utils.object.inherits(t.Comment,t.Icon),t.Comment.prototype.drawIcon_=function(e){t.utils.dom.createSvgElement("circle",{class:"blocklyIconShape",r:"8",cx:"8",cy:"8"},e),t.utils.dom.createSvgElement("path",{class:"blocklyIconSymbol",d:"m6.8,10h2c0.003,-0.617 0.271,-0.962 0.633,-1.266 2.875,-2.4050.607,-5.534 -3.765,-3.874v1.7c3.12,-1.657 3.698,0.118 2.336,1.25-1.201,0.998 -1.201,1.528 -1.204,2.19z"},e),t.utils.dom.createSvgElement("rect",{class:"blocklyIconSymbol",x:"6.8",y:"10.78",height:"2",width:"2"},e)},t.Comment.prototype.createEditor_=function(){this.foreignObject_=t.utils.dom.createSvgElement("foreignObject",{x:t.Bubble.BORDER_WIDTH,y:t.Bubble.BORDER_WIDTH},null);var e=document.createElementNS(t.utils.dom.HTML_NS,"body");e.setAttribute("xmlns",t.utils.dom.HTML_NS),e.className="blocklyMinimalBody";var o=this.textarea_=document.createElementNS(t.utils.dom.HTML_NS,"textarea");return o.className="blocklyCommentTextarea",o.setAttribute("dir",this.block_.RTL?"RTL":"LTR"),o.value=this.model_.text,this.resizeTextarea_(),e.appendChild(o),this.foreignObject_.appendChild(e),this.onMouseUpWrapper_=t.bindEventWithChecks_(o,"mouseup",this,this.startEdit_,!0,!0),this.onWheelWrapper_=t.bindEventWithChecks_(o,"wheel",this,(function(t){t.stopPropagation()})),this.onChangeWrapper_=t.bindEventWithChecks_(o,"change",this,(function(e){this.cachedText_!=this.model_.text&&t.Events.fire(new t.Events.BlockChange(this.block_,"comment",null,this.cachedText_,this.model_.text))})),this.onInputWrapper_=t.bindEventWithChecks_(o,"input",this,(function(t){this.model_.text=o.value})),setTimeout(o.focus.bind(o),0),this.foreignObject_},t.Comment.prototype.updateEditable=function(){t.Comment.superClass_.updateEditable.call(this),this.isVisible()&&(this.disposeBubble_(),this.createBubble_())},t.Comment.prototype.onBubbleResize_=function(){this.isVisible()&&(this.model_.size=this.bubble_.getBubbleSize(),this.resizeTextarea_())},t.Comment.prototype.resizeTextarea_=function(){var e=this.model_.size,o=2*t.Bubble.BORDER_WIDTH,i=e.width-o;e=e.height-o,this.foreignObject_.setAttribute("width",i),this.foreignObject_.setAttribute("height",e),this.textarea_.style.width=i-4+"px",this.textarea_.style.height=e-4+"px"},t.Comment.prototype.setVisible=function(e){e!=this.isVisible()&&(t.Events.fire(new t.Events.Ui(this.block_,"commentOpen",!e,e)),(this.model_.pinned=e)?this.createBubble_():this.disposeBubble_())},t.Comment.prototype.createBubble_=function(){!this.block_.isEditable()||t.utils.userAgent.IE?this.createNonEditableBubble_():this.createEditableBubble_()},t.Comment.prototype.createEditableBubble_=function(){this.bubble_=new t.Bubble(this.block_.workspace,this.createEditor_(),this.block_.pathObject.svgPath,this.iconXY_,this.model_.size.width,this.model_.size.height),this.bubble_.setSvgId(this.block_.id),this.bubble_.registerResizeEvent(this.onBubbleResize_.bind(this)),this.applyColour()},t.Comment.prototype.createNonEditableBubble_=function(){t.Warning.prototype.createBubble.call(this)},t.Comment.prototype.disposeBubble_=function(){this.paragraphElement_?t.Warning.prototype.disposeBubble.call(this):(this.onMouseUpWrapper_&&(t.unbindEvent_(this.onMouseUpWrapper_),this.onMouseUpWrapper_=null),this.onWheelWrapper_&&(t.unbindEvent_(this.onWheelWrapper_),this.onWheelWrapper_=null),this.onChangeWrapper_&&(t.unbindEvent_(this.onChangeWrapper_),this.onChangeWrapper_=null),this.onInputWrapper_&&(t.unbindEvent_(this.onInputWrapper_),this.onInputWrapper_=null),this.bubble_.dispose(),this.foreignObject_=this.textarea_=this.bubble_=null)},t.Comment.prototype.startEdit_=function(t){this.bubble_.promote()&&this.textarea_.focus(),this.cachedText_=this.model_.text},t.Comment.prototype.getBubbleSize=function(){return this.model_.size},t.Comment.prototype.setBubbleSize=function(t,e){this.bubble_?this.bubble_.setBubbleSize(t,e):(this.model_.size.width=t,this.model_.size.height=e)},t.Comment.prototype.getText=function(){return this.model_.text||""},t.Comment.prototype.setText=function(t){this.model_.text!=t&&(this.model_.text=t,this.updateText())},t.Comment.prototype.updateText=function(){this.textarea_?this.textarea_.value=this.model_.text:this.paragraphElement_&&(this.paragraphElement_.firstChild.textContent=this.model_.text)},t.Comment.prototype.dispose=function(){this.block_.comment=null,t.Icon.prototype.dispose.call(this)},t.Css.register(".blocklyCommentTextarea {,background-color: #fef49c;,border: 0;,outline: 0;,margin: 0;,padding: 3px;,resize: none;,display: block;,overflow: hidden;,}".split(",")),t.FlyoutCursor=function(){t.FlyoutCursor.superClass_.constructor.call(this)},t.utils.object.inherits(t.FlyoutCursor,t.Cursor),t.FlyoutCursor.prototype.onBlocklyAction=function(e){switch(e.name){case t.navigation.actionNames.PREVIOUS:return this.prev(),!0;case t.navigation.actionNames.NEXT:return this.next(),!0;default:return!1}},t.FlyoutCursor.prototype.next=function(){var t=this.getCurNode();return t?((t=t.next())&&this.setCurNode(t),t):null},t.FlyoutCursor.prototype.in=function(){return null},t.FlyoutCursor.prototype.prev=function(){var t=this.getCurNode();return t?((t=t.prev())&&this.setCurNode(t),t):null},t.FlyoutCursor.prototype.out=function(){return null},t.Flyout=function(e){e.getMetrics=this.getMetrics_.bind(this),e.setMetrics=this.setMetrics_.bind(this),this.workspace_=new t.WorkspaceSvg(e),this.workspace_.isFlyout=!0,this.workspace_.setVisible(this.isVisible_),this.RTL=!!e.RTL,this.toolboxPosition_=e.toolboxPosition,this.eventWrappers_=[],this.mats_=[],this.buttons_=[],this.listeners_=[],this.permanentlyDisabled_=[],this.tabWidth_=this.workspace_.getRenderer().getConstants().TAB_WIDTH},t.Flyout.prototype.autoClose=!0,t.Flyout.prototype.isVisible_=!1,t.Flyout.prototype.containerVisible_=!0,t.Flyout.prototype.CORNER_RADIUS=8,t.Flyout.prototype.MARGIN=t.Flyout.prototype.CORNER_RADIUS,t.Flyout.prototype.GAP_X=3*t.Flyout.prototype.MARGIN,t.Flyout.prototype.GAP_Y=3*t.Flyout.prototype.MARGIN,t.Flyout.prototype.SCROLLBAR_PADDING=2,t.Flyout.prototype.width_=0,t.Flyout.prototype.height_=0,t.Flyout.prototype.dragAngleRange_=70,t.Flyout.prototype.createDom=function(e){return this.svgGroup_=t.utils.dom.createSvgElement(e,{class:"blocklyFlyout",style:"display: none"},null),this.svgBackground_=t.utils.dom.createSvgElement("path",{class:"blocklyFlyoutBackground"},this.svgGroup_),this.svgGroup_.appendChild(this.workspace_.createDom()),this.workspace_.getThemeManager().subscribe(this.svgBackground_,"flyoutBackgroundColour","fill"),this.workspace_.getThemeManager().subscribe(this.svgBackground_,"flyoutOpacity","fill-opacity"),this.workspace_.getMarkerManager().setCursor(new t.FlyoutCursor),this.svgGroup_},t.Flyout.prototype.init=function(e){this.targetWorkspace_=e,this.workspace_.targetWorkspace=e,this.scrollbar_=new t.Scrollbar(this.workspace_,this.horizontalLayout_,!1,"blocklyFlyoutScrollbar"),this.hide(),Array.prototype.push.apply(this.eventWrappers_,t.bindEventWithChecks_(this.svgGroup_,"wheel",this,this.wheel_)),this.autoClose||(this.filterWrapper_=this.filterForCapacity_.bind(this),this.targetWorkspace_.addChangeListener(this.filterWrapper_)),Array.prototype.push.apply(this.eventWrappers_,t.bindEventWithChecks_(this.svgBackground_,"mousedown",this,this.onMouseDown_)),this.workspace_.getGesture=this.targetWorkspace_.getGesture.bind(this.targetWorkspace_),this.workspace_.setVariableMap(this.targetWorkspace_.getVariableMap()),this.workspace_.createPotentialVariableMap()},t.Flyout.prototype.dispose=function(){this.hide(),t.unbindEvent_(this.eventWrappers_),this.filterWrapper_&&(this.targetWorkspace_.removeChangeListener(this.filterWrapper_),this.filterWrapper_=null),this.scrollbar_&&(this.scrollbar_.dispose(),this.scrollbar_=null),this.workspace_&&(this.workspace_.getThemeManager().unsubscribe(this.svgBackground_),this.workspace_.targetWorkspace=null,this.workspace_.dispose(),this.workspace_=null),this.svgGroup_&&(t.utils.dom.removeNode(this.svgGroup_),this.svgGroup_=null),this.targetWorkspace_=this.svgBackground_=null},t.Flyout.prototype.getWidth=function(){return this.width_},t.Flyout.prototype.getHeight=function(){return this.height_},t.Flyout.prototype.getWorkspace=function(){return this.workspace_},t.Flyout.prototype.isVisible=function(){return this.isVisible_},t.Flyout.prototype.setVisible=function(t){var e=t!=this.isVisible();this.isVisible_=t,e&&this.updateDisplay_()},t.Flyout.prototype.setContainerVisible=function(t){var e=t!=this.containerVisible_;this.containerVisible_=t,e&&this.updateDisplay_()},t.Flyout.prototype.updateDisplay_=function(){var t=!!this.containerVisible_&&this.isVisible();this.svgGroup_.style.display=t?"block":"none",this.scrollbar_.setContainerVisible(t)},t.Flyout.prototype.positionAt_=function(e,o,i,n){this.svgGroup_.setAttribute("width",e),this.svgGroup_.setAttribute("height",o),"svg"==this.svgGroup_.tagName?t.utils.dom.setCssTransform(this.svgGroup_,"translate("+i+"px,"+n+"px)"):this.svgGroup_.setAttribute("transform","translate("+i+","+n+")"),this.scrollbar_&&(this.scrollbar_.setOrigin(i,n),this.scrollbar_.resize(),this.scrollbar_.setPosition_(this.scrollbar_.position_.x,this.scrollbar_.position_.y))},t.Flyout.prototype.hide=function(){if(this.isVisible()){this.setVisible(!1);for(var e,o=0;e=this.listeners_[o];o++)t.unbindEvent_(e);this.listeners_.length=0,this.reflowWrapper_&&(this.workspace_.removeChangeListener(this.reflowWrapper_),this.reflowWrapper_=null)}},t.Flyout.prototype.show=function(e){if(this.workspace_.setResizesEnabled(!1),this.hide(),this.clearOldBlocks_(),"string"==typeof e){if("function"!=typeof(e=this.workspace_.targetWorkspace.getToolboxCategoryCallback(e)))throw TypeError("Couldn't find a callback function when opening a toolbox category.");if(e=e(this.workspace_.targetWorkspace),!Array.isArray(e))throw TypeError("Result of toolbox category callback must be an array.")}this.setVisible(!0);var o=[],i=[];this.permanentlyDisabled_.length=0;for(var n,s=this.horizontalLayout_?this.GAP_X:this.GAP_Y,r=0;n=e[r];r++)if(n.tagName)switch(n.tagName.toUpperCase()){case"BLOCK":var a=t.Xml.domToBlock(n,this.workspace_);a.isEnabled()||this.permanentlyDisabled_.push(a),o.push({type:"block",block:a}),n=parseInt(n.getAttribute("gap"),10),i.push(isNaN(n)?s:n);break;case"SEP":n=parseInt(n.getAttribute("gap"),10),!isNaN(n)&&0<i.length?i[i.length-1]=n:i.push(s);break;case"LABEL":case"BUTTON":if(a="LABEL"==n.tagName.toUpperCase(),!t.FlyoutButton)throw Error("Missing require for Blockly.FlyoutButton");n=new t.FlyoutButton(this.workspace_,this.targetWorkspace_,n,a),o.push({type:"button",button:n}),i.push(s)}this.layout_(o,i),this.listeners_.push(t.bindEventWithChecks_(this.svgBackground_,"mouseover",this,(function(){for(var t,e=this.workspace_.getTopBlocks(!1),o=0;t=e[o];o++)t.removeSelect()}))),this.horizontalLayout_?this.height_=0:this.width_=0,this.workspace_.setResizesEnabled(!0),this.reflow(),this.filterForCapacity_(),this.position(),this.reflowWrapper_=this.reflow.bind(this),this.workspace_.addChangeListener(this.reflowWrapper_)},t.Flyout.prototype.clearOldBlocks_=function(){for(var e,o=this.workspace_.getTopBlocks(!1),i=0;e=o[i];i++)e.workspace==this.workspace_&&e.dispose(!1,!1);for(i=0;i<this.mats_.length;i++)(o=this.mats_[i])&&(t.Tooltip.unbindMouseEvents(o),t.utils.dom.removeNode(o));for(i=this.mats_.length=0;o=this.buttons_[i];i++)o.dispose();this.buttons_.length=0,this.workspace_.getPotentialVariableMap().clear()},t.Flyout.prototype.addBlockListeners_=function(e,o,i){this.listeners_.push(t.bindEventWithChecks_(e,"mousedown",null,this.blockMouseDown_(o))),this.listeners_.push(t.bindEventWithChecks_(i,"mousedown",null,this.blockMouseDown_(o))),this.listeners_.push(t.bindEvent_(e,"mouseenter",o,o.addSelect)),this.listeners_.push(t.bindEvent_(e,"mouseleave",o,o.removeSelect)),this.listeners_.push(t.bindEvent_(i,"mouseenter",o,o.addSelect)),this.listeners_.push(t.bindEvent_(i,"mouseleave",o,o.removeSelect))},t.Flyout.prototype.blockMouseDown_=function(t){var e=this;return function(o){var i=e.targetWorkspace_.getGesture(o);i&&(i.setStartBlock(t),i.handleFlyoutStart(o,e))}},t.Flyout.prototype.onMouseDown_=function(t){var e=this.targetWorkspace_.getGesture(t);e&&e.handleFlyoutStart(t,this)},t.Flyout.prototype.isBlockCreatable_=function(t){return t.isEnabled()},t.Flyout.prototype.createBlock=function(e){var o=null;t.Events.disable();var i=this.targetWorkspace_.getAllVariables();this.targetWorkspace_.setResizesEnabled(!1);try{o=this.placeNewBlock_(e),t.hideChaff()}finally{t.Events.enable()}if(e=t.Variables.getAddedVariables(this.targetWorkspace_,i),t.Events.isEnabled())for(t.Events.setGroup(!0),t.Events.fire(new t.Events.Create(o)),i=0;i<e.length;i++)t.Events.fire(new t.Events.VarCreate(e[i]));return this.autoClose?this.hide():this.filterForCapacity_(),o},t.Flyout.prototype.initFlyoutButton_=function(e,o,i){var n=e.createDom();e.moveTo(o,i),e.show(),this.listeners_.push(t.bindEventWithChecks_(n,"mousedown",this,this.onMouseDown_)),this.buttons_.push(e)},t.Flyout.prototype.createRect_=function(e,o,i,n,s){return(o=t.utils.dom.createSvgElement("rect",{"fill-opacity":0,x:o,y:i,height:n.height,width:n.width},null)).tooltip=e,t.Tooltip.bindMouseEvents(o),this.workspace_.getCanvas().insertBefore(o,e.getSvgRoot()),e.flyoutRect_=o,this.mats_[s]=o},t.Flyout.prototype.moveRectToBlock_=function(t,e){var o=e.getHeightWidth();t.setAttribute("width",o.width),t.setAttribute("height",o.height),e=e.getRelativeToSurfaceXY(),t.setAttribute("y",e.y),t.setAttribute("x",this.RTL?e.x-o.width:e.x)},t.Flyout.prototype.filterForCapacity_=function(){for(var e,o=this.workspace_.getTopBlocks(!1),i=0;e=o[i];i++)if(-1==this.permanentlyDisabled_.indexOf(e))for(var n=this.targetWorkspace_.isCapacityAvailable(t.utils.getBlockTypeCounts(e));e;)e.setEnabled(n),e=e.getNextBlock()},t.Flyout.prototype.reflow=function(){this.reflowWrapper_&&this.workspace_.removeChangeListener(this.reflowWrapper_),this.reflowInternal_(),this.reflowWrapper_&&this.workspace_.addChangeListener(this.reflowWrapper_)},t.Flyout.prototype.isScrollable=function(){return!!this.scrollbar_&&this.scrollbar_.isVisible()},t.Flyout.prototype.placeNewBlock_=function(e){var o=this.targetWorkspace_;if(!e.getSvgRoot())throw Error("oldBlock is not rendered.");var i=t.Xml.blockToDom(e,!0);if(o.setResizesEnabled(!1),!(i=t.Xml.domToBlock(i,o)).getSvgRoot())throw Error("block is not rendered.");var n=o.getOriginOffsetInPixels(),s=this.workspace_.getOriginOffsetInPixels();return(e=e.getRelativeToSurfaceXY()).scale(this.workspace_.scale),e=t.utils.Coordinate.sum(s,e),(n=t.utils.Coordinate.difference(e,n)).scale(1/o.scale),i.moveBy(n.x,n.y),i},t.Flyout.prototype.onBlocklyAction=function(t){return this.workspace_.getCursor().onBlocklyAction(t)},t.HorizontalFlyout=function(e){e.getMetrics=this.getMetrics_.bind(this),e.setMetrics=this.setMetrics_.bind(this),t.HorizontalFlyout.superClass_.constructor.call(this,e),this.horizontalLayout_=!0},t.utils.object.inherits(t.HorizontalFlyout,t.Flyout),t.HorizontalFlyout.prototype.getMetrics_=function(){if(!this.isVisible())return null;try{var e=this.workspace_.getCanvas().getBBox()}catch(t){e={height:0,y:0,width:0,x:0}}var o=this.SCROLLBAR_PADDING,i=this.SCROLLBAR_PADDING;this.toolboxPosition_==t.TOOLBOX_AT_BOTTOM&&(o=0);var n=this.height_;return this.toolboxPosition_==t.TOOLBOX_AT_TOP&&(n-=this.SCROLLBAR_PADDING),{viewHeight:n,viewWidth:this.width_-2*this.SCROLLBAR_PADDING,contentHeight:(e.height+2*this.MARGIN)*this.workspace_.scale,contentWidth:(e.width+2*this.MARGIN)*this.workspace_.scale,viewTop:-this.workspace_.scrollY,viewLeft:-this.workspace_.scrollX,contentTop:0,contentLeft:0,absoluteTop:o,absoluteLeft:i}},t.HorizontalFlyout.prototype.setMetrics_=function(t){var e=this.getMetrics_();e&&("number"==typeof t.x&&(this.workspace_.scrollX=-e.contentWidth*t.x),this.workspace_.translate(this.workspace_.scrollX+e.absoluteLeft,this.workspace_.scrollY+e.absoluteTop))},t.HorizontalFlyout.prototype.position=function(){if(this.isVisible()){var e=this.targetWorkspace_.getMetrics();e&&(this.width_=e.viewWidth,this.setBackgroundPath_(e.viewWidth-2*this.CORNER_RADIUS,this.height_-this.CORNER_RADIUS),this.positionAt_(this.width_,this.height_,0,this.targetWorkspace_.toolboxPosition==this.toolboxPosition_?e.toolboxHeight?this.toolboxPosition_==t.TOOLBOX_AT_TOP?e.toolboxHeight:e.viewHeight-this.height_:this.toolboxPosition_==t.TOOLBOX_AT_TOP?0:e.viewHeight:this.toolboxPosition_==t.TOOLBOX_AT_TOP?0:e.viewHeight+e.absoluteTop-this.height_))}},t.HorizontalFlyout.prototype.setBackgroundPath_=function(e,o){var i=this.toolboxPosition_==t.TOOLBOX_AT_TOP,n=["M 0,"+(i?0:this.CORNER_RADIUS)];i?(n.push("h",e+2*this.CORNER_RADIUS),n.push("v",o),n.push("a",this.CORNER_RADIUS,this.CORNER_RADIUS,0,0,1,-this.CORNER_RADIUS,this.CORNER_RADIUS),n.push("h",-e),n.push("a",this.CORNER_RADIUS,this.CORNER_RADIUS,0,0,1,-this.CORNER_RADIUS,-this.CORNER_RADIUS)):(n.push("a",this.CORNER_RADIUS,this.CORNER_RADIUS,0,0,1,this.CORNER_RADIUS,-this.CORNER_RADIUS),n.push("h",e),n.push("a",this.CORNER_RADIUS,this.CORNER_RADIUS,0,0,1,this.CORNER_RADIUS,this.CORNER_RADIUS),n.push("v",o),n.push("h",-e-2*this.CORNER_RADIUS)),n.push("z"),this.svgBackground_.setAttribute("d",n.join(" "))},t.HorizontalFlyout.prototype.scrollToStart=function(){this.scrollbar_.set(this.RTL?1/0:0)},t.HorizontalFlyout.prototype.wheel_=function(e){var o=t.utils.getScrollDeltaPixels(e),i=o.x||o.y;i&&(i=(o=this.getMetrics_()).viewLeft+i,i=Math.min(i,o.contentWidth-o.viewWidth),i=Math.max(i,0),this.scrollbar_.set(i),t.WidgetDiv.hide()),e.preventDefault(),e.stopPropagation()},t.HorizontalFlyout.prototype.layout_=function(t,e){this.workspace_.scale=this.targetWorkspace_.scale;var o=this.MARGIN,i=o+this.tabWidth_;this.RTL&&(t=t.reverse());for(var n,s=0;n=t[s];s++)if("block"==n.type){for(var r,a=(n=n.block).getDescendants(!1),l=0;r=a[l];l++)r.isInFlyout=!0;n.render(),a=n.getSvgRoot(),l=n.getHeightWidth(),r=n.outputConnection?this.tabWidth_:0,r=this.RTL?i+l.width:i-r,n.moveBy(r,o),r=this.createRect_(n,r,o,l,s),i+=l.width+e[s],this.addBlockListeners_(a,n,r)}else"button"==n.type&&(this.initFlyoutButton_(n.button,i,o),i+=n.button.width+e[s])},t.HorizontalFlyout.prototype.isDragTowardWorkspace=function(t){t=Math.atan2(t.y,t.x)/Math.PI*180;var e=this.dragAngleRange_;return t<90+e&&t>90-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>-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;o<t.length;o++){var i=t[o].getCommentText();i&&e.push(i)}return e.length&&e.push(""),e.join("\n")},t.Generator.prototype.blockToCode=function(t,e){if(!t)return"";if(!t.isEnabled())return e?"":this.blockToCode(t.getNextBlock());var o=this[t.type];if("function"!=typeof o)throw Error('Language "'+this.name_+'" does not know how to generate  code for block type "'+t.type+'".');if(o=o.call(t,t),Array.isArray(o)){if(!t.outputConnection)throw TypeError("Expecting string from statement block: "+t.type);return[this.scrub_(t,o[0],e),o[1]]}if("string"==typeof o)return this.STATEMENT_PREFIX&&!t.suppressPrefixSuffix&&(o=this.injectId(this.STATEMENT_PREFIX,t)+o),this.STATEMENT_SUFFIX&&!t.suppressPrefixSuffix&&(o+=this.injectId(this.STATEMENT_SUFFIX,t)),this.scrub_(t,o,e);if(null===o)return"";throw SyntaxError("Invalid code generated: "+o)},t.Generator.prototype.valueToCode=function(t,e,o){if(isNaN(o))throw TypeError("Expecting valid order from block: "+t.type);var i=t.getInputTargetBlock(e);if(!i)return"";if(""===(e=this.blockToCode(i)))return"";if(!Array.isArray(e))throw TypeError("Expecting tuple from value block: "+i.type);if(t=e[0],e=e[1],isNaN(e))throw TypeError("Expecting valid order from value block: "+i.type);if(!t)return"";i=!1;var n=Math.floor(o),s=Math.floor(e);if(n<=s&&(n!=s||0!=n&&99!=n))for(i=!0,n=0;n<this.ORDER_OVERRIDES.length;n++)if(this.ORDER_OVERRIDES[n][0]==o&&this.ORDER_OVERRIDES[n][1]==e){i=!1;break}return i&&(t="("+t+")"),t},t.Generator.prototype.statementToCode=function(t,e){if(t=t.getInputTargetBlock(e),"string"!=typeof(e=this.blockToCode(t)))throw TypeError("Expecting code from statement block: "+(t&&t.type));return e&&(e=this.prefixLines(e,this.INDENT)),e},t.Generator.prototype.addLoopTrap=function(t,e){return this.INFINITE_LOOP_TRAP&&(t=this.prefixLines(this.injectId(this.INFINITE_LOOP_TRAP,e),this.INDENT)+t),this.STATEMENT_SUFFIX&&!e.suppressPrefixSuffix&&(t=this.prefixLines(this.injectId(this.STATEMENT_SUFFIX,e),this.INDENT)+t),this.STATEMENT_PREFIX&&!e.suppressPrefixSuffix&&(t+=this.prefixLines(this.injectId(this.STATEMENT_PREFIX,e),this.INDENT)),t},t.Generator.prototype.injectId=function(t,e){return e=e.id.replace(/\$/g,"$$$$"),t.replace(/%1/g,"'"+e+"'")},t.Generator.prototype.RESERVED_WORDS_="",t.Generator.prototype.addReservedWords=function(t){this.RESERVED_WORDS_+=t+","},t.Generator.prototype.FUNCTION_NAME_PLACEHOLDER_="{leCUI8hutHZI4480Dc}",t.Generator.prototype.provideFunction_=function(e,o){if(!this.definitions_[e]){var i,n=this.variableDB_.getDistinctName(e,t.PROCEDURE_CATEGORY_NAME);for(this.functionNames_[e]=n,o=o.join("\n").replace(this.FUNCTION_NAME_PLACEHOLDER_REGEXP_,n);i!=o;)i=o,o=o.replace(/^(( {2})*) {2}/gm,"$1\0");o=o.replace(/\0/g,this.INDENT),this.definitions_[e]=o}return this.functionNames_[e]},t.Generator.prototype.init=function(t){},t.Generator.prototype.scrub_=function(t,e,o){return e},t.Generator.prototype.finish=function(t){return t},t.Generator.prototype.scrubNakedValue=function(t){return t},t.tree={},t.tree.BaseNode=function(e,o){t.Component.call(this),this.content=e,this.config_=o,this.expanded_=this.selected_=!1,this.isUserCollapsible_=!0,this.depth_=-1},t.utils.object.inherits(t.tree.BaseNode,t.Component),t.tree.BaseNode.allNodes={},t.tree.BaseNode.prototype.disposeInternal=function(){t.tree.BaseNode.superClass_.disposeInternal.call(this),this.tree&&(this.tree=null),this.setElementInternal(null)},t.tree.BaseNode.prototype.initAccessibility=function(){var e=this.getElement();if(e){var o=this.getLabelElement();if(o&&!o.id&&(o.id=this.getId()+".label"),t.utils.aria.setRole(e,t.utils.aria.Role.TREEITEM),t.utils.aria.setState(e,t.utils.aria.State.SELECTED,!1),t.utils.aria.setState(e,t.utils.aria.State.LEVEL,this.getDepth()),o&&t.utils.aria.setState(e,t.utils.aria.State.LABELLEDBY,o.id),(o=this.getIconElement())&&t.utils.aria.setRole(o,t.utils.aria.Role.PRESENTATION),(o=this.getChildrenElement())&&(t.utils.aria.setRole(o,t.utils.aria.Role.GROUP),o.hasChildNodes()))for(t.utils.aria.setState(e,t.utils.aria.State.EXPANDED,!1),e=this.getChildCount(),o=1;o<=e;o++){var i=this.getChildAt(o-1).getElement();t.utils.aria.setState(i,t.utils.aria.State.SETSIZE,e),t.utils.aria.setState(i,t.utils.aria.State.POSINSET,o)}}},t.tree.BaseNode.prototype.createDom=function(){var t=document.createElement("div");t.appendChild(this.toDom()),this.setElementInternal(t)},t.tree.BaseNode.prototype.enterDocument=function(){t.tree.BaseNode.superClass_.enterDocument.call(this),t.tree.BaseNode.allNodes[this.getId()]=this,this.initAccessibility()},t.tree.BaseNode.prototype.exitDocument=function(){t.tree.BaseNode.superClass_.exitDocument.call(this),delete t.tree.BaseNode.allNodes[this.getId()]},t.tree.BaseNode.prototype.addChildAt=function(e,o){var i=this.getChildAt(o-1),n=this.getChildAt(o);if(t.tree.BaseNode.superClass_.addChildAt.call(this,e,o),e.previousSibling_=i,e.nextSibling_=n,i&&(i.nextSibling_=e),n&&(n.previousSibling_=e),(o=this.getTree())&&e.setTreeInternal(o),e.setDepth_(this.getDepth()+1),(o=this.getElement())&&(this.updateExpandIcon(),t.utils.aria.setState(o,t.utils.aria.State.EXPANDED,this.expanded_),this.expanded_)){o=this.getChildrenElement(),e.getElement()||e.createDom();var s=e.getElement(),r=n&&n.getElement();o.insertBefore(s,r),this.isInDocument()&&e.enterDocument(),n||(i?i.updateExpandIcon():(t.utils.style.setElementShown(o,!0),this.setExpanded(this.expanded_)))}},t.tree.BaseNode.prototype.add=function(e){if(e.getParent())throw Error(t.Component.Error.PARENT_UNABLE_TO_BE_SET);this.addChildAt(e,this.getChildCount())},t.tree.BaseNode.prototype.getTree=function(){return null},t.tree.BaseNode.prototype.getDepth=function(){var t=this.depth_;return 0>t&&(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("<<<PATH>>>/handdelete.cur"), auto;',"}",".blocklyToolboxGrab {",'cursor: url("<<<PATH>>>/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(<<<PATH>>>/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("<<<PATH>>>/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 0<this.workspace_.options.maxTrashcanContents&&(t.utils.dom.insertAfter(this.flyout.createDom("svg"),this.workspace_.getParentSvg()),this.flyout.init(this.workspace_)),this.verticalSpacing_=this.MARGIN_BOTTOM_+e,this.setOpen(!1),this.verticalSpacing_+this.BODY_HEIGHT_+this.LID_HEIGHT_},t.Trashcan.prototype.dispose=function(){this.svgGroup_&&(t.utils.dom.removeNode(this.svgGroup_),this.svgGroup_=null),this.workspace_=this.svgLid_=null,clearTimeout(this.lidTask_)},t.Trashcan.prototype.contentsIsOpen=function(){return this.flyout.isVisible()},t.Trashcan.prototype.emptyContents=function(){this.contents_.length&&(this.contents_.length=0,this.setMinOpenness_(0),this.contentsIsOpen()&&this.flyout.hide())},t.Trashcan.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,this.top_=e.toolboxPosition==t.TOOLBOX_AT_BOTTOM?this.verticalSpacing_:e.viewHeight+e.absoluteTop-(this.BODY_HEIGHT_+this.LID_HEIGHT_)-this.verticalSpacing_,this.svgGroup_.setAttribute("transform","translate("+this.left_+","+this.top_+")"))}},t.Trashcan.prototype.getClientRect=function(){if(!this.svgGroup_)return null;var e=this.svgGroup_.getBoundingClientRect(),o=e.top+this.SPRITE_TOP_-this.MARGIN_HOTSPOT_;return e=e.left+this.SPRITE_LEFT_-this.MARGIN_HOTSPOT_,new t.utils.Rect(o,o+this.LID_HEIGHT_+this.BODY_HEIGHT_+2*this.MARGIN_HOTSPOT_,e,e+this.WIDTH_+2*this.MARGIN_HOTSPOT_)},t.Trashcan.prototype.setOpen=function(t){this.isOpen!=t&&(clearTimeout(this.lidTask_),this.isOpen=t,this.animateLid_())},t.Trashcan.prototype.animateLid_=function(){var e=t.Trashcan.ANIMATION_FRAMES_,o=1/(e+1);this.lidOpen_+=this.isOpen?o:-o,this.lidOpen_=Math.min(Math.max(this.lidOpen_,this.minOpenness_),1),this.setLidAngle_(this.lidOpen_*t.Trashcan.MAX_LID_ANGLE_),o=t.Trashcan.OPACITY_MIN_,this.svgGroup_.style.opacity=o+this.lidOpen_*(t.Trashcan.OPACITY_MAX_-o),this.lidOpen_>this.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.length;o++){var i=e[o];i.setStyle(i.getStyleName())}for(t=t.getFlyout().workspace_.getAllBlocks(!1),o=0;o<t.length;o++)(i=t[o]).setStyle(i.getStyleName())}},t.Mutator.reconnect=function(t,e,o){if(!t||!t.getSourceBlock().workspace)return!1;o=e.getInput(o).connection;var i=t.targetBlock();return!(i&&i!=e||o.targetConnection==t||(o.isConnected()&&o.disconnect(),o.connect(t),0))},t.Mutator.findParentWs=function(t){var e=null;if(t&&t.options){var o=t.options.parentWorkspace;t.isFlyout?o&&o.options&&(e=o.options.parentWorkspace):o&&(e=o)}return e},t.FieldTextInput=function(e,o,i){this.spellcheck_=!0,null==e&&(e=""),t.FieldTextInput.superClass_.constructor.call(this,e,o,i),this.onKeyInputWrapper_=this.onKeyDownWrapper_=this.htmlInput_=null,this.fullBlockClickTarget_=!1},t.utils.object.inherits(t.FieldTextInput,t.Field),t.FieldTextInput.fromJson=function(e){var o=t.utils.replaceMessageReferences(e.text);return new t.FieldTextInput(o,void 0,e)},t.FieldTextInput.prototype.SERIALIZABLE=!0,t.FieldTextInput.BORDERRADIUS=4,t.FieldTextInput.prototype.CURSOR="text",t.FieldTextInput.prototype.configure_=function(e){t.FieldTextInput.superClass_.configure_.call(this,e),"boolean"==typeof e.spellcheck&&(this.spellcheck_=e.spellcheck)},t.FieldTextInput.prototype.initView=function(){if(this.getConstants().FULL_BLOCK_FIELDS){for(var t,e=0,o=0,i=0;t=this.sourceBlock_.inputList[i];i++){for(var n=0;t.fieldRow[n];n++)e++;t.connection&&o++}this.fullBlockClickTarget_=1>=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<e&&(o+=360),o=this.clockwise_?this.offset_+360-o:360-(this.offset_-o),this.displayMouseOrKeyboardValue_(o))},t.FieldAngle.prototype.displayMouseOrKeyboardValue_=function(t){this.round_&&(t=Math.round(t/this.round_)*this.round_),(t=this.wrapValue_(t))!=this.value_&&this.setEditorValue_(t)},t.FieldAngle.prototype.updateGraph_=function(){if(this.gauge_){var e=Number(this.getText())+this.offset_,o=t.utils.math.toRadians(e%360);e=["M ",t.FieldAngle.HALF,",",t.FieldAngle.HALF];var i=t.FieldAngle.HALF,n=t.FieldAngle.HALF;if(!isNaN(o)){var s=Number(this.clockwise_),r=t.utils.math.toRadians(this.offset_),a=Math.cos(r)*t.FieldAngle.RADIUS,l=Math.sin(r)*-t.FieldAngle.RADIUS;s&&(o=2*r-o),i+=Math.cos(o)*t.FieldAngle.RADIUS,n-=Math.sin(o)*t.FieldAngle.RADIUS,o=Math.abs(Math.floor((o-r)/Math.PI)%2),s&&(o=1-o),e.push(" l ",a,",",l," A ",t.FieldAngle.RADIUS,",",t.FieldAngle.RADIUS," 0 ",o," ",s," ",i,",",n," z")}this.gauge_.setAttribute("d",e.join("")),this.line_.setAttribute("x2",i),this.line_.setAttribute("y2",n)}},t.FieldAngle.prototype.onHtmlInputKeyDown_=function(e){var o;if(t.FieldAngle.superClass_.onHtmlInputKeyDown_.call(this,e),e.keyCode===t.utils.KeyCodes.LEFT?o=this.sourceBlock_.RTL?1:-1:e.keyCode===t.utils.KeyCodes.RIGHT?o=this.sourceBlock_.RTL?-1:1:e.keyCode===t.utils.KeyCodes.DOWN?o=-1:e.keyCode===t.utils.KeyCodes.UP&&(o=1),o){var i=this.getValue();this.displayMouseOrKeyboardValue_(i+o*this.round_),e.preventDefault(),e.stopPropagation()}},t.FieldAngle.prototype.doClassValidation_=function(t){return t=Number(t),isNaN(t)||!isFinite(t)?null:this.wrapValue_(t)},t.FieldAngle.prototype.wrapValue_=function(t){return 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&&0<r?(s=n-1,r--):0>s&&(s=0):0<e?s>n-1&&r<Math.floor(i.length/n)-1?(s=0,r++):s>n-1&&s--:0>o?0>r&&(r=0):0<o&&r>Math.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;a<o.length;a++){0==a%e&&(r=document.createElement("tr"),t.utils.aria.setRole(r,t.utils.aria.Role.ROW),s.appendChild(r));var l=document.createElement("td");r.appendChild(l),l.label=o[a],l.title=i[a]||o[a],l.id=t.utils.IdGenerator.getNextUniqueId(),l.setAttribute("data-index",a),t.utils.aria.setRole(l,t.utils.aria.Role.GRIDCELL),t.utils.aria.setState(l,t.utils.aria.State.LABEL,o[a]),t.utils.aria.setState(l,t.utils.aria.State.SELECTED,o[a]==n),l.style.backgroundColor=o[a],o[a]==n&&(l.className="blocklyColourSelected",this.highlightedIndex_=a)}return this.onClickWrapper_=t.bindEventWithChecks_(s,"click",this,this.onClick_,!0),this.onMouseMoveWrapper_=t.bindEventWithChecks_(s,"mousemove",this,this.onMouseMove_,!0),this.onMouseEnterWrapper_=t.bindEventWithChecks_(s,"mouseenter",this,this.onMouseEnter_,!0),this.onMouseLeaveWrapper_=t.bindEventWithChecks_(s,"mouseleave",this,this.onMouseLeave_,!0),this.onKeyDownWrapper_=t.bindEventWithChecks_(s,"keydown",this,this.onKeyDown_),s},t.FieldColour.prototype.dropdownDispose_=function(){this.onClickWrapper_&&(t.unbindEvent_(this.onClickWrapper_),this.onClickWrapper_=null),this.onMouseMoveWrapper_&&(t.unbindEvent_(this.onMouseMoveWrapper_),this.onMouseMoveWrapper_=null),this.onMouseEnterWrapper_&&(t.unbindEvent_(this.onMouseEnterWrapper_),this.onMouseEnterWrapper_=null),this.onMouseLeaveWrapper_&&(t.unbindEvent_(this.onMouseLeaveWrapper_),this.onMouseLeaveWrapper_=null),this.onKeyDownWrapper_&&(t.unbindEvent_(this.onKeyDownWrapper_),this.onKeyDownWrapper_=null),this.highlightedIndex_=this.picker_=null},t.Css.register([".blocklyColourTable {","border-collapse: collapse;","display: block;","outline: none;","padding: 1px;","}",".blocklyColourTable>tr>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;i<o.length;i++){var n=o[i][0],s=o[i][1];if("object"==typeof n){var r=new Image(n.width,n.height);r.src=n.src,r.alt=n.alt||"",n=r}(n=new t.MenuItem(n)).setRole(t.utils.aria.Role.OPTION),n.setRightToLeft(this.sourceBlock_.RTL),n.setValue(s),n.setCheckable(!0),e.addChild(n,!0),n.setChecked(s==this.value_),s==this.value_&&(this.selectedMenuItem_=n),n.onAction(this.handleMenuActionEvent_,this)}return t.utils.aria.setState(e.getElement(),t.utils.aria.State.ACTIVEDESCENDANT,this.selectedMenuItem_?this.selectedMenuItem_.getId():""),e},t.FieldDropdown.prototype.dropdownDispose_=function(){this.menu_&&this.menu_.dispose(),this.selectedMenuItem_=this.menu_=null,this.applyColour()},t.FieldDropdown.prototype.handleMenuActionEvent_=function(e){t.DropDownDiv.hideIfOwner(this,!0),this.onItemSelected_(this.menu_,e)},t.FieldDropdown.prototype.onItemSelected_=function(t,e){this.setValue(e.getValue())},t.FieldDropdown.prototype.trimOptions_=function(){this.suffixField=this.prefixField=null;var e=this.menuGenerator_;if(Array.isArray(e)){for(var o=!1,i=0;i<e.length;i++){var n=e[i][0];"string"==typeof n?e[i][0]=t.utils.replaceMessageReferences(n):(null!=n.alt&&(e[i][0].alt=t.utils.replaceMessageReferences(n.alt)),o=!0)}if(!(o||2>e.length)){for(o=[],i=0;i<e.length;i++)o.push(e[i][0]);i=t.utils.string.shortestStringLength(o),n=t.utils.string.commonWordPrefix(o,i);var s=t.utils.string.commonWordSuffix(o,i);!n&&!s||i<=n+s||(n&&(this.prefixField=o[0].substring(0,n-1)),s&&(this.suffixField=o[0].substr(1-s)),this.menuGenerator_=t.FieldDropdown.applyTrim_(e,n,s))}}},t.FieldDropdown.applyTrim_=function(t,e,o){for(var i=[],n=0;n<t.length;n++){var s=t[n][0],r=t[n][1];s=s.substring(e,s.length-o),i[n]=[s,r]}return i},t.FieldDropdown.prototype.isOptionListDynamic=function(){return"function"==typeof this.menuGenerator_},t.FieldDropdown.prototype.getOptions=function(e){return this.isOptionListDynamic()?(this.generatedOptions_&&e||(this.generatedOptions_=this.menuGenerator_.call(this),t.FieldDropdown.validateOptions_(this.generatedOptions_)),this.generatedOptions_):this.menuGenerator_},t.FieldDropdown.prototype.doClassValidation_=function(t){for(var e,o=!1,i=this.getOptions(!0),n=0;e=i[n];n++)if(e[1]==t){o=!0;break}return o?t:(this.sourceBlock_&&console.warn("Cannot set the dropdown's value to an unavailable option. Block type: "+this.sourceBlock_.type+", Field name: "+this.name+", Value: "+t),null)},t.FieldDropdown.prototype.doValueUpdate_=function(e){t.FieldDropdown.superClass_.doValueUpdate_.call(this,e),e=this.getOptions(!0);for(var o,i=0;o=e[i];i++)o[1]==this.value_&&(this.selectedOption_=o)},t.FieldDropdown.prototype.applyColour=function(){this.borderRect_&&(this.borderRect_.setAttribute("stroke",this.sourceBlock_.style.colourTertiary),this.menu_?this.borderRect_.setAttribute("fill",this.sourceBlock_.style.colourTertiary):this.borderRect_.setAttribute("fill","transparent")),this.sourceBlock_&&this.arrow_&&(this.sourceBlock_.isShadow()?this.arrow_.style.fill=this.sourceBlock_.style.colourSecondary:this.arrow_.style.fill=this.sourceBlock_.style.colourPrimary)},t.FieldDropdown.prototype.render_=function(){this.textContent_.nodeValue="",this.imageElement_.style.display="none";var t=this.selectedOption_&&this.selectedOption_[0];t&&"object"==typeof t?this.renderSelectedImage_(t):this.renderSelectedText_(),this.positionBorderRect_()},t.FieldDropdown.prototype.renderSelectedImage_=function(e){this.imageElement_.style.display="",this.imageElement_.setAttributeNS(t.utils.dom.XLINK_NS,"xlink:href",e.src),this.imageElement_.setAttribute("height",e.height),this.imageElement_.setAttribute("width",e.width);var o=Number(e.height);e=Number(e.width);var i=!!this.borderRect_,n=Math.max(i?this.getConstants().FIELD_DROPDOWN_BORDER_RECT_HEIGHT:0,o+t.FieldDropdown.IMAGE_Y_PADDING);i=i?this.getConstants().FIELD_BORDER_RECT_X_PADDING:0;var s=this.svgArrow_?this.positionSVGArrow_(e+i,n/2-this.getConstants().FIELD_DROPDOWN_SVG_ARROW_SIZE/2):t.utils.dom.getFastTextWidth(this.arrow_,this.getConstants().FIELD_TEXT_FONTSIZE,this.getConstants().FIELD_TEXT_FONTWEIGHT,this.getConstants().FIELD_TEXT_FONTFAMILY);this.size_.width=e+s+2*i,this.size_.height=n;var r=0;this.sourceBlock_.RTL?this.imageElement_.setAttribute("x",i+s):(r=e+s,this.textElement_.setAttribute("text-anchor","end"),this.imageElement_.setAttribute("x",i)),this.imageElement_.setAttribute("y",n/2-o/2),this.positionTextElement_(r+i,e+s)},t.FieldDropdown.prototype.renderSelectedText_=function(){this.textContent_.nodeValue=this.getDisplayText_(),t.utils.dom.addClass(this.textElement_,"blocklyDropdownText"),this.textElement_.setAttribute("text-anchor","start");var e=!!this.borderRect_,o=Math.max(e?this.getConstants().FIELD_DROPDOWN_BORDER_RECT_HEIGHT:0,this.getConstants().FIELD_TEXT_HEIGHT),i=t.utils.dom.getFastTextWidth(this.textElement_,this.getConstants().FIELD_TEXT_FONTSIZE,this.getConstants().FIELD_TEXT_FONTWEIGHT,this.getConstants().FIELD_TEXT_FONTFAMILY);e=e?this.getConstants().FIELD_BORDER_RECT_X_PADDING:0;var n=0;this.svgArrow_&&(n=this.positionSVGArrow_(i+e,o/2-this.getConstants().FIELD_DROPDOWN_SVG_ARROW_SIZE/2)),this.size_.width=i+n+2*e,this.size_.height=o,this.positionTextElement_(e,i)},t.FieldDropdown.prototype.positionSVGArrow_=function(t,e){if(!this.svgArrow_)return 0;var o=this.borderRect_?this.getConstants().FIELD_BORDER_RECT_X_PADDING:0,i=this.getConstants().FIELD_DROPDOWN_SVG_ARROW_PADDING,n=this.getConstants().FIELD_DROPDOWN_SVG_ARROW_SIZE;return this.svgArrow_.setAttribute("transform","translate("+(this.sourceBlock_.RTL?o:t+i)+","+e+")"),n+i},t.FieldDropdown.prototype.getText_=function(){if(!this.selectedOption_)return null;var t=this.selectedOption_[0];return"object"==typeof t?t.alt:t},t.FieldDropdown.validateOptions_=function(t){if(!Array.isArray(t))throw TypeError("FieldDropdown options must be an array.");if(!t.length)throw TypeError("FieldDropdown options must not be an empty array.");for(var e=!1,o=0;o<t.length;++o){var i=t[o];Array.isArray(i)?"string"!=typeof i[1]?(e=!0,console.error("Invalid option["+o+"]: Each FieldDropdown option id must be a string. Found "+i[1]+" in: ",i)):i[0]&&"string"!=typeof i[0]&&"string"!=typeof i[0].src&&(e=!0,console.error("Invalid option["+o+"]: Each FieldDropdown option must have a string label or image description. Found"+i[0]+" in: ",i)):(e=!0,console.error("Invalid option["+o+"]: Each FieldDropdown option must be an array. Found: ",i))}if(e)throw TypeError("Found invalid FieldDropdown options.")},t.FieldDropdown.prototype.onBlocklyAction=function(e){if(this.menu_){if(e===t.navigation.ACTION_PREVIOUS)return this.menu_.highlightPrevious(),!0;if(e===t.navigation.ACTION_NEXT)return this.menu_.highlightNext(),!0}return t.FieldDropdown.superClass_.onBlocklyAction.call(this,e)},t.fieldRegistry.register("field_dropdown",t.FieldDropdown),t.FieldLabelSerializable=function(e,o,i){t.FieldLabelSerializable.superClass_.constructor.call(this,e,o,i)},t.utils.object.inherits(t.FieldLabelSerializable,t.FieldLabel),t.FieldLabelSerializable.fromJson=function(e){var o=t.utils.replaceMessageReferences(e.text);return new t.FieldLabelSerializable(o,void 0,e)},t.FieldLabelSerializable.prototype.EDITABLE=!1,t.FieldLabelSerializable.prototype.SERIALIZABLE=!0,t.fieldRegistry.register("field_label_serializable",t.FieldLabelSerializable),t.FieldImage=function(e,o,i,n,s,r,a){if(!e)throw Error("Src value of an image field is required");if(e=t.utils.replaceMessageReferences(e),i=Number(t.utils.replaceMessageReferences(i)),o=Number(t.utils.replaceMessageReferences(o)),isNaN(i)||isNaN(o))throw Error("Height and width values of an image field must cast to numbers.");if(0>=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;i<o.length;i++){var n=o[i];n.length>this.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;i<e.length;i++){var n=this.getConstants().FIELD_TEXT_HEIGHT+this.getConstants().FIELD_BORDER_RECT_Y_PADDING;t.utils.dom.createSvgElement("text",{class:"blocklyText blocklyMultilineText",x:this.getConstants().FIELD_BORDER_RECT_X_PADDING,y:o+this.getConstants().FIELD_BORDER_RECT_Y_PADDING,dy:this.getConstants().FIELD_TEXT_BASELINE},this.textGroup_).appendChild(document.createTextNode(e[i])),o+=n}this.updateSize_(),this.isBeingEdited_&&(this.sourceBlock_.RTL?setTimeout(this.resizeEditor_.bind(this),0):this.resizeEditor_(),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.FieldMultilineInput.prototype.updateSize_=function(){for(var e=this.textGroup_.childNodes,o=0,i=0,n=0;n<e.length;n++){var s=t.utils.dom.getTextWidth(e[n]);s>o&&(o=s),i+=this.getConstants().FIELD_TEXT_HEIGHT+(0<n?this.getConstants().FIELD_BORDER_RECT_Y_PADDING:0)}this.borderRect_&&(i+=2*this.getConstants().FIELD_BORDER_RECT_Y_PADDING,o+=2*this.getConstants().FIELD_BORDER_RECT_X_PADDING,this.borderRect_.setAttribute("width",o),this.borderRect_.setAttribute("height",i)),this.size_.width=o,this.size_.height=i,this.positionBorderRect_()},t.FieldMultilineInput.prototype.widgetCreate_=function(){var e=t.WidgetDiv.DIV,o=this.workspace_.getScale(),i=document.createElement("textarea");i.className="blocklyHtmlInput blocklyHtmlTextAreaInput",i.setAttribute("spellcheck",this.spellcheck_);var n=this.getConstants().FIELD_TEXT_FONTSIZE*o+"pt";e.style.fontSize=n,i.style.fontSize=n,i.style.borderRadius=t.FieldTextInput.BORDERRADIUS*o+"px",n=this.getConstants().FIELD_BORDER_RECT_X_PADDING*o;var s=this.getConstants().FIELD_BORDER_RECT_Y_PADDING*o/2;return i.style.padding=s+"px "+n+"px "+s+"px "+n+"px",n=this.getConstants().FIELD_TEXT_HEIGHT+this.getConstants().FIELD_BORDER_RECT_Y_PADDING,i.style.lineHeight=n*o+"px",e.appendChild(i),i.value=i.defaultValue=this.getEditorText_(this.value_),i.untypedDefaultValue_=this.value_,i.oldValue_=null,t.utils.userAgent.GECKO?setTimeout(this.resizeEditor_.bind(this),0):this.resizeEditor_(),this.bindInputEvents_(i),i},t.FieldMultilineInput.prototype.onHtmlInputKeyDown_=function(e){e.keyCode!==t.utils.KeyCodes.ENTER&&t.FieldMultilineInput.superClass_.onHtmlInputKeyDown_.call(this,e)},t.Css.register(".blocklyHtmlTextAreaInput {,font-family: monospace;,resize: none;,overflow: hidden;,height: 100%;,text-align: left;,}".split(",")),t.fieldRegistry.register("field_multilinetext",t.FieldMultilineInput),t.FieldNumber=function(e,o,i,n,s,r){this.min_=-1/0,this.max_=1/0,this.precision_=0,this.decimalPlaces_=null,t.FieldNumber.superClass_.constructor.call(this,e||0,s,r),r||this.setConstraints(o,i,n)},t.utils.object.inherits(t.FieldNumber,t.FieldTextInput),t.FieldNumber.fromJson=function(e){return new t.FieldNumber(e.value,void 0,void 0,void 0,void 0,e)},t.FieldNumber.prototype.SERIALIZABLE=!0,t.FieldNumber.prototype.configure_=function(e){t.FieldNumber.superClass_.configure_.call(this,e),this.setMinInternal_(e.min),this.setMaxInternal_(e.max),this.setPrecisionInternal_(e.precision)},t.FieldNumber.prototype.setConstraints=function(t,e,o){this.setMinInternal_(t),this.setMaxInternal_(e),this.setPrecisionInternal_(o),this.setValue(this.getValue())},t.FieldNumber.prototype.setMin=function(t){this.setMinInternal_(t),this.setValue(this.getValue())},t.FieldNumber.prototype.setMinInternal_=function(t){null==t?this.min_=-1/0:(t=Number(t),isNaN(t)||(this.min_=t))},t.FieldNumber.prototype.getMin=function(){return this.min_},t.FieldNumber.prototype.setMax=function(t){this.setMaxInternal_(t),this.setValue(this.getValue())},t.FieldNumber.prototype.setMaxInternal_=function(t){null==t?this.max_=1/0:(t=Number(t),isNaN(t)||(this.max_=t))},t.FieldNumber.prototype.getMax=function(){return this.max_},t.FieldNumber.prototype.setPrecision=function(t){this.setPrecisionInternal_(t),this.setValue(this.getValue())},t.FieldNumber.prototype.setPrecisionInternal_=function(t){null==t?this.precision_=0:(t=Number(t),isNaN(t)||(this.precision_=t));var e=this.precision_.toString(),o=e.indexOf(".");this.decimalPlaces_=-1==o?t?0:null:e.length-o-1},t.FieldNumber.prototype.getPrecision=function(){return this.precision_},t.FieldNumber.prototype.doClassValidation_=function(t){return null===t?null:(t=(t=(t=(t=String(t)).replace(/O/gi,"0")).replace(/,/g,"")).replace(/infinity/i,"Infinity"),t=Number(t||0),isNaN(t)?null:(t=Math.min(Math.max(t,this.min_),this.max_),this.precision_&&isFinite(t)&&(t=Math.round(t/this.precision_)*this.precision_),null!=this.decimalPlaces_&&(t=Number(t.toFixed(this.decimalPlaces_))),t))},t.FieldNumber.prototype.widgetCreate_=function(){var e=t.FieldNumber.superClass_.widgetCreate_.call(this);return-1/0<this.min_&&t.utils.aria.setState(e,t.utils.aria.State.VALUEMIN,this.min_),1/0>this.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;o<e.length;o++)if(t==e[o])return!0;return!1},t.FieldVariable.prototype.getVariableTypes_=function(){var t=this.variableTypes;if(null===t&&this.sourceBlock_&&this.sourceBlock_.workspace)return this.sourceBlock_.workspace.getVariableTypes();if(0==(t=t||[""]).length)throw t=this.getText(),Error("'variableTypes' of field variable "+t+" was an empty list");return t},t.FieldVariable.prototype.setTypes_=function(t,e){if(e=e||"",null==t||null==t)t=null;else{if(!Array.isArray(t))throw Error("'variableTypes' was not an array in the definition of a FieldVariable");for(var o=!1,i=0;i<t.length;i++)t[i]==e&&(o=!0);if(!o)throw Error("Invalid default type '"+e+"' in the definition of a FieldVariable")}this.defaultType_=e,this.variableTypes=t},t.FieldVariable.prototype.refreshVariableName=function(){this.forceRerender()},t.FieldVariable.dropdownCreate=function(){if(!this.variable_)throw Error("Tried to call dropdownCreate on a variable field with no variable selected.");var e=this.getText(),o=[];if(this.sourceBlock_&&this.sourceBlock_.workspace)for(var i=this.getVariableTypes_(),n=0;n<i.length;n++){var s=this.sourceBlock_.workspace.getVariablesOfType(i[n]);o=o.concat(s)}for(o.sort(t.VariableModel.compareByName),i=[],n=0;n<o.length;n++)i[n]=[o[n].name,o[n].getId()];return i.push([t.Msg.RENAME_VARIABLE,t.RENAME_VARIABLE_ID]),t.Msg.DELETE_VARIABLE&&i.push([t.Msg.DELETE_VARIABLE.replace("%1",e),t.DELETE_VARIABLE_ID]),i},t.FieldVariable.prototype.onItemSelected_=function(e,o){if(e=o.getValue(),this.sourceBlock_&&this.sourceBlock_.workspace){if(e==t.RENAME_VARIABLE_ID)return void t.Variables.renameVariable(this.sourceBlock_.workspace,this.variable_);if(e==t.DELETE_VARIABLE_ID)return void this.sourceBlock_.workspace.deleteVariableById(this.variable_.getId())}this.setValue(e)},t.FieldVariable.prototype.referencesVariables=function(){return!0},t.fieldRegistry.register("field_variable",t.FieldVariable),t.utils.svgPaths={},t.utils.svgPaths.point=function(t,e){return" "+t+","+e+" "},t.utils.svgPaths.curve=function(t,e){return" "+t+e.join("")},t.utils.svgPaths.moveTo=function(t,e){return" M "+t+","+e+" "},t.utils.svgPaths.moveBy=function(t,e){return" m "+t+","+e+" "},t.utils.svgPaths.lineTo=function(t,e){return" l "+t+","+e+" "},t.utils.svgPaths.line=function(t){return" l"+t.join("")},t.utils.svgPaths.lineOnAxis=function(t,e){return" "+t+" "+e+" "},t.utils.svgPaths.arc=function(t,e,o,i){return t+" "+o+" "+o+" "+e+i},t.blockRendering.ConstantProvider=function(){this.NO_PADDING=0,this.SMALL_PADDING=3,this.MEDIUM_PADDING=5,this.MEDIUM_LARGE_PADDING=8,this.LARGE_PADDING=10,this.TALL_INPUT_FIELD_OFFSET_Y=this.MEDIUM_PADDING,this.TAB_HEIGHT=15,this.TAB_OFFSET_FROM_TOP=5,this.TAB_VERTICAL_OVERLAP=2.5,this.TAB_WIDTH=8,this.NOTCH_WIDTH=15,this.NOTCH_HEIGHT=4,this.MIN_BLOCK_WIDTH=12,this.EMPTY_BLOCK_SPACER_HEIGHT=16,this.DUMMY_INPUT_SHADOW_MIN_HEIGHT=this.DUMMY_INPUT_MIN_HEIGHT=this.TAB_HEIGHT,this.CORNER_RADIUS=8,this.STATEMENT_INPUT_NOTCH_OFFSET=this.NOTCH_OFFSET_LEFT=15,this.STATEMENT_BOTTOM_SPACER=0,this.STATEMENT_INPUT_PADDING_LEFT=20,this.BETWEEN_STATEMENT_PADDING_Y=4,this.TOP_ROW_MIN_HEIGHT=this.MEDIUM_PADDING,this.TOP_ROW_PRECEDES_STATEMENT_MIN_HEIGHT=this.LARGE_PADDING,this.BOTTOM_ROW_MIN_HEIGHT=this.MEDIUM_PADDING,this.BOTTOM_ROW_AFTER_STATEMENT_MIN_HEIGHT=this.LARGE_PADDING,this.ADD_START_HATS=!1,this.START_HAT_HEIGHT=15,this.START_HAT_WIDTH=100,this.SPACER_DEFAULT_HEIGHT=15,this.MIN_BLOCK_HEIGHT=24,this.EMPTY_INLINE_INPUT_PADDING=14.5,this.EMPTY_INLINE_INPUT_HEIGHT=this.TAB_HEIGHT+11,this.EXTERNAL_VALUE_INPUT_PADDING=2,this.EMPTY_STATEMENT_INPUT_HEIGHT=this.MIN_BLOCK_HEIGHT,this.START_POINT=t.utils.svgPaths.moveBy(0,0),this.JAGGED_TEETH_HEIGHT=12,this.JAGGED_TEETH_WIDTH=6,this.FIELD_TEXT_FONTSIZE=11,this.FIELD_TEXT_FONTWEIGHT="normal",this.FIELD_TEXT_FONTFAMILY="sans-serif",this.FIELD_TEXT_BASELINE=this.FIELD_TEXT_HEIGHT=-1,this.FIELD_BORDER_RECT_RADIUS=4,this.FIELD_BORDER_RECT_HEIGHT=16,this.FIELD_BORDER_RECT_X_PADDING=5,this.FIELD_BORDER_RECT_Y_PADDING=3,this.FIELD_BORDER_RECT_COLOUR="#fff",this.FIELD_TEXT_BASELINE_CENTER=!t.utils.userAgent.IE&&!t.utils.userAgent.EDGE,this.FIELD_DROPDOWN_BORDER_RECT_HEIGHT=this.FIELD_BORDER_RECT_HEIGHT,this.FIELD_DROPDOWN_SVG_ARROW=this.FIELD_DROPDOWN_COLOURED_DIV=this.FIELD_DROPDOWN_NO_BORDER_RECT_SHADOW=!1,this.FIELD_DROPDOWN_SVG_ARROW_PADDING=this.FIELD_BORDER_RECT_X_PADDING,this.FIELD_DROPDOWN_SVG_ARROW_SIZE=12,this.FIELD_DROPDOWN_SVG_ARROW_DATAURI="data:image/svg+xml;base64,PHN2ZyBpZD0iTGF5ZXJfMSIgZGF0YS1uYW1lPSJMYXllciAxIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxMi43MSIgaGVpZ2h0PSI4Ljc5IiB2aWV3Qm94PSIwIDAgMTIuNzEgOC43OSI+PHRpdGxlPmRyb3Bkb3duLWFycm93PC90aXRsZT48ZyBvcGFjaXR5PSIwLjEiPjxwYXRoIGQ9Ik0xMi43MSwyLjQ0QTIuNDEsMi40MSwwLDAsMSwxMiw0LjE2TDguMDgsOC4wOGEyLjQ1LDIuNDUsMCwwLDEtMy40NSwwTDAuNzIsNC4xNkEyLjQyLDIuNDIsMCwwLDEsMCwyLjQ0LDIuNDgsMi40OCwwLDAsMSwuNzEuNzFDMSwwLjQ3LDEuNDMsMCw2LjM2LDBTMTEuNzUsMC40NiwxMiwuNzFBMi40NCwyLjQ0LDAsMCwxLDEyLjcxLDIuNDRaIiBmaWxsPSIjMjMxZjIwIi8+PC9nPjxwYXRoIGQ9Ik02LjM2LDcuNzlhMS40MywxLjQzLDAsMCwxLTEtLjQyTDEuNDIsMy40NWExLjQ0LDEuNDQsMCwwLDEsMC0yYzAuNTYtLjU2LDkuMzEtMC41Niw5Ljg3LDBhMS40NCwxLjQ0LDAsMCwxLDAsMkw3LjM3LDcuMzdBMS40MywxLjQzLDAsMCwxLDYuMzYsNy43OVoiIGZpbGw9IiNmZmYiLz48L3N2Zz4=",this.FIELD_COLOUR_FULL_BLOCK=this.FIELD_TEXTINPUT_BOX_SHADOW=!1,this.FIELD_COLOUR_DEFAULT_WIDTH=26,this.FIELD_COLOUR_DEFAULT_HEIGHT=this.FIELD_BORDER_RECT_HEIGHT,this.FIELD_CHECKBOX_X_OFFSET=this.FIELD_BORDER_RECT_X_PADDING-3,this.randomIdentifier=String(Math.random()).substring(2),this.embossFilterId="",this.embossFilter_=null,this.disabledPatternId="",this.disabledPattern_=null,this.debugFilterId="",this.cssNode_=this.debugFilter_=null,this.CURSOR_COLOUR="#cc0a0a",this.MARKER_COLOUR="#4286f4",this.CURSOR_WS_WIDTH=100,this.WS_CURSOR_HEIGHT=5,this.CURSOR_STACK_PADDING=10,this.CURSOR_BLOCK_PADDING=2,this.CURSOR_STROKE_WIDTH=4,this.FULL_BLOCK_FIELDS=!1,this.INSERTION_MARKER_COLOUR="#000000",this.INSERTION_MARKER_OPACITY=.2,this.SHAPES={PUZZLE:1,NOTCH:2}},t.blockRendering.ConstantProvider.prototype.init=function(){this.JAGGED_TEETH=this.makeJaggedTeeth(),this.NOTCH=this.makeNotch(),this.START_HAT=this.makeStartHat(),this.PUZZLE_TAB=this.makePuzzleTab(),this.INSIDE_CORNERS=this.makeInsideCorners(),this.OUTSIDE_CORNERS=this.makeOutsideCorners()},t.blockRendering.ConstantProvider.prototype.setTheme=function(t){this.blockStyles={};var e,o=t.blockStyles;for(e in o)this.blockStyles[e]=this.validatedBlockStyle_(o[e]);this.setDynamicProperties_(t)},t.blockRendering.ConstantProvider.prototype.setDynamicProperties_=function(t){this.setFontConstants_(t),this.setComponentConstants_(t),this.ADD_START_HATS=null!=t.startHats?t.startHats:this.ADD_START_HATS},t.blockRendering.ConstantProvider.prototype.setFontConstants_=function(e){this.FIELD_TEXT_FONTFAMILY=e.fontStyle&&null!=e.fontStyle.family?e.fontStyle.family:this.FIELD_TEXT_FONTFAMILY,this.FIELD_TEXT_FONTWEIGHT=e.fontStyle&&null!=e.fontStyle.weight?e.fontStyle.weight:this.FIELD_TEXT_FONTWEIGHT,this.FIELD_TEXT_FONTSIZE=e.fontStyle&&null!=e.fontStyle.size?e.fontStyle.size:this.FIELD_TEXT_FONTSIZE,e=t.utils.dom.measureFontMetrics("Hg",this.FIELD_TEXT_FONTSIZE+"pt",this.FIELD_TEXT_FONTWEIGHT,this.FIELD_TEXT_FONTFAMILY),this.FIELD_TEXT_HEIGHT=e.height,this.FIELD_TEXT_BASELINE=e.baseline},t.blockRendering.ConstantProvider.prototype.setComponentConstants_=function(t){this.CURSOR_COLOUR=t.getComponentStyle("cursorColour")||this.CURSOR_COLOUR,this.MARKER_COLOUR=t.getComponentStyle("markerColour")||this.MARKER_COLOUR,this.INSERTION_MARKER_COLOUR=t.getComponentStyle("insertionMarkerColour")||this.INSERTION_MARKER_COLOUR,this.INSERTION_MARKER_OPACITY=Number(t.getComponentStyle("insertionMarkerOpacity"))||this.INSERTION_MARKER_OPACITY},t.blockRendering.ConstantProvider.prototype.getBlockStyleForColour=function(t){var e="auto_"+t;return this.blockStyles[e]||(this.blockStyles[e]=this.createBlockStyle_(t)),{style:this.blockStyles[e],name:e}},t.blockRendering.ConstantProvider.prototype.getBlockStyle=function(t){return this.blockStyles[t||""]||(t&&0==t.indexOf("auto_")?this.getBlockStyleForColour(t.substring(5)).style:this.createBlockStyle_("#000000"))},t.blockRendering.ConstantProvider.prototype.createBlockStyle_=function(t){return this.validatedBlockStyle_({colourPrimary:t})},t.blockRendering.ConstantProvider.prototype.validatedBlockStyle_=function(e){var o={};return e&&t.utils.object.mixin(o,e),e=t.utils.parseBlockColour(o.colourPrimary||"#000"),o.colourPrimary=e.hex,o.colourSecondary=o.colourSecondary?t.utils.parseBlockColour(o.colourSecondary).hex:this.generateSecondaryColour_(o.colourPrimary),o.colourTertiary=o.colourTertiary?t.utils.parseBlockColour(o.colourTertiary).hex:this.generateTertiaryColour_(o.colourPrimary),o.hat=o.hat||"",o},t.blockRendering.ConstantProvider.prototype.generateSecondaryColour_=function(e){return t.utils.colour.blend("#fff",e,.6)||e},t.blockRendering.ConstantProvider.prototype.generateTertiaryColour_=function(e){return t.utils.colour.blend("#fff",e,.3)||e},t.blockRendering.ConstantProvider.prototype.dispose=function(){this.embossFilter_&&t.utils.dom.removeNode(this.embossFilter_),this.disabledPattern_&&t.utils.dom.removeNode(this.disabledPattern_),this.debugFilter_&&t.utils.dom.removeNode(this.debugFilter_),this.cssNode_=null},t.blockRendering.ConstantProvider.prototype.makeJaggedTeeth=function(){var e=this.JAGGED_TEETH_HEIGHT,o=this.JAGGED_TEETH_WIDTH;return{height:e,width:o,path:t.utils.svgPaths.line([t.utils.svgPaths.point(o,e/4),t.utils.svgPaths.point(2*-o,e/2),t.utils.svgPaths.point(o,e/4)])}},t.blockRendering.ConstantProvider.prototype.makeStartHat=function(){var e=this.START_HAT_HEIGHT,o=this.START_HAT_WIDTH;return{height:e,width:o,path:t.utils.svgPaths.curve("c",[t.utils.svgPaths.point(30,-e),t.utils.svgPaths.point(70,-e),t.utils.svgPaths.point(o,0)])}},t.blockRendering.ConstantProvider.prototype.makePuzzleTab=function(){function e(e){var n=-(e=e?-1:1),s=i/2,r=s+2.5,a=s+.5,l=t.utils.svgPaths.point(-o,e*s);return s=t.utils.svgPaths.point(o,e*s),t.utils.svgPaths.curve("c",[t.utils.svgPaths.point(0,e*r),t.utils.svgPaths.point(-o,n*a),l])+t.utils.svgPaths.curve("s",[t.utils.svgPaths.point(o,2.5*n),s])}var o=this.TAB_WIDTH,i=this.TAB_HEIGHT,n=e(!0),s=e(!1);return{type:this.SHAPES.PUZZLE,width:o,height:i,pathDown:s,pathUp:n}},t.blockRendering.ConstantProvider.prototype.makeNotch=function(){function e(e){return t.utils.svgPaths.line([t.utils.svgPaths.point(e*n,i),t.utils.svgPaths.point(3*e,0),t.utils.svgPaths.point(e*n,-i)])}var o=this.NOTCH_WIDTH,i=this.NOTCH_HEIGHT,n=(o-3)/2,s=e(1),r=e(-1);return{type:this.SHAPES.NOTCH,width:o,height:i,pathLeft:s,pathRight:r}},t.blockRendering.ConstantProvider.prototype.makeInsideCorners=function(){var e=this.CORNER_RADIUS;return{width:e,height:e,pathTop:t.utils.svgPaths.arc("a","0 0,0",e,t.utils.svgPaths.point(-e,e)),pathBottom:t.utils.svgPaths.arc("a","0 0,0",e,t.utils.svgPaths.point(e,e))}},t.blockRendering.ConstantProvider.prototype.makeOutsideCorners=function(){var e=this.CORNER_RADIUS,o=t.utils.svgPaths.moveBy(0,e)+t.utils.svgPaths.arc("a","0 0,1",e,t.utils.svgPaths.point(e,-e)),i=t.utils.svgPaths.arc("a","0 0,1",e,t.utils.svgPaths.point(e,e)),n=t.utils.svgPaths.arc("a","0 0,1",e,t.utils.svgPaths.point(-e,-e));return{topLeft:o,topRight:i,bottomRight:t.utils.svgPaths.arc("a","0 0,1",e,t.utils.svgPaths.point(-e,e)),bottomLeft:n,rightHeight:e}},t.blockRendering.ConstantProvider.prototype.shapeFor=function(e){switch(e.type){case t.INPUT_VALUE:case t.OUTPUT_VALUE:return this.PUZZLE_TAB;case t.PREVIOUS_STATEMENT:case t.NEXT_STATEMENT:return this.NOTCH;default:throw Error("Unknown connection type")}},t.blockRendering.ConstantProvider.prototype.createDom=function(e,o,i){this.injectCSS_(o,i),e=t.utils.dom.createSvgElement("defs",{},e),o=t.utils.dom.createSvgElement("filter",{id:"blocklyEmbossFilter"+this.randomIdentifier},e),t.utils.dom.createSvgElement("feGaussianBlur",{in:"SourceAlpha",stdDeviation:1,result:"blur"},o),i=t.utils.dom.createSvgElement("feSpecularLighting",{in:"blur",surfaceScale:1,specularConstant:.5,specularExponent:10,"lighting-color":"white",result:"specOut"},o),t.utils.dom.createSvgElement("fePointLight",{x:-5e3,y:-1e4,z:2e4},i),t.utils.dom.createSvgElement("feComposite",{in:"specOut",in2:"SourceAlpha",operator:"in",result:"specOut"},o),t.utils.dom.createSvgElement("feComposite",{in:"SourceGraphic",in2:"specOut",operator:"arithmetic",k1:0,k2:1,k3:1,k4:0},o),this.embossFilterId=o.id,this.embossFilter_=o,o=t.utils.dom.createSvgElement("pattern",{id:"blocklyDisabledPattern"+this.randomIdentifier,patternUnits:"userSpaceOnUse",width:10,height:10},e),t.utils.dom.createSvgElement("rect",{width:10,height:10,fill:"#aaa"},o),t.utils.dom.createSvgElement("path",{d:"M 0 0 L 10 10 M 10 0 L 0 10",stroke:"#cc0"},o),this.disabledPatternId=o.id,this.disabledPattern_=o,t.blockRendering.Debug&&(e=t.utils.dom.createSvgElement("filter",{id:"blocklyDebugFilter"+this.randomIdentifier,height:"160%",width:"180%",y:"-30%",x:"-40%"},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":"#ff0000","flood-opacity":.5,result:"outColor"},e),t.utils.dom.createSvgElement("feComposite",{in:"outColor",in2:"outBlur",operator:"in",result:"outGlow"},e),this.debugFilterId=e.id,this.debugFilter_=e)},t.blockRendering.ConstantProvider.prototype.injectCSS_=function(t,e){e=this.getCSS_(e),t="blockly-renderer-style-"+t,this.cssNode_=document.getElementById(t);var o=e.join("\n");this.cssNode_?this.cssNode_.firstChild.textContent=o:((e=document.createElement("style")).id=t,t=document.createTextNode(o),e.appendChild(t),document.head.insertBefore(e,document.head.firstChild),this.cssNode_=e)},t.blockRendering.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,",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<i.length-1;n++){e.elements.push(i[n]);var s=this.getInRowSpacing_(i[n],i[n+1]);e.elements.push(new t.blockRendering.InRowSpacer(this.constants_,s))}e.elements.push(i[i.length-1]),e.endsWithElemSpacer()&&e.elements.push(new t.blockRendering.InRowSpacer(this.constants_,this.getInRowSpacing_(i[i.length-1],null)))}}},t.blockRendering.RenderInfo.prototype.getInRowSpacing_=function(e,o){if(!e&&o&&t.blockRendering.Types.isStatementInput(o))return this.constants_.STATEMENT_INPUT_PADDING_LEFT;if(e&&t.blockRendering.Types.isInput(e)&&!o){if(t.blockRendering.Types.isExternalInput(e))return this.constants_.NO_PADDING;if(t.blockRendering.Types.isInlineInput(e))return this.constants_.LARGE_PADDING;if(t.blockRendering.Types.isStatementInput(e))return this.constants_.NO_PADDING}return e&&t.blockRendering.Types.isLeftSquareCorner(e)&&o&&(t.blockRendering.Types.isPreviousConnection(o)||t.blockRendering.Types.isNextConnection(o))?o.notchOffset:e&&t.blockRendering.Types.isLeftRoundedCorner(e)&&o&&(t.blockRendering.Types.isPreviousConnection(o)||t.blockRendering.Types.isNextConnection(o))?o.notchOffset-this.constants_.CORNER_RADIUS:this.constants_.MEDIUM_PADDING},t.blockRendering.RenderInfo.prototype.computeBounds_=function(){for(var t,e=0,o=0,i=0,n=0;t=this.rows[n];n++){if(t.measure(),o=Math.max(o,t.width),t.hasStatement){var s=t.getLastInput();e=Math.max(e,t.width-s.width)}i=Math.max(i,t.widthWithConnectedBlocks)}for(this.statementEdge=e,this.width=o,n=0;t=this.rows[n];n++)t.hasStatement&&(t.statementEdge=this.statementEdge);this.widthWithChildren=Math.max(o,i),this.outputConnection&&(this.startX=this.outputConnection.width,this.width+=this.outputConnection.width,this.widthWithChildren+=this.outputConnection.width)},t.blockRendering.RenderInfo.prototype.alignRowElements_=function(){for(var e,o=0;e=this.rows[o];o++)if(e.hasStatement)this.alignStatementRow_(e);else{var i=e.width;0<(i=this.getDesiredRowWidth_(e)-i)&&this.addAlignmentPadding_(e,i),t.blockRendering.Types.isTopOrBottomRow(e)&&(e.widthWithConnectedBlocks=e.width)}},t.blockRendering.RenderInfo.prototype.getDesiredRowWidth_=function(t){return this.width-this.startX},t.blockRendering.RenderInfo.prototype.addAlignmentPadding_=function(e,o){var i=e.getFirstSpacer(),n=e.getLastSpacer();(e.hasExternalInput||e.hasStatement)&&(e.widthWithConnectedBlocks+=o),e.align==t.ALIGN_LEFT?n.width+=o:e.align==t.ALIGN_CENTRE?(i.width+=o/2,n.width+=o/2):e.align==t.ALIGN_RIGHT?i.width+=o:n.width+=o,e.width+=o},t.blockRendering.RenderInfo.prototype.alignStatementRow_=function(t){var e=t.getLastInput(),o=t.width-e.width,i=this.statementEdge;0<(o=i-o)&&this.addAlignmentPadding_(t,o),o=t.width,i=this.getDesiredRowWidth_(t),e.width+=i-o,e.height=Math.max(e.height,t.height),t.width+=i-o,t.widthWithConnectedBlocks=Math.max(t.width,this.statementEdge+t.connectedBlockWidths)},t.blockRendering.RenderInfo.prototype.addRowSpacing_=function(){var t=this.rows;this.rows=[];for(var e=0;e<t.length;e++)this.rows.push(t[e]),e!=t.length-1&&this.rows.push(this.makeSpacerRow_(t[e],t[e+1]))},t.blockRendering.RenderInfo.prototype.makeSpacerRow_=function(e,o){var i=this.getSpacerRowHeight_(e,o),n=this.getSpacerRowWidth_(e,o);return i=new t.blockRendering.SpacerRow(this.constants_,i,n),e.hasStatement&&(i.followsStatement=!0),o.hasStatement&&(i.precedesStatement=!0),i},t.blockRendering.RenderInfo.prototype.getSpacerRowWidth_=function(t,e){return this.width-this.startX},t.blockRendering.RenderInfo.prototype.getSpacerRowHeight_=function(t,e){return this.constants_.MEDIUM_PADDING},t.blockRendering.RenderInfo.prototype.getElemCenterline_=function(e,o){return t.blockRendering.Types.isSpacer(o)?e.yPos+o.height/2:t.blockRendering.Types.isBottomRow(e)?(e=e.yPos+e.height-e.descenderHeight,t.blockRendering.Types.isNextConnection(o)?e+o.height/2:e-o.height/2):t.blockRendering.Types.isTopRow(e)?t.blockRendering.Types.isHat(o)?e.capline-o.height/2:e.capline+o.height/2:e.yPos+e.height/2},t.blockRendering.RenderInfo.prototype.recordElemPositions_=function(e){for(var o,i=e.xPos,n=0;o=e.elements[n];n++)t.blockRendering.Types.isSpacer(o)&&(o.height=e.height),o.xPos=i,o.centerline=this.getElemCenterline_(e,o),i+=o.width},t.blockRendering.RenderInfo.prototype.finalize_=function(){for(var t,e=0,o=0,i=0;t=this.rows[i];i++)t.yPos=o,t.xPos=this.startX,o+=t.height,e=Math.max(e,t.widthWithConnectedBlocks),this.recordElemPositions_(t);this.outputConnection&&this.block_.nextConnection&&this.block_.nextConnection.isConnected()&&(e=Math.max(e,this.block_.nextConnection.targetBlock().getHeightWidth().width)),this.widthWithChildren=e+this.startX,this.height=o,this.startY=this.topRow.capline,this.bottomRow.baseline=o-this.bottomRow.descenderHeight},t.blockRendering.Drawer=function(t,e){this.block_=t,this.info_=e,this.topLeft_=t.getRelativeToSurfaceXY(),this.inlinePath_=this.outlinePath_="",this.constants_=e.getRenderer().getConstants()},t.blockRendering.Drawer.prototype.draw=function(){this.hideHiddenIcons_(),this.drawOutline_(),this.drawInternals_(),this.block_.pathObject.setPath(this.outlinePath_+"\n"+this.inlinePath_),this.info_.RTL&&this.block_.pathObject.flipRTL(),t.blockRendering.useDebugger&&this.block_.renderingDebugger.drawDebug(this.block_,this.info_),this.recordSizeOnBlock_()},t.blockRendering.Drawer.prototype.recordSizeOnBlock_=function(){this.block_.height=this.info_.height,this.block_.width=this.info_.widthWithChildren},t.blockRendering.Drawer.prototype.hideHiddenIcons_=function(){for(var t,e=0;t=this.info_.hiddenIcons[e];e++)t.icon.iconGroup_.setAttribute("display","none")},t.blockRendering.Drawer.prototype.drawOutline_=function(){this.drawTop_();for(var t=1;t<this.info_.rows.length-1;t++){var e=this.info_.rows[t];e.hasJaggedEdge?this.drawJaggedEdge_(e):e.hasStatement?this.drawStatementInput_(e):e.hasExternalInput?this.drawValueInput_(e):this.drawRightSideRow_(e)}this.drawBottom_(),this.drawLeft_()},t.blockRendering.Drawer.prototype.drawTop_=function(){var e=this.info_.topRow,o=e.elements;this.positionPreviousConnection_(),this.outlinePath_+=t.utils.svgPaths.moveBy(e.xPos,this.info_.startY);for(var i,n=0;i=o[n];n++)t.blockRendering.Types.isLeftRoundedCorner(i)?this.outlinePath_+=this.constants_.OUTSIDE_CORNERS.topLeft:t.blockRendering.Types.isRightRoundedCorner(i)?this.outlinePath_+=this.constants_.OUTSIDE_CORNERS.topRight:t.blockRendering.Types.isPreviousConnection(i)?this.outlinePath_+=i.shape.pathLeft:t.blockRendering.Types.isHat(i)?this.outlinePath_+=this.constants_.START_HAT.path:t.blockRendering.Types.isSpacer(i)&&(this.outlinePath_+=t.utils.svgPaths.lineOnAxis("h",i.width));this.outlinePath_+=t.utils.svgPaths.lineOnAxis("v",e.height)},t.blockRendering.Drawer.prototype.drawJaggedEdge_=function(e){this.outlinePath_+=this.constants_.JAGGED_TEETH.path+t.utils.svgPaths.lineOnAxis("v",e.height-this.constants_.JAGGED_TEETH.height)},t.blockRendering.Drawer.prototype.drawValueInput_=function(e){var o=e.getLastInput();this.positionExternalValueConnection_(e);var i="function"==typeof o.shape.pathDown?o.shape.pathDown(o.height):o.shape.pathDown;this.outlinePath_+=t.utils.svgPaths.lineOnAxis("H",o.xPos+o.width)+i+t.utils.svgPaths.lineOnAxis("v",e.height-o.connectionHeight)},t.blockRendering.Drawer.prototype.drawStatementInput_=function(e){var o=e.getLastInput(),i=o.xPos+o.notchOffset+o.shape.width;o=o.shape.pathRight+t.utils.svgPaths.lineOnAxis("h",-(o.notchOffset-this.constants_.INSIDE_CORNERS.width))+this.constants_.INSIDE_CORNERS.pathTop;var n=e.height-2*this.constants_.INSIDE_CORNERS.height;this.outlinePath_+=t.utils.svgPaths.lineOnAxis("H",i)+o+t.utils.svgPaths.lineOnAxis("v",n)+this.constants_.INSIDE_CORNERS.pathBottom+t.utils.svgPaths.lineOnAxis("H",e.xPos+e.width),this.positionStatementInputConnection_(e)},t.blockRendering.Drawer.prototype.drawRightSideRow_=function(e){this.outlinePath_+=t.utils.svgPaths.lineOnAxis("V",e.yPos+e.height)},t.blockRendering.Drawer.prototype.drawBottom_=function(){var e=this.info_.bottomRow,o=e.elements;this.positionNextConnection_();for(var i,n=0,s="",r=o.length-1;i=o[r];r--)t.blockRendering.Types.isNextConnection(i)?s+=i.shape.pathRight:t.blockRendering.Types.isLeftSquareCorner(i)?s+=t.utils.svgPaths.lineOnAxis("H",e.xPos):t.blockRendering.Types.isLeftRoundedCorner(i)?s+=this.constants_.OUTSIDE_CORNERS.bottomLeft:t.blockRendering.Types.isRightRoundedCorner(i)?(s+=this.constants_.OUTSIDE_CORNERS.bottomRight,n=this.constants_.OUTSIDE_CORNERS.rightHeight):t.blockRendering.Types.isSpacer(i)&&(s+=t.utils.svgPaths.lineOnAxis("h",-1*i.width));this.outlinePath_+=t.utils.svgPaths.lineOnAxis("V",e.baseline-n),this.outlinePath_+=s},t.blockRendering.Drawer.prototype.drawLeft_=function(){var e=this.info_.outputConnection;if(this.positionOutputConnection_(),e){var o=e.connectionOffsetY+e.height;e="function"==typeof e.shape.pathUp?e.shape.pathUp(e.height):e.shape.pathUp,this.outlinePath_+=t.utils.svgPaths.lineOnAxis("V",o)+e}this.outlinePath_+="z"},t.blockRendering.Drawer.prototype.drawInternals_=function(){for(var e,o=0;e=this.info_.rows[o];o++)for(var i,n=0;i=e.elements[n];n++)t.blockRendering.Types.isInlineInput(i)?this.drawInlineInput_(i):(t.blockRendering.Types.isIcon(i)||t.blockRendering.Types.isField(i))&&this.layoutField_(i)},t.blockRendering.Drawer.prototype.layoutField_=function(e){if(t.blockRendering.Types.isField(e))var o=e.field.getSvgRoot();else t.blockRendering.Types.isIcon(e)&&(o=e.icon.iconGroup_);var i=e.centerline-e.height/2,n=e.xPos,s="";this.info_.RTL&&(n=-(n+e.width),e.flipRtl&&(n+=e.width,s="scale(-1 1)")),t.blockRendering.Types.isIcon(e)?(o.setAttribute("display","block"),o.setAttribute("transform","translate("+n+","+i+")"),e.icon.computeIconLocation()):o.setAttribute("transform","translate("+n+","+i+")"+s),this.info_.isInsertionMarker&&o.setAttribute("display","none")},t.blockRendering.Drawer.prototype.drawInlineInput_=function(e){var o=e.width,i=e.height,n=e.connectionOffsetY,s=e.connectionHeight+n;this.inlinePath_+=t.utils.svgPaths.moveTo(e.xPos+e.connectionWidth,e.centerline-i/2)+t.utils.svgPaths.lineOnAxis("v",n)+e.shape.pathDown+t.utils.svgPaths.lineOnAxis("v",i-s)+t.utils.svgPaths.lineOnAxis("h",o-e.connectionWidth)+t.utils.svgPaths.lineOnAxis("v",-i)+"z",this.positionInlineInputConnection_(e)},t.blockRendering.Drawer.prototype.positionInlineInputConnection_=function(t){var e=t.centerline-t.height/2;if(t.connectionModel){var o=t.xPos+t.connectionWidth+t.connectionOffsetX;this.info_.RTL&&(o*=-1),t.connectionModel.setOffsetInBlock(o,e+t.connectionOffsetY)}},t.blockRendering.Drawer.prototype.positionStatementInputConnection_=function(t){var e=t.getLastInput();if(e.connectionModel){var o=t.xPos+t.statementEdge+e.notchOffset;this.info_.RTL&&(o*=-1),e.connectionModel.setOffsetInBlock(o,t.yPos)}},t.blockRendering.Drawer.prototype.positionExternalValueConnection_=function(t){var e=t.getLastInput();if(e.connectionModel){var o=t.xPos+t.width;this.info_.RTL&&(o*=-1),e.connectionModel.setOffsetInBlock(o,t.yPos)}},t.blockRendering.Drawer.prototype.positionPreviousConnection_=function(){var t=this.info_.topRow;if(t.connection){var e=t.xPos+t.notchOffset;t.connection.connectionModel.setOffsetInBlock(this.info_.RTL?-e:e,0)}},t.blockRendering.Drawer.prototype.positionNextConnection_=function(){var t=this.info_.bottomRow;if(t.connection){var e=t.connection,o=e.xPos;e.connectionModel.setOffsetInBlock(this.info_.RTL?-o:o,t.baseline)}},t.blockRendering.Drawer.prototype.positionOutputConnection_=function(){if(this.info_.outputConnection){var t=this.info_.startX+this.info_.outputConnection.connectionOffsetX;this.block_.outputConnection.setOffsetInBlock(this.info_.RTL?-t:t,this.info_.outputConnection.connectionOffsetY)}},t.blockRendering.PathObject=function(e,o,i){this.constants=i,this.svgRoot=e,this.svgPath=t.utils.dom.createSvgElement("path",{class:"blocklyPath"},this.svgRoot),this.style=o,this.markerSvg=this.cursorSvg=null},t.blockRendering.PathObject.prototype.setPath=function(t){this.svgPath.setAttribute("d",t)},t.blockRendering.PathObject.prototype.flipRTL=function(){this.svgPath.setAttribute("transform","scale(-1 1)")},t.blockRendering.PathObject.prototype.setCursorSvg=function(t){t?(this.svgRoot.appendChild(t),this.cursorSvg=t):this.cursorSvg=null},t.blockRendering.PathObject.prototype.setMarkerSvg=function(t){t?(this.cursorSvg?this.svgRoot.insertBefore(t,this.cursorSvg):this.svgRoot.appendChild(t),this.markerSvg=t):this.markerSvg=null},t.blockRendering.PathObject.prototype.applyColour=function(t){this.svgPath.setAttribute("stroke",this.style.colourTertiary),this.svgPath.setAttribute("fill",this.style.colourPrimary),this.updateShadow_(t.isShadow()),this.updateDisabled_(!t.isEnabled()||t.getInheritedDisabled())},t.blockRendering.PathObject.prototype.setStyle=function(t){this.style=t},t.blockRendering.PathObject.prototype.setClass_=function(e,o){o?t.utils.dom.addClass(this.svgRoot,e):t.utils.dom.removeClass(this.svgRoot,e)},t.blockRendering.PathObject.prototype.updateHighlighted=function(t){t?this.svgPath.setAttribute("filter","url(#"+this.constants.embossFilterId+")"):this.svgPath.setAttribute("filter","none")},t.blockRendering.PathObject.prototype.updateShadow_=function(t){t&&(this.svgPath.setAttribute("stroke","none"),this.svgPath.setAttribute("fill",this.style.colourSecondary))},t.blockRendering.PathObject.prototype.updateDisabled_=function(t){this.setClass_("blocklyDisabled",t),t&&this.svgPath.setAttribute("fill","url(#"+this.constants.disabledPatternId+")")},t.blockRendering.PathObject.prototype.updateSelected=function(t){this.setClass_("blocklySelected",t)},t.blockRendering.PathObject.prototype.updateDraggingDelete=function(t){this.setClass_("blocklyDraggingDelete",t)},t.blockRendering.PathObject.prototype.updateInsertionMarker=function(t){this.setClass_("blocklyInsertionMarker",t)},t.blockRendering.PathObject.prototype.updateMovable=function(t){this.setClass_("blocklyDraggable",t)},t.blockRendering.PathObject.prototype.updateReplacementFade=function(t){this.setClass_("blocklyReplaceable",t)},t.blockRendering.PathObject.prototype.updateShapeForInputHighlight=function(t,e){},t.blockRendering.Renderer=function(t){this.name=t,this.overrides=this.constants_=null},t.blockRendering.Renderer.prototype.getClassName=function(){return this.name+"-renderer"},t.blockRendering.Renderer.prototype.init=function(e,o){this.constants_=this.makeConstants_(),o&&(this.overrides=o,t.utils.object.mixin(this.constants_,o)),this.constants_.setTheme(e),this.constants_.init()},t.blockRendering.Renderer.prototype.createDom=function(t,e){this.constants_.createDom(t,this.name+"-"+e.name,"."+this.getClassName()+"."+e.getClassName())},t.blockRendering.Renderer.prototype.refreshDom=function(e,o){var i=this.getConstants();i.dispose(),this.constants_=this.makeConstants_(),this.overrides&&t.utils.object.mixin(this.constants_,this.overrides),this.constants_.randomIdentifier=i.randomIdentifier,this.constants_.setTheme(o),this.constants_.init(),this.createDom(e,o)},t.blockRendering.Renderer.prototype.dispose=function(){this.constants_&&this.constants_.dispose()},t.blockRendering.Renderer.prototype.makeConstants_=function(){return new t.blockRendering.ConstantProvider},t.blockRendering.Renderer.prototype.makeRenderInfo_=function(e){return new t.blockRendering.RenderInfo(this,e)},t.blockRendering.Renderer.prototype.makeDrawer_=function(e,o){return new t.blockRendering.Drawer(e,o)},t.blockRendering.Renderer.prototype.makeDebugger_=function(){if(!t.blockRendering.Debug)throw Error("Missing require for Blockly.blockRendering.Debug");return new t.blockRendering.Debug(this.getConstants())},t.blockRendering.Renderer.prototype.makeMarkerDrawer=function(e,o){return new t.blockRendering.MarkerSvg(e,this.getConstants(),o)},t.blockRendering.Renderer.prototype.makePathObject=function(e,o){return new t.blockRendering.PathObject(e,o,this.constants_)},t.blockRendering.Renderer.prototype.getConstants=function(){return this.constants_},t.blockRendering.Renderer.prototype.shouldHighlightConnection=function(t){return!0},t.blockRendering.Renderer.prototype.orphanCanConnectAtEnd=function(e,o,i){return i==t.OUTPUT_VALUE?(i=o.outputConnection,e=t.Connection.lastConnectionInRow(e,o)):(i=o.previousConnection,e=e.lastConnectionInStack()),!!e&&i.checkType(e)},t.blockRendering.Renderer.prototype.getConnectionPreviewMethod=function(e,o,i){return o.type==t.OUTPUT_VALUE||o.type==t.PREVIOUS_STATEMENT?!e.isConnected()||this.orphanCanConnectAtEnd(i,e.targetBlock(),o.type)?t.InsertionMarkerManager.PREVIEW_TYPE.INSERTION_MARKER:t.InsertionMarkerManager.PREVIEW_TYPE.REPLACEMENT_FADE:t.InsertionMarkerManager.PREVIEW_TYPE.INSERTION_MARKER},t.blockRendering.Renderer.prototype.render=function(e){t.blockRendering.useDebugger&&!e.renderingDebugger&&(e.renderingDebugger=this.makeDebugger_());var o=this.makeRenderInfo_(e);o.measure(),this.makeDrawer_(e,o).draw()},t.geras={},t.geras.ConstantProvider=function(){t.geras.ConstantProvider.superClass_.constructor.call(this),this.FIELD_TEXT_BASELINE_CENTER=!1,this.DARK_PATH_OFFSET=1,this.MAX_BOTTOM_WIDTH=30},t.utils.object.inherits(t.geras.ConstantProvider,t.blockRendering.ConstantProvider),t.geras.ConstantProvider.prototype.getCSS_=function(e){return t.geras.ConstantProvider.superClass_.getCSS_.call(this,e).concat([e+" .blocklyInsertionMarker>.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;s<n.length-1;s++){e.elements.push(n[s]);var r=this.getInRowSpacing_(n[s],n[s+1]);e.elements.push(new t.blockRendering.InRowSpacer(this.constants_,r))}e.elements.push(n[n.length-1]),e.endsWithElemSpacer()&&(r=this.getInRowSpacing_(n[n.length-1],null),o&&e.hasDummyInput&&(r+=this.constants_.TAB_WIDTH),e.elements.push(new t.blockRendering.InRowSpacer(this.constants_,r)))}}},t.geras.RenderInfo.prototype.getInRowSpacing_=function(e,o){if(!e)return o&&t.blockRendering.Types.isField(o)&&o.isEditable?this.constants_.MEDIUM_PADDING:o&&t.blockRendering.Types.isInlineInput(o)?this.constants_.MEDIUM_LARGE_PADDING:o&&t.blockRendering.Types.isStatementInput(o)?this.constants_.STATEMENT_INPUT_PADDING_LEFT:this.constants_.LARGE_PADDING;if(!t.blockRendering.Types.isInput(e)&&(!o||t.blockRendering.Types.isStatementInput(o)))return t.blockRendering.Types.isField(e)&&e.isEditable?this.constants_.MEDIUM_PADDING:t.blockRendering.Types.isIcon(e)?2*this.constants_.LARGE_PADDING+1:t.blockRendering.Types.isHat(e)?this.constants_.NO_PADDING:t.blockRendering.Types.isPreviousOrNextConnection(e)?this.constants_.LARGE_PADDING:t.blockRendering.Types.isLeftRoundedCorner(e)?this.constants_.MIN_BLOCK_WIDTH:t.blockRendering.Types.isJaggedEdge(e)?this.constants_.NO_PADDING:this.constants_.LARGE_PADDING;if(t.blockRendering.Types.isInput(e)&&!o){if(t.blockRendering.Types.isExternalInput(e))return this.constants_.NO_PADDING;if(t.blockRendering.Types.isInlineInput(e))return this.constants_.LARGE_PADDING;if(t.blockRendering.Types.isStatementInput(e))return this.constants_.NO_PADDING}if(!t.blockRendering.Types.isInput(e)&&o&&t.blockRendering.Types.isInput(o)){if(t.blockRendering.Types.isField(e)&&e.isEditable){if(t.blockRendering.Types.isInlineInput(o)||t.blockRendering.Types.isExternalInput(o))return this.constants_.SMALL_PADDING}else{if(t.blockRendering.Types.isInlineInput(o)||t.blockRendering.Types.isExternalInput(o))return this.constants_.MEDIUM_LARGE_PADDING;if(t.blockRendering.Types.isStatementInput(o))return this.constants_.LARGE_PADDING}return this.constants_.LARGE_PADDING-1}if(t.blockRendering.Types.isIcon(e)&&o&&!t.blockRendering.Types.isInput(o))return this.constants_.LARGE_PADDING;if(t.blockRendering.Types.isInlineInput(e)&&o&&t.blockRendering.Types.isField(o))return o.isEditable?this.constants_.MEDIUM_PADDING:this.constants_.LARGE_PADDING;if(t.blockRendering.Types.isLeftSquareCorner(e)&&o){if(t.blockRendering.Types.isHat(o))return this.constants_.NO_PADDING;if(t.blockRendering.Types.isPreviousConnection(o))return o.notchOffset;if(t.blockRendering.Types.isNextConnection(o))return e=(this.RTL?1:-1)*this.constants_.DARK_PATH_OFFSET/2,o.notchOffset+e}if(t.blockRendering.Types.isLeftRoundedCorner(e)&&o){if(t.blockRendering.Types.isPreviousConnection(o))return o.notchOffset-this.constants_.CORNER_RADIUS;if(t.blockRendering.Types.isNextConnection(o))return e=(this.RTL?1:-1)*this.constants_.DARK_PATH_OFFSET/2,o.notchOffset-this.constants_.CORNER_RADIUS+e}return t.blockRendering.Types.isField(e)&&o&&t.blockRendering.Types.isField(o)&&e.isEditable==o.isEditable||o&&t.blockRendering.Types.isJaggedEdge(o)?this.constants_.LARGE_PADDING:this.constants_.MEDIUM_PADDING},t.geras.RenderInfo.prototype.getSpacerRowHeight_=function(e,o){return t.blockRendering.Types.isTopRow(e)&&t.blockRendering.Types.isBottomRow(o)?this.constants_.EMPTY_BLOCK_SPACER_HEIGHT:t.blockRendering.Types.isTopRow(e)||t.blockRendering.Types.isBottomRow(o)?this.constants_.NO_PADDING:e.hasExternalInput&&o.hasExternalInput?this.constants_.LARGE_PADDING:!e.hasStatement&&o.hasStatement?this.constants_.BETWEEN_STATEMENT_PADDING_Y:e.hasStatement&&o.hasStatement||!e.hasStatement&&o.hasDummyInput||e.hasDummyInput?this.constants_.LARGE_PADDING:this.constants_.MEDIUM_PADDING},t.geras.RenderInfo.prototype.getElemCenterline_=function(e,o){if(t.blockRendering.Types.isSpacer(o))return e.yPos+o.height/2;if(t.blockRendering.Types.isBottomRow(e))return e=e.yPos+e.height-e.descenderHeight,t.blockRendering.Types.isNextConnection(o)?e+o.height/2:e-o.height/2;if(t.blockRendering.Types.isTopRow(e))return t.blockRendering.Types.isHat(o)?e.capline-o.height/2:e.capline+o.height/2;var i=e.yPos;return t.blockRendering.Types.isField(o)||t.blockRendering.Types.isIcon(o)?(i+=o.height/2,(e.hasInlineInput||e.hasStatement)&&o.height+this.constants_.TALL_INPUT_FIELD_OFFSET_Y<=e.height&&(i+=this.constants_.TALL_INPUT_FIELD_OFFSET_Y)):i=t.blockRendering.Types.isInlineInput(o)?i+o.height/2:i+e.height/2,i},t.geras.RenderInfo.prototype.alignRowElements_=function(){if(this.isInline){for(var e,o=0,i=null,n=this.rows.length-1;e=this.rows[n];n--)e.nextRightEdge=o,t.blockRendering.Types.isInputRow(e)&&(e.hasStatement&&this.alignStatementRow_(e),i&&i.hasStatement&&e.width<i.width?e.nextRightEdge=i.width:o=e.width,i=e);for(n=o=0;e=this.rows[n];n++)e.hasStatement?o=this.getDesiredRowWidth_(e):t.blockRendering.Types.isSpacer(e)?e.width=Math.max(o,e.nextRightEdge):(0<(o=Math.max(o,e.nextRightEdge)-e.width)&&this.addAlignmentPadding_(e,o),o=e.width)}else t.geras.RenderInfo.superClass_.alignRowElements_.call(this)},t.geras.RenderInfo.prototype.getDesiredRowWidth_=function(e){return this.isInline&&e.hasStatement?this.statementEdge+this.constants_.MAX_BOTTOM_WIDTH+this.startX:t.geras.RenderInfo.superClass_.getDesiredRowWidth_.call(this,e)},t.geras.RenderInfo.prototype.finalize_=function(){for(var t,e=0,o=0,i=0;t=this.rows[i];i++){t.yPos=o,t.xPos=this.startX,o+=t.height,e=Math.max(e,t.widthWithConnectedBlocks);var n=o-this.topRow.ascenderHeight;t==this.bottomRow&&n<this.constants_.MIN_BLOCK_HEIGHT&&(n=this.constants_.MIN_BLOCK_HEIGHT-n,this.bottomRow.height+=n,o+=n),this.recordElemPositions_(t)}this.outputConnection&&this.block_.nextConnection&&this.block_.nextConnection.isConnected()&&(e=Math.max(e,this.block_.nextConnection.targetBlock().getHeightWidth().width-this.constants_.DARK_PATH_OFFSET)),this.bottomRow.baseline=o-this.bottomRow.descenderHeight,this.widthWithChildren=e+this.startX+this.constants_.DARK_PATH_OFFSET,this.width+=this.constants_.DARK_PATH_OFFSET,this.height=o+this.constants_.DARK_PATH_OFFSET,this.startY=this.topRow.capline},t.geras.Drawer=function(e,o){t.geras.Drawer.superClass_.constructor.call(this,e,o),this.highlighter_=new t.geras.Highlighter(o)},t.utils.object.inherits(t.geras.Drawer,t.blockRendering.Drawer),t.geras.Drawer.prototype.draw=function(){this.hideHiddenIcons_(),this.drawOutline_(),this.drawInternals_();var e=this.block_.pathObject;e.setPath(this.outlinePath_+"\n"+this.inlinePath_),e.setHighlightPath(this.highlighter_.getPath()),this.info_.RTL&&e.flipRTL(),t.blockRendering.useDebugger&&this.block_.renderingDebugger.drawDebug(this.block_,this.info_),this.recordSizeOnBlock_()},t.geras.Drawer.prototype.drawTop_=function(){this.highlighter_.drawTopCorner(this.info_.topRow),this.highlighter_.drawRightSideRow(this.info_.topRow),t.geras.Drawer.superClass_.drawTop_.call(this)},t.geras.Drawer.prototype.drawJaggedEdge_=function(e){this.highlighter_.drawJaggedEdge_(e),t.geras.Drawer.superClass_.drawJaggedEdge_.call(this,e)},t.geras.Drawer.prototype.drawValueInput_=function(e){this.highlighter_.drawValueInput(e),t.geras.Drawer.superClass_.drawValueInput_.call(this,e)},t.geras.Drawer.prototype.drawStatementInput_=function(e){this.highlighter_.drawStatementInput(e),t.geras.Drawer.superClass_.drawStatementInput_.call(this,e)},t.geras.Drawer.prototype.drawRightSideRow_=function(e){this.highlighter_.drawRightSideRow(e),this.outlinePath_+=t.utils.svgPaths.lineOnAxis("H",e.xPos+e.width)+t.utils.svgPaths.lineOnAxis("V",e.yPos+e.height)},t.geras.Drawer.prototype.drawBottom_=function(){this.highlighter_.drawBottomRow(this.info_.bottomRow),t.geras.Drawer.superClass_.drawBottom_.call(this)},t.geras.Drawer.prototype.drawLeft_=function(){this.highlighter_.drawLeft(),t.geras.Drawer.superClass_.drawLeft_.call(this)},t.geras.Drawer.prototype.drawInlineInput_=function(e){this.highlighter_.drawInlineInput(e),t.geras.Drawer.superClass_.drawInlineInput_.call(this,e)},t.geras.Drawer.prototype.positionInlineInputConnection_=function(t){var e=t.centerline-t.height/2;if(t.connectionModel){var o=t.xPos+t.connectionWidth+this.constants_.DARK_PATH_OFFSET;this.info_.RTL&&(o*=-1),t.connectionModel.setOffsetInBlock(o,e+t.connectionOffsetY+this.constants_.DARK_PATH_OFFSET)}},t.geras.Drawer.prototype.positionStatementInputConnection_=function(t){var e=t.getLastInput();if(e.connectionModel){var o=t.xPos+t.statementEdge+e.notchOffset;o=this.info_.RTL?-1*o:o+this.constants_.DARK_PATH_OFFSET,e.connectionModel.setOffsetInBlock(o,t.yPos+this.constants_.DARK_PATH_OFFSET)}},t.geras.Drawer.prototype.positionExternalValueConnection_=function(t){var e=t.getLastInput();if(e.connectionModel){var o=t.xPos+t.width+this.constants_.DARK_PATH_OFFSET;this.info_.RTL&&(o*=-1),e.connectionModel.setOffsetInBlock(o,t.yPos)}},t.geras.Drawer.prototype.positionNextConnection_=function(){var t=this.info_.bottomRow;if(t.connection){var e=t.connection,o=e.xPos;e.connectionModel.setOffsetInBlock((this.info_.RTL?-o:o)+this.constants_.DARK_PATH_OFFSET/2,t.baseline+this.constants_.DARK_PATH_OFFSET)}},t.geras.HighlightConstantProvider=function(e){this.constantProvider=e,this.OFFSET=.5,this.START_POINT=t.utils.svgPaths.moveBy(this.OFFSET,this.OFFSET)},t.geras.HighlightConstantProvider.prototype.init=function(){this.INSIDE_CORNER=this.makeInsideCorner(),this.OUTSIDE_CORNER=this.makeOutsideCorner(),this.PUZZLE_TAB=this.makePuzzleTab(),this.NOTCH=this.makeNotch(),this.JAGGED_TEETH=this.makeJaggedTeeth(),this.START_HAT=this.makeStartHat()},t.geras.HighlightConstantProvider.prototype.makeInsideCorner=function(){var e=this.constantProvider.CORNER_RADIUS,o=this.OFFSET,i=(1-Math.SQRT1_2)*(e+o)-o,n=t.utils.svgPaths.moveBy(i,i)+t.utils.svgPaths.arc("a","0 0,0",e,t.utils.svgPaths.point(-i-o,e-i)),s=t.utils.svgPaths.arc("a","0 0,0",e+o,t.utils.svgPaths.point(e+o,e+o)),r=t.utils.svgPaths.moveBy(i,-i)+t.utils.svgPaths.arc("a","0 0,0",e+o,t.utils.svgPaths.point(e-i,i+o));return{width:e+o,height:e,pathTop:function(t){return t?n:""},pathBottom:function(t){return t?s:r}}},t.geras.HighlightConstantProvider.prototype.makeOutsideCorner=function(){var e=this.constantProvider.CORNER_RADIUS,o=this.OFFSET,i=(1-Math.SQRT1_2)*(e-o)+o,n=t.utils.svgPaths.moveBy(i,i)+t.utils.svgPaths.arc("a","0 0,1",e-o,t.utils.svgPaths.point(e-i,-i+o)),s=t.utils.svgPaths.moveBy(o,e)+t.utils.svgPaths.arc("a","0 0,1",e-o,t.utils.svgPaths.point(e,-e+o)),r=-i,a=t.utils.svgPaths.moveBy(i,r)+t.utils.svgPaths.arc("a","0 0,1",e-o,t.utils.svgPaths.point(-i+o,-r-e));return{height:e,topLeft:function(t){return t?n:s},bottomLeft:function(){return a}}},t.geras.HighlightConstantProvider.prototype.makePuzzleTab=function(){var e=this.constantProvider.TAB_WIDTH,o=this.constantProvider.TAB_HEIGHT,i=t.utils.svgPaths.moveBy(-2,3.4-o)+t.utils.svgPaths.lineTo(-.45*e,-2.1),n=t.utils.svgPaths.lineOnAxis("v",2.5)+t.utils.svgPaths.moveBy(.97*-e,2.5)+t.utils.svgPaths.curve("q",[t.utils.svgPaths.point(.05*-e,10),t.utils.svgPaths.point(.3*e,9.5)])+t.utils.svgPaths.moveBy(.67*e,-1.9)+t.utils.svgPaths.lineOnAxis("v",2.5),s=t.utils.svgPaths.lineOnAxis("v",-1.5)+t.utils.svgPaths.moveBy(-.92*e,-.5)+t.utils.svgPaths.curve("q",[t.utils.svgPaths.point(-.19*e,-5.5),t.utils.svgPaths.point(0,-11)])+t.utils.svgPaths.moveBy(.92*e,1),r=t.utils.svgPaths.moveBy(-5,o-.7)+t.utils.svgPaths.lineTo(.46*e,-2.1);return{width:e,height:o,pathUp:function(t){return t?i:s},pathDown:function(t){return t?n:r}}},t.geras.HighlightConstantProvider.prototype.makeNotch=function(){return{pathLeft:t.utils.svgPaths.lineOnAxis("h",this.OFFSET)+this.constantProvider.NOTCH.pathLeft}},t.geras.HighlightConstantProvider.prototype.makeJaggedTeeth=function(){return{pathLeft:t.utils.svgPaths.lineTo(5.1,2.6)+t.utils.svgPaths.moveBy(-10.2,6.8)+t.utils.svgPaths.lineTo(5.1,2.6),height:12,width:10.2}},t.geras.HighlightConstantProvider.prototype.makeStartHat=function(){var e=this.constantProvider.START_HAT.height,o=t.utils.svgPaths.moveBy(25,-8.7)+t.utils.svgPaths.curve("c",[t.utils.svgPaths.point(29.7,-6.2),t.utils.svgPaths.point(57.2,-.5),t.utils.svgPaths.point(75,8.7)]),i=t.utils.svgPaths.curve("c",[t.utils.svgPaths.point(17.8,-9.2),t.utils.svgPaths.point(45.3,-14.9),t.utils.svgPaths.point(75,-8.7)])+t.utils.svgPaths.moveTo(100.5,e+.5);return{path:function(t){return t?o:i}}},t.geras.PathObject=function(e,o,i){this.constants=i,this.svgRoot=e,this.svgPathDark=t.utils.dom.createSvgElement("path",{class:"blocklyPathDark",transform:"translate(1,1)"},this.svgRoot),this.svgPath=t.utils.dom.createSvgElement("path",{class:"blocklyPath"},this.svgRoot),this.svgPathLight=t.utils.dom.createSvgElement("path",{class:"blocklyPathLight"},this.svgRoot),this.colourDark="#000000",this.style=o},t.utils.object.inherits(t.geras.PathObject,t.blockRendering.PathObject),t.geras.PathObject.prototype.setPath=function(t){this.svgPath.setAttribute("d",t),this.svgPathDark.setAttribute("d",t)},t.geras.PathObject.prototype.setHighlightPath=function(t){this.svgPathLight.setAttribute("d",t)},t.geras.PathObject.prototype.flipRTL=function(){this.svgPath.setAttribute("transform","scale(-1 1)"),this.svgPathLight.setAttribute("transform","scale(-1 1)"),this.svgPathDark.setAttribute("transform","translate(1,1) scale(-1 1)")},t.geras.PathObject.prototype.applyColour=function(e){this.svgPathLight.style.display="",this.svgPathDark.style.display="",this.svgPathLight.setAttribute("stroke",this.style.colourTertiary),this.svgPathDark.setAttribute("fill",this.colourDark),t.geras.PathObject.superClass_.applyColour.call(this,e),this.svgPath.setAttribute("stroke","none")},t.geras.PathObject.prototype.setStyle=function(e){this.style=e,this.colourDark=t.utils.colour.blend("#000",this.style.colourPrimary,.2)||this.colourDark},t.geras.PathObject.prototype.updateHighlighted=function(t){t?(this.svgPath.setAttribute("filter","url(#"+this.constants.embossFilterId+")"),this.svgPathLight.style.display="none"):(this.svgPath.setAttribute("filter","none"),this.svgPathLight.style.display="inline")},t.geras.PathObject.prototype.updateShadow_=function(t){t&&(this.svgPathLight.style.display="none",this.svgPathDark.setAttribute("fill",this.style.colourSecondary),this.svgPath.setAttribute("stroke","none"),this.svgPath.setAttribute("fill",this.style.colourSecondary))},t.geras.PathObject.prototype.updateDisabled_=function(e){t.geras.PathObject.superClass_.updateDisabled_.call(this,e),e&&this.svgPath.setAttribute("stroke","none")},t.geras.Renderer=function(e){t.geras.Renderer.superClass_.constructor.call(this,e),this.highlightConstants_=null},t.utils.object.inherits(t.geras.Renderer,t.blockRendering.Renderer),t.geras.Renderer.prototype.init=function(e,o){t.geras.Renderer.superClass_.init.call(this,e,o),this.highlightConstants_=this.makeHighlightConstants_(),this.highlightConstants_.init()},t.geras.Renderer.prototype.refreshDom=function(e,o){t.geras.Renderer.superClass_.refreshDom.call(this,e,o),this.getHighlightConstants().init()},t.geras.Renderer.prototype.makeConstants_=function(){return new t.geras.ConstantProvider},t.geras.Renderer.prototype.makeRenderInfo_=function(e){return new t.geras.RenderInfo(this,e)},t.geras.Renderer.prototype.makeDrawer_=function(e,o){return new t.geras.Drawer(e,o)},t.geras.Renderer.prototype.makePathObject=function(e,o){return new t.geras.PathObject(e,o,this.getConstants())},t.geras.Renderer.prototype.makeHighlightConstants_=function(){return new t.geras.HighlightConstantProvider(this.getConstants())},t.geras.Renderer.prototype.getHighlightConstants=function(){return this.highlightConstants_},t.blockRendering.register("geras",t.geras.Renderer),t.thrasos={},t.thrasos.RenderInfo=function(e,o){t.thrasos.RenderInfo.superClass_.constructor.call(this,e,o)},t.utils.object.inherits(t.thrasos.RenderInfo,t.blockRendering.RenderInfo),t.thrasos.RenderInfo.prototype.getRenderer=function(){return this.renderer_},t.thrasos.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;e.elements=[],e.startsWithElemSpacer()&&e.elements.push(new t.blockRendering.InRowSpacer(this.constants_,this.getInRowSpacing_(null,n[0])));for(var s=0;s<n.length-1;s++){e.elements.push(n[s]);var r=this.getInRowSpacing_(n[s],n[s+1]);e.elements.push(new t.blockRendering.InRowSpacer(this.constants_,r))}e.elements.push(n[n.length-1]),e.endsWithElemSpacer()&&(r=this.getInRowSpacing_(n[n.length-1],null),o&&e.hasDummyInput&&(r+=this.constants_.TAB_WIDTH),e.elements.push(new t.blockRendering.InRowSpacer(this.constants_,r)))}},t.thrasos.RenderInfo.prototype.getInRowSpacing_=function(e,o){if(!e)return o&&t.blockRendering.Types.isField(o)&&o.isEditable?this.constants_.MEDIUM_PADDING:o&&t.blockRendering.Types.isInlineInput(o)?this.constants_.MEDIUM_LARGE_PADDING:o&&t.blockRendering.Types.isStatementInput(o)?this.constants_.STATEMENT_INPUT_PADDING_LEFT:this.constants_.LARGE_PADDING;if(!t.blockRendering.Types.isInput(e)&&!o)return t.blockRendering.Types.isField(e)&&e.isEditable?this.constants_.MEDIUM_PADDING:t.blockRendering.Types.isIcon(e)?2*this.constants_.LARGE_PADDING+1:t.blockRendering.Types.isHat(e)?this.constants_.NO_PADDING:t.blockRendering.Types.isPreviousOrNextConnection(e)?this.constants_.LARGE_PADDING:t.blockRendering.Types.isLeftRoundedCorner(e)?this.constants_.MIN_BLOCK_WIDTH:t.blockRendering.Types.isJaggedEdge(e)?this.constants_.NO_PADDING:this.constants_.LARGE_PADDING;if(t.blockRendering.Types.isInput(e)&&!o){if(t.blockRendering.Types.isExternalInput(e))return this.constants_.NO_PADDING;if(t.blockRendering.Types.isInlineInput(e))return this.constants_.LARGE_PADDING;if(t.blockRendering.Types.isStatementInput(e))return this.constants_.NO_PADDING}if(!t.blockRendering.Types.isInput(e)&&o&&t.blockRendering.Types.isInput(o)){if(t.blockRendering.Types.isField(e)&&e.isEditable){if(t.blockRendering.Types.isInlineInput(o)||t.blockRendering.Types.isExternalInput(o))return this.constants_.SMALL_PADDING}else{if(t.blockRendering.Types.isInlineInput(o)||t.blockRendering.Types.isExternalInput(o))return this.constants_.MEDIUM_LARGE_PADDING;if(t.blockRendering.Types.isStatementInput(o))return this.constants_.LARGE_PADDING}return this.constants_.LARGE_PADDING-1}if(t.blockRendering.Types.isIcon(e)&&o&&!t.blockRendering.Types.isInput(o))return this.constants_.LARGE_PADDING;if(t.blockRendering.Types.isInlineInput(e)&&o&&t.blockRendering.Types.isField(o))return o.isEditable?this.constants_.MEDIUM_PADDING:this.constants_.LARGE_PADDING;if(t.blockRendering.Types.isLeftSquareCorner(e)&&o){if(t.blockRendering.Types.isHat(o))return this.constants_.NO_PADDING;if(t.blockRendering.Types.isPreviousConnection(o)||t.blockRendering.Types.isNextConnection(o))return o.notchOffset}return t.blockRendering.Types.isLeftRoundedCorner(e)&&o?o.notchOffset-this.constants_.CORNER_RADIUS:t.blockRendering.Types.isField(e)&&o&&t.blockRendering.Types.isField(o)&&e.isEditable==o.isEditable||o&&t.blockRendering.Types.isJaggedEdge(o)?this.constants_.LARGE_PADDING:this.constants_.MEDIUM_PADDING},t.thrasos.RenderInfo.prototype.getSpacerRowHeight_=function(e,o){return t.blockRendering.Types.isTopRow(e)&&t.blockRendering.Types.isBottomRow(o)?this.constants_.EMPTY_BLOCK_SPACER_HEIGHT:t.blockRendering.Types.isTopRow(e)||t.blockRendering.Types.isBottomRow(o)?this.constants_.NO_PADDING:e.hasExternalInput&&o.hasExternalInput?this.constants_.LARGE_PADDING:!e.hasStatement&&o.hasStatement?this.constants_.BETWEEN_STATEMENT_PADDING_Y:e.hasStatement&&o.hasStatement||e.hasDummyInput||o.hasDummyInput?this.constants_.LARGE_PADDING:this.constants_.MEDIUM_PADDING},t.thrasos.RenderInfo.prototype.getElemCenterline_=function(e,o){if(t.blockRendering.Types.isSpacer(o))return e.yPos+o.height/2;if(t.blockRendering.Types.isBottomRow(e))return e=e.yPos+e.height-e.descenderHeight,t.blockRendering.Types.isNextConnection(o)?e+o.height/2:e-o.height/2;if(t.blockRendering.Types.isTopRow(e))return t.blockRendering.Types.isHat(o)?e.capline-o.height/2:e.capline+o.height/2;var i=e.yPos;return t.blockRendering.Types.isField(o)&&e.hasStatement?i+(this.constants_.TALL_INPUT_FIELD_OFFSET_Y+o.height/2):i+e.height/2},t.thrasos.RenderInfo.prototype.finalize_=function(){for(var t,e=0,o=0,i=0;t=this.rows[i];i++){t.yPos=o,t.xPos=this.startX,o+=t.height,e=Math.max(e,t.widthWithConnectedBlocks);var n=o-this.topRow.ascenderHeight;t==this.bottomRow&&n<this.constants_.MIN_BLOCK_HEIGHT&&(n=this.constants_.MIN_BLOCK_HEIGHT-n,this.bottomRow.height+=n,o+=n),this.recordElemPositions_(t)}this.outputConnection&&this.block_.nextConnection&&this.block_.nextConnection.isConnected()&&(e=Math.max(e,this.block_.nextConnection.targetBlock().getHeightWidth().width)),this.bottomRow.baseline=o-this.bottomRow.descenderHeight,this.widthWithChildren=e+this.startX,this.height=o,this.startY=this.topRow.capline},t.thrasos.Renderer=function(e){t.thrasos.Renderer.superClass_.constructor.call(this,e)},t.utils.object.inherits(t.thrasos.Renderer,t.blockRendering.Renderer),t.thrasos.Renderer.prototype.makeRenderInfo_=function(e){return new t.thrasos.RenderInfo(this,e)},t.blockRendering.register("thrasos",t.thrasos.Renderer),t.zelos={},t.zelos.ConstantProvider=function(){t.zelos.ConstantProvider.superClass_.constructor.call(this),this.SMALL_PADDING=this.GRID_UNIT=4,this.MEDIUM_PADDING=2*this.GRID_UNIT,this.MEDIUM_LARGE_PADDING=3*this.GRID_UNIT,this.LARGE_PADDING=4*this.GRID_UNIT,this.CORNER_RADIUS=1*this.GRID_UNIT,this.NOTCH_WIDTH=9*this.GRID_UNIT,this.NOTCH_HEIGHT=2*this.GRID_UNIT,this.STATEMENT_INPUT_NOTCH_OFFSET=this.NOTCH_OFFSET_LEFT=3*this.GRID_UNIT,this.MIN_BLOCK_WIDTH=2*this.GRID_UNIT,this.MIN_BLOCK_HEIGHT=12*this.GRID_UNIT,this.EMPTY_STATEMENT_INPUT_HEIGHT=6*this.GRID_UNIT,this.TAB_OFFSET_FROM_TOP=0,this.TOP_ROW_MIN_HEIGHT=this.CORNER_RADIUS,this.TOP_ROW_PRECEDES_STATEMENT_MIN_HEIGHT=this.LARGE_PADDING,this.BOTTOM_ROW_MIN_HEIGHT=this.CORNER_RADIUS,this.BOTTOM_ROW_AFTER_STATEMENT_MIN_HEIGHT=6*this.GRID_UNIT,this.STATEMENT_BOTTOM_SPACER=-this.NOTCH_HEIGHT,this.STATEMENT_INPUT_SPACER_MIN_WIDTH=40*this.GRID_UNIT,this.STATEMENT_INPUT_PADDING_LEFT=4*this.GRID_UNIT,this.EMPTY_INLINE_INPUT_PADDING=4*this.GRID_UNIT,this.EMPTY_INLINE_INPUT_HEIGHT=8*this.GRID_UNIT,this.DUMMY_INPUT_MIN_HEIGHT=8*this.GRID_UNIT,this.DUMMY_INPUT_SHADOW_MIN_HEIGHT=6*this.GRID_UNIT,this.CURSOR_WS_WIDTH=20*this.GRID_UNIT,this.CURSOR_COLOUR="#ffa200",this.CURSOR_RADIUS=5,this.JAGGED_TEETH_WIDTH=this.JAGGED_TEETH_HEIGHT=0,this.START_HAT_HEIGHT=22,this.START_HAT_WIDTH=96,this.SHAPES={HEXAGONAL:1,ROUND:2,SQUARE:3,PUZZLE:4,NOTCH:5},this.SHAPE_IN_SHAPE_PADDING={1:{0:5*this.GRID_UNIT,1:2*this.GRID_UNIT,2:5*this.GRID_UNIT,3:5*this.GRID_UNIT},2:{0:3*this.GRID_UNIT,1:3*this.GRID_UNIT,2:1*this.GRID_UNIT,3:2*this.GRID_UNIT},3:{0:2*this.GRID_UNIT,1:2*this.GRID_UNIT,2:2*this.GRID_UNIT,3:2*this.GRID_UNIT}},this.FULL_BLOCK_FIELDS=!0,this.FIELD_TEXT_FONTSIZE=3*this.GRID_UNIT,this.FIELD_TEXT_FONTWEIGHT="bold",this.FIELD_TEXT_FONTFAMILY='"Helvetica Neue", "Segoe UI", Helvetica, sans-serif',this.FIELD_BORDER_RECT_RADIUS=this.CORNER_RADIUS,this.FIELD_BORDER_RECT_X_PADDING=2*this.GRID_UNIT,this.FIELD_BORDER_RECT_Y_PADDING=1.625*this.GRID_UNIT,this.FIELD_BORDER_RECT_HEIGHT=8*this.GRID_UNIT,this.FIELD_DROPDOWN_BORDER_RECT_HEIGHT=8*this.GRID_UNIT,this.FIELD_DROPDOWN_SVG_ARROW=this.FIELD_DROPDOWN_COLOURED_DIV=this.FIELD_DROPDOWN_NO_BORDER_RECT_SHADOW=!0,this.FIELD_DROPDOWN_SVG_ARROW_PADDING=this.FIELD_BORDER_RECT_X_PADDING,this.FIELD_COLOUR_FULL_BLOCK=this.FIELD_TEXTINPUT_BOX_SHADOW=!0,this.FIELD_COLOUR_DEFAULT_WIDTH=2*this.GRID_UNIT,this.FIELD_COLOUR_DEFAULT_HEIGHT=4*this.GRID_UNIT,this.FIELD_CHECKBOX_X_OFFSET=1*this.GRID_UNIT,this.MAX_DYNAMIC_CONNECTION_SHAPE_WIDTH=12*this.GRID_UNIT,this.SELECTED_GLOW_COLOUR="#fff200",this.SELECTED_GLOW_SIZE=.5,this.REPLACEMENT_GLOW_COLOUR="#fff200",this.REPLACEMENT_GLOW_SIZE=2,this.selectedGlowFilterId="",this.selectedGlowFilter_=null,this.replacementGlowFilterId="",this.replacementGlowFilter_=null},t.utils.object.inherits(t.zelos.ConstantProvider,t.blockRendering.ConstantProvider),t.zelos.ConstantProvider.prototype.setFontConstants_=function(e){t.zelos.ConstantProvider.superClass_.setFontConstants_.call(this,e),this.FIELD_DROPDOWN_BORDER_RECT_HEIGHT=this.FIELD_BORDER_RECT_HEIGHT=this.FIELD_TEXT_HEIGHT+2*this.FIELD_BORDER_RECT_Y_PADDING},t.zelos.ConstantProvider.prototype.init=function(){t.zelos.ConstantProvider.superClass_.init.call(this),this.HEXAGONAL=this.makeHexagonal(),this.ROUNDED=this.makeRounded(),this.SQUARED=this.makeSquared(),this.STATEMENT_INPUT_NOTCH_OFFSET=this.NOTCH_OFFSET_LEFT+this.INSIDE_CORNERS.rightWidth},t.zelos.ConstantProvider.prototype.setDynamicProperties_=function(e){t.zelos.ConstantProvider.superClass_.setDynamicProperties_.call(this,e),this.SELECTED_GLOW_COLOUR=e.getComponentStyle("selectedGlowColour")||this.SELECTED_GLOW_COLOUR;var o=Number(e.getComponentStyle("selectedGlowSize"));this.SELECTED_GLOW_SIZE=o&&!isNaN(o)?o:this.SELECTED_GLOW_SIZE,this.REPLACEMENT_GLOW_COLOUR=e.getComponentStyle("replacementGlowColour")||this.REPLACEMENT_GLOW_COLOUR,this.REPLACEMENT_GLOW_SIZE=(e=Number(e.getComponentStyle("replacementGlowSize")))&&!isNaN(e)?e:this.REPLACEMENT_GLOW_SIZE},t.zelos.ConstantProvider.prototype.dispose=function(){t.zelos.ConstantProvider.superClass_.dispose.call(this),this.selectedGlowFilter_&&t.utils.dom.removeNode(this.selectedGlowFilter_),this.replacementGlowFilter_&&t.utils.dom.removeNode(this.replacementGlowFilter_)},t.zelos.ConstantProvider.prototype.makeStartHat=function(){var e=this.START_HAT_HEIGHT,o=this.START_HAT_WIDTH;return{height:e,width:o,path:t.utils.svgPaths.curve("c",[t.utils.svgPaths.point(25,-e),t.utils.svgPaths.point(71,-e),t.utils.svgPaths.point(o,0)])}},t.zelos.ConstantProvider.prototype.makeHexagonal=function(){function e(e,i,n){var s=e/2;return s=s>o?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<o.statementInputCount,this.rightSide=this.outputConnection?new t.zelos.RightConnectionShape(this.constants_):null},t.utils.object.inherits(t.zelos.RenderInfo,t.blockRendering.RenderInfo),t.zelos.RenderInfo.prototype.getRenderer=function(){return this.renderer_},t.zelos.RenderInfo.prototype.measure=function(){this.createRows_(),this.addElemSpacing_(),this.addRowSpacing_(),this.adjustXPosition_(),this.computeBounds_(),this.alignRowElements_(),this.finalize_()},t.zelos.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||this.isMultiRow))},t.zelos.RenderInfo.prototype.getDesiredRowWidth_=function(e){return e.hasStatement?this.width-this.startX-(this.constants_.INSIDE_CORNERS.rightWidth||0):t.zelos.RenderInfo.superClass_.getDesiredRowWidth_.call(this,e)},t.zelos.RenderInfo.prototype.getInRowSpacing_=function(e,o){return e&&o||!this.outputConnection||!this.outputConnection.isDynamicShape||this.hasStatementInput||this.bottomRow.hasNextConnection?!e&&o&&t.blockRendering.Types.isStatementInput(o)?this.constants_.STATEMENT_INPUT_PADDING_LEFT:e&&t.blockRendering.Types.isLeftRoundedCorner(e)&&o&&(t.blockRendering.Types.isPreviousConnection(o)||t.blockRendering.Types.isNextConnection(o))?o.notchOffset-this.constants_.CORNER_RADIUS:e&&t.blockRendering.Types.isLeftSquareCorner(e)&&o&&t.blockRendering.Types.isHat(o)?this.constants_.NO_PADDING:this.constants_.MEDIUM_PADDING:this.constants_.NO_PADDING},t.zelos.RenderInfo.prototype.getSpacerRowHeight_=function(e,o){if(t.blockRendering.Types.isTopRow(e)&&t.blockRendering.Types.isBottomRow(o))return this.constants_.EMPTY_BLOCK_SPACER_HEIGHT;var i=t.blockRendering.Types.isInputRow(e)&&e.hasStatement,n=t.blockRendering.Types.isInputRow(o)&&o.hasStatement;return n||i?(e=Math.max(this.constants_.NOTCH_HEIGHT,this.constants_.INSIDE_CORNERS.rightHeight||0),n&&i?Math.max(e,this.constants_.DUMMY_INPUT_MIN_HEIGHT):e):t.blockRendering.Types.isTopRow(e)?e.hasPreviousConnection||this.outputConnection&&!this.hasStatementInput?this.constants_.NO_PADDING:Math.abs(this.constants_.NOTCH_HEIGHT-this.constants_.CORNER_RADIUS):t.blockRendering.Types.isBottomRow(o)?this.outputConnection?!o.hasNextConnection&&this.hasStatementInput?Math.abs(this.constants_.NOTCH_HEIGHT-this.constants_.CORNER_RADIUS):this.constants_.NO_PADDING:Math.max(this.topRow.minHeight,Math.max(this.constants_.NOTCH_HEIGHT,this.constants_.CORNER_RADIUS))-this.constants_.CORNER_RADIUS:this.constants_.MEDIUM_PADDING},t.zelos.RenderInfo.prototype.getSpacerRowWidth_=function(e,o){var i=this.width-this.startX;return t.blockRendering.Types.isInputRow(e)&&e.hasStatement||t.blockRendering.Types.isInputRow(o)&&o.hasStatement?Math.max(i,this.constants_.STATEMENT_INPUT_SPACER_MIN_WIDTH):i},t.zelos.RenderInfo.prototype.getElemCenterline_=function(e,o){if(e.hasStatement&&!t.blockRendering.Types.isSpacer(o)&&!t.blockRendering.Types.isStatementInput(o))return e.yPos+this.constants_.EMPTY_STATEMENT_INPUT_HEIGHT/2;if(t.blockRendering.Types.isInlineInput(o)){var i=o.connectedBlock;if(i&&i.outputConnection&&i.nextConnection)return e.yPos+i.height/2}return t.zelos.RenderInfo.superClass_.getElemCenterline_.call(this,e,o)},t.zelos.RenderInfo.prototype.addInput_=function(e,o){e.type==t.DUMMY_INPUT&&o.hasDummyInput&&o.align==t.ALIGN_LEFT&&e.align==t.ALIGN_RIGHT&&(o.rightAlignedDummyInput=e),t.zelos.RenderInfo.superClass_.addInput_.call(this,e,o)},t.zelos.RenderInfo.prototype.addAlignmentPadding_=function(e,o){if(e.rightAlignedDummyInput){for(var i,n,s=0;(n=e.elements[s])&&(t.blockRendering.Types.isSpacer(n)&&(i=n),!t.blockRendering.Types.isField(n)||n.parentInput!=e.rightAlignedDummyInput);s++);if(i)return i.width+=o,void(e.width+=o)}t.zelos.RenderInfo.superClass_.addAlignmentPadding_.call(this,e,o)},t.zelos.RenderInfo.prototype.adjustXPosition_=function(){for(var e=this.constants_.NOTCH_OFFSET_LEFT+this.constants_.NOTCH_WIDTH,o=e,i=2;i<this.rows.length-1;i+=2){var n=this.rows[i-1],s=this.rows[i],r=this.rows[i+1];if(n=2==i?!!this.topRow.hasPreviousConnection:!!n.followsStatement,r=i+2>=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))&&r<o)||t.blockRendering.Types.isField(a)&&(a.field instanceof t.FieldLabel||a.field instanceof t.FieldImage)||(n.width+=o-r),r+=a.width}}},t.zelos.RenderInfo.prototype.finalizeOutputConnection_=function(){if(this.outputConnection&&this.outputConnection.isDynamicShape){for(var t,e=0,o=0;t=this.rows[o];o++)t.yPos=e,e+=t.height;this.height=e,o=this.bottomRow.hasNextConnection?this.height-this.bottomRow.descenderHeight:this.height,e=this.outputConnection.shape.height(o),o=this.outputConnection.shape.width(o),this.outputConnection.height=e,this.outputConnection.width=o,this.outputConnection.startX=o,this.outputConnection.connectionOffsetY=this.outputConnection.shape.connectionOffsetY(e),this.outputConnection.connectionOffsetX=this.outputConnection.shape.connectionOffsetX(o),t=0,this.hasStatementInput||this.bottomRow.hasNextConnection||(t=o,this.rightSide.height=e,this.rightSide.width=t,this.rightSide.centerline=e/2,this.rightSide.xPos=this.width+t),this.startX=o,this.width+=o+t,this.widthWithChildren+=o+t}},t.zelos.RenderInfo.prototype.finalizeHorizontalAlignment_=function(){if(this.outputConnection&&!this.hasStatementInput&&!this.bottomRow.hasNextConnection){for(var e,o=0,i=0;e=this.rows[i];i++)if(t.blockRendering.Types.isInputRow(e)){o=e.elements[e.elements.length-2];var n=this.getNegativeSpacing_(e.elements[1]),s=this.getNegativeSpacing_(o);o=n+s;var r=this.constants_.MIN_BLOCK_WIDTH+2*this.outputConnection.width;this.width-o<r&&(n=(o=this.width-r)/2,s=o/2),e.elements.unshift(new t.blockRendering.InRowSpacer(this.constants_,-n)),e.elements.push(new t.blockRendering.InRowSpacer(this.constants_,-s))}if(o)for(this.width-=o,this.widthWithChildren-=o,this.rightSide.xPos-=o,i=0;e=this.rows[i];i++)t.blockRendering.Types.isTopOrBottomRow(e)&&(e.elements[1].width-=o,e.elements[1].widthWithConnectedBlocks-=o),e.width-=o,e.widthWithConnectedBlocks-=o}},t.zelos.RenderInfo.prototype.getNegativeSpacing_=function(e){if(!e)return 0;var o=this.outputConnection.width,i=this.outputConnection.shape.type,n=this.constants_;if(this.isMultiRow&&1<this.inputRows.length)switch(i){case n.SHAPES.ROUND:return i=this.constants_.MAX_DYNAMIC_CONNECTION_SHAPE_WIDTH,o-(i=this.height/2>i?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;e+=2){var o=this.rows[e-1],i=this.rows[e],n=this.rows[e+1],s=2==e,r=e+2>=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<o?t.utils.svgPaths.lineOnAxis("V",e.yPos+o):"")+(e.precedesStatement?this.constants_.INSIDE_CORNERS.pathTopRight:"")}else this.outlinePath_+=t.utils.svgPaths.lineOnAxis("V",e.yPos+e.height)},t.zelos.Drawer.prototype.drawRightDynamicConnection_=function(){this.outlinePath_+=this.info_.outputConnection.shape.pathRightDown(this.info_.outputConnection.height)},t.zelos.Drawer.prototype.drawLeftDynamicConnection_=function(){this.positionOutputConnection_(),this.outlinePath_+=this.info_.outputConnection.shape.pathUp(this.info_.outputConnection.height),this.outlinePath_+="z"},t.zelos.Drawer.prototype.drawFlatTop_=function(){var e=this.info_.topRow;this.positionPreviousConnection_(),this.outlinePath_+=t.utils.svgPaths.moveBy(e.xPos,this.info_.startY),this.outlinePath_+=t.utils.svgPaths.lineOnAxis("h",e.width)},t.zelos.Drawer.prototype.drawFlatBottom_=function(){var e=this.info_.bottomRow;this.positionNextConnection_(),this.outlinePath_+=t.utils.svgPaths.lineOnAxis("V",e.baseline),this.outlinePath_+=t.utils.svgPaths.lineOnAxis("h",-e.width)},t.zelos.Drawer.prototype.drawInlineInput_=function(e){this.positionInlineInputConnection_(e);var o=e.input.name;if(!e.connectedBlock&&!this.info_.isInsertionMarker){var i=e.width-2*e.connectionWidth;e=t.utils.svgPaths.moveTo(e.xPos+e.connectionWidth,e.centerline-e.height/2)+t.utils.svgPaths.lineOnAxis("h",i)+e.shape.pathRightDown(e.height)+t.utils.svgPaths.lineOnAxis("h",-i)+e.shape.pathUp(e.height)+"z",this.block_.pathObject.setOutlinePath(o,e)}},t.zelos.Drawer.prototype.drawStatementInput_=function(e){var o=e.getLastInput(),i=o.xPos+o.notchOffset+o.shape.width,n=o.shape.pathRight+t.utils.svgPaths.lineOnAxis("h",-(o.notchOffset-this.constants_.INSIDE_CORNERS.width))+this.constants_.INSIDE_CORNERS.pathTop,s=e.height-2*this.constants_.INSIDE_CORNERS.height;o=this.constants_.INSIDE_CORNERS.pathBottom+t.utils.svgPaths.lineOnAxis("h",o.notchOffset-this.constants_.INSIDE_CORNERS.width)+(o.connectedBottomNextConnection?"":o.shape.pathLeft),this.outlinePath_+=t.utils.svgPaths.lineOnAxis("H",i)+n+t.utils.svgPaths.lineOnAxis("v",s)+o+t.utils.svgPaths.lineOnAxis("H",e.xPos+e.width),this.positionStatementInputConnection_(e)},t.zelos.PathObject=function(e,o,i){t.zelos.PathObject.superClass_.constructor.call(this,e,o,i),this.constants=i,this.svgPathSelected_=null,this.outlines_={},this.outputShapeType=this.remainingOutlines_=null},t.utils.object.inherits(t.zelos.PathObject,t.blockRendering.PathObject),t.zelos.PathObject.prototype.setPath=function(e){t.zelos.PathObject.superClass_.setPath.call(this,e),this.svgPathSelected_&&this.svgPathSelected_.setAttribute("d",e)},t.zelos.PathObject.prototype.applyColour=function(e){t.zelos.PathObject.superClass_.applyColour.call(this,e),e.isShadow()&&e.getParent()&&this.svgPath.setAttribute("stroke",e.getParent().style.colourTertiary),e=0;for(var o,i=Object.keys(this.outlines_);o=i[e];e++)this.outlines_[o].setAttribute("fill",this.style.colourTertiary)},t.zelos.PathObject.prototype.flipRTL=function(){t.zelos.PathObject.superClass_.flipRTL.call(this);for(var e,o=0,i=Object.keys(this.outlines_);e=i[o];o++)this.outlines_[e].setAttribute("transform","scale(-1 1)")},t.zelos.PathObject.prototype.updateSelected=function(t){this.setClass_("blocklySelected",t),t?this.svgPathSelected_||(this.svgPathSelected_=this.svgPath.cloneNode(!0),this.svgPathSelected_.setAttribute("fill","none"),this.svgPathSelected_.setAttribute("filter","url(#"+this.constants.selectedGlowFilterId+")"),this.svgRoot.appendChild(this.svgPathSelected_)):this.svgPathSelected_&&(this.svgRoot.removeChild(this.svgPathSelected_),this.svgPathSelected_=null)},t.zelos.PathObject.prototype.updateReplacementFade=function(t){this.setClass_("blocklyReplaceable",t),t?this.svgPath.setAttribute("filter","url(#"+this.constants.replacementGlowFilterId+")"):this.svgPath.removeAttribute("filter")},t.zelos.PathObject.prototype.updateShapeForInputHighlight=function(t,e){t=t.getParentInput().name,(t=this.getOutlinePath_(t))&&(e?t.setAttribute("filter","url(#"+this.constants.replacementGlowFilterId+")"):t.removeAttribute("filter"))},t.zelos.PathObject.prototype.beginDrawing=function(){this.remainingOutlines_={};for(var t,e=0,o=Object.keys(this.outlines_);t=o[e];e++)this.remainingOutlines_[t]=1},t.zelos.PathObject.prototype.endDrawing=function(){if(this.remainingOutlines_)for(var t,e=0,o=Object.keys(this.remainingOutlines_);t=o[e];e++)this.removeOutlinePath_(t);this.remainingOutlines_=null},t.zelos.PathObject.prototype.setOutlinePath=function(t,e){(t=this.getOutlinePath_(t)).setAttribute("d",e),t.setAttribute("fill",this.style.colourTertiary)},t.zelos.PathObject.prototype.getOutlinePath_=function(e){return this.outlines_[e]||(this.outlines_[e]=t.utils.dom.createSvgElement("path",{class:"blocklyOutlinePath",d:""},this.svgRoot)),this.remainingOutlines_&&delete this.remainingOutlines_[e],this.outlines_[e]},t.zelos.PathObject.prototype.removeOutlinePath_=function(t){this.outlines_[t].parentNode.removeChild(this.outlines_[t]),delete this.outlines_[t]},t.zelos.MarkerSvg=function(e,o,i){t.zelos.MarkerSvg.superClass_.constructor.call(this,e,o,i)},t.utils.object.inherits(t.zelos.MarkerSvg,t.blockRendering.MarkerSvg),t.zelos.MarkerSvg.prototype.showWithInput_=function(t){var e=t.getSourceBlock();t=t.getLocation().getOffsetInBlock(),this.positionCircle_(t.x,t.y),this.setParent_(e),this.showCurrent_()},t.zelos.MarkerSvg.prototype.showWithBlock_=function(t){var e=(t=t.getLocation()).getHeightWidth();this.positionRect_(0,0,e.width,e.height),this.setParent_(t),this.showCurrent_()},t.zelos.MarkerSvg.prototype.positionCircle_=function(t,e){this.markerCircle_.setAttribute("cx",t),this.markerCircle_.setAttribute("cy",e),this.currentMarkerSvg=this.markerCircle_},t.zelos.MarkerSvg.prototype.showAtLocation_=function(e){var o=!1;e.getType()==t.ASTNode.types.OUTPUT?(this.showWithInput_(e),o=!0):e.getType()==t.ASTNode.types.BLOCK&&(this.showWithBlock_(e),o=!0),o||t.zelos.MarkerSvg.superClass_.showAtLocation_.call(this,e)},t.zelos.MarkerSvg.prototype.hide=function(){t.zelos.MarkerSvg.superClass_.hide.call(this),this.markerCircle_.style.display="none"},t.zelos.MarkerSvg.prototype.createDomInternal_=function(){if(t.zelos.MarkerSvg.superClass_.createDomInternal_.call(this),this.markerCircle_=t.utils.dom.createSvgElement("circle",{r:this.constants_.CURSOR_RADIUS,style:"display: none","stroke-width":this.constants_.CURSOR_STROKE_WIDTH},this.markerSvg_),this.isCursor()){var e=this.getBlinkProperties_();t.utils.dom.createSvgElement("animate",e,this.markerCircle_)}return this.markerSvg_},t.zelos.MarkerSvg.prototype.applyColour_=function(){t.zelos.MarkerSvg.superClass_.applyColour_.call(this),this.markerCircle_.setAttribute("fill",this.colour_),this.markerCircle_.setAttribute("stroke",this.colour_),this.isCursor()&&this.markerCircle_.firstChild.setAttribute("values",this.colour_+";transparent;transparent;")},t.zelos.Renderer=function(e){t.zelos.Renderer.superClass_.constructor.call(this,e)},t.utils.object.inherits(t.zelos.Renderer,t.blockRendering.Renderer),t.zelos.Renderer.prototype.makeConstants_=function(){return new t.zelos.ConstantProvider},t.zelos.Renderer.prototype.makeRenderInfo_=function(e){return new t.zelos.RenderInfo(this,e)},t.zelos.Renderer.prototype.makeDrawer_=function(e,o){return new t.zelos.Drawer(e,o)},t.zelos.Renderer.prototype.makeMarkerDrawer=function(e,o){return new t.zelos.MarkerSvg(e,this.getConstants(),o)},t.zelos.Renderer.prototype.makePathObject=function(e,o){return new t.zelos.PathObject(e,o,this.getConstants())},t.zelos.Renderer.prototype.shouldHighlightConnection=function(e){return e.type!=t.INPUT_VALUE&&e.type!==t.OUTPUT_VALUE},t.zelos.Renderer.prototype.getConnectionPreviewMethod=function(e,o,i){return o.type==t.OUTPUT_VALUE?e.isConnected()?t.InsertionMarkerManager.PREVIEW_TYPE.REPLACEMENT_FADE:t.InsertionMarkerManager.PREVIEW_TYPE.INPUT_OUTLINE:t.zelos.Renderer.superClass_.getConnectionPreviewMethod(e,o,i)},t.blockRendering.register("zelos",t.zelos.Renderer),t.Themes.Dark=t.Theme.defineTheme("dark",{base:t.Themes.Classic,componentStyles:{workspaceBackgroundColour:"#1e1e1e",toolboxBackgroundColour:"#333",toolboxForegroundColour:"#fff",flyoutBackgroundColour:"#252526",flyoutForegroundColour:"#ccc",flyoutOpacity:1,scrollbarColour:"#797979",insertionMarkerColour:"#fff",insertionMarkerOpacity:.3,scrollbarOpacity:.4,cursorColour:"#d0d0d0"}}),t.Themes.Deuteranopia={},t.Themes.Deuteranopia.defaultBlockStyles={colour_blocks:{colourPrimary:"#f2a72c",colourSecondary:"#f1c172",colourTertiary:"#da921c"},list_blocks:{colourPrimary:"#7d65ab",colourSecondary:"#a88be0",colourTertiary:"#66518e"},logic_blocks:{colourPrimary:"#9fd2f1",colourSecondary:"#c0e0f4",colourTertiary:"#74bae5"},loop_blocks:{colourPrimary:"#795a07",colourSecondary:"#ac8726",colourTertiary:"#c4a03f"},math_blocks:{colourPrimary:"#e6da39",colourSecondary:"#f3ec8e",colourTertiary:"#f2eeb7"},procedure_blocks:{colourPrimary:"#590721",colourSecondary:"#8c475d",colourTertiary:"#885464"},text_blocks:{colourPrimary:"#058863",colourSecondary:"#5ecfaf",colourTertiary:"#04684c"},variable_blocks:{colourPrimary:"#47025a",colourSecondary:"#820fa1",colourTertiary:"#8e579d"},variable_dynamic_blocks:{colourPrimary:"#47025a",colourSecondary:"#820fa1",colourTertiary:"#8e579d"}},t.Themes.Deuteranopia.categoryStyles={colour_category:{colour:"#f2a72c"},list_category:{colour:"#7d65ab"},logic_category:{colour:"#9fd2f1"},loop_category:{colour:"#795a07"},math_category:{colour:"#e6da39"},procedure_category:{colour:"#590721"},text_category:{colour:"#058863"},variable_category:{colour:"#47025a"},variable_dynamic_category:{colour:"#47025a"}},t.Themes.Deuteranopia=new t.Theme("deuteranopia",t.Themes.Deuteranopia.defaultBlockStyles,t.Themes.Deuteranopia.categoryStyles),t.Themes.HighContrast={},t.Themes.HighContrast.defaultBlockStyles={colour_blocks:{colourPrimary:"#a52714",colourSecondary:"#FB9B8C",colourTertiary:"#FBE1DD"},list_blocks:{colourPrimary:"#4a148c",colourSecondary:"#AD7BE9",colourTertiary:"#CDB6E9"},logic_blocks:{colourPrimary:"#01579b",colourSecondary:"#64C7FF",colourTertiary:"#C5EAFF"},loop_blocks:{colourPrimary:"#33691e",colourSecondary:"#9AFF78",colourTertiary:"#E1FFD7"},math_blocks:{colourPrimary:"#1a237e",colourSecondary:"#8A9EFF",colourTertiary:"#DCE2FF"},procedure_blocks:{colourPrimary:"#006064",colourSecondary:"#77E6EE",colourTertiary:"#CFECEE"},text_blocks:{colourPrimary:"#004d40",colourSecondary:"#5ae27c",colourTertiary:"#D2FFDD"},variable_blocks:{colourPrimary:"#880e4f",colourSecondary:"#FF73BE",colourTertiary:"#FFD4EB"},variable_dynamic_blocks:{colourPrimary:"#880e4f",colourSecondary:"#FF73BE",colourTertiary:"#FFD4EB"},hat_blocks:{colourPrimary:"#880e4f",colourSecondary:"#FF73BE",colourTertiary:"#FFD4EB",hat:"cap"}},t.Themes.HighContrast.categoryStyles={colour_category:{colour:"#a52714"},list_category:{colour:"#4a148c"},logic_category:{colour:"#01579b"},loop_category:{colour:"#33691e"},math_category:{colour:"#1a237e"},procedure_category:{colour:"#006064"},text_category:{colour:"#004d40"},variable_category:{colour:"#880e4f"},variable_dynamic_category:{colour:"#880e4f"}},t.Themes.HighContrast=new t.Theme("highcontrast",t.Themes.HighContrast.defaultBlockStyles,t.Themes.HighContrast.categoryStyles),t.Themes.HighContrast.setComponentStyle("selectedGlowColour","#000000"),t.Themes.HighContrast.setComponentStyle("selectedGlowSize",1),t.Themes.HighContrast.setComponentStyle("replacementGlowColour","#000000"),t.Themes.HighContrast.setFontStyle({family:null,weight:null,size:16}),t.Themes.Tritanopia={},t.Themes.Tritanopia.defaultBlockStyles={colour_blocks:{colourPrimary:"#05427f",colourSecondary:"#2974c0",colourTertiary:"#2d74bb"},list_blocks:{colourPrimary:"#b69ce8",colourSecondary:"#ccbaef",colourTertiary:"#9176c5"},logic_blocks:{colourPrimary:"#9fd2f1",colourSecondary:"#c0e0f4",colourTertiary:"#74bae5"},loop_blocks:{colourPrimary:"#aa1846",colourSecondary:"#d36185",colourTertiary:"#7c1636"},math_blocks:{colourPrimary:"#e6da39",colourSecondary:"#f3ec8e",colourTertiary:"#f2eeb7"},procedure_blocks:{colourPrimary:"#590721",colourSecondary:"#8c475d",colourTertiary:"#885464"},text_blocks:{colourPrimary:"#058863",colourSecondary:"#5ecfaf",colourTertiary:"#04684c"},variable_blocks:{colourPrimary:"#4b2d84",colourSecondary:"#816ea7",colourTertiary:"#83759e"},variable_dynamic_blocks:{colourPrimary:"#4b2d84",colourSecondary:"#816ea7",colourTertiary:"#83759e"}},t.Themes.Tritanopia.categoryStyles={colour_category:{colour:"#05427f"},list_category:{colour:"#b69ce8"},logic_category:{colour:"#9fd2f1"},loop_category:{colour:"#aa1846"},math_category:{colour:"#e6da39"},procedure_category:{colour:"#590721"},text_category:{colour:"#058863"},variable_category:{colour:"#4b2d84"},variable_dynamic_category:{colour:"#4b2d84"}},t.Themes.Tritanopia=new t.Theme("tritanopia",t.Themes.Tritanopia.defaultBlockStyles,t.Themes.Tritanopia.categoryStyles),t.requires={},t})?i.apply(e,n):i)||(t.exports=s)}).call(this,o(7))},function(t,e){var o;o=function(){return this}();try{o=o||new Function("return this")()}catch(t){"object"==typeof window&&(o=window)}t.exports=o},function(t,e,o){var i,n,s;n=[o(3)],void 0===(s="function"==typeof(i=function(t){return(t={Msg:{}}).Msg.ADD_COMMENT="Add Comment",t.Msg.CANNOT_DELETE_VARIABLE_PROCEDURE="Can't delete the variable '%1' because it's part of the definition of the function '%2'",t.Msg.CHANGE_VALUE_TITLE="Change value:",t.Msg.CLEAN_UP="Clean up Blocks",t.Msg.COLLAPSED_WARNINGS_WARNING="Collapsed blocks contain warnings.",t.Msg.COLLAPSE_ALL="Collapse Blocks",t.Msg.COLLAPSE_BLOCK="Collapse Block",t.Msg.COLOUR_BLEND_COLOUR1="colour 1",t.Msg.COLOUR_BLEND_COLOUR2="colour 2",t.Msg.COLOUR_BLEND_HELPURL="https://meyerweb.com/eric/tools/color-blend/#:::rgbp",t.Msg.COLOUR_BLEND_RATIO="ratio",t.Msg.COLOUR_BLEND_TITLE="blend",t.Msg.COLOUR_BLEND_TOOLTIP="Blends two colours together with a given ratio (0.0 - 1.0).",t.Msg.COLOUR_PICKER_HELPURL="https://en.wikipedia.org/wiki/Color",t.Msg.COLOUR_PICKER_TOOLTIP="Choose a colour from the palette.",t.Msg.COLOUR_RANDOM_HELPURL="http://randomcolour.com",t.Msg.COLOUR_RANDOM_TITLE="random colour",t.Msg.COLOUR_RANDOM_TOOLTIP="Choose a colour at random.",t.Msg.COLOUR_RGB_BLUE="blue",t.Msg.COLOUR_RGB_GREEN="green",t.Msg.COLOUR_RGB_HELPURL="https://www.december.com/html/spec/colorpercompact.html",t.Msg.COLOUR_RGB_RED="red",t.Msg.COLOUR_RGB_TITLE="colour with",t.Msg.COLOUR_RGB_TOOLTIP="Create a colour with the specified amount of red, green, and blue. All values must be between 0 and 100.",t.Msg.CONTROLS_FLOW_STATEMENTS_HELPURL="https://github.com/google/blockly/wiki/Loops#loop-termination-blocks",t.Msg.CONTROLS_FLOW_STATEMENTS_OPERATOR_BREAK="break out of loop",t.Msg.CONTROLS_FLOW_STATEMENTS_OPERATOR_CONTINUE="continue with next iteration of loop",t.Msg.CONTROLS_FLOW_STATEMENTS_TOOLTIP_BREAK="Break out of the containing loop.",t.Msg.CONTROLS_FLOW_STATEMENTS_TOOLTIP_CONTINUE="Skip the rest of this loop, and continue with the next iteration.",t.Msg.CONTROLS_FLOW_STATEMENTS_WARNING="Warning: This block may only be used within a loop.",t.Msg.CONTROLS_FOREACH_HELPURL="https://github.com/google/blockly/wiki/Loops#for-each",t.Msg.CONTROLS_FOREACH_TITLE="for each item %1 in list %2",t.Msg.CONTROLS_FOREACH_TOOLTIP="For each item in a list, set the variable '%1' to the item, and then do some statements.",t.Msg.CONTROLS_FOR_HELPURL="https://github.com/google/blockly/wiki/Loops#count-with",t.Msg.CONTROLS_FOR_TITLE="count with %1 from %2 to %3 by %4",t.Msg.CONTROLS_FOR_TOOLTIP="Have the variable '%1' take on the values from the start number to the end number, counting by the specified interval, and do the specified blocks.",t.Msg.CONTROLS_IF_ELSEIF_TOOLTIP="Add a condition to the if block.",t.Msg.CONTROLS_IF_ELSE_TOOLTIP="Add a final, catch-all condition to the if block.",t.Msg.CONTROLS_IF_HELPURL="https://github.com/google/blockly/wiki/IfElse",t.Msg.CONTROLS_IF_IF_TOOLTIP="Add, remove, or reorder sections to reconfigure this if block.",t.Msg.CONTROLS_IF_MSG_ELSE="else",t.Msg.CONTROLS_IF_MSG_ELSEIF="else if",t.Msg.CONTROLS_IF_MSG_IF="if",t.Msg.CONTROLS_IF_TOOLTIP_1="If a value is true, then do some statements.",t.Msg.CONTROLS_IF_TOOLTIP_2="If a value is true, then do the first block of statements. Otherwise, do the second block of statements.",t.Msg.CONTROLS_IF_TOOLTIP_3="If the first value is true, then do the first block of statements. Otherwise, if the second value is true, do the second block of statements.",t.Msg.CONTROLS_IF_TOOLTIP_4="If the first value is true, then do the first block of statements. Otherwise, if the second value is true, do the second block of statements. If none of the values are true, do the last block of statements.",t.Msg.CONTROLS_REPEAT_HELPURL="https://en.wikipedia.org/wiki/For_loop",t.Msg.CONTROLS_REPEAT_INPUT_DO="do",t.Msg.CONTROLS_REPEAT_TITLE="repeat %1 times",t.Msg.CONTROLS_REPEAT_TOOLTIP="Do some statements several times.",t.Msg.CONTROLS_WHILEUNTIL_HELPURL="https://github.com/google/blockly/wiki/Loops#repeat",t.Msg.CONTROLS_WHILEUNTIL_OPERATOR_UNTIL="repeat until",t.Msg.CONTROLS_WHILEUNTIL_OPERATOR_WHILE="repeat while",t.Msg.CONTROLS_WHILEUNTIL_TOOLTIP_UNTIL="While a value is false, then do some statements.",t.Msg.CONTROLS_WHILEUNTIL_TOOLTIP_WHILE="While a value is true, then do some statements.",t.Msg.DELETE_ALL_BLOCKS="Delete all %1 blocks?",t.Msg.DELETE_BLOCK="Delete Block",t.Msg.DELETE_VARIABLE="Delete the '%1' variable",t.Msg.DELETE_VARIABLE_CONFIRMATION="Delete %1 uses of the '%2' variable?",t.Msg.DELETE_X_BLOCKS="Delete %1 Blocks",t.Msg.DISABLE_BLOCK="Disable Block",t.Msg.DUPLICATE_BLOCK="Duplicate",t.Msg.DUPLICATE_COMMENT="Duplicate Comment",t.Msg.ENABLE_BLOCK="Enable Block",t.Msg.EXPAND_ALL="Expand Blocks",t.Msg.EXPAND_BLOCK="Expand Block",t.Msg.EXTERNAL_INPUTS="External Inputs",t.Msg.HELP="Help",t.Msg.INLINE_INPUTS="Inline Inputs",t.Msg.IOS_CANCEL="Cancel",t.Msg.IOS_ERROR="Error",t.Msg.IOS_OK="OK",t.Msg.IOS_PROCEDURES_ADD_INPUT="+ Add Input",t.Msg.IOS_PROCEDURES_ALLOW_STATEMENTS="Allow statements",t.Msg.IOS_PROCEDURES_DUPLICATE_INPUTS_ERROR="This function has duplicate inputs.",t.Msg.IOS_PROCEDURES_INPUTS="INPUTS",t.Msg.IOS_VARIABLES_ADD_BUTTON="Add",t.Msg.IOS_VARIABLES_ADD_VARIABLE="+ Add Variable",t.Msg.IOS_VARIABLES_DELETE_BUTTON="Delete",t.Msg.IOS_VARIABLES_EMPTY_NAME_ERROR="You can't use an empty variable name.",t.Msg.IOS_VARIABLES_RENAME_BUTTON="Rename",t.Msg.IOS_VARIABLES_VARIABLE_NAME="Variable name",t.Msg.LISTS_CREATE_EMPTY_HELPURL="https://github.com/google/blockly/wiki/Lists#create-empty-list",t.Msg.LISTS_CREATE_EMPTY_TITLE="create empty list",t.Msg.LISTS_CREATE_EMPTY_TOOLTIP="Returns a list, of length 0, containing no data records",t.Msg.LISTS_CREATE_WITH_CONTAINER_TITLE_ADD="list",t.Msg.LISTS_CREATE_WITH_CONTAINER_TOOLTIP="Add, remove, or reorder sections to reconfigure this list block.",t.Msg.LISTS_CREATE_WITH_HELPURL="https://github.com/google/blockly/wiki/Lists#create-list-with",t.Msg.LISTS_CREATE_WITH_INPUT_WITH="create list with",t.Msg.LISTS_CREATE_WITH_ITEM_TOOLTIP="Add an item to the list.",t.Msg.LISTS_CREATE_WITH_TOOLTIP="Create a list with any number of items.",t.Msg.LISTS_GET_INDEX_FIRST="first",t.Msg.LISTS_GET_INDEX_FROM_END="# from end",t.Msg.LISTS_GET_INDEX_FROM_START="#",t.Msg.LISTS_GET_INDEX_GET="get",t.Msg.LISTS_GET_INDEX_GET_REMOVE="get and remove",t.Msg.LISTS_GET_INDEX_LAST="last",t.Msg.LISTS_GET_INDEX_RANDOM="random",t.Msg.LISTS_GET_INDEX_REMOVE="remove",t.Msg.LISTS_GET_INDEX_TAIL="",t.Msg.LISTS_GET_INDEX_TOOLTIP_GET_FIRST="Returns the first item in a list.",t.Msg.LISTS_GET_INDEX_TOOLTIP_GET_FROM="Returns the item at the specified position in a list.",t.Msg.LISTS_GET_INDEX_TOOLTIP_GET_LAST="Returns the last item in a list.",t.Msg.LISTS_GET_INDEX_TOOLTIP_GET_RANDOM="Returns a random item in a list.",t.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_FIRST="Removes and returns the first item in a list.",t.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_FROM="Removes and returns the item at the specified position in a list.",t.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_LAST="Removes and returns the last item in a list.",t.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_RANDOM="Removes and returns a random item in a list.",t.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_FIRST="Removes the first item in a list.",t.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_FROM="Removes the item at the specified position in a list.",t.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_LAST="Removes the last item in a list.",t.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_RANDOM="Removes a random item in a list.",t.Msg.LISTS_GET_SUBLIST_END_FROM_END="to # from end",t.Msg.LISTS_GET_SUBLIST_END_FROM_START="to #",t.Msg.LISTS_GET_SUBLIST_END_LAST="to last",t.Msg.LISTS_GET_SUBLIST_HELPURL="https://github.com/google/blockly/wiki/Lists#getting-a-sublist",t.Msg.LISTS_GET_SUBLIST_START_FIRST="get sub-list from first",t.Msg.LISTS_GET_SUBLIST_START_FROM_END="get sub-list from # from end",t.Msg.LISTS_GET_SUBLIST_START_FROM_START="get sub-list from #",t.Msg.LISTS_GET_SUBLIST_TAIL="",t.Msg.LISTS_GET_SUBLIST_TOOLTIP="Creates a copy of the specified portion of a list.",t.Msg.LISTS_INDEX_FROM_END_TOOLTIP="%1 is the last item.",t.Msg.LISTS_INDEX_FROM_START_TOOLTIP="%1 is the first item.",t.Msg.LISTS_INDEX_OF_FIRST="find first occurrence of item",t.Msg.LISTS_INDEX_OF_HELPURL="https://github.com/google/blockly/wiki/Lists#getting-items-from-a-list",t.Msg.LISTS_INDEX_OF_LAST="find last occurrence of item",t.Msg.LISTS_INDEX_OF_TOOLTIP="Returns the index of the first/last occurrence of the item in the list. Returns %1 if item is not found.",t.Msg.LISTS_INLIST="in list",t.Msg.LISTS_ISEMPTY_HELPURL="https://github.com/google/blockly/wiki/Lists#is-empty",t.Msg.LISTS_ISEMPTY_TITLE="%1 is empty",t.Msg.LISTS_ISEMPTY_TOOLTIP="Returns true if the list is empty.",t.Msg.LISTS_LENGTH_HELPURL="https://github.com/google/blockly/wiki/Lists#length-of",t.Msg.LISTS_LENGTH_TITLE="length of %1",t.Msg.LISTS_LENGTH_TOOLTIP="Returns the length of a list.",t.Msg.LISTS_REPEAT_HELPURL="https://github.com/google/blockly/wiki/Lists#create-list-with",t.Msg.LISTS_REPEAT_TITLE="create list with item %1 repeated %2 times",t.Msg.LISTS_REPEAT_TOOLTIP="Creates a list consisting of the given value repeated the specified number of times.",t.Msg.LISTS_REVERSE_HELPURL="https://github.com/google/blockly/wiki/Lists#reversing-a-list",t.Msg.LISTS_REVERSE_MESSAGE0="reverse %1",t.Msg.LISTS_REVERSE_TOOLTIP="Reverse a copy of a list.",t.Msg.LISTS_SET_INDEX_HELPURL="https://github.com/google/blockly/wiki/Lists#in-list--set",t.Msg.LISTS_SET_INDEX_INPUT_TO="as",t.Msg.LISTS_SET_INDEX_INSERT="insert at",t.Msg.LISTS_SET_INDEX_SET="set",t.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_FIRST="Inserts the item at the start of a list.",t.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_FROM="Inserts the item at the specified position in a list.",t.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_LAST="Append the item to the end of a list.",t.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_RANDOM="Inserts the item randomly in a list.",t.Msg.LISTS_SET_INDEX_TOOLTIP_SET_FIRST="Sets the first item in a list.",t.Msg.LISTS_SET_INDEX_TOOLTIP_SET_FROM="Sets the item at the specified position in a list.",t.Msg.LISTS_SET_INDEX_TOOLTIP_SET_LAST="Sets the last item in a list.",t.Msg.LISTS_SET_INDEX_TOOLTIP_SET_RANDOM="Sets a random item in a list.",t.Msg.LISTS_SORT_HELPURL="https://github.com/google/blockly/wiki/Lists#sorting-a-list",t.Msg.LISTS_SORT_ORDER_ASCENDING="ascending",t.Msg.LISTS_SORT_ORDER_DESCENDING="descending",t.Msg.LISTS_SORT_TITLE="sort %1 %2 %3",t.Msg.LISTS_SORT_TOOLTIP="Sort a copy of a list.",t.Msg.LISTS_SORT_TYPE_IGNORECASE="alphabetic, ignore case",t.Msg.LISTS_SORT_TYPE_NUMERIC="numeric",t.Msg.LISTS_SORT_TYPE_TEXT="alphabetic",t.Msg.LISTS_SPLIT_HELPURL="https://github.com/google/blockly/wiki/Lists#splitting-strings-and-joining-lists",t.Msg.LISTS_SPLIT_LIST_FROM_TEXT="make list from text",t.Msg.LISTS_SPLIT_TEXT_FROM_LIST="make text from list",t.Msg.LISTS_SPLIT_TOOLTIP_JOIN="Join a list of texts into one text, separated by a delimiter.",t.Msg.LISTS_SPLIT_TOOLTIP_SPLIT="Split text into a list of texts, breaking at each delimiter.",t.Msg.LISTS_SPLIT_WITH_DELIMITER="with delimiter",t.Msg.LOGIC_BOOLEAN_FALSE="false",t.Msg.LOGIC_BOOLEAN_HELPURL="https://github.com/google/blockly/wiki/Logic#values",t.Msg.LOGIC_BOOLEAN_TOOLTIP="Returns either true or false.",t.Msg.LOGIC_BOOLEAN_TRUE="true",t.Msg.LOGIC_COMPARE_HELPURL="https://en.wikipedia.org/wiki/Inequality_(mathematics)",t.Msg.LOGIC_COMPARE_TOOLTIP_EQ="Return true if both inputs equal each other.",t.Msg.LOGIC_COMPARE_TOOLTIP_GT="Return true if the first input is greater than the second input.",t.Msg.LOGIC_COMPARE_TOOLTIP_GTE="Return true if the first input is greater than or equal to the second input.",t.Msg.LOGIC_COMPARE_TOOLTIP_LT="Return true if the first input is smaller than the second input.",t.Msg.LOGIC_COMPARE_TOOLTIP_LTE="Return true if the first input is smaller than or equal to the second input.",t.Msg.LOGIC_COMPARE_TOOLTIP_NEQ="Return true if both inputs are not equal to each other.",t.Msg.LOGIC_NEGATE_HELPURL="https://github.com/google/blockly/wiki/Logic#not",t.Msg.LOGIC_NEGATE_TITLE="not %1",t.Msg.LOGIC_NEGATE_TOOLTIP="Returns true if the input is false. Returns false if the input is true.",t.Msg.LOGIC_NULL="null",t.Msg.LOGIC_NULL_HELPURL="https://en.wikipedia.org/wiki/Nullable_type",t.Msg.LOGIC_NULL_TOOLTIP="Returns null.",t.Msg.LOGIC_OPERATION_AND="and",t.Msg.LOGIC_OPERATION_HELPURL="https://github.com/google/blockly/wiki/Logic#logical-operations",t.Msg.LOGIC_OPERATION_OR="or",t.Msg.LOGIC_OPERATION_TOOLTIP_AND="Return true if both inputs are true.",t.Msg.LOGIC_OPERATION_TOOLTIP_OR="Return true if at least one of the inputs is true.",t.Msg.LOGIC_TERNARY_CONDITION="test",t.Msg.LOGIC_TERNARY_HELPURL="https://en.wikipedia.org/wiki/%3F:",t.Msg.LOGIC_TERNARY_IF_FALSE="if false",t.Msg.LOGIC_TERNARY_IF_TRUE="if true",t.Msg.LOGIC_TERNARY_TOOLTIP="Check the condition in 'test'. If the condition is true, returns the 'if true' value; otherwise returns the 'if false' value.",t.Msg.MATH_ADDITION_SYMBOL="+",t.Msg.MATH_ARITHMETIC_HELPURL="https://en.wikipedia.org/wiki/Arithmetic",t.Msg.MATH_ARITHMETIC_TOOLTIP_ADD="Return the sum of the two numbers.",t.Msg.MATH_ARITHMETIC_TOOLTIP_DIVIDE="Return the quotient of the two numbers.",t.Msg.MATH_ARITHMETIC_TOOLTIP_MINUS="Return the difference of the two numbers.",t.Msg.MATH_ARITHMETIC_TOOLTIP_MULTIPLY="Return the product of the two numbers.",t.Msg.MATH_ARITHMETIC_TOOLTIP_POWER="Return the first number raised to the power of the second number.",t.Msg.MATH_ATAN2_HELPURL="https://en.wikipedia.org/wiki/Atan2",t.Msg.MATH_ATAN2_TITLE="atan2 of X:%1 Y:%2",t.Msg.MATH_ATAN2_TOOLTIP="Return the arctangent of point (X, Y) in degrees from -180 to 180.",t.Msg.MATH_CHANGE_HELPURL="https://en.wikipedia.org/wiki/Programming_idiom#Incrementing_a_counter",t.Msg.MATH_CHANGE_TITLE="change %1 by %2",t.Msg.MATH_CHANGE_TOOLTIP="Add a number to variable '%1'.",t.Msg.MATH_CONSTANT_HELPURL="https://en.wikipedia.org/wiki/Mathematical_constant",t.Msg.MATH_CONSTANT_TOOLTIP="Return one of the common constants: π (3.141…), e (2.718…), φ (1.618…), sqrt(2) (1.414…), sqrt(½) (0.707…), or ∞ (infinity).",t.Msg.MATH_CONSTRAIN_HELPURL="https://en.wikipedia.org/wiki/Clamping_(graphics)",t.Msg.MATH_CONSTRAIN_TITLE="constrain %1 low %2 high %3",t.Msg.MATH_CONSTRAIN_TOOLTIP="Constrain a number to be between the specified limits (inclusive).",t.Msg.MATH_DIVISION_SYMBOL="÷",t.Msg.MATH_IS_DIVISIBLE_BY="is divisible by",t.Msg.MATH_IS_EVEN="is even",t.Msg.MATH_IS_NEGATIVE="is negative",t.Msg.MATH_IS_ODD="is odd",t.Msg.MATH_IS_POSITIVE="is positive",t.Msg.MATH_IS_PRIME="is prime",t.Msg.MATH_IS_TOOLTIP="Check if a number is an even, odd, prime, whole, positive, negative, or if it is divisible by certain number. Returns true or false.",t.Msg.MATH_IS_WHOLE="is whole",t.Msg.MATH_MODULO_HELPURL="https://en.wikipedia.org/wiki/Modulo_operation",t.Msg.MATH_MODULO_TITLE="remainder of %1 ÷ %2",t.Msg.MATH_MODULO_TOOLTIP="Return the remainder from dividing the two numbers.",t.Msg.MATH_MULTIPLICATION_SYMBOL="×",t.Msg.MATH_NUMBER_HELPURL="https://en.wikipedia.org/wiki/Number",t.Msg.MATH_NUMBER_TOOLTIP="A number.",t.Msg.MATH_ONLIST_HELPURL="",t.Msg.MATH_ONLIST_OPERATOR_AVERAGE="average of list",t.Msg.MATH_ONLIST_OPERATOR_MAX="max of list",t.Msg.MATH_ONLIST_OPERATOR_MEDIAN="median of list",t.Msg.MATH_ONLIST_OPERATOR_MIN="min of list",t.Msg.MATH_ONLIST_OPERATOR_MODE="modes of list",t.Msg.MATH_ONLIST_OPERATOR_RANDOM="random item of list",t.Msg.MATH_ONLIST_OPERATOR_STD_DEV="standard deviation of list",t.Msg.MATH_ONLIST_OPERATOR_SUM="sum of list",t.Msg.MATH_ONLIST_TOOLTIP_AVERAGE="Return the average (arithmetic mean) of the numeric values in the list.",t.Msg.MATH_ONLIST_TOOLTIP_MAX="Return the largest number in the list.",t.Msg.MATH_ONLIST_TOOLTIP_MEDIAN="Return the median number in the list.",t.Msg.MATH_ONLIST_TOOLTIP_MIN="Return the smallest number in the list.",t.Msg.MATH_ONLIST_TOOLTIP_MODE="Return a list of the most common item(s) in the list.",t.Msg.MATH_ONLIST_TOOLTIP_RANDOM="Return a random element from the list.",t.Msg.MATH_ONLIST_TOOLTIP_STD_DEV="Return the standard deviation of the list.",t.Msg.MATH_ONLIST_TOOLTIP_SUM="Return the sum of all the numbers in the list.",t.Msg.MATH_POWER_SYMBOL="^",t.Msg.MATH_RANDOM_FLOAT_HELPURL="https://en.wikipedia.org/wiki/Random_number_generation",t.Msg.MATH_RANDOM_FLOAT_TITLE_RANDOM="random fraction",t.Msg.MATH_RANDOM_FLOAT_TOOLTIP="Return a random fraction between 0.0 (inclusive) and 1.0 (exclusive).",t.Msg.MATH_RANDOM_INT_HELPURL="https://en.wikipedia.org/wiki/Random_number_generation",t.Msg.MATH_RANDOM_INT_TITLE="random integer from %1 to %2",t.Msg.MATH_RANDOM_INT_TOOLTIP="Return a random integer between the two specified limits, inclusive.",t.Msg.MATH_ROUND_HELPURL="https://en.wikipedia.org/wiki/Rounding",t.Msg.MATH_ROUND_OPERATOR_ROUND="round",t.Msg.MATH_ROUND_OPERATOR_ROUNDDOWN="round down",t.Msg.MATH_ROUND_OPERATOR_ROUNDUP="round up",t.Msg.MATH_ROUND_TOOLTIP="Round a number up or down.",t.Msg.MATH_SINGLE_HELPURL="https://en.wikipedia.org/wiki/Square_root",t.Msg.MATH_SINGLE_OP_ABSOLUTE="absolute",t.Msg.MATH_SINGLE_OP_ROOT="square root",t.Msg.MATH_SINGLE_TOOLTIP_ABS="Return the absolute value of a number.",t.Msg.MATH_SINGLE_TOOLTIP_EXP="Return e to the power of a number.",t.Msg.MATH_SINGLE_TOOLTIP_LN="Return the natural logarithm of a number.",t.Msg.MATH_SINGLE_TOOLTIP_LOG10="Return the base 10 logarithm of a number.",t.Msg.MATH_SINGLE_TOOLTIP_NEG="Return the negation of a number.",t.Msg.MATH_SINGLE_TOOLTIP_POW10="Return 10 to the power of a number.",t.Msg.MATH_SINGLE_TOOLTIP_ROOT="Return the square root of a number.",t.Msg.MATH_SUBTRACTION_SYMBOL="-",t.Msg.MATH_TRIG_ACOS="acos",t.Msg.MATH_TRIG_ASIN="asin",t.Msg.MATH_TRIG_ATAN="atan",t.Msg.MATH_TRIG_COS="cos",t.Msg.MATH_TRIG_HELPURL="https://en.wikipedia.org/wiki/Trigonometric_functions",t.Msg.MATH_TRIG_SIN="sin",t.Msg.MATH_TRIG_TAN="tan",t.Msg.MATH_TRIG_TOOLTIP_ACOS="Return the arccosine of a number.",t.Msg.MATH_TRIG_TOOLTIP_ASIN="Return the arcsine of a number.",t.Msg.MATH_TRIG_TOOLTIP_ATAN="Return the arctangent of a number.",t.Msg.MATH_TRIG_TOOLTIP_COS="Return the cosine of a degree (not radian).",t.Msg.MATH_TRIG_TOOLTIP_SIN="Return the sine of a degree (not radian).",t.Msg.MATH_TRIG_TOOLTIP_TAN="Return the tangent of a degree (not radian).",t.Msg.NEW_COLOUR_VARIABLE="Create colour variable...",t.Msg.NEW_NUMBER_VARIABLE="Create number variable...",t.Msg.NEW_STRING_VARIABLE="Create string variable...",t.Msg.NEW_VARIABLE="Create variable...",t.Msg.NEW_VARIABLE_TITLE="New variable name:",t.Msg.NEW_VARIABLE_TYPE_TITLE="New variable type:",t.Msg.ORDINAL_NUMBER_SUFFIX="",t.Msg.PROCEDURES_ALLOW_STATEMENTS="allow statements",t.Msg.PROCEDURES_BEFORE_PARAMS="with:",t.Msg.PROCEDURES_CALLNORETURN_HELPURL="https://en.wikipedia.org/wiki/Subroutine",t.Msg.PROCEDURES_CALLNORETURN_TOOLTIP="Run the user-defined function '%1'.",t.Msg.PROCEDURES_CALLRETURN_HELPURL="https://en.wikipedia.org/wiki/Subroutine",t.Msg.PROCEDURES_CALLRETURN_TOOLTIP="Run the user-defined function '%1' and use its output.",t.Msg.PROCEDURES_CALL_BEFORE_PARAMS="with:",t.Msg.PROCEDURES_CREATE_DO="Create '%1'",t.Msg.PROCEDURES_DEFNORETURN_COMMENT="Describe this function...",t.Msg.PROCEDURES_DEFNORETURN_DO="",t.Msg.PROCEDURES_DEFNORETURN_HELPURL="https://en.wikipedia.org/wiki/Subroutine",t.Msg.PROCEDURES_DEFNORETURN_PROCEDURE="do something",t.Msg.PROCEDURES_DEFNORETURN_TITLE="to",t.Msg.PROCEDURES_DEFNORETURN_TOOLTIP="Creates a function with no output.",t.Msg.PROCEDURES_DEFRETURN_HELPURL="https://en.wikipedia.org/wiki/Subroutine",t.Msg.PROCEDURES_DEFRETURN_RETURN="return",t.Msg.PROCEDURES_DEFRETURN_TOOLTIP="Creates a function with an output.",t.Msg.PROCEDURES_DEF_DUPLICATE_WARNING="Warning: This function has duplicate parameters.",t.Msg.PROCEDURES_HIGHLIGHT_DEF="Highlight function definition",t.Msg.PROCEDURES_IFRETURN_HELPURL="http://c2.com/cgi/wiki?GuardClause",t.Msg.PROCEDURES_IFRETURN_TOOLTIP="If a value is true, then return a second value.",t.Msg.PROCEDURES_IFRETURN_WARNING="Warning: This block may be used only within a function definition.",t.Msg.PROCEDURES_MUTATORARG_TITLE="input name:",t.Msg.PROCEDURES_MUTATORARG_TOOLTIP="Add an input to the function.",t.Msg.PROCEDURES_MUTATORCONTAINER_TITLE="inputs",t.Msg.PROCEDURES_MUTATORCONTAINER_TOOLTIP="Add, remove, or reorder inputs to this function.",t.Msg.REDO="Redo",t.Msg.REMOVE_COMMENT="Remove Comment",t.Msg.RENAME_VARIABLE="Rename variable...",t.Msg.RENAME_VARIABLE_TITLE="Rename all '%1' variables to:",t.Msg.TEXT_APPEND_HELPURL="https://github.com/google/blockly/wiki/Text#text-modification",t.Msg.TEXT_APPEND_TITLE="to %1 append text %2",t.Msg.TEXT_APPEND_TOOLTIP="Append some text to variable '%1'.",t.Msg.TEXT_CHANGECASE_HELPURL="https://github.com/google/blockly/wiki/Text#adjusting-text-case",t.Msg.TEXT_CHANGECASE_OPERATOR_LOWERCASE="to lower case",t.Msg.TEXT_CHANGECASE_OPERATOR_TITLECASE="to Title Case",t.Msg.TEXT_CHANGECASE_OPERATOR_UPPERCASE="to UPPER CASE",t.Msg.TEXT_CHANGECASE_TOOLTIP="Return a copy of the text in a different case.",t.Msg.TEXT_CHARAT_FIRST="get first letter",t.Msg.TEXT_CHARAT_FROM_END="get letter # from end",t.Msg.TEXT_CHARAT_FROM_START="get letter #",t.Msg.TEXT_CHARAT_HELPURL="https://github.com/google/blockly/wiki/Text#extracting-text",t.Msg.TEXT_CHARAT_LAST="get last letter",t.Msg.TEXT_CHARAT_RANDOM="get random letter",t.Msg.TEXT_CHARAT_TAIL="",t.Msg.TEXT_CHARAT_TITLE="in text %1 %2",t.Msg.TEXT_CHARAT_TOOLTIP="Returns the letter at the specified position.",t.Msg.TEXT_COUNT_HELPURL="https://github.com/google/blockly/wiki/Text#counting-substrings",t.Msg.TEXT_COUNT_MESSAGE0="count %1 in %2",t.Msg.TEXT_COUNT_TOOLTIP="Count how many times some text occurs within some other text.",t.Msg.TEXT_CREATE_JOIN_ITEM_TOOLTIP="Add an item to the text.",t.Msg.TEXT_CREATE_JOIN_TITLE_JOIN="join",t.Msg.TEXT_CREATE_JOIN_TOOLTIP="Add, remove, or reorder sections to reconfigure this text block.",t.Msg.TEXT_GET_SUBSTRING_END_FROM_END="to letter # from end",t.Msg.TEXT_GET_SUBSTRING_END_FROM_START="to letter #",t.Msg.TEXT_GET_SUBSTRING_END_LAST="to last letter",t.Msg.TEXT_GET_SUBSTRING_HELPURL="https://github.com/google/blockly/wiki/Text#extracting-a-region-of-text",t.Msg.TEXT_GET_SUBSTRING_INPUT_IN_TEXT="in text",t.Msg.TEXT_GET_SUBSTRING_START_FIRST="get substring from first letter",t.Msg.TEXT_GET_SUBSTRING_START_FROM_END="get substring from letter # from end",t.Msg.TEXT_GET_SUBSTRING_START_FROM_START="get substring from letter #",t.Msg.TEXT_GET_SUBSTRING_TAIL="",t.Msg.TEXT_GET_SUBSTRING_TOOLTIP="Returns a specified portion of the text.",t.Msg.TEXT_INDEXOF_HELPURL="https://github.com/google/blockly/wiki/Text#finding-text",t.Msg.TEXT_INDEXOF_OPERATOR_FIRST="find first occurrence of text",t.Msg.TEXT_INDEXOF_OPERATOR_LAST="find last occurrence of text",t.Msg.TEXT_INDEXOF_TITLE="in text %1 %2 %3",t.Msg.TEXT_INDEXOF_TOOLTIP="Returns the index of the first/last occurrence of the first text in the second text. Returns %1 if text is not found.",t.Msg.TEXT_ISEMPTY_HELPURL="https://github.com/google/blockly/wiki/Text#checking-for-empty-text",t.Msg.TEXT_ISEMPTY_TITLE="%1 is empty",t.Msg.TEXT_ISEMPTY_TOOLTIP="Returns true if the provided text is empty.",t.Msg.TEXT_JOIN_HELPURL="https://github.com/google/blockly/wiki/Text#text-creation",t.Msg.TEXT_JOIN_TITLE_CREATEWITH="create text with",t.Msg.TEXT_JOIN_TOOLTIP="Create a piece of text by joining together any number of items.",t.Msg.TEXT_LENGTH_HELPURL="https://github.com/google/blockly/wiki/Text#text-modification",t.Msg.TEXT_LENGTH_TITLE="length of %1",t.Msg.TEXT_LENGTH_TOOLTIP="Returns the number of letters (including spaces) in the provided text.",t.Msg.TEXT_PRINT_HELPURL="https://github.com/google/blockly/wiki/Text#printing-text",t.Msg.TEXT_PRINT_TITLE="print %1",t.Msg.TEXT_PRINT_TOOLTIP="Print the specified text, number or other value.",t.Msg.TEXT_PROMPT_HELPURL="https://github.com/google/blockly/wiki/Text#getting-input-from-the-user",t.Msg.TEXT_PROMPT_TOOLTIP_NUMBER="Prompt for user for a number.",t.Msg.TEXT_PROMPT_TOOLTIP_TEXT="Prompt for user for some text.",t.Msg.TEXT_PROMPT_TYPE_NUMBER="prompt for number with message",t.Msg.TEXT_PROMPT_TYPE_TEXT="prompt for text with message",t.Msg.TEXT_REPLACE_HELPURL="https://github.com/google/blockly/wiki/Text#replacing-substrings",t.Msg.TEXT_REPLACE_MESSAGE0="replace %1 with %2 in %3",t.Msg.TEXT_REPLACE_TOOLTIP="Replace all occurances of some text within some other text.",t.Msg.TEXT_REVERSE_HELPURL="https://github.com/google/blockly/wiki/Text#reversing-text",t.Msg.TEXT_REVERSE_MESSAGE0="reverse %1",t.Msg.TEXT_REVERSE_TOOLTIP="Reverses the order of the characters in the text.",t.Msg.TEXT_TEXT_HELPURL="https://en.wikipedia.org/wiki/String_(computer_science)",t.Msg.TEXT_TEXT_TOOLTIP="A letter, word, or line of text.",t.Msg.TEXT_TRIM_HELPURL="https://github.com/google/blockly/wiki/Text#trimming-removing-spaces",t.Msg.TEXT_TRIM_OPERATOR_BOTH="trim spaces from both sides of",t.Msg.TEXT_TRIM_OPERATOR_LEFT="trim spaces from left side of",t.Msg.TEXT_TRIM_OPERATOR_RIGHT="trim spaces from right side of",t.Msg.TEXT_TRIM_TOOLTIP="Return a copy of the text with spaces removed from one or both ends.",t.Msg.TODAY="Today",t.Msg.UNDO="Undo",t.Msg.UNNAMED_KEY="unnamed",t.Msg.VARIABLES_DEFAULT_NAME="item",t.Msg.VARIABLES_GET_CREATE_SET="Create 'set %1'",t.Msg.VARIABLES_GET_HELPURL="https://github.com/google/blockly/wiki/Variables#get",t.Msg.VARIABLES_GET_TOOLTIP="Returns the value of this variable.",t.Msg.VARIABLES_SET="set %1 to %2",t.Msg.VARIABLES_SET_CREATE_GET="Create 'get %1'",t.Msg.VARIABLES_SET_HELPURL="https://github.com/google/blockly/wiki/Variables#set",t.Msg.VARIABLES_SET_TOOLTIP="Sets this variable to be equal to the input.",t.Msg.VARIABLE_ALREADY_EXISTS="A variable named '%1' already exists.",t.Msg.VARIABLE_ALREADY_EXISTS_FOR_ANOTHER_TYPE="A variable named '%1' already exists for another type: '%2'.",t.Msg.WORKSPACE_ARIA_LABEL="Blockly Workspace",t.Msg.WORKSPACE_COMMENT_DEFAULT_TEXT="Say something...",t.Msg.CONTROLS_FOREACH_INPUT_DO=t.Msg.CONTROLS_REPEAT_INPUT_DO,t.Msg.CONTROLS_FOR_INPUT_DO=t.Msg.CONTROLS_REPEAT_INPUT_DO,t.Msg.CONTROLS_IF_ELSEIF_TITLE_ELSEIF=t.Msg.CONTROLS_IF_MSG_ELSEIF,t.Msg.CONTROLS_IF_ELSE_TITLE_ELSE=t.Msg.CONTROLS_IF_MSG_ELSE,t.Msg.CONTROLS_IF_IF_TITLE_IF=t.Msg.CONTROLS_IF_MSG_IF,t.Msg.CONTROLS_IF_MSG_THEN=t.Msg.CONTROLS_REPEAT_INPUT_DO,t.Msg.CONTROLS_WHILEUNTIL_INPUT_DO=t.Msg.CONTROLS_REPEAT_INPUT_DO,t.Msg.LISTS_CREATE_WITH_ITEM_TITLE=t.Msg.VARIABLES_DEFAULT_NAME,t.Msg.LISTS_GET_INDEX_HELPURL=t.Msg.LISTS_INDEX_OF_HELPURL,t.Msg.LISTS_GET_INDEX_INPUT_IN_LIST=t.Msg.LISTS_INLIST,t.Msg.LISTS_GET_SUBLIST_INPUT_IN_LIST=t.Msg.LISTS_INLIST,t.Msg.LISTS_INDEX_OF_INPUT_IN_LIST=t.Msg.LISTS_INLIST,t.Msg.LISTS_SET_INDEX_INPUT_IN_LIST=t.Msg.LISTS_INLIST,t.Msg.MATH_CHANGE_TITLE_ITEM=t.Msg.VARIABLES_DEFAULT_NAME,t.Msg.PROCEDURES_DEFRETURN_COMMENT=t.Msg.PROCEDURES_DEFNORETURN_COMMENT,t.Msg.PROCEDURES_DEFRETURN_DO=t.Msg.PROCEDURES_DEFNORETURN_DO,t.Msg.PROCEDURES_DEFRETURN_PROCEDURE=t.Msg.PROCEDURES_DEFNORETURN_PROCEDURE,t.Msg.PROCEDURES_DEFRETURN_TITLE=t.Msg.PROCEDURES_DEFNORETURN_TITLE,t.Msg.TEXT_APPEND_VARIABLE=t.Msg.VARIABLES_DEFAULT_NAME,t.Msg.TEXT_CREATE_JOIN_ITEM_TITLE_ITEM=t.Msg.VARIABLES_DEFAULT_NAME,t.Msg.MATH_HUE="230",t.Msg.LOOPS_HUE="120",t.Msg.LISTS_HUE="260",t.Msg.LOGIC_HUE="210",t.Msg.VARIABLES_HUE="330",t.Msg.TEXTS_HUE="160",t.Msg.PROCEDURES_HUE="290",t.Msg.COLOUR_HUE="20",t.Msg.VARIABLES_DYNAMIC_HUE="310",t.Msg})?i.apply(e,n):i)||(t.exports=s)},function(t,e,o){var i,n,s;n=[o(3)],void 0===(s="function"==typeof(i=function(t){return t.Blocks={},t.Blocks.colour={},t.Constants={},t.Constants.Colour={},t.Constants.Colour.HUE=20,t.defineBlocksWithJsonArray([{type:"colour_picker",message0:"%1",args0:[{type:"field_colour",name:"COLOUR",colour:"#ff0000"}],output:"Colour",helpUrl:"%{BKY_COLOUR_PICKER_HELPURL}",style:"colour_blocks",tooltip:"%{BKY_COLOUR_PICKER_TOOLTIP}",extensions:["parent_tooltip_when_inline"]},{type:"colour_random",message0:"%{BKY_COLOUR_RANDOM_TITLE}",output:"Colour",helpUrl:"%{BKY_COLOUR_RANDOM_HELPURL}",style:"colour_blocks",tooltip:"%{BKY_COLOUR_RANDOM_TOOLTIP}"},{type:"colour_rgb",message0:"%{BKY_COLOUR_RGB_TITLE} %{BKY_COLOUR_RGB_RED} %1 %{BKY_COLOUR_RGB_GREEN} %2 %{BKY_COLOUR_RGB_BLUE} %3",args0:[{type:"input_value",name:"RED",check:"Number",align:"RIGHT"},{type:"input_value",name:"GREEN",check:"Number",align:"RIGHT"},{type:"input_value",name:"BLUE",check:"Number",align:"RIGHT"}],output:"Colour",helpUrl:"%{BKY_COLOUR_RGB_HELPURL}",style:"colour_blocks",tooltip:"%{BKY_COLOUR_RGB_TOOLTIP}"},{type:"colour_blend",message0:"%{BKY_COLOUR_BLEND_TITLE} %{BKY_COLOUR_BLEND_COLOUR1} %1 %{BKY_COLOUR_BLEND_COLOUR2} %2 %{BKY_COLOUR_BLEND_RATIO} %3",args0:[{type:"input_value",name:"COLOUR1",check:"Colour",align:"RIGHT"},{type:"input_value",name:"COLOUR2",check:"Colour",align:"RIGHT"},{type:"input_value",name:"RATIO",check:"Number",align:"RIGHT"}],output:"Colour",helpUrl:"%{BKY_COLOUR_BLEND_HELPURL}",style:"colour_blocks",tooltip:"%{BKY_COLOUR_BLEND_TOOLTIP}"}]),t.Blocks.lists={},t.Constants.Lists={},t.Constants.Lists.HUE=260,t.defineBlocksWithJsonArray([{type:"lists_create_empty",message0:"%{BKY_LISTS_CREATE_EMPTY_TITLE}",output:"Array",style:"list_blocks",tooltip:"%{BKY_LISTS_CREATE_EMPTY_TOOLTIP}",helpUrl:"%{BKY_LISTS_CREATE_EMPTY_HELPURL}"},{type:"lists_repeat",message0:"%{BKY_LISTS_REPEAT_TITLE}",args0:[{type:"input_value",name:"ITEM"},{type:"input_value",name:"NUM",check:"Number"}],output:"Array",style:"list_blocks",tooltip:"%{BKY_LISTS_REPEAT_TOOLTIP}",helpUrl:"%{BKY_LISTS_REPEAT_HELPURL}"},{type:"lists_reverse",message0:"%{BKY_LISTS_REVERSE_MESSAGE0}",args0:[{type:"input_value",name:"LIST",check:"Array"}],output:"Array",inputsInline:!0,style:"list_blocks",tooltip:"%{BKY_LISTS_REVERSE_TOOLTIP}",helpUrl:"%{BKY_LISTS_REVERSE_HELPURL}"},{type:"lists_isEmpty",message0:"%{BKY_LISTS_ISEMPTY_TITLE}",args0:[{type:"input_value",name:"VALUE",check:["String","Array"]}],output:"Boolean",style:"list_blocks",tooltip:"%{BKY_LISTS_ISEMPTY_TOOLTIP}",helpUrl:"%{BKY_LISTS_ISEMPTY_HELPURL}"},{type:"lists_length",message0:"%{BKY_LISTS_LENGTH_TITLE}",args0:[{type:"input_value",name:"VALUE",check:["String","Array"]}],output:"Number",style:"list_blocks",tooltip:"%{BKY_LISTS_LENGTH_TOOLTIP}",helpUrl:"%{BKY_LISTS_LENGTH_HELPURL}"}]),t.Blocks.lists_create_with={init:function(){this.setHelpUrl(t.Msg.LISTS_CREATE_WITH_HELPURL),this.setStyle("list_blocks"),this.itemCount_=3,this.updateShape_(),this.setOutput(!0,"Array"),this.setMutator(new t.Mutator(["lists_create_with_item"])),this.setTooltip(t.Msg.LISTS_CREATE_WITH_TOOLTIP)},mutationToDom:function(){var e=t.utils.xml.createElement("mutation");return e.setAttribute("items",this.itemCount_),e},domToMutation:function(t){this.itemCount_=parseInt(t.getAttribute("items"),10),this.updateShape_()},decompose:function(t){var e=t.newBlock("lists_create_with_container");e.initSvg();for(var o=e.getInput("STACK").connection,i=0;i<this.itemCount_;i++){var n=t.newBlock("lists_create_with_item");n.initSvg(),o.connect(n.previousConnection),o=n.nextConnection}return e},compose:function(e){var o=e.getInputTargetBlock("STACK");for(e=[];o;)e.push(o.valueConnection_),o=o.nextConnection&&o.nextConnection.targetBlock();for(o=0;o<this.itemCount_;o++){var i=this.getInput("ADD"+o).connection.targetConnection;i&&-1==e.indexOf(i)&&i.disconnect()}for(this.itemCount_=e.length,this.updateShape_(),o=0;o<this.itemCount_;o++)t.Mutator.reconnect(e[o],this,"ADD"+o)},saveConnections:function(t){t=t.getInputTargetBlock("STACK");for(var e=0;t;){var o=this.getInput("ADD"+e);t.valueConnection_=o&&o.connection.targetConnection,e++,t=t.nextConnection&&t.nextConnection.targetBlock()}},updateShape_:function(){this.itemCount_&&this.getInput("EMPTY")?this.removeInput("EMPTY"):this.itemCount_||this.getInput("EMPTY")||this.appendDummyInput("EMPTY").appendField(t.Msg.LISTS_CREATE_EMPTY_TITLE);for(var e=0;e<this.itemCount_;e++)if(!this.getInput("ADD"+e)){var o=this.appendValueInput("ADD"+e).setAlign(t.ALIGN_RIGHT);0==e&&o.appendField(t.Msg.LISTS_CREATE_WITH_INPUT_WITH)}for(;this.getInput("ADD"+e);)this.removeInput("ADD"+e),e++}},t.Blocks.lists_create_with_container={init:function(){this.setStyle("list_blocks"),this.appendDummyInput().appendField(t.Msg.LISTS_CREATE_WITH_CONTAINER_TITLE_ADD),this.appendStatementInput("STACK"),this.setTooltip(t.Msg.LISTS_CREATE_WITH_CONTAINER_TOOLTIP),this.contextMenu=!1}},t.Blocks.lists_create_with_item={init:function(){this.setStyle("list_blocks"),this.appendDummyInput().appendField(t.Msg.LISTS_CREATE_WITH_ITEM_TITLE),this.setPreviousStatement(!0),this.setNextStatement(!0),this.setTooltip(t.Msg.LISTS_CREATE_WITH_ITEM_TOOLTIP),this.contextMenu=!1}},t.Blocks.lists_indexOf={init:function(){var e=[[t.Msg.LISTS_INDEX_OF_FIRST,"FIRST"],[t.Msg.LISTS_INDEX_OF_LAST,"LAST"]];this.setHelpUrl(t.Msg.LISTS_INDEX_OF_HELPURL),this.setStyle("list_blocks"),this.setOutput(!0,"Number"),this.appendValueInput("VALUE").setCheck("Array").appendField(t.Msg.LISTS_INDEX_OF_INPUT_IN_LIST),this.appendValueInput("FIND").appendField(new t.FieldDropdown(e),"END"),this.setInputsInline(!0);var o=this;this.setTooltip((function(){return t.Msg.LISTS_INDEX_OF_TOOLTIP.replace("%1",o.workspace.options.oneBasedIndex?"0":"-1")}))}},t.Blocks.lists_getIndex={init:function(){var e=[[t.Msg.LISTS_GET_INDEX_GET,"GET"],[t.Msg.LISTS_GET_INDEX_GET_REMOVE,"GET_REMOVE"],[t.Msg.LISTS_GET_INDEX_REMOVE,"REMOVE"]];this.WHERE_OPTIONS=[[t.Msg.LISTS_GET_INDEX_FROM_START,"FROM_START"],[t.Msg.LISTS_GET_INDEX_FROM_END,"FROM_END"],[t.Msg.LISTS_GET_INDEX_FIRST,"FIRST"],[t.Msg.LISTS_GET_INDEX_LAST,"LAST"],[t.Msg.LISTS_GET_INDEX_RANDOM,"RANDOM"]],this.setHelpUrl(t.Msg.LISTS_GET_INDEX_HELPURL),this.setStyle("list_blocks"),e=new t.FieldDropdown(e,(function(t){t="REMOVE"==t,this.getSourceBlock().updateStatement_(t)})),this.appendValueInput("VALUE").setCheck("Array").appendField(t.Msg.LISTS_GET_INDEX_INPUT_IN_LIST),this.appendDummyInput().appendField(e,"MODE").appendField("","SPACE"),this.appendDummyInput("AT"),t.Msg.LISTS_GET_INDEX_TAIL&&this.appendDummyInput("TAIL").appendField(t.Msg.LISTS_GET_INDEX_TAIL),this.setInputsInline(!0),this.setOutput(!0),this.updateAt_(!0);var o=this;this.setTooltip((function(){var e=o.getFieldValue("MODE"),i=o.getFieldValue("WHERE"),n="";switch(e+" "+i){case"GET FROM_START":case"GET FROM_END":n=t.Msg.LISTS_GET_INDEX_TOOLTIP_GET_FROM;break;case"GET FIRST":n=t.Msg.LISTS_GET_INDEX_TOOLTIP_GET_FIRST;break;case"GET LAST":n=t.Msg.LISTS_GET_INDEX_TOOLTIP_GET_LAST;break;case"GET RANDOM":n=t.Msg.LISTS_GET_INDEX_TOOLTIP_GET_RANDOM;break;case"GET_REMOVE FROM_START":case"GET_REMOVE FROM_END":n=t.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_FROM;break;case"GET_REMOVE FIRST":n=t.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_FIRST;break;case"GET_REMOVE LAST":n=t.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_LAST;break;case"GET_REMOVE RANDOM":n=t.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_RANDOM;break;case"REMOVE FROM_START":case"REMOVE FROM_END":n=t.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_FROM;break;case"REMOVE FIRST":n=t.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_FIRST;break;case"REMOVE LAST":n=t.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_LAST;break;case"REMOVE RANDOM":n=t.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_RANDOM}return"FROM_START"!=i&&"FROM_END"!=i||(n+="  "+("FROM_START"==i?t.Msg.LISTS_INDEX_FROM_START_TOOLTIP:t.Msg.LISTS_INDEX_FROM_END_TOOLTIP).replace("%1",o.workspace.options.oneBasedIndex?"#1":"#0")),n}))},mutationToDom:function(){var e=t.utils.xml.createElement("mutation");e.setAttribute("statement",!this.outputConnection);var o=this.getInput("AT").type==t.INPUT_VALUE;return e.setAttribute("at",o),e},domToMutation:function(t){var e="true"==t.getAttribute("statement");this.updateStatement_(e),t="false"!=t.getAttribute("at"),this.updateAt_(t)},updateStatement_:function(t){t!=!this.outputConnection&&(this.unplug(!0,!0),t?(this.setOutput(!1),this.setPreviousStatement(!0),this.setNextStatement(!0)):(this.setPreviousStatement(!1),this.setNextStatement(!1),this.setOutput(!0)))},updateAt_:function(e){this.removeInput("AT"),this.removeInput("ORDINAL",!0),e?(this.appendValueInput("AT").setCheck("Number"),t.Msg.ORDINAL_NUMBER_SUFFIX&&this.appendDummyInput("ORDINAL").appendField(t.Msg.ORDINAL_NUMBER_SUFFIX)):this.appendDummyInput("AT");var o=new t.FieldDropdown(this.WHERE_OPTIONS,(function(t){var o="FROM_START"==t||"FROM_END"==t;if(o!=e){var i=this.getSourceBlock();return i.updateAt_(o),i.setFieldValue(t,"WHERE"),null}}));this.getInput("AT").appendField(o,"WHERE"),t.Msg.LISTS_GET_INDEX_TAIL&&this.moveInputBefore("TAIL",null)}},t.Blocks.lists_setIndex={init:function(){var e=[[t.Msg.LISTS_SET_INDEX_SET,"SET"],[t.Msg.LISTS_SET_INDEX_INSERT,"INSERT"]];this.WHERE_OPTIONS=[[t.Msg.LISTS_GET_INDEX_FROM_START,"FROM_START"],[t.Msg.LISTS_GET_INDEX_FROM_END,"FROM_END"],[t.Msg.LISTS_GET_INDEX_FIRST,"FIRST"],[t.Msg.LISTS_GET_INDEX_LAST,"LAST"],[t.Msg.LISTS_GET_INDEX_RANDOM,"RANDOM"]],this.setHelpUrl(t.Msg.LISTS_SET_INDEX_HELPURL),this.setStyle("list_blocks"),this.appendValueInput("LIST").setCheck("Array").appendField(t.Msg.LISTS_SET_INDEX_INPUT_IN_LIST),this.appendDummyInput().appendField(new t.FieldDropdown(e),"MODE").appendField("","SPACE"),this.appendDummyInput("AT"),this.appendValueInput("TO").appendField(t.Msg.LISTS_SET_INDEX_INPUT_TO),this.setInputsInline(!0),this.setPreviousStatement(!0),this.setNextStatement(!0),this.setTooltip(t.Msg.LISTS_SET_INDEX_TOOLTIP),this.updateAt_(!0);var o=this;this.setTooltip((function(){var e=o.getFieldValue("MODE"),i=o.getFieldValue("WHERE"),n="";switch(e+" "+i){case"SET FROM_START":case"SET FROM_END":n=t.Msg.LISTS_SET_INDEX_TOOLTIP_SET_FROM;break;case"SET FIRST":n=t.Msg.LISTS_SET_INDEX_TOOLTIP_SET_FIRST;break;case"SET LAST":n=t.Msg.LISTS_SET_INDEX_TOOLTIP_SET_LAST;break;case"SET RANDOM":n=t.Msg.LISTS_SET_INDEX_TOOLTIP_SET_RANDOM;break;case"INSERT FROM_START":case"INSERT FROM_END":n=t.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_FROM;break;case"INSERT FIRST":n=t.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_FIRST;break;case"INSERT LAST":n=t.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_LAST;break;case"INSERT RANDOM":n=t.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_RANDOM}return"FROM_START"!=i&&"FROM_END"!=i||(n+="  "+t.Msg.LISTS_INDEX_FROM_START_TOOLTIP.replace("%1",o.workspace.options.oneBasedIndex?"#1":"#0")),n}))},mutationToDom:function(){var e=t.utils.xml.createElement("mutation"),o=this.getInput("AT").type==t.INPUT_VALUE;return e.setAttribute("at",o),e},domToMutation:function(t){t="false"!=t.getAttribute("at"),this.updateAt_(t)},updateAt_:function(e){this.removeInput("AT"),this.removeInput("ORDINAL",!0),e?(this.appendValueInput("AT").setCheck("Number"),t.Msg.ORDINAL_NUMBER_SUFFIX&&this.appendDummyInput("ORDINAL").appendField(t.Msg.ORDINAL_NUMBER_SUFFIX)):this.appendDummyInput("AT");var o=new t.FieldDropdown(this.WHERE_OPTIONS,(function(t){var o="FROM_START"==t||"FROM_END"==t;if(o!=e){var i=this.getSourceBlock();return i.updateAt_(o),i.setFieldValue(t,"WHERE"),null}}));this.moveInputBefore("AT","TO"),this.getInput("ORDINAL")&&this.moveInputBefore("ORDINAL","TO"),this.getInput("AT").appendField(o,"WHERE")}},t.Blocks.lists_getSublist={init:function(){this.WHERE_OPTIONS_1=[[t.Msg.LISTS_GET_SUBLIST_START_FROM_START,"FROM_START"],[t.Msg.LISTS_GET_SUBLIST_START_FROM_END,"FROM_END"],[t.Msg.LISTS_GET_SUBLIST_START_FIRST,"FIRST"]],this.WHERE_OPTIONS_2=[[t.Msg.LISTS_GET_SUBLIST_END_FROM_START,"FROM_START"],[t.Msg.LISTS_GET_SUBLIST_END_FROM_END,"FROM_END"],[t.Msg.LISTS_GET_SUBLIST_END_LAST,"LAST"]],this.setHelpUrl(t.Msg.LISTS_GET_SUBLIST_HELPURL),this.setStyle("list_blocks"),this.appendValueInput("LIST").setCheck("Array").appendField(t.Msg.LISTS_GET_SUBLIST_INPUT_IN_LIST),this.appendDummyInput("AT1"),this.appendDummyInput("AT2"),t.Msg.LISTS_GET_SUBLIST_TAIL&&this.appendDummyInput("TAIL").appendField(t.Msg.LISTS_GET_SUBLIST_TAIL),this.setInputsInline(!0),this.setOutput(!0,"Array"),this.updateAt_(1,!0),this.updateAt_(2,!0),this.setTooltip(t.Msg.LISTS_GET_SUBLIST_TOOLTIP)},mutationToDom:function(){var e=t.utils.xml.createElement("mutation"),o=this.getInput("AT1").type==t.INPUT_VALUE;return e.setAttribute("at1",o),o=this.getInput("AT2").type==t.INPUT_VALUE,e.setAttribute("at2",o),e},domToMutation:function(t){var e="true"==t.getAttribute("at1");t="true"==t.getAttribute("at2"),this.updateAt_(1,e),this.updateAt_(2,t)},updateAt_:function(e,o){this.removeInput("AT"+e),this.removeInput("ORDINAL"+e,!0),o?(this.appendValueInput("AT"+e).setCheck("Number"),t.Msg.ORDINAL_NUMBER_SUFFIX&&this.appendDummyInput("ORDINAL"+e).appendField(t.Msg.ORDINAL_NUMBER_SUFFIX)):this.appendDummyInput("AT"+e);var i=new t.FieldDropdown(this["WHERE_OPTIONS_"+e],(function(t){var i="FROM_START"==t||"FROM_END"==t;if(i!=o){var n=this.getSourceBlock();return n.updateAt_(e,i),n.setFieldValue(t,"WHERE"+e),null}}));this.getInput("AT"+e).appendField(i,"WHERE"+e),1==e&&(this.moveInputBefore("AT1","AT2"),this.getInput("ORDINAL1")&&this.moveInputBefore("ORDINAL1","AT2")),t.Msg.LISTS_GET_SUBLIST_TAIL&&this.moveInputBefore("TAIL",null)}},t.Blocks.lists_sort={init:function(){this.jsonInit({message0:t.Msg.LISTS_SORT_TITLE,args0:[{type:"field_dropdown",name:"TYPE",options:[[t.Msg.LISTS_SORT_TYPE_NUMERIC,"NUMERIC"],[t.Msg.LISTS_SORT_TYPE_TEXT,"TEXT"],[t.Msg.LISTS_SORT_TYPE_IGNORECASE,"IGNORE_CASE"]]},{type:"field_dropdown",name:"DIRECTION",options:[[t.Msg.LISTS_SORT_ORDER_ASCENDING,"1"],[t.Msg.LISTS_SORT_ORDER_DESCENDING,"-1"]]},{type:"input_value",name:"LIST",check:"Array"}],output:"Array",style:"list_blocks",tooltip:t.Msg.LISTS_SORT_TOOLTIP,helpUrl:t.Msg.LISTS_SORT_HELPURL})}},t.Blocks.lists_split={init:function(){var e=this,o=new t.FieldDropdown([[t.Msg.LISTS_SPLIT_LIST_FROM_TEXT,"SPLIT"],[t.Msg.LISTS_SPLIT_TEXT_FROM_LIST,"JOIN"]],(function(t){e.updateType_(t)}));this.setHelpUrl(t.Msg.LISTS_SPLIT_HELPURL),this.setStyle("list_blocks"),this.appendValueInput("INPUT").setCheck("String").appendField(o,"MODE"),this.appendValueInput("DELIM").setCheck("String").appendField(t.Msg.LISTS_SPLIT_WITH_DELIMITER),this.setInputsInline(!0),this.setOutput(!0,"Array"),this.setTooltip((function(){var o=e.getFieldValue("MODE");if("SPLIT"==o)return t.Msg.LISTS_SPLIT_TOOLTIP_SPLIT;if("JOIN"==o)return t.Msg.LISTS_SPLIT_TOOLTIP_JOIN;throw Error("Unknown mode: "+o)}))},updateType_:function(t){if(this.getFieldValue("MODE")!=t){var e=this.getInput("INPUT").connection;e.setShadowDom(null);var o=e.targetBlock();o&&(e.disconnect(),o.isShadow()?o.dispose():this.bumpNeighbours())}"SPLIT"==t?(this.outputConnection.setCheck("Array"),this.getInput("INPUT").setCheck("String")):(this.outputConnection.setCheck("String"),this.getInput("INPUT").setCheck("Array"))},mutationToDom:function(){var e=t.utils.xml.createElement("mutation");return e.setAttribute("mode",this.getFieldValue("MODE")),e},domToMutation:function(t){this.updateType_(t.getAttribute("mode"))}},t.Blocks.logic={},t.Constants.Logic={},t.Constants.Logic.HUE=210,t.defineBlocksWithJsonArray([{type:"logic_boolean",message0:"%1",args0:[{type:"field_dropdown",name:"BOOL",options:[["%{BKY_LOGIC_BOOLEAN_TRUE}","TRUE"],["%{BKY_LOGIC_BOOLEAN_FALSE}","FALSE"]]}],output:"Boolean",style:"logic_blocks",tooltip:"%{BKY_LOGIC_BOOLEAN_TOOLTIP}",helpUrl:"%{BKY_LOGIC_BOOLEAN_HELPURL}"},{type:"controls_if",message0:"%{BKY_CONTROLS_IF_MSG_IF} %1",args0:[{type:"input_value",name:"IF0",check:"Boolean"}],message1:"%{BKY_CONTROLS_IF_MSG_THEN} %1",args1:[{type:"input_statement",name:"DO0"}],previousStatement:null,nextStatement:null,style:"logic_blocks",helpUrl:"%{BKY_CONTROLS_IF_HELPURL}",mutator:"controls_if_mutator",extensions:["controls_if_tooltip"]},{type:"controls_ifelse",message0:"%{BKY_CONTROLS_IF_MSG_IF} %1",args0:[{type:"input_value",name:"IF0",check:"Boolean"}],message1:"%{BKY_CONTROLS_IF_MSG_THEN} %1",args1:[{type:"input_statement",name:"DO0"}],message2:"%{BKY_CONTROLS_IF_MSG_ELSE} %1",args2:[{type:"input_statement",name:"ELSE"}],previousStatement:null,nextStatement:null,style:"logic_blocks",tooltip:"%{BKYCONTROLS_IF_TOOLTIP_2}",helpUrl:"%{BKY_CONTROLS_IF_HELPURL}",extensions:["controls_if_tooltip"]},{type:"logic_compare",message0:"%1 %2 %3",args0:[{type:"input_value",name:"A"},{type:"field_dropdown",name:"OP",options:[["=","EQ"],["≠","NEQ"],["‏<","LT"],["‏≤","LTE"],["‏>","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;i<this.argumentVarModels_.length;i++){var n=t.utils.xml.createElement("arg"),s=this.argumentVarModels_[i];n.setAttribute("name",s.name),n.setAttribute("varid",s.getId()),e&&this.paramIds_&&n.setAttribute("paramId",this.paramIds_[i]),o.appendChild(n)}return this.hasStatements_||o.setAttribute("statements","false"),o},domToMutation:function(e){this.arguments_=[],this.argumentVarModels_=[];for(var o,i=0;o=e.childNodes[i];i++)if("arg"==o.nodeName.toLowerCase()){var n=o.getAttribute("name");o=o.getAttribute("varid")||o.getAttribute("varId"),this.arguments_.push(n),null!=(o=t.Variables.getOrCreateVariablePackage(this.workspace,o,n,""))?this.argumentVarModels_.push(o):console.log("Failed to create a variable with name "+n+", ignoring.")}this.updateParams_(),t.Procedures.mutateCallers(this),this.setStatements_("false"!==e.getAttribute("statements"))},decompose:function(e){var o=t.utils.xml.createElement("block");o.setAttribute("type","procedures_mutatorcontainer");var i=t.utils.xml.createElement("statement");i.setAttribute("name","STACK"),o.appendChild(i);for(var n=0;n<this.arguments_.length;n++){var s=t.utils.xml.createElement("block");s.setAttribute("type","procedures_mutatorarg");var r=t.utils.xml.createElement("field");r.setAttribute("name","NAME");var a=t.utils.xml.createTextNode(this.arguments_[n]);r.appendChild(a),s.appendChild(r),r=t.utils.xml.createElement("next"),s.appendChild(r),i.appendChild(s),i=r}return e=t.Xml.domToBlock(o,e),"procedures_defreturn"==this.type?e.setFieldValue(this.hasStatements_,"STATEMENTS"):e.removeInput("STATEMENT_INPUT"),t.Procedures.mutateCallers(this),e},compose:function(e){this.arguments_=[],this.paramIds_=[],this.argumentVarModels_=[];for(var o=e.getInputTargetBlock("STACK");o;){var i=o.getFieldValue("NAME");this.arguments_.push(i),i=this.workspace.getVariable(i,""),this.argumentVarModels_.push(i),this.paramIds_.push(o.id),o=o.nextConnection&&o.nextConnection.targetBlock()}this.updateParams_(),t.Procedures.mutateCallers(this),null!==(e=e.getFieldValue("STATEMENTS"))&&(e="TRUE"==e,this.hasStatements_!=e)&&(e?(this.setStatements_(!0),t.Mutator.reconnect(this.statementConnection_,this,"STACK"),this.statementConnection_=null):(e=this.getInput("STACK").connection,(this.statementConnection_=e.targetConnection)&&((e=e.targetBlock()).unplug(),e.bumpNeighbours()),this.setStatements_(!1)))},getProcedureDef:function(){return[this.getFieldValue("NAME"),this.arguments_,!1]},getVars:function(){return this.arguments_},getVarModels:function(){return this.argumentVarModels_},renameVarById:function(e,o){var i=this.workspace.getVariableById(e);if(""==i.type){i=i.name,o=this.workspace.getVariableById(o);for(var n=!1,s=0;s<this.argumentVarModels_.length;s++)this.argumentVarModels_[s].getId()==e&&(this.arguments_[s]=o.name,this.argumentVarModels_[s]=o,n=!0);n&&(this.displayRenamedVar_(i,o.name),t.Procedures.mutateCallers(this))}},updateVarName:function(e){for(var o=e.name,i=!1,n=0;n<this.argumentVarModels_.length;n++)if(this.argumentVarModels_[n].getId()==e.getId()){var s=this.arguments_[n];this.arguments_[n]=o,i=!0}i&&(this.displayRenamedVar_(s,o),t.Procedures.mutateCallers(this))},displayRenamedVar_:function(e,o){if(this.updateParams_(),this.mutator&&this.mutator.isVisible())for(var i,n=this.mutator.workspace_.getAllBlocks(!1),s=0;i=n[s];s++)"procedures_mutatorarg"==i.type&&t.Names.equals(e,i.getFieldValue("NAME"))&&i.setFieldValue(o,"NAME")},customContextMenu:function(e){if(!this.isInFlyout){var o={enabled:!0},i=this.getFieldValue("NAME");o.text=t.Msg.PROCEDURES_CREATE_DO.replace("%1",i);var n=t.utils.xml.createElement("mutation");for(n.setAttribute("name",i),i=0;i<this.arguments_.length;i++){var s=t.utils.xml.createElement("arg");s.setAttribute("name",this.arguments_[i]),n.appendChild(s)}if((i=t.utils.xml.createElement("block")).setAttribute("type",this.callType_),i.appendChild(n),o.callback=t.ContextMenu.callbackFactory(this,i),e.push(o),!this.isCollapsed())for(i=0;i<this.argumentVarModels_.length;i++)o={enabled:!0},n=this.argumentVarModels_[i],o.text=t.Msg.VARIABLES_SET_CREATE_GET.replace("%1",n.name),n=t.Variables.generateVariableFieldDom(n),(s=t.utils.xml.createElement("block")).setAttribute("type","variables_get"),s.appendChild(n),o.callback=t.ContextMenu.callbackFactory(this,s),e.push(o)}},callType_:"procedures_callnoreturn"},t.Blocks.procedures_defreturn={init:function(){var e=new t.FieldTextInput("",t.Procedures.rename);e.setSpellcheck(!1),this.appendDummyInput().appendField(t.Msg.PROCEDURES_DEFRETURN_TITLE).appendField(e,"NAME").appendField("","PARAMS"),this.appendValueInput("RETURN").setAlign(t.ALIGN_RIGHT).appendField(t.Msg.PROCEDURES_DEFRETURN_RETURN),this.setMutator(new t.Mutator(["procedures_mutatorarg"])),(this.workspace.options.comments||this.workspace.options.parentWorkspace&&this.workspace.options.parentWorkspace.options.comments)&&t.Msg.PROCEDURES_DEFRETURN_COMMENT&&this.setCommentText(t.Msg.PROCEDURES_DEFRETURN_COMMENT),this.setStyle("procedure_blocks"),this.setTooltip(t.Msg.PROCEDURES_DEFRETURN_TOOLTIP),this.setHelpUrl(t.Msg.PROCEDURES_DEFRETURN_HELPURL),this.arguments_=[],this.argumentVarModels_=[],this.setStatements_(!0),this.statementConnection_=null},setStatements_:t.Blocks.procedures_defnoreturn.setStatements_,updateParams_:t.Blocks.procedures_defnoreturn.updateParams_,mutationToDom:t.Blocks.procedures_defnoreturn.mutationToDom,domToMutation:t.Blocks.procedures_defnoreturn.domToMutation,decompose:t.Blocks.procedures_defnoreturn.decompose,compose:t.Blocks.procedures_defnoreturn.compose,getProcedureDef:function(){return[this.getFieldValue("NAME"),this.arguments_,!0]},getVars:t.Blocks.procedures_defnoreturn.getVars,getVarModels:t.Blocks.procedures_defnoreturn.getVarModels,renameVarById:t.Blocks.procedures_defnoreturn.renameVarById,updateVarName:t.Blocks.procedures_defnoreturn.updateVarName,displayRenamedVar_:t.Blocks.procedures_defnoreturn.displayRenamedVar_,customContextMenu:t.Blocks.procedures_defnoreturn.customContextMenu,callType_:"procedures_callreturn"},t.Blocks.procedures_mutatorcontainer={init:function(){this.appendDummyInput().appendField(t.Msg.PROCEDURES_MUTATORCONTAINER_TITLE),this.appendStatementInput("STACK"),this.appendDummyInput("STATEMENT_INPUT").appendField(t.Msg.PROCEDURES_ALLOW_STATEMENTS).appendField(new t.FieldCheckbox("TRUE"),"STATEMENTS"),this.setStyle("procedure_blocks"),this.setTooltip(t.Msg.PROCEDURES_MUTATORCONTAINER_TOOLTIP),this.contextMenu=!1}},t.Blocks.procedures_mutatorarg={init:function(){var e=new t.FieldTextInput(t.Procedures.DEFAULT_ARG,this.validator_);e.oldShowEditorFn_=e.showEditor_,e.showEditor_=function(){this.createdVariables_=[],this.oldShowEditorFn_()},this.appendDummyInput().appendField(t.Msg.PROCEDURES_MUTATORARG_TITLE).appendField(e,"NAME"),this.setPreviousStatement(!0),this.setNextStatement(!0),this.setStyle("procedure_blocks"),this.setTooltip(t.Msg.PROCEDURES_MUTATORARG_TOOLTIP),this.contextMenu=!1,e.onFinishEditing_=this.deleteIntermediateVars_,e.createdVariables_=[],e.onFinishEditing_("x")},validator_:function(e){var o=this.getSourceBlock(),i=t.Mutator.findParentWs(o.workspace);if(!(e=e.replace(/[\s\xa0]+/g," ").replace(/^ | $/g,"")))return null;for(var n=(o.workspace.targetWorkspace||o.workspace).getAllBlocks(!1),s=e.toLowerCase(),r=0;r<n.length;r++)if(n[r].id!=this.getSourceBlock().id){var a=n[r].getFieldValue("NAME");if(a&&a.toLowerCase()==s)return null}return o.isInFlyout||((o=i.getVariable(e,""))&&o.name!=e&&i.renameVariableById(o.getId(),e),o||(o=i.createVariable(e,""))&&this.createdVariables_&&this.createdVariables_.push(o)),e},deleteIntermediateVars_:function(e){var o=t.Mutator.findParentWs(this.getSourceBlock().workspace);if(o)for(var i=0;i<this.createdVariables_.length;i++){var n=this.createdVariables_[i];n.name!=e&&o.deleteVariableById(n.getId())}}},t.Blocks.procedures_callnoreturn={init:function(){this.appendDummyInput("TOPROW").appendField(this.id,"NAME"),this.setPreviousStatement(!0),this.setNextStatement(!0),this.setStyle("procedure_blocks"),this.setHelpUrl(t.Msg.PROCEDURES_CALLNORETURN_HELPURL),this.arguments_=[],this.argumentVarModels_=[],this.quarkConnections_={},this.quarkIds_=null,this.previousEnabledState_=!0},getProcedureCall:function(){return this.getFieldValue("NAME")},renameProcedure:function(e,o){t.Names.equals(e,this.getProcedureCall())&&(this.setFieldValue(o,"NAME"),this.setTooltip((this.outputConnection?t.Msg.PROCEDURES_CALLRETURN_TOOLTIP:t.Msg.PROCEDURES_CALLNORETURN_TOOLTIP).replace("%1",o)))},setProcedureParameters_:function(e,o){var i=t.Procedures.getDefinition(this.getProcedureCall(),this.workspace),n=i&&i.mutator&&i.mutator.isVisible();if(n||(this.quarkConnections_={},this.quarkIds_=null),o)if(e.join("\n")==this.arguments_.join("\n"))this.quarkIds_=o;else{if(o.length!=e.length)throw RangeError("paramNames and paramIds must be the same length.");this.setCollapsed(!1),this.quarkIds_||(this.quarkConnections_={},this.quarkIds_=[]),i=this.rendered,this.rendered=!1;for(var s=0;s<this.arguments_.length;s++){var r=this.getInput("ARG"+s);r&&(r=r.connection.targetConnection,this.quarkConnections_[this.quarkIds_[s]]=r,n&&r&&-1==o.indexOf(this.quarkIds_[s])&&(r.disconnect(),r.getSourceBlock().bumpNeighbours()))}for(this.arguments_=[].concat(e),this.argumentVarModels_=[],s=0;s<this.arguments_.length;s++)e=t.Variables.getOrCreateVariablePackage(this.workspace,null,this.arguments_[s],""),this.argumentVarModels_.push(e);if(this.updateShape_(),this.quarkIds_=o)for(s=0;s<this.arguments_.length;s++)(o=this.quarkIds_[s])in this.quarkConnections_&&(r=this.quarkConnections_[o],t.Mutator.reconnect(r,this,"ARG"+s)||delete this.quarkConnections_[o]);(this.rendered=i)&&this.render()}},updateShape_:function(){for(var e=0;e<this.arguments_.length;e++){var o=this.getField("ARGNAME"+e);if(o){t.Events.disable();try{o.setValue(this.arguments_[e])}finally{t.Events.enable()}}else o=new t.FieldLabel(this.arguments_[e]),this.appendValueInput("ARG"+e).setAlign(t.ALIGN_RIGHT).appendField(o,"ARGNAME"+e).init()}for(;this.getInput("ARG"+e);)this.removeInput("ARG"+e),e++;(e=this.getInput("TOPROW"))&&(this.arguments_.length?this.getField("WITH")||(e.appendField(t.Msg.PROCEDURES_CALL_BEFORE_PARAMS,"WITH"),e.init()):this.getField("WITH")&&e.removeField("WITH"))},mutationToDom:function(){var e=t.utils.xml.createElement("mutation");e.setAttribute("name",this.getProcedureCall());for(var o=0;o<this.arguments_.length;o++){var i=t.utils.xml.createElement("arg");i.setAttribute("name",this.arguments_[o]),e.appendChild(i)}return e},domToMutation:function(t){var e=t.getAttribute("name");this.renameProcedure(this.getProcedureCall(),e),e=[];for(var o,i=[],n=0;o=t.childNodes[n];n++)"arg"==o.nodeName.toLowerCase()&&(e.push(o.getAttribute("name")),i.push(o.getAttribute("paramId")));this.setProcedureParameters_(e,i)},getVarModels:function(){return this.argumentVarModels_},onchange:function(e){if(this.workspace&&!this.workspace.isFlyout&&e.recordUndo)if(e.type==t.Events.BLOCK_CREATE&&-1!=e.ids.indexOf(this.id)){var o=this.getProcedureCall();if(!(o=t.Procedures.getDefinition(o,this.workspace))||o.type==this.defType_&&JSON.stringify(o.arguments_)==JSON.stringify(this.arguments_)||(o=null),!o){t.Events.setGroup(e.group),e=t.utils.xml.createElement("xml"),(o=t.utils.xml.createElement("block")).setAttribute("type",this.defType_);var i=this.getRelativeToSurfaceXY(),n=i.y+2*t.SNAP_RADIUS;o.setAttribute("x",i.x+t.SNAP_RADIUS*(this.RTL?-1:1)),o.setAttribute("y",n),i=this.mutationToDom(),o.appendChild(i),(i=t.utils.xml.createElement("field")).setAttribute("name","NAME"),i.appendChild(t.utils.xml.createTextNode(this.getProcedureCall())),o.appendChild(i),e.appendChild(o),t.Xml.domToWorkspace(e,this.workspace),t.Events.setGroup(!1)}}else e.type==t.Events.BLOCK_DELETE?(o=this.getProcedureCall(),(o=t.Procedures.getDefinition(o,this.workspace))||(t.Events.setGroup(e.group),this.dispose(!0),t.Events.setGroup(!1))):e.type==t.Events.CHANGE&&"disabled"==e.element&&(o=this.getProcedureCall(),(o=t.Procedures.getDefinition(o,this.workspace))&&o.id==e.blockId&&((o=t.Events.getGroup())&&console.log("Saw an existing group while responding to a definition change"),t.Events.setGroup(e.group),e.newValue?(this.previousEnabledState_=this.isEnabled(),this.setEnabled(!1)):this.setEnabled(this.previousEnabledState_),t.Events.setGroup(o)))},customContextMenu:function(e){if(this.workspace.isMovable()){var o={enabled:!0};o.text=t.Msg.PROCEDURES_HIGHLIGHT_DEF;var i=this.getProcedureCall(),n=this.workspace;o.callback=function(){var e=t.Procedures.getDefinition(i,n);e&&(n.centerOnBlock(e.id),e.select())},e.push(o)}},defType_:"procedures_defnoreturn"},t.Blocks.procedures_callreturn={init:function(){this.appendDummyInput("TOPROW").appendField("","NAME"),this.setOutput(!0),this.setStyle("procedure_blocks"),this.setHelpUrl(t.Msg.PROCEDURES_CALLRETURN_HELPURL),this.arguments_=[],this.quarkConnections_={},this.quarkIds_=null,this.previousEnabledState_=!0},getProcedureCall:t.Blocks.procedures_callnoreturn.getProcedureCall,renameProcedure:t.Blocks.procedures_callnoreturn.renameProcedure,setProcedureParameters_:t.Blocks.procedures_callnoreturn.setProcedureParameters_,updateShape_:t.Blocks.procedures_callnoreturn.updateShape_,mutationToDom:t.Blocks.procedures_callnoreturn.mutationToDom,domToMutation:t.Blocks.procedures_callnoreturn.domToMutation,getVarModels:t.Blocks.procedures_callnoreturn.getVarModels,onchange:t.Blocks.procedures_callnoreturn.onchange,customContextMenu:t.Blocks.procedures_callnoreturn.customContextMenu,defType_:"procedures_defreturn"},t.Blocks.procedures_ifreturn={init:function(){this.appendValueInput("CONDITION").setCheck("Boolean").appendField(t.Msg.CONTROLS_IF_MSG_IF),this.appendValueInput("VALUE").appendField(t.Msg.PROCEDURES_DEFRETURN_RETURN),this.setInputsInline(!0),this.setPreviousStatement(!0),this.setNextStatement(!0),this.setStyle("procedure_blocks"),this.setTooltip(t.Msg.PROCEDURES_IFRETURN_TOOLTIP),this.setHelpUrl(t.Msg.PROCEDURES_IFRETURN_HELPURL),this.hasReturnValue_=!0},mutationToDom:function(){var e=t.utils.xml.createElement("mutation");return e.setAttribute("value",Number(this.hasReturnValue_)),e},domToMutation:function(e){this.hasReturnValue_=1==e.getAttribute("value"),this.hasReturnValue_||(this.removeInput("VALUE"),this.appendDummyInput("VALUE").appendField(t.Msg.PROCEDURES_DEFRETURN_RETURN))},onchange:function(e){if(this.workspace.isDragging&&!this.workspace.isDragging()){e=!1;var o=this;do{if(-1!=this.FUNCTION_TYPES.indexOf(o.type)){e=!0;break}o=o.getSurroundParent()}while(o);e?("procedures_defnoreturn"==o.type&&this.hasReturnValue_?(this.removeInput("VALUE"),this.appendDummyInput("VALUE").appendField(t.Msg.PROCEDURES_DEFRETURN_RETURN),this.hasReturnValue_=!1):"procedures_defreturn"!=o.type||this.hasReturnValue_||(this.removeInput("VALUE"),this.appendValueInput("VALUE").appendField(t.Msg.PROCEDURES_DEFRETURN_RETURN),this.hasReturnValue_=!0),this.setWarningText(null),this.isInFlyout||this.setEnabled(!0)):(this.setWarningText(t.Msg.PROCEDURES_IFRETURN_WARNING),this.isInFlyout||this.getInheritedDisabled()||this.setEnabled(!1))}},FUNCTION_TYPES:["procedures_defnoreturn","procedures_defreturn"]},t.Blocks.texts={},t.Constants.Text={},t.Constants.Text.HUE=160,t.defineBlocksWithJsonArray([{type:"text",message0:"%1",args0:[{type:"field_input",name:"TEXT",text:""}],output:"String",style:"text_blocks",helpUrl:"%{BKY_TEXT_TEXT_HELPURL}",tooltip:"%{BKY_TEXT_TEXT_TOOLTIP}",extensions:["text_quotes","parent_tooltip_when_inline"]},{type:"text_multiline",message0:"%1 %2",args0:[{type:"field_image",src:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAARCAYAAADpPU2iAAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAAdhgAAHYYBXaITgQAAABh0RVh0U29mdHdhcmUAcGFpbnQubmV0IDQuMS42/U4J6AAAAP1JREFUOE+Vks0KQUEYhjmRIja4ABtZ2dm5A3t3Ia6AUm7CylYuQRaUhZSlLZJiQbFAyRnPN33y01HOW08z8873zpwzM4F3GWOCruvGIE4/rLaV+Nq1hVGMBqzhqlxgCys4wJA65xnogMHsQ5lujnYHTejBBCK2mE4abjCgMGhNxHgDFWjDSG07kdfVa2pZMf4ZyMAdWmpZMfYOsLiDMYMjlMB+K613QISRhTnITnsYg5yUd0DETmEoMlkFOeIT/A58iyK5E18BuTBfgYXfwNJv4P9/oEBerLylOnRhygmGdPpTTBZAPkde61lbQe4moWUvYUZYLfUNftIY4zwA5X2Z9AYnQrEAAAAASUVORK5CYII=",width:12,height:17,alt:"¶"},{type:"field_multilinetext",name:"TEXT",text:""}],output:"String",style:"text_blocks",helpUrl:"%{BKY_TEXT_TEXT_HELPURL}",tooltip:"%{BKY_TEXT_TEXT_TOOLTIP}",extensions:["parent_tooltip_when_inline"]},{type:"text_join",message0:"",output:"String",style:"text_blocks",helpUrl:"%{BKY_TEXT_JOIN_HELPURL}",tooltip:"%{BKY_TEXT_JOIN_TOOLTIP}",mutator:"text_join_mutator"},{type:"text_create_join_container",message0:"%{BKY_TEXT_CREATE_JOIN_TITLE_JOIN} %1 %2",args0:[{type:"input_dummy"},{type:"input_statement",name:"STACK"}],style:"text_blocks",tooltip:"%{BKY_TEXT_CREATE_JOIN_TOOLTIP}",enableContextMenu:!1},{type:"text_create_join_item",message0:"%{BKY_TEXT_CREATE_JOIN_ITEM_TITLE_ITEM}",previousStatement:null,nextStatement:null,style:"text_blocks",tooltip:"%{BKY_TEXT_CREATE_JOIN_ITEM_TOOLTIP}",enableContextMenu:!1},{type:"text_append",message0:"%{BKY_TEXT_APPEND_TITLE}",args0:[{type:"field_variable",name:"VAR",variable:"%{BKY_TEXT_APPEND_VARIABLE}"},{type:"input_value",name:"TEXT"}],previousStatement:null,nextStatement:null,style:"text_blocks",extensions:["text_append_tooltip"]},{type:"text_length",message0:"%{BKY_TEXT_LENGTH_TITLE}",args0:[{type:"input_value",name:"VALUE",check:["String","Array"]}],output:"Number",style:"text_blocks",tooltip:"%{BKY_TEXT_LENGTH_TOOLTIP}",helpUrl:"%{BKY_TEXT_LENGTH_HELPURL}"},{type:"text_isEmpty",message0:"%{BKY_TEXT_ISEMPTY_TITLE}",args0:[{type:"input_value",name:"VALUE",check:["String","Array"]}],output:"Boolean",style:"text_blocks",tooltip:"%{BKY_TEXT_ISEMPTY_TOOLTIP}",helpUrl:"%{BKY_TEXT_ISEMPTY_HELPURL}"},{type:"text_indexOf",message0:"%{BKY_TEXT_INDEXOF_TITLE}",args0:[{type:"input_value",name:"VALUE",check:"String"},{type:"field_dropdown",name:"END",options:[["%{BKY_TEXT_INDEXOF_OPERATOR_FIRST}","FIRST"],["%{BKY_TEXT_INDEXOF_OPERATOR_LAST}","LAST"]]},{type:"input_value",name:"FIND",check:"String"}],output:"Number",style:"text_blocks",helpUrl:"%{BKY_TEXT_INDEXOF_HELPURL}",inputsInline:!0,extensions:["text_indexOf_tooltip"]},{type:"text_charAt",message0:"%{BKY_TEXT_CHARAT_TITLE}",args0:[{type:"input_value",name:"VALUE",check:"String"},{type:"field_dropdown",name:"WHERE",options:[["%{BKY_TEXT_CHARAT_FROM_START}","FROM_START"],["%{BKY_TEXT_CHARAT_FROM_END}","FROM_END"],["%{BKY_TEXT_CHARAT_FIRST}","FIRST"],["%{BKY_TEXT_CHARAT_LAST}","LAST"],["%{BKY_TEXT_CHARAT_RANDOM}","RANDOM"]]}],output:"String",style:"text_blocks",helpUrl:"%{BKY_TEXT_CHARAT_HELPURL}",inputsInline:!0,mutator:"text_charAt_mutator"}]),t.Blocks.text_getSubstring={init:function(){this.WHERE_OPTIONS_1=[[t.Msg.TEXT_GET_SUBSTRING_START_FROM_START,"FROM_START"],[t.Msg.TEXT_GET_SUBSTRING_START_FROM_END,"FROM_END"],[t.Msg.TEXT_GET_SUBSTRING_START_FIRST,"FIRST"]],this.WHERE_OPTIONS_2=[[t.Msg.TEXT_GET_SUBSTRING_END_FROM_START,"FROM_START"],[t.Msg.TEXT_GET_SUBSTRING_END_FROM_END,"FROM_END"],[t.Msg.TEXT_GET_SUBSTRING_END_LAST,"LAST"]],this.setHelpUrl(t.Msg.TEXT_GET_SUBSTRING_HELPURL),this.setStyle("text_blocks"),this.appendValueInput("STRING").setCheck("String").appendField(t.Msg.TEXT_GET_SUBSTRING_INPUT_IN_TEXT),this.appendDummyInput("AT1"),this.appendDummyInput("AT2"),t.Msg.TEXT_GET_SUBSTRING_TAIL&&this.appendDummyInput("TAIL").appendField(t.Msg.TEXT_GET_SUBSTRING_TAIL),this.setInputsInline(!0),this.setOutput(!0,"String"),this.updateAt_(1,!0),this.updateAt_(2,!0),this.setTooltip(t.Msg.TEXT_GET_SUBSTRING_TOOLTIP)},mutationToDom:function(){var e=t.utils.xml.createElement("mutation"),o=this.getInput("AT1").type==t.INPUT_VALUE;return e.setAttribute("at1",o),o=this.getInput("AT2").type==t.INPUT_VALUE,e.setAttribute("at2",o),e},domToMutation:function(t){var e="true"==t.getAttribute("at1");t="true"==t.getAttribute("at2"),this.updateAt_(1,e),this.updateAt_(2,t)},updateAt_:function(e,o){this.removeInput("AT"+e),this.removeInput("ORDINAL"+e,!0),o?(this.appendValueInput("AT"+e).setCheck("Number"),t.Msg.ORDINAL_NUMBER_SUFFIX&&this.appendDummyInput("ORDINAL"+e).appendField(t.Msg.ORDINAL_NUMBER_SUFFIX)):this.appendDummyInput("AT"+e),2==e&&t.Msg.TEXT_GET_SUBSTRING_TAIL&&(this.removeInput("TAIL",!0),this.appendDummyInput("TAIL").appendField(t.Msg.TEXT_GET_SUBSTRING_TAIL));var i=new t.FieldDropdown(this["WHERE_OPTIONS_"+e],(function(t){var i="FROM_START"==t||"FROM_END"==t;if(i!=o){var n=this.getSourceBlock();return n.updateAt_(e,i),n.setFieldValue(t,"WHERE"+e),null}}));this.getInput("AT"+e).appendField(i,"WHERE"+e),1==e&&(this.moveInputBefore("AT1","AT2"),this.getInput("ORDINAL1")&&this.moveInputBefore("ORDINAL1","AT2"))}},t.Blocks.text_changeCase={init:function(){var e=[[t.Msg.TEXT_CHANGECASE_OPERATOR_UPPERCASE,"UPPERCASE"],[t.Msg.TEXT_CHANGECASE_OPERATOR_LOWERCASE,"LOWERCASE"],[t.Msg.TEXT_CHANGECASE_OPERATOR_TITLECASE,"TITLECASE"]];this.setHelpUrl(t.Msg.TEXT_CHANGECASE_HELPURL),this.setStyle("text_blocks"),this.appendValueInput("TEXT").setCheck("String").appendField(new t.FieldDropdown(e),"CASE"),this.setOutput(!0,"String"),this.setTooltip(t.Msg.TEXT_CHANGECASE_TOOLTIP)}},t.Blocks.text_trim={init:function(){var e=[[t.Msg.TEXT_TRIM_OPERATOR_BOTH,"BOTH"],[t.Msg.TEXT_TRIM_OPERATOR_LEFT,"LEFT"],[t.Msg.TEXT_TRIM_OPERATOR_RIGHT,"RIGHT"]];this.setHelpUrl(t.Msg.TEXT_TRIM_HELPURL),this.setStyle("text_blocks"),this.appendValueInput("TEXT").setCheck("String").appendField(new t.FieldDropdown(e),"MODE"),this.setOutput(!0,"String"),this.setTooltip(t.Msg.TEXT_TRIM_TOOLTIP)}},t.Blocks.text_print={init:function(){this.jsonInit({message0:t.Msg.TEXT_PRINT_TITLE,args0:[{type:"input_value",name:"TEXT"}],previousStatement:null,nextStatement:null,style:"text_blocks",tooltip:t.Msg.TEXT_PRINT_TOOLTIP,helpUrl:t.Msg.TEXT_PRINT_HELPURL})}},t.Blocks.text_prompt_ext={init:function(){var e=[[t.Msg.TEXT_PROMPT_TYPE_TEXT,"TEXT"],[t.Msg.TEXT_PROMPT_TYPE_NUMBER,"NUMBER"]];this.setHelpUrl(t.Msg.TEXT_PROMPT_HELPURL),this.setStyle("text_blocks");var o=this;e=new t.FieldDropdown(e,(function(t){o.updateType_(t)})),this.appendValueInput("TEXT").appendField(e,"TYPE"),this.setOutput(!0,"String"),this.setTooltip((function(){return"TEXT"==o.getFieldValue("TYPE")?t.Msg.TEXT_PROMPT_TOOLTIP_TEXT:t.Msg.TEXT_PROMPT_TOOLTIP_NUMBER}))},updateType_:function(t){this.outputConnection.setCheck("NUMBER"==t?"Number":"String")},mutationToDom:function(){var e=t.utils.xml.createElement("mutation");return e.setAttribute("type",this.getFieldValue("TYPE")),e},domToMutation:function(t){this.updateType_(t.getAttribute("type"))}},t.Blocks.text_prompt={init:function(){this.mixin(t.Constants.Text.QUOTE_IMAGE_MIXIN);var e=[[t.Msg.TEXT_PROMPT_TYPE_TEXT,"TEXT"],[t.Msg.TEXT_PROMPT_TYPE_NUMBER,"NUMBER"]],o=this;this.setHelpUrl(t.Msg.TEXT_PROMPT_HELPURL),this.setStyle("text_blocks"),e=new t.FieldDropdown(e,(function(t){o.updateType_(t)})),this.appendDummyInput().appendField(e,"TYPE").appendField(this.newQuote_(!0)).appendField(new t.FieldTextInput(""),"TEXT").appendField(this.newQuote_(!1)),this.setOutput(!0,"String"),this.setTooltip((function(){return"TEXT"==o.getFieldValue("TYPE")?t.Msg.TEXT_PROMPT_TOOLTIP_TEXT:t.Msg.TEXT_PROMPT_TOOLTIP_NUMBER}))},updateType_:t.Blocks.text_prompt_ext.updateType_,mutationToDom:t.Blocks.text_prompt_ext.mutationToDom,domToMutation:t.Blocks.text_prompt_ext.domToMutation},t.Blocks.text_count={init:function(){this.jsonInit({message0:t.Msg.TEXT_COUNT_MESSAGE0,args0:[{type:"input_value",name:"SUB",check:"String"},{type:"input_value",name:"TEXT",check:"String"}],output:"Number",inputsInline:!0,style:"text_blocks",tooltip:t.Msg.TEXT_COUNT_TOOLTIP,helpUrl:t.Msg.TEXT_COUNT_HELPURL})}},t.Blocks.text_replace={init:function(){this.jsonInit({message0:t.Msg.TEXT_REPLACE_MESSAGE0,args0:[{type:"input_value",name:"FROM",check:"String"},{type:"input_value",name:"TO",check:"String"},{type:"input_value",name:"TEXT",check:"String"}],output:"String",inputsInline:!0,style:"text_blocks",tooltip:t.Msg.TEXT_REPLACE_TOOLTIP,helpUrl:t.Msg.TEXT_REPLACE_HELPURL})}},t.Blocks.text_reverse={init:function(){this.jsonInit({message0:t.Msg.TEXT_REVERSE_MESSAGE0,args0:[{type:"input_value",name:"TEXT",check:"String"}],output:"String",inputsInline:!0,style:"text_blocks",tooltip:t.Msg.TEXT_REVERSE_TOOLTIP,helpUrl:t.Msg.TEXT_REVERSE_HELPURL})}},t.Constants.Text.QUOTE_IMAGE_MIXIN={QUOTE_IMAGE_LEFT_DATAURI:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAAKCAQAAAAqJXdxAAAAn0lEQVQI1z3OMa5BURSF4f/cQhAKjUQhuQmFNwGJEUi0RKN5rU7FHKhpjEH3TEMtkdBSCY1EIv8r7nFX9e29V7EBAOvu7RPjwmWGH/VuF8CyN9/OAdvqIXYLvtRaNjx9mMTDyo+NjAN1HNcl9ZQ5oQMM3dgDUqDo1l8DzvwmtZN7mnD+PkmLa+4mhrxVA9fRowBWmVBhFy5gYEjKMfz9AylsaRRgGzvZAAAAAElFTkSuQmCC",QUOTE_IMAGE_RIGHT_DATAURI:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAAKCAQAAAAqJXdxAAAAqUlEQVQI1z3KvUpCcRiA8ef9E4JNHhI0aFEacm1o0BsI0Slx8wa8gLauoDnoBhq7DcfWhggONDmJJgqCPA7neJ7p934EOOKOnM8Q7PDElo/4x4lFb2DmuUjcUzS3URnGib9qaPNbuXvBO3sGPHJDRG6fGVdMSeWDP2q99FQdFrz26Gu5Tq7dFMzUvbXy8KXeAj57cOklgA+u1B5AoslLtGIHQMaCVnwDnADZIFIrXsoXrgAAAABJRU5ErkJggg==",QUOTE_IMAGE_WIDTH:12,QUOTE_IMAGE_HEIGHT:12,quoteField_:function(t){for(var e,o=0;e=this.inputList[o];o++)for(var i,n=0;i=e.fieldRow[n];n++)if(t==i.name)return e.insertFieldAt(n,this.newQuote_(!0)),void e.insertFieldAt(n+2,this.newQuote_(!1));console.warn('field named "'+t+'" not found in '+this.toDevString())},newQuote_:function(e){return e=this.RTL?!e:e,new t.FieldImage(e?this.QUOTE_IMAGE_LEFT_DATAURI:this.QUOTE_IMAGE_RIGHT_DATAURI,this.QUOTE_IMAGE_WIDTH,this.QUOTE_IMAGE_HEIGHT,e?"“":"”")}},t.Constants.Text.TEXT_QUOTES_EXTENSION=function(){this.mixin(t.Constants.Text.QUOTE_IMAGE_MIXIN),this.quoteField_("TEXT")},t.Constants.Text.TEXT_JOIN_MUTATOR_MIXIN={mutationToDom:function(){var e=t.utils.xml.createElement("mutation");return e.setAttribute("items",this.itemCount_),e},domToMutation:function(t){this.itemCount_=parseInt(t.getAttribute("items"),10),this.updateShape_()},decompose:function(t){var e=t.newBlock("text_create_join_container");e.initSvg();for(var o=e.getInput("STACK").connection,i=0;i<this.itemCount_;i++){var n=t.newBlock("text_create_join_item");n.initSvg(),o.connect(n.previousConnection),o=n.nextConnection}return e},compose:function(e){var o=e.getInputTargetBlock("STACK");for(e=[];o;)e.push(o.valueConnection_),o=o.nextConnection&&o.nextConnection.targetBlock();for(o=0;o<this.itemCount_;o++){var i=this.getInput("ADD"+o).connection.targetConnection;i&&-1==e.indexOf(i)&&i.disconnect()}for(this.itemCount_=e.length,this.updateShape_(),o=0;o<this.itemCount_;o++)t.Mutator.reconnect(e[o],this,"ADD"+o)},saveConnections:function(t){t=t.getInputTargetBlock("STACK");for(var e=0;t;){var o=this.getInput("ADD"+e);t.valueConnection_=o&&o.connection.targetConnection,e++,t=t.nextConnection&&t.nextConnection.targetBlock()}},updateShape_:function(){this.itemCount_&&this.getInput("EMPTY")?this.removeInput("EMPTY"):this.itemCount_||this.getInput("EMPTY")||this.appendDummyInput("EMPTY").appendField(this.newQuote_(!0)).appendField(this.newQuote_(!1));for(var e=0;e<this.itemCount_;e++)if(!this.getInput("ADD"+e)){var o=this.appendValueInput("ADD"+e).setAlign(t.ALIGN_RIGHT);0==e&&o.appendField(t.Msg.TEXT_JOIN_TITLE_CREATEWITH)}for(;this.getInput("ADD"+e);)this.removeInput("ADD"+e),e++}},t.Constants.Text.TEXT_JOIN_EXTENSION=function(){this.mixin(t.Constants.Text.QUOTE_IMAGE_MIXIN),this.itemCount_=2,this.updateShape_(),this.setMutator(new t.Mutator(["text_create_join_item"]))},t.Extensions.register("text_append_tooltip",t.Extensions.buildTooltipWithFieldText("%{BKY_TEXT_APPEND_TOOLTIP}","VAR")),t.Constants.Text.TEXT_INDEXOF_TOOLTIP_EXTENSION=function(){var e=this;this.setTooltip((function(){return t.Msg.TEXT_INDEXOF_TOOLTIP.replace("%1",e.workspace.options.oneBasedIndex?"0":"-1")}))},t.Constants.Text.TEXT_CHARAT_MUTATOR_MIXIN={mutationToDom:function(){var e=t.utils.xml.createElement("mutation");return e.setAttribute("at",!!this.isAt_),e},domToMutation:function(t){t="false"!=t.getAttribute("at"),this.updateAt_(t)},updateAt_:function(e){this.removeInput("AT",!0),this.removeInput("ORDINAL",!0),e&&(this.appendValueInput("AT").setCheck("Number"),t.Msg.ORDINAL_NUMBER_SUFFIX&&this.appendDummyInput("ORDINAL").appendField(t.Msg.ORDINAL_NUMBER_SUFFIX)),t.Msg.TEXT_CHARAT_TAIL&&(this.removeInput("TAIL",!0),this.appendDummyInput("TAIL").appendField(t.Msg.TEXT_CHARAT_TAIL)),this.isAt_=e}},t.Constants.Text.TEXT_CHARAT_EXTENSION=function(){this.getField("WHERE").setValidator((function(t){(t="FROM_START"==t||"FROM_END"==t)!=this.isAt_&&this.getSourceBlock().updateAt_(t)})),this.updateAt_(!0);var e=this;this.setTooltip((function(){var o=e.getFieldValue("WHERE"),i=t.Msg.TEXT_CHARAT_TOOLTIP;return("FROM_START"==o||"FROM_END"==o)&&(o="FROM_START"==o?t.Msg.LISTS_INDEX_FROM_START_TOOLTIP:t.Msg.LISTS_INDEX_FROM_END_TOOLTIP)&&(i+="  "+o.replace("%1",e.workspace.options.oneBasedIndex?"#1":"#0")),i}))},t.Extensions.register("text_indexOf_tooltip",t.Constants.Text.TEXT_INDEXOF_TOOLTIP_EXTENSION),t.Extensions.register("text_quotes",t.Constants.Text.TEXT_QUOTES_EXTENSION),t.Extensions.registerMutator("text_join_mutator",t.Constants.Text.TEXT_JOIN_MUTATOR_MIXIN,t.Constants.Text.TEXT_JOIN_EXTENSION),t.Extensions.registerMutator("text_charAt_mutator",t.Constants.Text.TEXT_CHARAT_MUTATOR_MIXIN,t.Constants.Text.TEXT_CHARAT_EXTENSION),t.Blocks.variables={},t.Constants.Variables={},t.Constants.Variables.HUE=330,t.defineBlocksWithJsonArray([{type:"variables_get",message0:"%1",args0:[{type:"field_variable",name:"VAR",variable:"%{BKY_VARIABLES_DEFAULT_NAME}"}],output:null,style:"variable_blocks",helpUrl:"%{BKY_VARIABLES_GET_HELPURL}",tooltip:"%{BKY_VARIABLES_GET_TOOLTIP}",extensions:["contextMenu_variableSetterGetter"]},{type:"variables_set",message0:"%{BKY_VARIABLES_SET}",args0:[{type:"field_variable",name:"VAR",variable:"%{BKY_VARIABLES_DEFAULT_NAME}"},{type:"input_value",name:"VALUE"}],previousStatement:null,nextStatement:null,style:"variable_blocks",tooltip:"%{BKY_VARIABLES_SET_TOOLTIP}",helpUrl:"%{BKY_VARIABLES_SET_HELPURL}",extensions:["contextMenu_variableSetterGetter"]}]),t.Constants.Variables.CUSTOM_CONTEXT_MENU_VARIABLE_GETTER_SETTER_MIXIN={customContextMenu:function(e){if(this.isInFlyout)"variables_get"!=this.type&&"variables_get_reporter"!=this.type||(o={text:t.Msg.RENAME_VARIABLE,enabled:!0,callback:t.Constants.Variables.RENAME_OPTION_CALLBACK_FACTORY(this)},s=this.getField("VAR").getText(),n={text:t.Msg.DELETE_VARIABLE.replace("%1",s),enabled:!0,callback:t.Constants.Variables.DELETE_OPTION_CALLBACK_FACTORY(this)},e.unshift(o),e.unshift(n));else{if("variables_get"==this.type)var o="variables_set",i=t.Msg.VARIABLES_GET_CREATE_SET;else o="variables_get",i=t.Msg.VARIABLES_SET_CREATE_GET;var n={enabled:0<this.workspace.remainingCapacity()},s=this.getField("VAR").getText();n.text=i.replace("%1",s),(i=t.utils.xml.createElement("field")).setAttribute("name","VAR"),i.appendChild(t.utils.xml.createTextNode(s)),(s=t.utils.xml.createElement("block")).setAttribute("type",o),s.appendChild(i),n.callback=t.ContextMenu.callbackFactory(this,s),e.push(n)}}},t.Constants.Variables.RENAME_OPTION_CALLBACK_FACTORY=function(e){return function(){var o=e.workspace,i=e.getField("VAR").getVariable();t.Variables.renameVariable(o,i)}},t.Constants.Variables.DELETE_OPTION_CALLBACK_FACTORY=function(t){return function(){var e=t.workspace,o=t.getField("VAR").getVariable();e.deleteVariableById(o.getId()),e.refreshToolboxSelection()}},t.Extensions.registerMixin("contextMenu_variableSetterGetter",t.Constants.Variables.CUSTOM_CONTEXT_MENU_VARIABLE_GETTER_SETTER_MIXIN),t.Constants.VariablesDynamic={},t.Constants.VariablesDynamic.HUE=310,t.defineBlocksWithJsonArray([{type:"variables_get_dynamic",message0:"%1",args0:[{type:"field_variable",name:"VAR",variable:"%{BKY_VARIABLES_DEFAULT_NAME}"}],output:null,style:"variable_dynamic_blocks",helpUrl:"%{BKY_VARIABLES_GET_HELPURL}",tooltip:"%{BKY_VARIABLES_GET_TOOLTIP}",extensions:["contextMenu_variableDynamicSetterGetter"]},{type:"variables_set_dynamic",message0:"%{BKY_VARIABLES_SET}",args0:[{type:"field_variable",name:"VAR",variable:"%{BKY_VARIABLES_DEFAULT_NAME}"},{type:"input_value",name:"VALUE"}],previousStatement:null,nextStatement:null,style:"variable_dynamic_blocks",tooltip:"%{BKY_VARIABLES_SET_TOOLTIP}",helpUrl:"%{BKY_VARIABLES_SET_HELPURL}",extensions:["contextMenu_variableDynamicSetterGetter"]}]),t.Constants.VariablesDynamic.CUSTOM_CONTEXT_MENU_VARIABLE_GETTER_SETTER_MIXIN={customContextMenu:function(e){if(this.isInFlyout)"variables_get_dynamic"!=this.type&&"variables_get_reporter_dynamic"!=this.type||(o={text:t.Msg.RENAME_VARIABLE,enabled:!0,callback:t.Constants.Variables.RENAME_OPTION_CALLBACK_FACTORY(this)},r=this.getField("VAR").getText(),s={text:t.Msg.DELETE_VARIABLE.replace("%1",r),enabled:!0,callback:t.Constants.Variables.DELETE_OPTION_CALLBACK_FACTORY(this)},e.unshift(o),e.unshift(s));else{var o=this.getFieldValue("VAR"),i=this.workspace.getVariableById(o).type;if("variables_get_dynamic"==this.type){o="variables_set_dynamic";var n=t.Msg.VARIABLES_GET_CREATE_SET}else o="variables_get_dynamic",n=t.Msg.VARIABLES_SET_CREATE_GET;var s={enabled:0<this.workspace.remainingCapacity()},r=this.getField("VAR").getText();s.text=n.replace("%1",r),(n=t.utils.xml.createElement("field")).setAttribute("name","VAR"),n.setAttribute("variabletype",i),n.appendChild(t.utils.xml.createTextNode(r)),(r=t.utils.xml.createElement("block")).setAttribute("type",o),r.appendChild(n),s.callback=t.ContextMenu.callbackFactory(this,r),e.push(s)}},onchange:function(e){e=this.getFieldValue("VAR"),e=t.Variables.getVariable(this.workspace,e),"variables_get_dynamic"==this.type?this.outputConnection.setCheck(e.type):this.getInput("VALUE").connection.setCheck(e.type)}},t.Constants.VariablesDynamic.RENAME_OPTION_CALLBACK_FACTORY=function(e){return function(){var o=e.workspace,i=e.getField("VAR").getVariable();t.Variables.renameVariable(o,i)}},t.Constants.VariablesDynamic.DELETE_OPTION_CALLBACK_FACTORY=function(t){return function(){var e=t.workspace,o=t.getField("VAR").getVariable();e.deleteVariableById(o.getId()),e.refreshToolboxSelection()}},t.Extensions.registerMixin("contextMenu_variableDynamicSetterGetter",t.Constants.VariablesDynamic.CUSTOM_CONTEXT_MENU_VARIABLE_GETTER_SETTER_MIXIN),t.Blocks})?i.apply(e,n):i)||(t.exports=s)},function(t,e,o){var i,n,s;n=[o(3)],void 0===(s="function"==typeof(i=function(t){"use strict";return t.JavaScript=new t.Generator("JavaScript"),t.JavaScript.addReservedWords("break,case,catch,class,const,continue,debugger,default,delete,do,else,export,extends,finally,for,function,if,import,in,instanceof,new,return,super,switch,this,throw,try,typeof,var,void,while,with,yield,enum,implements,interface,let,package,private,protected,public,static,await,null,true,false,arguments,"+Object.getOwnPropertyNames(t.utils.global).join(",")),t.JavaScript.ORDER_ATOMIC=0,t.JavaScript.ORDER_NEW=1.1,t.JavaScript.ORDER_MEMBER=1.2,t.JavaScript.ORDER_FUNCTION_CALL=2,t.JavaScript.ORDER_INCREMENT=3,t.JavaScript.ORDER_DECREMENT=3,t.JavaScript.ORDER_BITWISE_NOT=4.1,t.JavaScript.ORDER_UNARY_PLUS=4.2,t.JavaScript.ORDER_UNARY_NEGATION=4.3,t.JavaScript.ORDER_LOGICAL_NOT=4.4,t.JavaScript.ORDER_TYPEOF=4.5,t.JavaScript.ORDER_VOID=4.6,t.JavaScript.ORDER_DELETE=4.7,t.JavaScript.ORDER_AWAIT=4.8,t.JavaScript.ORDER_EXPONENTIATION=5,t.JavaScript.ORDER_MULTIPLICATION=5.1,t.JavaScript.ORDER_DIVISION=5.2,t.JavaScript.ORDER_MODULUS=5.3,t.JavaScript.ORDER_SUBTRACTION=6.1,t.JavaScript.ORDER_ADDITION=6.2,t.JavaScript.ORDER_BITWISE_SHIFT=7,t.JavaScript.ORDER_RELATIONAL=8,t.JavaScript.ORDER_IN=8,t.JavaScript.ORDER_INSTANCEOF=8,t.JavaScript.ORDER_EQUALITY=9,t.JavaScript.ORDER_BITWISE_AND=10,t.JavaScript.ORDER_BITWISE_XOR=11,t.JavaScript.ORDER_BITWISE_OR=12,t.JavaScript.ORDER_LOGICAL_AND=13,t.JavaScript.ORDER_LOGICAL_OR=14,t.JavaScript.ORDER_CONDITIONAL=15,t.JavaScript.ORDER_ASSIGNMENT=16,t.JavaScript.ORDER_YIELD=17,t.JavaScript.ORDER_COMMA=18,t.JavaScript.ORDER_NONE=99,t.JavaScript.ORDER_OVERRIDES=[[t.JavaScript.ORDER_FUNCTION_CALL,t.JavaScript.ORDER_MEMBER],[t.JavaScript.ORDER_FUNCTION_CALL,t.JavaScript.ORDER_FUNCTION_CALL],[t.JavaScript.ORDER_MEMBER,t.JavaScript.ORDER_MEMBER],[t.JavaScript.ORDER_MEMBER,t.JavaScript.ORDER_FUNCTION_CALL],[t.JavaScript.ORDER_LOGICAL_NOT,t.JavaScript.ORDER_LOGICAL_NOT],[t.JavaScript.ORDER_MULTIPLICATION,t.JavaScript.ORDER_MULTIPLICATION],[t.JavaScript.ORDER_ADDITION,t.JavaScript.ORDER_ADDITION],[t.JavaScript.ORDER_LOGICAL_AND,t.JavaScript.ORDER_LOGICAL_AND],[t.JavaScript.ORDER_LOGICAL_OR,t.JavaScript.ORDER_LOGICAL_OR]],t.JavaScript.init=function(e){t.JavaScript.definitions_=Object.create(null),t.JavaScript.functionNames_=Object.create(null),t.JavaScript.variableDB_?t.JavaScript.variableDB_.reset():t.JavaScript.variableDB_=new t.Names(t.JavaScript.RESERVED_WORDS_),t.JavaScript.variableDB_.setVariableMap(e.getVariableMap());for(var o=[],i=t.Variables.allDeveloperVariables(e),n=0;n<i.length;n++)o.push(t.JavaScript.variableDB_.getName(i[n],t.Names.DEVELOPER_VARIABLE_TYPE));for(e=t.Variables.allUsedVarModels(e),n=0;n<e.length;n++)o.push(t.JavaScript.variableDB_.getName(e[n].getId(),t.VARIABLE_CATEGORY_NAME));o.length&&(t.JavaScript.definitions_.variables="var "+o.join(", ")+";")},t.JavaScript.finish=function(e){var o,i=[];for(o in t.JavaScript.definitions_)i.push(t.JavaScript.definitions_[o]);return delete t.JavaScript.definitions_,delete t.JavaScript.functionNames_,t.JavaScript.variableDB_.reset(),i.join("\n\n")+"\n\n\n"+e},t.JavaScript.scrubNakedValue=function(t){return t+";\n"},t.JavaScript.quote_=function(t){return"'"+(t=t.replace(/\\/g,"\\\\").replace(/\n/g,"\\\n").replace(/'/g,"\\'"))+"'"},t.JavaScript.multiline_quote_=function(e){return e.split(/\n/g).map(t.JavaScript.quote_).join(" + '\\n' +\n")},t.JavaScript.scrub_=function(e,o,i){var n="";if(!e.outputConnection||!e.outputConnection.targetConnection){var s=e.getCommentText();s&&(s=t.utils.string.wrap(s,t.JavaScript.COMMENT_WRAP-3),n+=t.JavaScript.prefixLines(s+"\n","// "));for(var r=0;r<e.inputList.length;r++)e.inputList[r].type==t.INPUT_VALUE&&(s=e.inputList[r].connection.targetBlock())&&(s=t.JavaScript.allNestedComments(s))&&(n+=t.JavaScript.prefixLines(s,"// "))}return e=e.nextConnection&&e.nextConnection.targetBlock(),n+o+(i=i?"":t.JavaScript.blockToCode(e))},t.JavaScript.getAdjusted=function(e,o,i,n,s){i=i||0,s=s||t.JavaScript.ORDER_NONE,e.workspace.options.oneBasedIndex&&i--;var r=e.workspace.options.oneBasedIndex?"1":"0";if(e=0<i?t.JavaScript.valueToCode(e,o,t.JavaScript.ORDER_ADDITION)||r:0>i?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(0<i){e=e+" + "+i;var a=t.JavaScript.ORDER_ADDITION}else 0>i&&(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<e.itemCount_;i++)o[i]=t.JavaScript.valueToCode(e,"ADD"+i,t.JavaScript.ORDER_COMMA)||"null";return["["+o.join(", ")+"]",t.JavaScript.ORDER_ATOMIC]},t.JavaScript.lists_repeat=function(e){return[t.JavaScript.provideFunction_("listsRepeat",["function "+t.JavaScript.FUNCTION_NAME_PLACEHOLDER_+"(value, n) {","  var array = [];","  for (var i = 0; i < n; i++) {","    array[i] = value;","  }","  return array;","}"])+"("+(t.JavaScript.valueToCode(e,"ITEM",t.JavaScript.ORDER_COMMA)||"null")+", "+(e=t.JavaScript.valueToCode(e,"NUM",t.JavaScript.ORDER_COMMA)||"0")+")",t.JavaScript.ORDER_FUNCTION_CALL]},t.JavaScript.lists_length=function(e){return[(t.JavaScript.valueToCode(e,"VALUE",t.JavaScript.ORDER_MEMBER)||"[]")+".length",t.JavaScript.ORDER_MEMBER]},t.JavaScript.lists_isEmpty=function(e){return["!"+(t.JavaScript.valueToCode(e,"VALUE",t.JavaScript.ORDER_MEMBER)||"[]")+".length",t.JavaScript.ORDER_LOGICAL_NOT]},t.JavaScript.lists_indexOf=function(e){var o="FIRST"==e.getFieldValue("END")?"indexOf":"lastIndexOf",i=t.JavaScript.valueToCode(e,"FIND",t.JavaScript.ORDER_NONE)||"''";return o=(t.JavaScript.valueToCode(e,"VALUE",t.JavaScript.ORDER_MEMBER)||"[]")+"."+o+"("+i+")",e.workspace.options.oneBasedIndex?[o+" + 1",t.JavaScript.ORDER_ADDITION]:[o,t.JavaScript.ORDER_FUNCTION_CALL]},t.JavaScript.lists_getIndex=function(e){var o=e.getFieldValue("MODE")||"GET",i=e.getFieldValue("WHERE")||"FROM_START",n=t.JavaScript.valueToCode(e,"VALUE","RANDOM"==i?t.JavaScript.ORDER_COMMA:t.JavaScript.ORDER_MEMBER)||"[]";switch(i){case"FIRST":if("GET"==o)return[n+"[0]",t.JavaScript.ORDER_MEMBER];if("GET_REMOVE"==o)return[n+".shift()",t.JavaScript.ORDER_MEMBER];if("REMOVE"==o)return n+".shift();\n";break;case"LAST":if("GET"==o)return[n+".slice(-1)[0]",t.JavaScript.ORDER_MEMBER];if("GET_REMOVE"==o)return[n+".pop()",t.JavaScript.ORDER_MEMBER];if("REMOVE"==o)return n+".pop();\n";break;case"FROM_START":if(e=t.JavaScript.getAdjusted(e,"AT"),"GET"==o)return[n+"["+e+"]",t.JavaScript.ORDER_MEMBER];if("GET_REMOVE"==o)return[n+".splice("+e+", 1)[0]",t.JavaScript.ORDER_FUNCTION_CALL];if("REMOVE"==o)return n+".splice("+e+", 1);\n";break;case"FROM_END":if(e=t.JavaScript.getAdjusted(e,"AT",1,!0),"GET"==o)return[n+".slice("+e+")[0]",t.JavaScript.ORDER_FUNCTION_CALL];if("GET_REMOVE"==o)return[n+".splice("+e+", 1)[0]",t.JavaScript.ORDER_FUNCTION_CALL];if("REMOVE"==o)return n+".splice("+e+", 1);";break;case"RANDOM":if(n=t.JavaScript.provideFunction_("listsGetRandomItem",["function "+t.JavaScript.FUNCTION_NAME_PLACEHOLDER_+"(list, remove) {","  var x = Math.floor(Math.random() * list.length);","  if (remove) {","    return list.splice(x, 1)[0];","  } else {","    return list[x];","  }","}"])+"("+n+", "+("GET"!=o)+")","GET"==o||"GET_REMOVE"==o)return[n,t.JavaScript.ORDER_FUNCTION_CALL];if("REMOVE"==o)return n+";\n"}throw Error("Unhandled combination (lists_getIndex).")},t.JavaScript.lists_setIndex=function(e){function o(){if(i.match(/^\w+$/))return"";var e=t.JavaScript.variableDB_.getDistinctName("tmpList",t.VARIABLE_CATEGORY_NAME),o="var "+e+" = "+i+";\n";return i=e,o}var i=t.JavaScript.valueToCode(e,"LIST",t.JavaScript.ORDER_MEMBER)||"[]",n=e.getFieldValue("MODE")||"GET",s=e.getFieldValue("WHERE")||"FROM_START",r=t.JavaScript.valueToCode(e,"TO",t.JavaScript.ORDER_ASSIGNMENT)||"null";switch(s){case"FIRST":if("SET"==n)return i+"[0] = "+r+";\n";if("INSERT"==n)return i+".unshift("+r+");\n";break;case"LAST":if("SET"==n)return(e=o())+(i+"[")+i+".length - 1] = "+r+";\n";if("INSERT"==n)return i+".push("+r+");\n";break;case"FROM_START":if(s=t.JavaScript.getAdjusted(e,"AT"),"SET"==n)return i+"["+s+"] = "+r+";\n";if("INSERT"==n)return i+".splice("+s+", 0, "+r+");\n";break;case"FROM_END":if(s=t.JavaScript.getAdjusted(e,"AT",1,!1,t.JavaScript.ORDER_SUBTRACTION),e=o(),"SET"==n)return e+(i+"[")+i+".length - "+s+"] = "+r+";\n";if("INSERT"==n)return e+(i+".splice(")+i+".length - "+s+", 0, "+r+");\n";break;case"RANDOM":if(e=o(),e+="var "+(s=t.JavaScript.variableDB_.getDistinctName("tmpX",t.VARIABLE_CATEGORY_NAME))+" = Math.floor(Math.random() * "+i+".length);\n","SET"==n)return e+(i+"[")+s+"] = "+r+";\n";if("INSERT"==n)return e+(i+".splice(")+s+", 0, "+r+");\n"}throw Error("Unhandled combination (lists_setIndex).")},t.JavaScript.lists.getIndex_=function(t,e,o){return"FIRST"==e?"0":"FROM_END"==e?t+".length - 1 - "+o:"LAST"==e?t+".length - 1":o},t.JavaScript.lists_getSublist=function(e){var o=t.JavaScript.valueToCode(e,"LIST",t.JavaScript.ORDER_MEMBER)||"[]",i=e.getFieldValue("WHERE1"),n=e.getFieldValue("WHERE2");if("FIRST"==i&&"LAST"==n)o+=".slice(0)";else if(o.match(/^\w+$/)||"FROM_END"!=i&&"FROM_START"==n){switch(i){case"FROM_START":var s=t.JavaScript.getAdjusted(e,"AT1");break;case"FROM_END":s=o+".length - "+(s=t.JavaScript.getAdjusted(e,"AT1",1,!1,t.JavaScript.ORDER_SUBTRACTION));break;case"FIRST":s="0";break;default:throw Error("Unhandled option (lists_getSublist).")}switch(n){case"FROM_START":e=t.JavaScript.getAdjusted(e,"AT2",1);break;case"FROM_END":e=o+".length - "+(e=t.JavaScript.getAdjusted(e,"AT2",0,!1,t.JavaScript.ORDER_SUBTRACTION));break;case"LAST":e=o+".length";break;default:throw Error("Unhandled option (lists_getSublist).")}o=o+".slice("+s+", "+e+")"}else{s=t.JavaScript.getAdjusted(e,"AT1"),e=t.JavaScript.getAdjusted(e,"AT2");var r=t.JavaScript.lists.getIndex_,a={FIRST:"First",LAST:"Last",FROM_START:"FromStart",FROM_END:"FromEnd"};o=t.JavaScript.provideFunction_("subsequence"+a[i]+a[n],["function "+t.JavaScript.FUNCTION_NAME_PLACEHOLDER_+"(sequence"+("FROM_END"==i||"FROM_START"==i?", at1":"")+("FROM_END"==n||"FROM_START"==n?", at2":"")+") {","  var start = "+r("sequence",i,"at1")+";","  var end = "+r("sequence",n,"at2")+" + 1;","  return sequence.slice(start, end);","}"])+"("+o+("FROM_END"==i||"FROM_START"==i?", "+s:"")+("FROM_END"==n||"FROM_START"==n?", "+e:"")+")"}return[o,t.JavaScript.ORDER_FUNCTION_CALL]},t.JavaScript.lists_sort=function(e){var o=t.JavaScript.valueToCode(e,"LIST",t.JavaScript.ORDER_FUNCTION_CALL)||"[]",i="1"===e.getFieldValue("DIRECTION")?1:-1;return e=e.getFieldValue("TYPE"),[o+".slice().sort("+t.JavaScript.provideFunction_("listsGetSortCompare",["function "+t.JavaScript.FUNCTION_NAME_PLACEHOLDER_+"(type, direction) {","  var compareFuncs = {",'    "NUMERIC": function(a, b) {',"        return Number(a) - Number(b); },",'    "TEXT": function(a, b) {',"        return a.toString() > 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<o?" else ":"")+"if ("+n+") {\n"+s+"}",++o}while(e.getInput("IF"+o));return(e.getInput("ELSE")||t.JavaScript.STATEMENT_SUFFIX)&&(s=t.JavaScript.statementToCode(e,"ELSE"),t.JavaScript.STATEMENT_SUFFIX&&(s=t.JavaScript.prefixLines(t.JavaScript.injectId(t.JavaScript.STATEMENT_SUFFIX,e),t.JavaScript.INDENT)+s),i+=" else {\n"+s+"}"),i+"\n"},t.JavaScript.controls_ifelse=t.JavaScript.controls_if,t.JavaScript.logic_compare=function(e){var o={EQ:"==",NEQ:"!=",LT:"<",LTE:"<=",GT:">",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<e.arguments_.length;c++)l[c]=t.JavaScript.variableDB_.getName(e.arguments_[c],t.VARIABLE_CATEGORY_NAME);return i="function "+o+"("+l.join(", ")+") {\n"+i+n+s+a+r+"}",i=t.JavaScript.scrub_(e,i),t.JavaScript.definitions_["%"+o]=i,null},t.JavaScript.procedures_defnoreturn=t.JavaScript.procedures_defreturn,t.JavaScript.procedures_callreturn=function(e){for(var o=t.JavaScript.variableDB_.getName(e.getFieldValue("NAME"),t.PROCEDURE_CATEGORY_NAME),i=[],n=0;n<e.arguments_.length;n++)i[n]=t.JavaScript.valueToCode(e,"ARG"+n,t.JavaScript.ORDER_COMMA)||"null";return[o+"("+i.join(", ")+")",t.JavaScript.ORDER_FUNCTION_CALL]},t.JavaScript.procedures_callnoreturn=function(e){return t.JavaScript.procedures_callreturn(e)[0]+";\n"},t.JavaScript.procedures_ifreturn=function(e){var o="if ("+(t.JavaScript.valueToCode(e,"CONDITION",t.JavaScript.ORDER_NONE)||"false")+") {\n";return t.JavaScript.STATEMENT_SUFFIX&&(o+=t.JavaScript.prefixLines(t.JavaScript.injectId(t.JavaScript.STATEMENT_SUFFIX,e),t.JavaScript.INDENT)),e.hasReturnValue_?(e=t.JavaScript.valueToCode(e,"VALUE",t.JavaScript.ORDER_NONE)||"null",o+=t.JavaScript.INDENT+"return "+e+";\n"):o+=t.JavaScript.INDENT+"return;\n",o+"}\n"},t.JavaScript.texts={},t.JavaScript.text=function(e){return[t.JavaScript.quote_(e.getFieldValue("TEXT")),t.JavaScript.ORDER_ATOMIC]},t.JavaScript.text_multiline=function(e){return(e=t.JavaScript.multiline_quote_(e.getFieldValue("TEXT"))).includes("\n")&&(e="("+e+")"),[e,t.JavaScript.ORDER_ATOMIC]},t.JavaScript.text.forceString_=function(e){return t.JavaScript.text.forceString_.strRegExp.test(e)?e:"String("+e+")"},t.JavaScript.text.forceString_.strRegExp=/^\s*'([^']|\\')*'\s*$/,t.JavaScript.text_join=function(e){switch(e.itemCount_){case 0:return["''",t.JavaScript.ORDER_ATOMIC];case 1:return e=t.JavaScript.valueToCode(e,"ADD0",t.JavaScript.ORDER_NONE)||"''",[e=t.JavaScript.text.forceString_(e),t.JavaScript.ORDER_FUNCTION_CALL];case 2:var o=t.JavaScript.valueToCode(e,"ADD0",t.JavaScript.ORDER_NONE)||"''";return e=t.JavaScript.valueToCode(e,"ADD1",t.JavaScript.ORDER_NONE)||"''",[e=t.JavaScript.text.forceString_(o)+" + "+t.JavaScript.text.forceString_(e),t.JavaScript.ORDER_ADDITION];default:o=Array(e.itemCount_);for(var i=0;i<e.itemCount_;i++)o[i]=t.JavaScript.valueToCode(e,"ADD"+i,t.JavaScript.ORDER_COMMA)||"''";return[e="["+o.join(",")+"].join('')",t.JavaScript.ORDER_FUNCTION_CALL]}},t.JavaScript.text_append=function(e){var o=t.JavaScript.variableDB_.getName(e.getFieldValue("VAR"),t.VARIABLE_CATEGORY_NAME);return e=t.JavaScript.valueToCode(e,"TEXT",t.JavaScript.ORDER_NONE)||"''",o+" += "+t.JavaScript.text.forceString_(e)+";\n"},t.JavaScript.text_length=function(e){return[(t.JavaScript.valueToCode(e,"VALUE",t.JavaScript.ORDER_FUNCTION_CALL)||"''")+".length",t.JavaScript.ORDER_MEMBER]},t.JavaScript.text_isEmpty=function(e){return["!"+(t.JavaScript.valueToCode(e,"VALUE",t.JavaScript.ORDER_MEMBER)||"''")+".length",t.JavaScript.ORDER_LOGICAL_NOT]},t.JavaScript.text_indexOf=function(e){var o="FIRST"==e.getFieldValue("END")?"indexOf":"lastIndexOf",i=t.JavaScript.valueToCode(e,"FIND",t.JavaScript.ORDER_NONE)||"''";return o=(t.JavaScript.valueToCode(e,"VALUE",t.JavaScript.ORDER_MEMBER)||"''")+"."+o+"("+i+")",e.workspace.options.oneBasedIndex?[o+" + 1",t.JavaScript.ORDER_ADDITION]:[o,t.JavaScript.ORDER_FUNCTION_CALL]},t.JavaScript.text_charAt=function(e){var o=e.getFieldValue("WHERE")||"FROM_START",i=t.JavaScript.valueToCode(e,"VALUE","RANDOM"==o?t.JavaScript.ORDER_NONE:t.JavaScript.ORDER_MEMBER)||"''";switch(o){case"FIRST":return[i+".charAt(0)",t.JavaScript.ORDER_FUNCTION_CALL];case"LAST":return[i+".slice(-1)",t.JavaScript.ORDER_FUNCTION_CALL];case"FROM_START":return[i+".charAt("+(e=t.JavaScript.getAdjusted(e,"AT"))+")",t.JavaScript.ORDER_FUNCTION_CALL];case"FROM_END":return[i+".slice("+(e=t.JavaScript.getAdjusted(e,"AT",1,!0))+").charAt(0)",t.JavaScript.ORDER_FUNCTION_CALL];case"RANDOM":return[t.JavaScript.provideFunction_("textRandomLetter",["function "+t.JavaScript.FUNCTION_NAME_PLACEHOLDER_+"(text) {","  var x = Math.floor(Math.random() * text.length);","  return text[x];","}"])+"("+i+")",t.JavaScript.ORDER_FUNCTION_CALL]}throw Error("Unhandled option (text_charAt).")},t.JavaScript.text.getIndex_=function(t,e,o){return"FIRST"==e?"0":"FROM_END"==e?t+".length - 1 - "+o:"LAST"==e?t+".length - 1":o},t.JavaScript.text_getSubstring=function(e){var o=t.JavaScript.valueToCode(e,"STRING",t.JavaScript.ORDER_FUNCTION_CALL)||"''",i=e.getFieldValue("WHERE1"),n=e.getFieldValue("WHERE2");if("FIRST"!=i||"LAST"!=n)if(o.match(/^'?\w+'?$/)||"FROM_END"!=i&&"LAST"!=i&&"FROM_END"!=n&&"LAST"!=n){switch(i){case"FROM_START":var s=t.JavaScript.getAdjusted(e,"AT1");break;case"FROM_END":s=o+".length - "+(s=t.JavaScript.getAdjusted(e,"AT1",1,!1,t.JavaScript.ORDER_SUBTRACTION));break;case"FIRST":s="0";break;default:throw Error("Unhandled option (text_getSubstring).")}switch(n){case"FROM_START":e=t.JavaScript.getAdjusted(e,"AT2",1);break;case"FROM_END":e=o+".length - "+(e=t.JavaScript.getAdjusted(e,"AT2",0,!1,t.JavaScript.ORDER_SUBTRACTION));break;case"LAST":e=o+".length";break;default:throw Error("Unhandled option (text_getSubstring).")}o=o+".slice("+s+", "+e+")"}else{s=t.JavaScript.getAdjusted(e,"AT1"),e=t.JavaScript.getAdjusted(e,"AT2");var r=t.JavaScript.text.getIndex_,a={FIRST:"First",LAST:"Last",FROM_START:"FromStart",FROM_END:"FromEnd"};o=t.JavaScript.provideFunction_("subsequence"+a[i]+a[n],["function "+t.JavaScript.FUNCTION_NAME_PLACEHOLDER_+"(sequence"+("FROM_END"==i||"FROM_START"==i?", at1":"")+("FROM_END"==n||"FROM_START"==n?", at2":"")+") {","  var start = "+r("sequence",i,"at1")+";","  var end = "+r("sequence",n,"at2")+" + 1;","  return sequence.slice(start, end);","}"])+"("+o+("FROM_END"==i||"FROM_START"==i?", "+s:"")+("FROM_END"==n||"FROM_START"==n?", "+e:"")+")"}return[o,t.JavaScript.ORDER_FUNCTION_CALL]},t.JavaScript.text_changeCase=function(e){var o={UPPERCASE:".toUpperCase()",LOWERCASE:".toLowerCase()",TITLECASE:null}[e.getFieldValue("CASE")];return e=t.JavaScript.valueToCode(e,"TEXT",o?t.JavaScript.ORDER_MEMBER:t.JavaScript.ORDER_NONE)||"''",[o?e+o:t.JavaScript.provideFunction_("textToTitleCase",["function "+t.JavaScript.FUNCTION_NAME_PLACEHOLDER_+"(str) {","  return str.replace(/\\S+/g,","      function(txt) {return txt[0].toUpperCase() + txt.substring(1).toLowerCase();});","}"])+"("+e+")",t.JavaScript.ORDER_FUNCTION_CALL]},t.JavaScript.text_trim=function(e){var o={LEFT:".replace(/^[\\s\\xa0]+/, '')",RIGHT:".replace(/[\\s\\xa0]+$/, '')",BOTH:".trim()"}[e.getFieldValue("MODE")];return[(t.JavaScript.valueToCode(e,"TEXT",t.JavaScript.ORDER_MEMBER)||"''")+o,t.JavaScript.ORDER_FUNCTION_CALL]},t.JavaScript.text_print=function(e){return"window.alert("+(t.JavaScript.valueToCode(e,"TEXT",t.JavaScript.ORDER_NONE)||"''")+");\n"},t.JavaScript.text_prompt_ext=function(e){var o="window.prompt("+(e.getField("TEXT")?t.JavaScript.quote_(e.getFieldValue("TEXT")):t.JavaScript.valueToCode(e,"TEXT",t.JavaScript.ORDER_NONE)||"''")+")";return"NUMBER"==e.getFieldValue("TYPE")&&(o="Number("+o+")"),[o,t.JavaScript.ORDER_FUNCTION_CALL]},t.JavaScript.text_prompt=t.JavaScript.text_prompt_ext,t.JavaScript.text_count=function(e){var o=t.JavaScript.valueToCode(e,"TEXT",t.JavaScript.ORDER_MEMBER)||"''";return e=t.JavaScript.valueToCode(e,"SUB",t.JavaScript.ORDER_NONE)||"''",[t.JavaScript.provideFunction_("textCount",["function "+t.JavaScript.FUNCTION_NAME_PLACEHOLDER_+"(haystack, needle) {","  if (needle.length === 0) {","    return haystack.length + 1;","  } else {","    return haystack.split(needle).length - 1;","  }","}"])+"("+o+", "+e+")",t.JavaScript.ORDER_SUBTRACTION]},t.JavaScript.text_replace=function(e){var o=t.JavaScript.valueToCode(e,"TEXT",t.JavaScript.ORDER_MEMBER)||"''",i=t.JavaScript.valueToCode(e,"FROM",t.JavaScript.ORDER_NONE)||"''";return e=t.JavaScript.valueToCode(e,"TO",t.JavaScript.ORDER_NONE)||"''",[t.JavaScript.provideFunction_("textReplace",["function "+t.JavaScript.FUNCTION_NAME_PLACEHOLDER_+"(haystack, needle, replacement) {",'  needle = needle.replace(/([-()\\[\\]{}+?*.$\\^|,:#<!\\\\])/g,"\\\\$1")','                 .replace(/\\x08/g,"\\\\x08");',"  return haystack.replace(new RegExp(needle, 'g'), replacement);","}"])+"("+o+", "+i+", "+e+")",t.JavaScript.ORDER_MEMBER]},t.JavaScript.text_reverse=function(e){return[(t.JavaScript.valueToCode(e,"TEXT",t.JavaScript.ORDER_MEMBER)||"''")+".split('').reverse().join('')",t.JavaScript.ORDER_MEMBER]},t.JavaScript.variables={},t.JavaScript.variables_get=function(e){return[t.JavaScript.variableDB_.getName(e.getFieldValue("VAR"),t.VARIABLE_CATEGORY_NAME),t.JavaScript.ORDER_ATOMIC]},t.JavaScript.variables_set=function(e){var o=t.JavaScript.valueToCode(e,"VALUE",t.JavaScript.ORDER_ASSIGNMENT)||"0";return t.JavaScript.variableDB_.getName(e.getFieldValue("VAR"),t.VARIABLE_CATEGORY_NAME)+" = "+o+";\n"},t.JavaScript.variablesDynamic={},t.JavaScript.variables_get_dynamic=t.JavaScript.variables_get,t.JavaScript.variables_set_dynamic=t.JavaScript.variables_set,t.JavaScript})?i.apply(e,n):i)||(t.exports=s)},function(t,e){t.exports=function(t){if(!t.webpackPolyfill){var e=Object.create(t);e.children||(e.children=[]),Object.defineProperty(e,"loaded",{enumerable:!0,get:function(){return e.l}}),Object.defineProperty(e,"id",{enumerable:!0,get:function(){return e.i}}),Object.defineProperty(e,"exports",{enumerable:!0}),e.webpackPolyfill=1}return e}}]]);
\ No newline at end of file
diff --git a/static/bdk-cli/playground/2.playground.js b/static/bdk-cli/playground/2.playground.js
new file mode 100644 (file)
index 0000000..ac986de
--- /dev/null
@@ -0,0 +1 @@
+(window.webpackJsonp=window.webpackJsonp||[]).push([[2],{1:function(e,n,t){"use strict";t.r(n);var i=t(2),o=t(4),r=t.n(o),a={backupBlocks_:function(e){if("localStorage"in window){var n=r.a.Xml.workspaceToDom(e),t=window.location.href.split("#")[0];window.localStorage.setItem(t,r.a.Xml.domToText(n))}},backupOnUnload:function(e){var n=e||r.a.getMainWorkspace();window.addEventListener("unload",(function(){a.backupBlocks_(n)}),!1)},restoreBlocks:function(e){var n=window.location.href.split("#")[0];if("localStorage"in window&&window.localStorage[n]){var t=e||r.a.getMainWorkspace(),i=r.a.Xml.textToDom(window.localStorage[n]);r.a.Xml.domToWorkspace(i,t)}},link:function(e){var n=e||r.a.getMainWorkspace(),t=r.a.Xml.workspaceToDom(n,!0);if(1==n.getTopBlocks(!1).length&&t.querySelector){var i=t.querySelector("block");i&&(i.removeAttribute("x"),i.removeAttribute("y"))}var o=r.a.Xml.domToText(t);a.makeRequest_("/storage","xml",o,n)},retrieveXml:function(e,n){var t=n||r.a.getMainWorkspace();a.makeRequest_("/storage","key",e,t)},httpRequest_:null,makeRequest_:function(e,n,t,i){a.httpRequest_&&a.httpRequest_.abort(),a.httpRequest_=new XMLHttpRequest,a.httpRequest_.name=n,a.httpRequest_.onreadystatechange=a.handleRequest_,a.httpRequest_.open("POST",e),a.httpRequest_.setRequestHeader("Content-Type","application/x-www-form-urlencoded"),a.httpRequest_.send(n+"="+encodeURIComponent(t)),a.httpRequest_.workspace=i},handleRequest_:function(){if(4==a.httpRequest_.readyState){if(200!=a.httpRequest_.status)a.alert(a.HTTPREQUEST_ERROR+"\nhttpRequest_.status: "+a.httpRequest_.status);else{var e=a.httpRequest_.responseText.trim();"xml"==a.httpRequest_.name?(window.location.hash=e,a.alert(a.LINK_ALERT.replace("%1",window.location.href))):"key"==a.httpRequest_.name&&(e.length?a.loadXml_(e,a.httpRequest_.workspace):a.alert(a.HASH_ERROR.replace("%1",window.location.hash))),a.monitorChanges_(a.httpRequest_.workspace)}a.httpRequest_=null}},monitorChanges_:function(e){var n=r.a.Xml.workspaceToDom(e),t=r.a.Xml.domToText(n);e.addChangeListener((function n(){var i=r.a.Xml.workspaceToDom(e),o=r.a.Xml.domToText(i);t!=o&&(window.location.hash="",e.removeChangeListener(n))}))},loadXml_:function(e,n){try{e=r.a.Xml.textToDom(e)}catch(n){return void a.alert(a.XML_ERROR+"\nXML: "+e)}n.clear(),r.a.Xml.domToWorkspace(e,n)},alert:function(e){window.alert(e)}},l=a;!async function(){Object(i.ob)(),function(e,n){console.log("Blockly starting");const t=document.getElementById(n);r.a.JavaScript.INDENT="";var i={toolbox:'<xml xmlns="https://developers.google.com/blockly/xml">\n  <category name="Miniscript" colour="#5ba55b">\n    <block type="and"></block>\n    <block type="or">\n      <field name="A_weight">1</field>\n      <field name="B_weight">1</field>\n    </block>\n    <block type="thresh">\n      <field name="Threshold">1</field>\n    </block>\n    <block type="after">\n      <field name="NAME">1</field>\n    </block>\n    <block type="pk"></block>\n    <block type="adapter"></block>\n    <block type="older">\n      <field name="NAME">1</field>\n    </block>\n    <block type="alias_key">\n      <field name="label">Alias</field>\n      <field name="name">name</field>\n    </block>\n    <block type="existing_key">\n      <field name="NAME">Existing Key</field>\n      <field name="key">tpub, WIF, hex...</field>\n    </block>\n  </category>\n  <category name="Examples" colour="#5b67a5">\n    <block type="pk">\n      <value name="pk">\n        <block type="alias_key">\n          <field name="label">Alias</field>\n          <field name="name">Alice</field>\n        </block>\n      </value>\n    </block>\n    <block type="or">\n      <field name="A_weight">1</field>\n      <field name="B_weight">1</field>\n      <statement name="A">\n        <block type="pk">\n          <value name="pk">\n            <block type="alias_key">\n              <field name="label">Alias</field>\n              <field name="name">Alice</field>\n            </block>\n          </value>\n        </block>\n      </statement>\n      <statement name="B">\n        <block type="pk">\n          <value name="pk">\n            <block type="alias_key">\n              <field name="label">Alias</field>\n              <field name="name">Bob</field>\n            </block>\n          </value>\n        </block>\n      </statement>\n    </block>\n    <block type="or">\n      <field name="A_weight">99</field>\n      <field name="B_weight">1</field>\n      <statement name="A">\n        <block type="pk">\n          <value name="pk">\n            <block type="alias_key">\n              <field name="label">Alias</field>\n              <field name="name">KeyLikely</field>\n            </block>\n          </value>\n        </block>\n      </statement>\n      <statement name="B">\n        <block type="pk">\n          <value name="pk">\n            <block type="alias_key">\n              <field name="label">Alias</field>\n              <field name="name">Likely</field>\n            </block>\n          </value>\n        </block>\n      </statement>\n    </block>\n    <block type="and">\n      <statement name="A">\n        <block type="pk">\n          <value name="pk">\n            <block type="alias_key">\n              <field name="label">Alias</field>\n              <field name="name">User</field>\n            </block>\n          </value>\n        </block>\n      </statement>\n      <statement name="B">\n        <block type="or">\n          <field name="A_weight">99</field>\n          <field name="B_weight">1</field>\n          <statement name="A">\n            <block type="pk">\n              <value name="pk">\n                <block type="alias_key">\n                  <field name="label">Alias</field>\n                  <field name="name">Service</field>\n                </block>\n              </value>\n            </block>\n          </statement>\n          <statement name="B">\n            <block type="older">\n              <field name="NAME">12960</field>\n            </block>\n          </statement>\n        </block>\n      </statement>\n    </block>\n    <block type="thresh">\n      <field name="Threshold">3</field>\n      <statement name="A">\n        <block type="adapter">\n          <statement name="NAME">\n            <block type="pk">\n              <value name="pk">\n                <block type="alias_key">\n                  <field name="label">Alias</field>\n                  <field name="name">Alice</field>\n                </block>\n              </value>\n            </block>\n          </statement>\n          <next>\n            <block type="adapter">\n              <statement name="NAME">\n                <block type="pk">\n                  <value name="pk">\n                    <block type="alias_key">\n                      <field name="label">Alias</field>\n                      <field name="name">Bob</field>\n                    </block>\n                  </value>\n                </block>\n              </statement>\n              <next>\n                <block type="adapter">\n                  <statement name="NAME">\n                    <block type="pk">\n                      <value name="pk">\n                        <block type="alias_key">\n                          <field name="label">Alias</field>\n                          <field name="name">Carol</field>\n                        </block>\n                      </value>\n                    </block>\n                  </statement>\n                  <next>\n                    <block type="adapter">\n                      <statement name="NAME">\n                        <block type="older">\n                          <field name="NAME">12960</field>\n                        </block>\n                      </statement>\n                    </block>\n                  </next>\n                </block>\n              </next>\n            </block>\n          </next>\n        </block>\n      </statement>\n    </block>\n  </category>\n</xml>',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='<i class="fas fa-expand"></i>',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+=`<span class="command">> ${e}</span>\n`,a=r.push(e),l.run(e).then(e=>{e&&(t.innerHTML+=`<span class="success">${e}</span>\n`)}).catch(e=>t.innerHTML+=`<span class="error">${e}</span>\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&&a<r.length&&(o.value=r[++a]||"")},{run:u}}(a.value,u.value.length>0?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=`<span class="error">${e}</span>`))},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=`<span class="error">${e}</span>`)}}()},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(;a<i;a++){const n=e.charCodeAt(a);if(n>127)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;o<t;o++)i+=", "+e(n[o]);return i+="]",i}const i=/\[object ([^\]]+)\]/.exec(toString.call(n));let o;if(!(i.length>1))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 (file)
index 0000000..cdcd136
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 (file)
index 0000000..ab260a4
--- /dev/null
@@ -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;i<c.length;i++)n(c[i]);var b=f;u(u.s=0)}([function(e,n,t){Promise.all([t.e(1),t.e(2)]).then(t.bind(null,1)).catch(e=>console.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 (file)
index 87e47df..0000000
+++ /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.length<e.length?t:e})).length:0},t.utils.string.commonWordPrefix=function(e,o){if(!e.length)return 0;if(1==e.length)return e[0].length;var i=0;o=o||t.utils.string.shortestStringLength(e);for(var n=0;n<o;n++){for(var s=e[0][n],r=1;r<e.length;r++)if(s!=e[r][n])return i;" "==s&&(i=n+1)}for(r=1;r<e.length;r++)if((s=e[r][n])&&" "!=s)return i;return o},t.utils.string.commonWordSuffix=function(e,o){if(!e.length)return 0;if(1==e.length)return e[0].length;var i=0;o=o||t.utils.string.shortestStringLength(e);for(var n=0;n<o;n++){for(var s=e[0].substr(-n-1,1),r=1;r<e.length;r++)if(s!=e[r].substr(-n-1,1))return i;" "==s&&(i=n+1)}for(r=1;r<e.length;r++)if((s=e[r].charAt(e[r].length-n-1))&&" "!=s)return i;return o},t.utils.string.wrap=function(e,o){e=e.split("\n");for(var i=0;i<e.length;i++)e[i]=t.utils.string.wrapLine_(e[i],o);return e.join("\n")},t.utils.string.wrapLine_=function(e,o){if(e.length<=o)return e;for(var i=e.trim().split(/\s+/),n=0;n<i.length;n++)i[n].length>o&&(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;n<i.length-1;n++)c<(n+1.5)/l?(c++,e[n]=!0):e[n]=!1;e=t.utils.string.wrapMutate_(i,e,o),n=t.utils.string.wrapScore_(i,e,o),e=t.utils.string.wrapToText_(i,e),s++}while(n>r);return a},t.utils.string.wrapScore_=function(t,e,o){for(var i=[0],n=[],s=0;s<t.length;s++)i[i.length-1]+=t[s].length,!0===e[s]?(i.push(0),n.push(t[s].charAt(t[s].length-1))):!1===e[s]&&i[i.length-1]++;for(t=Math.max.apply(Math,i),s=e=0;s<i.length;s++)e-=2*Math.pow(Math.abs(o-i[s]),1.5),e-=Math.pow(t-i[s],1.5),-1!=".?!".indexOf(n[s])?e+=o/3:-1!=",;)]}".indexOf(n[s])&&(e+=o/4);return 1<i.length&&i[i.length-1]<=i[i.length-2]&&(e+=.5),e},t.utils.string.wrapMutate_=function(e,o,i){for(var n,s=t.utils.string.wrapScore_(e,o,i),r=0;r<o.length-1;r++)if(o[r]!=o[r+1]){var a=[].concat(o);a[r]=!a[r],a[r+1]=!a[r+1];var l=t.utils.string.wrapScore_(e,a,i);l>s&&(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<t.length;i++)o.push(t[i]),void 0!==e[i]&&o.push(e[i]?"\n":" ");return o.join("")},t.utils.Size=function(t,e){this.width=t,this.height=e},t.utils.Size.equals=function(t,e){return t==e||!(!t||!e)&&t.width==e.width&&t.height==e.height},t.utils.style={},t.utils.style.getSize=function(e){if("none"!=t.utils.style.getStyle_(e,"display"))return t.utils.style.getSizeWithDisplay_(e);var o=e.style,i=o.display,n=o.visibility,s=o.position;o.visibility="hidden",o.position="absolute",o.display="inline";var r=e.offsetWidth;return e=e.offsetHeight,o.display=i,o.position=s,o.visibility=n,new t.utils.Size(r,e)},t.utils.style.getSizeWithDisplay_=function(e){return new t.utils.Size(e.offsetWidth,e.offsetHeight)},t.utils.style.getStyle_=function(e,o){return t.utils.style.getComputedStyle(e,o)||t.utils.style.getCascadedStyle(e,o)||e.style&&e.style[o]},t.utils.style.getComputedStyle=function(t,e){return document.defaultView&&document.defaultView.getComputedStyle&&(t=document.defaultView.getComputedStyle(t,null))&&(t[e]||t.getPropertyValue(e))||""},t.utils.style.getCascadedStyle=function(t,e){return t.currentStyle?t.currentStyle[e]:null},t.utils.style.getPageOffset=function(e){var o=new t.utils.Coordinate(0,0);e=e.getBoundingClientRect();var i=document.documentElement;return i=new t.utils.Coordinate(window.pageXOffset||i.scrollLeft,window.pageYOffset||i.scrollTop),o.x=e.left+i.x,o.y=e.top+i.y,o},t.utils.style.getViewportPageOffset=function(){var e=document.body,o=document.documentElement;return new t.utils.Coordinate(e.scrollLeft||o.scrollLeft,e.scrollTop||o.scrollTop)},t.utils.style.setElementShown=function(t,e){t.style.display=e?"":"none"},t.utils.style.isRightToLeft=function(e){return"rtl"==t.utils.style.getStyle_(e,"direction")},t.utils.style.getBorderBox=function(e){var o=t.utils.style.getComputedStyle(e,"borderLeftWidth"),i=t.utils.style.getComputedStyle(e,"borderRightWidth"),n=t.utils.style.getComputedStyle(e,"borderTopWidth");return e=t.utils.style.getComputedStyle(e,"borderBottomWidth"),{top:parseFloat(n),right:parseFloat(i),bottom:parseFloat(e),left:parseFloat(o)}},t.utils.style.scrollIntoContainerView=function(e,o,i){e=t.utils.style.getContainerOffsetToScrollInto(e,o,i),o.scrollLeft=e.x,o.scrollTop=e.y},t.utils.style.getContainerOffsetToScrollInto=function(e,o,i){var n=t.utils.style.getPageOffset(e),s=t.utils.style.getPageOffset(o),r=t.utils.style.getBorderBox(o),a=n.x-s.x-r.left;return n=n.y-s.y-r.top,s=t.utils.style.getSizeWithDisplay_(e),e=o.clientWidth-s.width,s=o.clientHeight-s.height,r=o.scrollLeft,o=o.scrollTop,i?(r+=a-e/2,o+=n-s/2):(r+=Math.min(a,Math.max(a-e,0)),o+=Math.min(n,Math.max(n-s,0))),new t.utils.Coordinate(r,o)},t.utils.userAgent={},function(e){function o(t){return-1!=i.indexOf(t.toUpperCase())}t.utils.userAgent.raw=e;var i=t.utils.userAgent.raw.toUpperCase();t.utils.userAgent.IE=o("Trident")||o("MSIE"),t.utils.userAgent.EDGE=o("Edge"),t.utils.userAgent.JAVA_FX=o("JavaFX"),t.utils.userAgent.CHROME=(o("Chrome")||o("CriOS"))&&!t.utils.userAgent.EDGE,t.utils.userAgent.WEBKIT=o("WebKit")&&!t.utils.userAgent.EDGE,t.utils.userAgent.GECKO=o("Gecko")&&!t.utils.userAgent.WEBKIT&&!t.utils.userAgent.IE&&!t.utils.userAgent.EDGE,t.utils.userAgent.ANDROID=o("Android"),t.utils.userAgent.IPAD=o("iPad"),t.utils.userAgent.IPOD=o("iPod"),t.utils.userAgent.IPHONE=o("iPhone")&&!t.utils.userAgent.IPAD&&!t.utils.userAgent.IPOD,t.utils.userAgent.MAC=o("Macintosh"),t.utils.userAgent.TABLET=t.utils.userAgent.IPAD||t.utils.userAgent.ANDROID&&!o("Mobile")||o("Silk"),t.utils.userAgent.MOBILE=!t.utils.userAgent.TABLET&&(t.utils.userAgent.IPOD||t.utils.userAgent.IPHONE||t.utils.userAgent.ANDROID||o("IEMobile"))}(t.utils.global.navigator&&t.utils.global.navigator.userAgent||""),t.utils.noEvent=function(t){t.preventDefault(),t.stopPropagation()},t.utils.isTargetInput=function(t){return"textarea"==t.target.type||"text"==t.target.type||"number"==t.target.type||"email"==t.target.type||"password"==t.target.type||"search"==t.target.type||"tel"==t.target.type||"url"==t.target.type||t.target.isContentEditable},t.utils.getRelativeXY=function(e){var o=new t.utils.Coordinate(0,0),i=e.getAttribute("x");return i&&(o.x=parseInt(i,10)),(i=e.getAttribute("y"))&&(o.y=parseInt(i,10)),(i=(i=e.getAttribute("transform"))&&i.match(t.utils.getRelativeXY.XY_REGEX_))&&(o.x+=Number(i[1]),i[3]&&(o.y+=Number(i[3]))),(e=e.getAttribute("style"))&&-1<e.indexOf("translate")&&(e=e.match(t.utils.getRelativeXY.XY_STYLE_REGEX_))&&(o.x+=Number(e[1]),e[3]&&(o.y+=Number(e[3]))),o},t.utils.getInjectionDivXY_=function(e){for(var o=0,i=0;e;){var n=t.utils.getRelativeXY(e);if(o+=n.x,i+=n.y,-1!=(" "+(e.getAttribute("class")||"")+" ").indexOf(" injectionDiv "))break;e=e.parentNode}return new t.utils.Coordinate(o,i)},t.utils.getRelativeXY.XY_REGEX_=/translate\(\s*([-+\d.e]+)([ ,]\s*([-+\d.e]+)\s*)?/,t.utils.getRelativeXY.XY_STYLE_REGEX_=/transform:\s*translate(?:3d)?\(\s*([-+\d.e]+)\s*px([ ,]\s*([-+\d.e]+)\s*px)?/,t.utils.isRightButton=function(e){return!(!e.ctrlKey||!t.utils.userAgent.MAC)||2==e.button},t.utils.mouseToSvg=function(t,e,o){var i=e.createSVGPoint();return i.x=t.clientX,i.y=t.clientY,o||(o=e.getScreenCTM().inverse()),i.matrixTransform(o)},t.utils.getScrollDeltaPixels=function(e){switch(e.deltaMode){default:return{x:e.deltaX,y:e.deltaY};case 1:return{x:e.deltaX*t.LINE_MODE_MULTIPLIER,y:e.deltaY*t.LINE_MODE_MULTIPLIER};case 2:return{x:e.deltaX*t.PAGE_MODE_MULTIPLIER,y:e.deltaY*t.PAGE_MODE_MULTIPLIER}}},t.utils.tokenizeInterpolation=function(e){return t.utils.tokenizeInterpolation_(e,!0)},t.utils.replaceMessageReferences=function(e){return"string"!=typeof e?e:(e=t.utils.tokenizeInterpolation_(e,!1)).length?String(e[0]):""},t.utils.checkMessageReferences=function(e){for(var o=!0,i=t.Msg,n=e.match(/%{BKY_[A-Z]\w*}/gi),s=0;s<n.length;s++)null==i[n[s].toUpperCase().slice(6,-1)]&&(console.log("WARNING: No message string for "+n[s]+" in "+e),o=!1);return o},t.utils.tokenizeInterpolation_=function(e,o){var i=[],n=e.split("");n.push("");var s=0;e=[];for(var r=null,a=0;a<n.length;a++){var l=n[a];0==s?"%"==l?((l=e.join(""))&&i.push(l),e.length=0,s=1):e.push(l):1==s?"%"==l?(e.push(l),s=0):o&&"0"<=l&&"9">=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;a<i.length;++a)"string"==typeof i[a]?e.push(i[a]):((l=e.join(""))&&o.push(l),e.length=0,o.push(i[a]));return(l=e.join(""))&&o.push(l),e.length=0,o},t.utils.genUid=function(){for(var e=t.utils.genUid.soup_.length,o=[],i=0;20>i;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;i<o.length;i++)o[i]&&o[i]!=e||(o.splice(i,1),i--);return o.length?t.setAttribute("class",o.join(" ")):t.removeAttribute("class"),!0},t.utils.dom.hasClass=function(t,e){return-1!=(" "+t.getAttribute("class")+" ").indexOf(" "+e+" ")},t.utils.dom.removeNode=function(t){return t&&t.parentNode?t.parentNode.removeChild(t):null},t.utils.dom.insertAfter=function(t,e){var o=e.nextSibling;if(!(e=e.parentNode))throw Error("Reference node has no parent.");o?e.insertBefore(t,o):e.appendChild(t)},t.utils.dom.containsNode=function(e,o){return!!(e.compareDocumentPosition(o)&t.utils.dom.Node.DOCUMENT_POSITION_CONTAINED_BY)},t.utils.dom.setCssTransform=function(t,e){t.style.transform=e,t.style["-webkit-transform"]=e},t.utils.dom.startTextWidthCache=function(){t.utils.dom.cacheReference_++,t.utils.dom.cacheWidths_||(t.utils.dom.cacheWidths_={})},t.utils.dom.stopTextWidthCache=function(){t.utils.dom.cacheReference_--,t.utils.dom.cacheReference_||(t.utils.dom.cacheWidths_=null)},t.utils.dom.getTextWidth=function(e){var o,i=e.textContent+"\n"+e.className.baseVal;if(t.utils.dom.cacheWidths_&&(o=t.utils.dom.cacheWidths_[i]))return o;try{o=t.utils.userAgent.IE||t.utils.userAgent.EDGE?e.getBBox().width:e.getComputedTextLength()}catch(t){return 8*e.textContent.length}return t.utils.dom.cacheWidths_&&(t.utils.dom.cacheWidths_[i]=o),o},t.utils.dom.getFastTextWidth=function(e,o,i,n){return t.utils.dom.getFastTextWidthWithSizeString(e,o+"pt",i,n)},t.utils.dom.getFastTextWidthWithSizeString=function(e,o,i,n){var s,r=e.textContent;return e=r+"\n"+e.className.baseVal,t.utils.dom.cacheWidths_&&(s=t.utils.dom.cacheWidths_[e])||(t.utils.dom.canvasContext_||((s=document.createElement("canvas")).className="blocklyComputeCanvas",document.body.appendChild(s),t.utils.dom.canvasContext_=s.getContext("2d")),t.utils.dom.canvasContext_.font=i+" "+o+" "+n,s=t.utils.dom.canvasContext_.measureText(r).width,t.utils.dom.cacheWidths_&&(t.utils.dom.cacheWidths_[e]=s)),s},t.utils.dom.measureFontMetrics=function(t,e,o,i){var n=document.createElement("span");n.style.font=o+" "+e+" "+i,n.textContent=t,(t=document.createElement("div")).style.width="1px",t.style.height="0px",(e=document.createElement("div")).setAttribute("style","position: fixed; top: 0; left: 0; display: flex;"),e.appendChild(n),e.appendChild(t),document.body.appendChild(e);try{o={},e.style.alignItems="baseline",o.baseline=t.offsetTop-n.offsetTop,e.style.alignItems="flex-end",o.height=t.offsetTop-n.offsetTop}finally{document.body.removeChild(e)}return o},t.BlockDragSurfaceSvg=function(t){this.container_=t,this.createDom()},t.BlockDragSurfaceSvg.prototype.SVG_=null,t.BlockDragSurfaceSvg.prototype.dragGroup_=null,t.BlockDragSurfaceSvg.prototype.container_=null,t.BlockDragSurfaceSvg.prototype.scale_=1,t.BlockDragSurfaceSvg.prototype.surfaceXY_=null,t.BlockDragSurfaceSvg.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:"blocklyBlockDragSurface"},this.container_),this.dragGroup_=t.utils.dom.createSvgElement("g",{},this.SVG_))},t.BlockDragSurfaceSvg.prototype.setBlocksAndShow=function(e){if(this.dragGroup_.childNodes.length)throw Error("Already dragging a block.");this.dragGroup_.appendChild(e),this.SVG_.style.display="block",this.surfaceXY_=new t.utils.Coordinate(0,0)},t.BlockDragSurfaceSvg.prototype.translateAndScaleGroup=function(t,e,o){this.scale_=o,t=t.toFixed(0),e=e.toFixed(0),this.dragGroup_.setAttribute("transform","translate("+t+","+e+") scale("+o+")")},t.BlockDragSurfaceSvg.prototype.translateSurfaceInternal_=function(){var e=this.surfaceXY_.x,o=this.surfaceXY_.y;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.BlockDragSurfaceSvg.prototype.translateSurface=function(e,o){this.surfaceXY_=new t.utils.Coordinate(e*this.scale_,o*this.scale_),this.translateSurfaceInternal_()},t.BlockDragSurfaceSvg.prototype.getSurfaceTranslation=function(){var e=t.utils.getRelativeXY(this.SVG_);return new t.utils.Coordinate(e.x/this.scale_,e.y/this.scale_)},t.BlockDragSurfaceSvg.prototype.getGroup=function(){return this.dragGroup_},t.BlockDragSurfaceSvg.prototype.getCurrentBlock=function(){return this.dragGroup_.firstChild},t.BlockDragSurfaceSvg.prototype.clearAndHide=function(t){if(t?t.appendChild(this.getCurrentBlock()):this.dragGroup_.removeChild(this.getCurrentBlock()),this.SVG_.style.display="none",this.dragGroup_.childNodes.length)throw Error("Drag group was not cleared.");this.surfaceXY_=null},t.utils.IdGenerator={},t.utils.IdGenerator.nextId_=0,t.utils.IdGenerator.getNextUniqueId=function(){return"blockly:"+(t.utils.IdGenerator.nextId_++).toString(36)},t.Component=function(){this.rightToLeft_=t.Component.defaultRightToLeft,this.id_=null,this.inDocument_=!1,this.parent_=this.element_=null,this.children_=[],this.childIndex_={}},t.Component.defaultRightToLeft=!1,t.Component.Error={ALREADY_RENDERED:"Component already rendered",PARENT_UNABLE_TO_BE_SET:"Unable to set parent component",CHILD_INDEX_OUT_OF_BOUNDS:"Child component index out of bounds"},t.Component.prototype.getId=function(){return this.id_||(this.id_=t.utils.IdGenerator.getNextUniqueId())},t.Component.prototype.getElement=function(){return this.element_},t.Component.prototype.setElementInternal=function(t){this.element_=t},t.Component.prototype.setParent=function(e){if(this==e)throw Error(t.Component.Error.PARENT_UNABLE_TO_BE_SET);if(e&&this.parent_&&this.id_&&this.parent_.getChild(this.id_)&&this.parent_!=e)throw Error(t.Component.Error.PARENT_UNABLE_TO_BE_SET);this.parent_=e},t.Component.prototype.getParent=function(){return this.parent_},t.Component.prototype.isInDocument=function(){return this.inDocument_},t.Component.prototype.createDom=function(){this.element_=document.createElement("div")},t.Component.prototype.render=function(t){this.render_(t)},t.Component.prototype.renderBefore=function(t){this.render_(t.parentNode,t)},t.Component.prototype.render_=function(e,o){if(this.inDocument_)throw Error(t.Component.Error.ALREADY_RENDERED);this.element_||this.createDom(),e?e.insertBefore(this.element_,o||null):document.body.appendChild(this.element_),this.parent_&&!this.parent_.isInDocument()||this.enterDocument()},t.Component.prototype.enterDocument=function(){this.inDocument_=!0,this.forEachChild((function(t){!t.isInDocument()&&t.getElement()&&t.enterDocument()}))},t.Component.prototype.exitDocument=function(){this.forEachChild((function(t){t.isInDocument()&&t.exitDocument()})),this.inDocument_=!1},t.Component.prototype.dispose=function(){this.disposed_||(this.disposed_=!0,this.disposeInternal())},t.Component.prototype.disposeInternal=function(){this.inDocument_&&this.exitDocument(),this.forEachChild((function(t){t.dispose()})),this.element_&&t.utils.dom.removeNode(this.element_),this.parent_=this.element_=this.childIndex_=this.children_=null},t.Component.prototype.addChild=function(t,e){this.addChildAt(t,this.getChildCount(),e)},t.Component.prototype.addChildAt=function(e,o,i){if(e.inDocument_&&(i||!this.inDocument_))throw Error(t.Component.Error.ALREADY_RENDERED);if(0>o||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<n&&this.children_.splice(n,1)}e.setParent(this),this.children_.splice(o,0,e),e.inDocument_&&this.inDocument_&&e.getParent()==this?(o=(i=this.getContentElement()).childNodes[o]||null)!=e.getElement()&&i.insertBefore(e.getElement(),o):i?(this.element_||this.createDom(),o=this.getChildAt(o+1),e.render_(this.getContentElement(),o?o.element_:null)):this.inDocument_&&!e.inDocument_&&e.element_&&e.element_.parentNode&&e.element_.parentNode.nodeType==t.utils.dom.Node.ELEMENT_NODE&&e.enterDocument()},t.Component.prototype.getContentElement=function(){return this.element_},t.Component.prototype.setRightToLeft=function(e){if(this.inDocument_)throw Error(t.Component.Error.ALREADY_RENDERED);this.rightToLeft_=e},t.Component.prototype.hasChildren=function(){return 0!=this.children_.length},t.Component.prototype.getChildCount=function(){return this.children_.length},t.Component.prototype.getChild=function(t){return t&&this.childIndex_[t]||null},t.Component.prototype.getChildAt=function(t){return this.children_[t]||null},t.Component.prototype.forEachChild=function(t,e){for(var o=0;o<this.children_.length;o++)t.call(e,this.children_[o],o)},t.Component.prototype.indexOfChild=function(t){return this.children_.indexOf(t)},t.Css={},t.Css.injected_=!1,t.Css.register=function(e){if(t.Css.injected_)throw Error("CSS already injected");Array.prototype.push.apply(t.Css.CONTENT,e),e.length=0},t.Css.inject=function(e,o){if(!t.Css.injected_){t.Css.injected_=!0;var i=t.Css.CONTENT.join("\n");t.Css.CONTENT.length=0,e&&(e=o.replace(/[\\/]$/,""),i=i.replace(/<<<PATH>>>/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("<<<PATH>>>/handopen.cur"), auto;',"cursor: grab;","cursor: -webkit-grab;","}",".blocklyDragging {",'cursor: url("<<<PATH>>>/handclosed.cur"), auto;',"cursor: grabbing;","cursor: -webkit-grabbing;","}",".blocklyDraggable:active {",'cursor: url("<<<PATH>>>/handclosed.cur"), auto;',"cursor: grabbing;","cursor: -webkit-grabbing;","}",".blocklyBlockDragSurface .blocklyDraggable {",'cursor: url("<<<PATH>>>/handclosed.cur"), auto;',"cursor: grabbing;","cursor: -webkit-grabbing;","}",".blocklyDragging.blocklyDraggingDelete {",'cursor: url("<<<PATH>>>/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(<<<PATH>>>/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(o<t){var i=o;o=t,t=i}return Math.max(t,Math.min(e,o))},t.DropDownDiv=function(){},t.DropDownDiv.boundsElement_=null,t.DropDownDiv.owner_=null,t.DropDownDiv.positionToField_=null,t.DropDownDiv.ARROW_SIZE=16,t.DropDownDiv.BORDER_SIZE=1,t.DropDownDiv.ARROW_HORIZONTAL_PADDING=12,t.DropDownDiv.PADDING_Y=16,t.DropDownDiv.ANIMATION_TIME=.25,t.DropDownDiv.animateOutTimer_=null,t.DropDownDiv.onHide_=null,t.DropDownDiv.rendererClassName_="",t.DropDownDiv.themeClassName_="",t.DropDownDiv.createDom=function(){if(!t.DropDownDiv.DIV_){var e=document.createElement("div");e.className="blocklyDropDownDiv",(t.parentContainer||document.body).appendChild(e),t.DropDownDiv.DIV_=e;var o=document.createElement("div");o.className="blocklyDropDownContent",e.appendChild(o),t.DropDownDiv.content_=o,(o=document.createElement("div")).className="blocklyDropDownArrow",e.appendChild(o),t.DropDownDiv.arrow_=o,t.DropDownDiv.DIV_.style.opacity=0,t.DropDownDiv.DIV_.style.transition="transform "+t.DropDownDiv.ANIMATION_TIME+"s, opacity "+t.DropDownDiv.ANIMATION_TIME+"s",e.addEventListener("focusin",(function(){t.utils.dom.addClass(e,"focused")})),e.addEventListener("focusout",(function(){t.utils.dom.removeClass(e,"focused")}))}},t.DropDownDiv.setBoundsElement=function(e){t.DropDownDiv.boundsElement_=e},t.DropDownDiv.getContentDiv=function(){return t.DropDownDiv.content_},t.DropDownDiv.clearContent=function(){t.DropDownDiv.content_.textContent="",t.DropDownDiv.content_.style.width=""},t.DropDownDiv.setColour=function(e,o){t.DropDownDiv.DIV_.style.backgroundColor=e,t.DropDownDiv.DIV_.style.borderColor=o},t.DropDownDiv.showPositionedByBlock=function(e,o,i,n){return t.DropDownDiv.showPositionedByRect_(t.DropDownDiv.getScaledBboxOfBlock_(o),e,i,n)},t.DropDownDiv.showPositionedByField=function(e,o,i){return t.DropDownDiv.positionToField_=!0,t.DropDownDiv.showPositionedByRect_(t.DropDownDiv.getScaledBboxOfField_(e),e,o,i)},t.DropDownDiv.getScaledBboxOfBlock_=function(e){var o=e.getSvgRoot(),i=o.getBBox(),n=e.workspace.scale;return e=i.height*n,i=i.width*n,o=t.utils.style.getPageOffset(o),new t.utils.Rect(o.y,o.y+e,o.x,o.x+i)},t.DropDownDiv.getScaledBboxOfField_=function(e){return e=e.getScaledBBox(),new t.utils.Rect(e.top,e.bottom,e.left,e.right)},t.DropDownDiv.showPositionedByRect_=function(e,o,i,n){var s=e.left+(e.right-e.left)/2,r=e.bottom;return e=e.top,n&&(e+=n),n=o.getSourceBlock(),t.DropDownDiv.setBoundsElement(n.workspace.getParentSvg().parentNode),t.DropDownDiv.show(o,n.RTL,s,r,s,e,i)},t.DropDownDiv.show=function(e,o,i,n,s,r,a){return t.DropDownDiv.owner_=e,t.DropDownDiv.onHide_=a||null,(e=t.DropDownDiv.DIV_).style.direction=o?"rtl":"ltr",t.DropDownDiv.rendererClassName_=t.getMainWorkspace().getRenderer().getClassName(),t.DropDownDiv.themeClassName_=t.getMainWorkspace().getTheme().getClassName(),t.utils.dom.addClass(e,t.DropDownDiv.rendererClassName_),t.utils.dom.addClass(e,t.DropDownDiv.themeClassName_),t.DropDownDiv.positionInternal_(i,n,s,r)},t.DropDownDiv.getBoundsInfo_=function(){var e=t.utils.style.getPageOffset(t.DropDownDiv.boundsElement_),o=t.utils.style.getSize(t.DropDownDiv.boundsElement_);return{left:e.x,right:e.x+o.width,top:e.y,bottom:e.y+o.height,width:o.width,height:o.height}},t.DropDownDiv.getPositionMetrics_=function(e,o,i,n){var s=t.DropDownDiv.getBoundsInfo_(),r=t.utils.style.getSize(t.DropDownDiv.DIV_);return o+r.height<s.bottom?t.DropDownDiv.getPositionBelowMetrics_(e,o,s,r):n-r.height>s.top?t.DropDownDiv.getPositionAboveMetrics_(i,n,s,r):o+r.height<document.documentElement.clientHeight?t.DropDownDiv.getPositionBelowMetrics_(e,o,s,r):n-r.height>document.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),0<o.length&&0<o.spacing?(t.utils.dom.createSvgElement("line",{stroke:o.colour},e),1<o.length&&t.utils.dom.createSvgElement("line",{stroke:o.colour},e)):t.utils.dom.createSvgElement("line",{},e),e},t.Theme=function(t,e,o,i){this.name=t,this.blockStyles=e||Object.create(null),this.categoryStyles=o||Object.create(null),this.componentStyles=i||Object.create(null),this.fontStyle=Object.create(null),this.startHats=null},t.Theme.prototype.getClassName=function(){return this.name+"-theme"},t.Theme.prototype.setBlockStyle=function(t,e){this.blockStyles[t]=e},t.Theme.prototype.setCategoryStyle=function(t,e){this.categoryStyles[t]=e},t.Theme.prototype.getComponentStyle=function(t){return(t=this.componentStyles[t])&&"string"==typeof propertyValue&&this.getComponentStyle(t)?this.getComponentStyle(t):t?String(t):null},t.Theme.prototype.setComponentStyle=function(t,e){this.componentStyles[t]=e},t.Theme.prototype.setFontStyle=function(t){this.fontStyle=t},t.Theme.prototype.setStartHats=function(t){this.startHats=t},t.Theme.defineTheme=function(e,o){var i=new t.Theme(e),n=o.base;return n&&n instanceof t.Theme&&(t.utils.object.deepMerge(i,n),i.name=e),t.utils.object.deepMerge(i.blockStyles,o.blockStyles),t.utils.object.deepMerge(i.categoryStyles,o.categoryStyles),t.utils.object.deepMerge(i.componentStyles,o.componentStyles),t.utils.object.deepMerge(i.fontStyle,o.fontStyle),null!=o.startHats&&(i.startHats=o.startHats),i},t.Themes={},t.Themes.Classic={},t.Themes.Classic.defaultBlockStyles={colour_blocks:{colourPrimary:"20"},list_blocks:{colourPrimary:"260"},logic_blocks:{colourPrimary:"210"},loop_blocks:{colourPrimary:"120"},math_blocks:{colourPrimary:"230"},procedure_blocks:{colourPrimary:"290"},text_blocks:{colourPrimary:"160"},variable_blocks:{colourPrimary:"330"},variable_dynamic_blocks:{colourPrimary:"310"},hat_blocks:{colourPrimary:"330",hat:"cap"}},t.Themes.Classic.categoryStyles={colour_category:{colour:"20"},list_category:{colour:"260"},logic_category:{colour:"210"},loop_category:{colour:"120"},math_category:{colour:"230"},procedure_category:{colour:"290"},text_category:{colour:"160"},variable_category:{colour:"330"},variable_dynamic_category:{colour:"310"}},t.Themes.Classic=new t.Theme("classic",t.Themes.Classic.defaultBlockStyles,t.Themes.Classic.categoryStyles),t.utils.KeyCodes={WIN_KEY_FF_LINUX:0,MAC_ENTER:3,BACKSPACE:8,TAB:9,NUM_CENTER:12,ENTER:13,SHIFT:16,CTRL:17,ALT:18,PAUSE:19,CAPS_LOCK:20,ESC:27,SPACE:32,PAGE_UP:33,PAGE_DOWN:34,END:35,HOME:36,LEFT:37,UP:38,RIGHT:39,DOWN:40,PLUS_SIGN:43,PRINT_SCREEN:44,INSERT:45,DELETE:46,ZERO:48,ONE:49,TWO:50,THREE:51,FOUR:52,FIVE:53,SIX:54,SEVEN:55,EIGHT:56,NINE:57,FF_SEMICOLON:59,FF_EQUALS:61,FF_DASH:173,FF_HASH:163,QUESTION_MARK:63,AT_SIGN:64,A:65,B:66,C:67,D:68,E:69,F:70,G:71,H:72,I:73,J:74,K:75,L:76,M:77,N:78,O:79,P:80,Q:81,R:82,S:83,T:84,U:85,V:86,W:87,X:88,Y:89,Z:90,META:91,WIN_KEY_RIGHT:92,CONTEXT_MENU:93,NUM_ZERO:96,NUM_ONE:97,NUM_TWO:98,NUM_THREE:99,NUM_FOUR:100,NUM_FIVE:101,NUM_SIX:102,NUM_SEVEN:103,NUM_EIGHT:104,NUM_NINE:105,NUM_MULTIPLY:106,NUM_PLUS:107,NUM_MINUS:109,NUM_PERIOD:110,NUM_DIVISION:111,F1:112,F2:113,F3:114,F4:115,F5:116,F6:117,F7:118,F8:119,F9:120,F10:121,F11:122,F12:123,NUMLOCK:144,SCROLL_LOCK:145,FIRST_MEDIA_KEY:166,LAST_MEDIA_KEY:183,SEMICOLON:186,DASH:189,EQUALS:187,COMMA:188,PERIOD:190,SLASH:191,APOSTROPHE:192,TILDE:192,SINGLE_QUOTE:222,OPEN_SQUARE_BRACKET:219,BACKSLASH:220,CLOSE_SQUARE_BRACKET:221,WIN_KEY:224,MAC_FF_META:224,MAC_WK_CMD_LEFT:91,MAC_WK_CMD_RIGHT:93,WIN_IME:229,VK_NONAME:252,PHANTOM:255},t.user={},t.user.keyMap={},t.user.keyMap.map_={},t.user.keyMap.modifierKeys={SHIFT:"Shift",CONTROL:"Control",ALT:"Alt",META:"Meta"},t.user.keyMap.setActionForKey=function(e,o){var i=t.user.keyMap.getKeyByAction(o);i&&delete t.user.keyMap.map_[i],t.user.keyMap.map_[e]=o},t.user.keyMap.setKeyMap=function(e){t.user.keyMap.map_=e},t.user.keyMap.getKeyMap=function(){var e={};return t.utils.object.mixin(e,t.user.keyMap.map_),e},t.user.keyMap.getActionByKeyCode=function(e){return t.user.keyMap.map_[e]},t.user.keyMap.getKeyByAction=function(e){for(var o,i=Object.keys(t.user.keyMap.map_),n=0;o=i[n];n++)if(t.user.keyMap.map_[o].name===e.name)return o;return null},t.user.keyMap.serializeKeyEvent=function(e){for(var o,i=t.utils.object.values(t.user.keyMap.modifierKeys),n="",s=0;o=i[s];s++)e.getModifierState(o)&&(n+=o);return n+e.keyCode},t.user.keyMap.checkModifiers_=function(t,e){for(var o,i=0;o=t[i];i++)if(0>e.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.indexOf(s)&&(i+=s);return i+e},t.user.keyMap.createDefaultKeyMap=function(){var e={},o=t.user.keyMap.createSerializedKey(t.utils.KeyCodes.K,[t.user.keyMap.modifierKeys.CONTROL,t.user.keyMap.modifierKeys.SHIFT]),i=t.user.keyMap.createSerializedKey(t.utils.KeyCodes.W,[t.user.keyMap.modifierKeys.SHIFT]),n=t.user.keyMap.createSerializedKey(t.utils.KeyCodes.A,[t.user.keyMap.modifierKeys.SHIFT]),s=t.user.keyMap.createSerializedKey(t.utils.KeyCodes.S,[t.user.keyMap.modifierKeys.SHIFT]),r=t.user.keyMap.createSerializedKey(t.utils.KeyCodes.D,[t.user.keyMap.modifierKeys.SHIFT]);return e[t.utils.KeyCodes.W]=t.navigation.ACTION_PREVIOUS,e[t.utils.KeyCodes.A]=t.navigation.ACTION_OUT,e[t.utils.KeyCodes.S]=t.navigation.ACTION_NEXT,e[t.utils.KeyCodes.D]=t.navigation.ACTION_IN,e[t.utils.KeyCodes.I]=t.navigation.ACTION_INSERT,e[t.utils.KeyCodes.ENTER]=t.navigation.ACTION_MARK,e[t.utils.KeyCodes.X]=t.navigation.ACTION_DISCONNECT,e[t.utils.KeyCodes.T]=t.navigation.ACTION_TOOLBOX,e[t.utils.KeyCodes.E]=t.navigation.ACTION_EXIT,e[t.utils.KeyCodes.ESC]=t.navigation.ACTION_EXIT,e[o]=t.navigation.ACTION_TOGGLE_KEYBOARD_NAV,e[i]=t.navigation.ACTION_MOVE_WS_CURSOR_UP,e[n]=t.navigation.ACTION_MOVE_WS_CURSOR_LEFT,e[s]=t.navigation.ACTION_MOVE_WS_CURSOR_DOWN,e[r]=t.navigation.ACTION_MOVE_WS_CURSOR_RIGHT,e},t.utils.xml={},t.utils.xml.NAME_SPACE="https://developers.google.com/blockly/xml",t.utils.xml.document=function(){return document},t.utils.xml.createElement=function(e){return t.utils.xml.document().createElementNS(t.utils.xml.NAME_SPACE,e)},t.utils.xml.createTextNode=function(e){return t.utils.xml.document().createTextNode(e)},t.utils.xml.textToDomDocument=function(t){return(new DOMParser).parseFromString(t,"text/xml")},t.utils.xml.domToText=function(t){return(new XMLSerializer).serializeToString(t)},t.Events.BlockBase=function(e){t.Events.BlockBase.superClass_.constructor.call(this),this.blockId=e.id,this.workspaceId=e.workspace.id},t.utils.object.inherits(t.Events.BlockBase,t.Events.Abstract),t.Events.BlockBase.prototype.toJson=function(){var e=t.Events.BlockBase.superClass_.toJson.call(this);return e.blockId=this.blockId,e},t.Events.BlockBase.prototype.fromJson=function(e){t.Events.BlockBase.superClass_.fromJson.call(this,e),this.blockId=e.blockId},t.Events.Change=function(e,o,i,n,s){e&&(t.Events.Change.superClass_.constructor.call(this,e),this.element=o,this.name=i,this.oldValue=n,this.newValue=s)},t.utils.object.inherits(t.Events.Change,t.Events.BlockBase),t.Events.BlockChange=t.Events.Change,t.Events.Change.prototype.type=t.Events.CHANGE,t.Events.Change.prototype.toJson=function(){var e=t.Events.Change.superClass_.toJson.call(this);return e.element=this.element,this.name&&(e.name=this.name),e.newValue=this.newValue,e},t.Events.Change.prototype.fromJson=function(e){t.Events.Change.superClass_.fromJson.call(this,e),this.element=e.element,this.name=e.name,this.newValue=e.newValue},t.Events.Change.prototype.isNull=function(){return this.oldValue==this.newValue},t.Events.Change.prototype.run=function(e){var o=this.getEventWorkspace_().getBlockById(this.blockId);if(o)switch(o.mutator&&o.mutator.setVisible(!1),e=e?this.newValue:this.oldValue,this.element){case"field":(o=o.getField(this.name))?o.setValue(e):console.warn("Can't set non-existent field: "+this.name);break;case"comment":o.setCommentText(e||null);break;case"collapsed":o.setCollapsed(!!e);break;case"disabled":o.setEnabled(!e);break;case"inline":o.setInputsInline(!!e);break;case"mutation":var i="";if(o.mutationToDom&&(i=(i=o.mutationToDom())&&t.Xml.domToText(i)),o.domToMutation){var n=t.Xml.textToDom(e||"<mutation/>");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&#10;$2")}while(e!=i);return e.replace(/<(\w+)([^<]*)\/>/g,"<$1$2></$1>")},t.Xml.domToPrettyText=function(e){e=t.Xml.domToText(e).split("<");for(var o="",i=1;i<e.length;i++){var n=e[i];"/"==n[0]&&(o=o.substring(2)),e[i]=o+"<"+n,"/"!=n[0]&&"/>"!=n.slice(-2)&&(o+="  ")}return(e=(e=e.join("\n")).replace(/(<(\w+)\b[^>]*>[^\n]*)\n *<\/\2>/g,"$1</$2>")).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;i<e.length;i++){var c=o.getBlockById(e[i]).getRelativeToSurfaceXY();c.y<l&&(l=c.y),c.x<r&&(r=c.x),c.x>a&&(a=c.x)}for(n=n-l+10,s=o.RTL?s-a:s-r,i=0;i<e.length;i++)o.getBlockById(e[i]).moveBy(s,n)}return e},t.Xml.domToBlock=function(e,o){if(e instanceof t.Workspace){var i=e;e=o,o=i,console.warn("Deprecated call to Blockly.Xml.domToBlock, swap the arguments.")}t.Events.disable(),i=o.getAllVariables();try{var n=t.Xml.domToBlockHeadless_(e,o),s=n.getDescendants(!1);if(o.rendered){n.setConnectionTracking(!1);for(var r=s.length-1;0<=r;r--)s[r].initSvg();for(r=s.length-1;0<=r;r--)s[r].render(!1);setTimeout((function(){n.disposed||n.setConnectionTracking(!0)}),1),n.updateDisabled(),o.resizeContents()}else for(r=s.length-1;0<=r;r--)s[r].initModel()}finally{t.Events.enable()}if(t.Events.isEnabled()){for(e=t.Variables.getAddedVariables(o,i),r=0;r<e.length;r++)t.Events.fire(new t.Events.VarCreate(e[r]));t.Events.fire(new t.Events.BlockCreate(n))}return n},t.Xml.domToVariables=function(e,o){for(var i,n=0;i=e.childNodes[n];n++)if(i.nodeType==t.utils.dom.Node.ELEMENT_NODE){var s=i.getAttribute("type"),r=i.getAttribute("id");o.createVariable(i.textContent,s,r)}},t.Xml.domToBlockHeadless_=function(e,o){var i=null,n=e.getAttribute("type");if(!n)throw TypeError("Block type unspecified: "+e.outerHTML);var s=e.getAttribute("id");i=o.newBlock(n,s);var r,a=null;for(s=0;r=e.childNodes[s];s++)if(r.nodeType!=t.utils.dom.Node.TEXT_NODE){for(var l,c=a=null,h=0;l=r.childNodes[h];h++)l.nodeType==t.utils.dom.Node.ELEMENT_NODE&&("block"==l.nodeName.toLowerCase()?a=l:"shadow"==l.nodeName.toLowerCase()&&(c=l));switch(!a&&c&&(a=c),l=r.getAttribute("name"),h=r,r.nodeName.toLowerCase()){case"mutation":i.domToMutation&&(i.domToMutation(h),i.initSvg&&i.initSvg());break;case"comment":if(!t.Comment){console.warn("Missing require for Blockly.Comment, ignoring block comment.");break}a=h.textContent,c="true"==h.getAttribute("pinned"),r=parseInt(h.getAttribute("w"),10),h=parseInt(h.getAttribute("h"),10),i.setCommentText(a),i.commentModel.pinned=c,isNaN(r)||isNaN(h)||(i.commentModel.size=new t.utils.Size(r,h)),c&&i.getCommentIcon&&!i.isInFlyout&&setTimeout((function(){i.getCommentIcon().setVisible(!0)}),1);break;case"data":i.data=r.textContent;break;case"title":case"field":t.Xml.domToField_(i,l,h);break;case"value":case"statement":if(!(h=i.getInput(l))){console.warn("Ignoring non-existent input "+l+" in block "+n);break}if(c&&h.connection.setShadowDom(c),a)if((a=t.Xml.domToBlockHeadless_(a,o)).outputConnection)h.connection.connect(a.outputConnection);else{if(!a.previousConnection)throw TypeError("Child block does not have output or previous statement.");h.connection.connect(a.previousConnection)}break;case"next":if(c&&i.nextConnection&&i.nextConnection.setShadowDom(c),a){if(!i.nextConnection)throw TypeError("Next statement does not exist.");if(i.nextConnection.isConnected())throw TypeError("Next statement is already connected.");if(!(a=t.Xml.domToBlockHeadless_(a,o)).previousConnection)throw TypeError("Next block does not have previous statement.");i.nextConnection.connect(a.previousConnection)}break;default:console.warn("Ignoring unknown tag: "+r.nodeName)}}if((s=e.getAttribute("inline"))&&i.setInputsInline("true"==s),(s=e.getAttribute("disabled"))&&i.setEnabled("true"!=s&&"disabled"!=s),(s=e.getAttribute("deletable"))&&i.setDeletable("true"==s),(s=e.getAttribute("movable"))&&i.setMovable("true"==s),(s=e.getAttribute("editable"))&&i.setEditable("true"==s),(s=e.getAttribute("collapsed"))&&i.setCollapsed("true"==s),"shadow"==e.nodeName.toLowerCase()){for(e=i.getChildren(!1),s=0;o=e[s];s++)if(!o.isShadow())throw TypeError("Shadow block not allowed non-shadow child.");if(i.getVarModels().length)throw TypeError("Shadow blocks cannot have variable references.");i.setShadow(!0)}return i},t.Xml.domToField_=function(t,e,o){var i=t.getField(e);i?i.fromXml(o):console.warn("Ignoring non-existent field "+e+" in block "+t.type)},t.Xml.deleteNext=function(t){for(var e,o=0;e=t.childNodes[o];o++)if("next"==e.nodeName.toLowerCase()){t.removeChild(e);break}},t.Options=function(e){var o=!!e.readOnly;if(o)var i=null,n=!1,s=!1,r=!1,a=!1,l=!1,c=!1;else{n=!(!(i=t.Options.parseToolboxTree(e.toolbox||null))||!i.getElementsByTagName("category").length),void 0===(s=e.trashcan)&&(s=n);var h=e.maxTrashcanContents;s?void 0===h&&(h=32):h=0,void 0===(r=e.collapse)&&(r=n),void 0===(a=e.comments)&&(a=n),void 0===(l=e.disable)&&(l=n),void 0===(c=e.sounds)&&(c=!0)}var u=!!e.rtl,p=e.horizontalLayout;void 0===p&&(p=!1);var _=e.toolboxPosition;_="end"!==_,_=p?_?t.TOOLBOX_AT_TOP:t.TOOLBOX_AT_BOTTOM:_==u?t.TOOLBOX_AT_RIGHT:t.TOOLBOX_AT_LEFT;var d=e.css;void 0===d&&(d=!0);var g="https://blockly-demo.appspot.com/static/media/";e.media?g=e.media:e.path&&(g=e.path+"media/");var T=void 0===e.oneBasedIndex||!!e.oneBasedIndex,E=e.keyMap||t.user.keyMap.createDefaultKeyMap(),f=e.renderer||"geras";this.RTL=u,this.oneBasedIndex=T,this.collapse=r,this.comments=a,this.disable=l,this.readOnly=o,this.maxBlocks=e.maxBlocks||1/0,this.maxInstances=e.maxInstances,this.pathToMedia=g,this.hasCategories=n,this.moveOptions=t.Options.parseMoveOptions(e,n),this.hasScrollbars=this.moveOptions.scrollbars,this.hasTrashcan=s,this.maxTrashcanContents=h,this.hasSounds=c,this.hasCss=d,this.horizontalLayout=p,this.languageTree=i,this.gridOptions=t.Options.parseGridOptions_(e),this.zoomOptions=t.Options.parseZoomOptions_(e),this.toolboxPosition=_,this.theme=t.Options.parseThemeOptions_(e),this.keyMap=E,this.renderer=f,this.rendererOverrides=e.rendererOverrides,this.gridPattern=void 0,this.parentWorkspace=e.parentWorkspace},t.BlocklyOptions=function(){},t.Options.parseMoveOptions=function(t,e){var o=t.move||{},i={};return i.scrollbars=void 0===o.scrollbars&&void 0===t.scrollbars?e:!!o.scrollbars||!!t.scrollbars,i.wheel=!(!i.scrollbars||void 0===o.wheel||!o.wheel),i.drag=!(!i.scrollbars||void 0!==o.drag&&!o.drag),i},t.Options.parseZoomOptions_=function(t){t=t.zoom||{};var e={};return e.controls=void 0!==t.controls&&!!t.controls,e.wheel=void 0!==t.wheel&&!!t.wheel,e.startScale=void 0===t.startScale?1:Number(t.startScale),e.maxScale=void 0===t.maxScale?3:Number(t.maxScale),e.minScale=void 0===t.minScale?.3:Number(t.minScale),e.scaleSpeed=void 0===t.scaleSpeed?1.2:Number(t.scaleSpeed),e.pinch=void 0===t.pinch?e.wheel||e.controls:!!t.pinch,e},t.Options.parseGridOptions_=function(t){t=t.grid||{};var e={};return e.spacing=Number(t.spacing)||0,e.colour=t.colour||"#888",e.length=void 0===t.length?1:Number(t.length),e.snap=0<e.spacing&&!!t.snap,e},t.Options.parseThemeOptions_=function(e){return(e=e.theme||t.Themes.Classic)instanceof t.Theme?e:t.Theme.defineTheme("builtin",e)},t.Options.parseToolboxTree=function(e){if(e){if("string"!=typeof e&&(t.utils.userAgent.IE&&e.outerHTML?e=e.outerHTML:e instanceof Element||(e=null)),"string"==typeof e&&"xml"!=(e=t.Xml.textToDom(e)).nodeName.toLowerCase())throw TypeError("Toolbox should be an <xml> 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<t.changedTouches.length;o++)e[o]={type:t.type,changedTouches:[t.changedTouches[o]],target:t.target,stopPropagation:function(){t.stopPropagation()},preventDefault:function(){t.preventDefault()}};else e.push(t);return e},t.ScrollbarPair=function(e){this.workspace_=e,this.hScroll=new t.Scrollbar(e,!0,!0,"blocklyMainWorkspaceScrollbar"),this.vScroll=new t.Scrollbar(e,!1,!0,"blocklyMainWorkspaceScrollbar"),this.corner_=t.utils.dom.createSvgElement("rect",{height:t.Scrollbar.scrollbarThickness,width:t.Scrollbar.scrollbarThickness,class:"blocklyScrollbarBackground"},null),t.utils.dom.insertAfter(this.corner_,e.getBubbleCanvas())},t.ScrollbarPair.prototype.oldHostMetrics_=null,t.ScrollbarPair.prototype.dispose=function(){t.utils.dom.removeNode(this.corner_),this.oldHostMetrics_=this.workspace_=this.corner_=null,this.hScroll.dispose(),this.hScroll=null,this.vScroll.dispose(),this.vScroll=null},t.ScrollbarPair.prototype.resize=function(){var t=this.workspace_.getMetrics();if(t){var e=!1,o=!1;this.oldHostMetrics_&&this.oldHostMetrics_.viewWidth==t.viewWidth&&this.oldHostMetrics_.viewHeight==t.viewHeight&&this.oldHostMetrics_.absoluteTop==t.absoluteTop&&this.oldHostMetrics_.absoluteLeft==t.absoluteLeft?(this.oldHostMetrics_&&this.oldHostMetrics_.contentWidth==t.contentWidth&&this.oldHostMetrics_.viewLeft==t.viewLeft&&this.oldHostMetrics_.contentLeft==t.contentLeft||(e=!0),this.oldHostMetrics_&&this.oldHostMetrics_.contentHeight==t.contentHeight&&this.oldHostMetrics_.viewTop==t.viewTop&&this.oldHostMetrics_.contentTop==t.contentTop||(o=!0)):o=e=!0,e&&this.hScroll.resize(t),o&&this.vScroll.resize(t),this.oldHostMetrics_&&this.oldHostMetrics_.viewWidth==t.viewWidth&&this.oldHostMetrics_.absoluteLeft==t.absoluteLeft||this.corner_.setAttribute("x",this.vScroll.position_.x),this.oldHostMetrics_&&this.oldHostMetrics_.viewHeight==t.viewHeight&&this.oldHostMetrics_.absoluteTop==t.absoluteTop||this.corner_.setAttribute("y",this.hScroll.position_.y),this.oldHostMetrics_=t}},t.ScrollbarPair.prototype.set=function(t,e){var o={};t*=this.hScroll.ratio_,e*=this.vScroll.ratio_;var i=this.vScroll.scrollViewSize_;o.x=this.getRatio_(t,this.hScroll.scrollViewSize_),o.y=this.getRatio_(e,i),this.workspace_.setMetrics(o),this.hScroll.setHandlePosition(t),this.vScroll.setHandlePosition(e)},t.ScrollbarPair.prototype.getRatio_=function(t,e){return t/=e,isNaN(t)?0:t},t.Scrollbar=function(e,o,i,n){this.workspace_=e,this.pair_=i||!1,this.horizontal_=o,this.oldHostMetrics_=null,this.createDom_(n),this.position_=new t.utils.Coordinate(0,0),e=t.Scrollbar.scrollbarThickness,o?(this.svgBackground_.setAttribute("height",e),this.outerSvg_.setAttribute("height",e),this.svgHandle_.setAttribute("height",e-5),this.svgHandle_.setAttribute("y",2.5),this.lengthAttribute_="width",this.positionAttribute_="x"):(this.svgBackground_.setAttribute("width",e),this.outerSvg_.setAttribute("width",e),this.svgHandle_.setAttribute("width",e-5),this.svgHandle_.setAttribute("x",2.5),this.lengthAttribute_="height",this.positionAttribute_="y"),this.onMouseDownBarWrapper_=t.bindEventWithChecks_(this.svgBackground_,"mousedown",this,this.onMouseDownBar_),this.onMouseDownHandleWrapper_=t.bindEventWithChecks_(this.svgHandle_,"mousedown",this,this.onMouseDownHandle_)},t.Scrollbar.prototype.origin_=new t.utils.Coordinate(0,0),t.Scrollbar.prototype.startDragMouse_=0,t.Scrollbar.prototype.scrollViewSize_=0,t.Scrollbar.prototype.handleLength_=0,t.Scrollbar.prototype.handlePosition_=0,t.Scrollbar.prototype.isVisible_=!0,t.Scrollbar.prototype.containerVisible_=!0,t.Scrollbar.scrollbarThickness=15,t.Touch.TOUCH_ENABLED&&(t.Scrollbar.scrollbarThickness=25),t.Scrollbar.metricsAreEquivalent_=function(t,e){return!(!t||!e||t.viewWidth!=e.viewWidth||t.viewHeight!=e.viewHeight||t.viewLeft!=e.viewLeft||t.viewTop!=e.viewTop||t.absoluteTop!=e.absoluteTop||t.absoluteLeft!=e.absoluteLeft||t.contentWidth!=e.contentWidth||t.contentHeight!=e.contentHeight||t.contentLeft!=e.contentLeft||t.contentTop!=e.contentTop)},t.Scrollbar.prototype.dispose=function(){this.cleanUp_(),t.unbindEvent_(this.onMouseDownBarWrapper_),this.onMouseDownBarWrapper_=null,t.unbindEvent_(this.onMouseDownHandleWrapper_),this.onMouseDownHandleWrapper_=null,t.utils.dom.removeNode(this.outerSvg_),this.svgBackground_=this.svgGroup_=this.outerSvg_=null,this.svgHandle_&&(this.workspace_.getThemeManager().unsubscribe(this.svgHandle_),this.svgHandle_=null),this.workspace_=null},t.Scrollbar.prototype.setHandleLength_=function(t){this.handleLength_=t,this.svgHandle_.setAttribute(this.lengthAttribute_,this.handleLength_)},t.Scrollbar.prototype.setHandlePosition=function(t){this.handlePosition_=t,this.svgHandle_.setAttribute(this.positionAttribute_,this.handlePosition_)},t.Scrollbar.prototype.setScrollViewSize_=function(t){this.scrollViewSize_=t,this.outerSvg_.setAttribute(this.lengthAttribute_,this.scrollViewSize_),this.svgBackground_.setAttribute(this.lengthAttribute_,this.scrollViewSize_)},t.ScrollbarPair.prototype.setContainerVisible=function(t){this.hScroll.setContainerVisible(t),this.vScroll.setContainerVisible(t)},t.Scrollbar.prototype.setPosition_=function(e,o){this.position_.x=e,this.position_.y=o,t.utils.dom.setCssTransform(this.outerSvg_,"translate("+(this.position_.x+this.origin_.x)+"px,"+(this.position_.y+this.origin_.y)+"px)")},t.Scrollbar.prototype.resize=function(e){(e||(e=this.workspace_.getMetrics()))&&(t.Scrollbar.metricsAreEquivalent_(e,this.oldHostMetrics_)||(this.oldHostMetrics_=e,this.horizontal_?this.resizeHorizontal_(e):this.resizeVertical_(e),this.onScroll_()))},t.Scrollbar.prototype.resizeHorizontal_=function(t){this.resizeViewHorizontal(t)},t.Scrollbar.prototype.resizeViewHorizontal=function(e){var o=e.viewWidth-1;this.pair_&&(o-=t.Scrollbar.scrollbarThickness),this.setScrollViewSize_(Math.max(0,o)),o=e.absoluteLeft+.5,this.pair_&&this.workspace_.RTL&&(o+=t.Scrollbar.scrollbarThickness),this.setPosition_(o,e.absoluteTop+e.viewHeight-t.Scrollbar.scrollbarThickness-.5),this.resizeContentHorizontal(e)},t.Scrollbar.prototype.resizeContentHorizontal=function(t){this.pair_||this.setVisible(this.scrollViewSize_<t.contentWidth),this.ratio_=this.scrollViewSize_/t.contentWidth,(-1/0==this.ratio_||1/0==this.ratio_||isNaN(this.ratio_))&&(this.ratio_=0),this.setHandleLength_(Math.max(0,t.viewWidth*this.ratio_)),this.setHandlePosition(this.constrainHandle_((t.viewLeft-t.contentLeft)*this.ratio_))},t.Scrollbar.prototype.resizeVertical_=function(t){this.resizeViewVertical(t)},t.Scrollbar.prototype.resizeViewVertical=function(e){var o=e.viewHeight-1;this.pair_&&(o-=t.Scrollbar.scrollbarThickness),this.setScrollViewSize_(Math.max(0,o)),o=e.absoluteLeft+.5,this.workspace_.RTL||(o+=e.viewWidth-t.Scrollbar.scrollbarThickness-1),this.setPosition_(o,e.absoluteTop+.5),this.resizeContentVertical(e)},t.Scrollbar.prototype.resizeContentVertical=function(t){this.pair_||this.setVisible(this.scrollViewSize_<t.contentHeight),this.ratio_=this.scrollViewSize_/t.contentHeight,(-1/0==this.ratio_||1/0==this.ratio_||isNaN(this.ratio_))&&(this.ratio_=0),this.setHandleLength_(Math.max(0,t.viewHeight*this.ratio_)),this.setHandlePosition(this.constrainHandle_((t.viewTop-t.contentTop)*this.ratio_))},t.Scrollbar.prototype.createDom_=function(e){var o="blocklyScrollbar"+(this.horizontal_?"Horizontal":"Vertical");e&&(o+=" "+e),this.outerSvg_=t.utils.dom.createSvgElement("svg",{class:o},null),this.svgGroup_=t.utils.dom.createSvgElement("g",{},this.outerSvg_),this.svgBackground_=t.utils.dom.createSvgElement("rect",{class:"blocklyScrollbarBackground"},this.svgGroup_),e=Math.floor((t.Scrollbar.scrollbarThickness-5)/2),this.svgHandle_=t.utils.dom.createSvgElement("rect",{class:"blocklyScrollbarHandle",rx:e,ry:e},this.svgGroup_),this.workspace_.getThemeManager().subscribe(this.svgHandle_,"scrollbarColour","fill"),this.workspace_.getThemeManager().subscribe(this.svgHandle_,"scrollbarOpacity","fill-opacity"),t.utils.dom.insertAfter(this.outerSvg_,this.workspace_.getParentSvg())},t.Scrollbar.prototype.isVisible=function(){return this.isVisible_},t.Scrollbar.prototype.setContainerVisible=function(t){var e=t!=this.containerVisible_;this.containerVisible_=t,e&&this.updateDisplay_()},t.Scrollbar.prototype.setVisible=function(t){var e=t!=this.isVisible();if(this.pair_)throw Error("Unable to toggle visibility of paired scrollbars.");this.isVisible_=t,e&&this.updateDisplay_()},t.Scrollbar.prototype.updateDisplay_=function(){this.containerVisible_&&this.isVisible()?this.outerSvg_.setAttribute("display","block"):this.outerSvg_.setAttribute("display","none")},t.Scrollbar.prototype.onMouseDownBar_=function(e){if(this.workspace_.markFocused(),t.Touch.clearTouchIdentifier(),this.cleanUp_(),t.utils.isRightButton(e))e.stopPropagation();else{var o=t.utils.mouseToSvg(e,this.workspace_.getParentSvg(),this.workspace_.getInverseScreenCTM());o=this.horizontal_?o.x:o.y;var i=t.utils.getInjectionDivXY_(this.svgHandle_);i=this.horizontal_?i.x:i.y;var n=this.handlePosition_,s=.95*this.handleLength_;o<=i?n-=s: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_<this.handleLength_?0:Math.min(t,this.scrollViewSize_-this.handleLength_)},t.Scrollbar.prototype.onScroll_=function(){var t=this.handlePosition_/this.scrollViewSize_;isNaN(t)&&(t=0);var e={};this.horizontal_?e.x=t:e.y=t,this.workspace_.setMetrics(e)},t.Scrollbar.prototype.set=function(t){this.setHandlePosition(this.constrainHandle_(t*this.ratio_)),this.onScroll_()},t.Scrollbar.prototype.setOrigin=function(e,o){this.origin_=new t.utils.Coordinate(e,o)},t.Tooltip={},t.Tooltip.visible=!1,t.Tooltip.blocked_=!1,t.Tooltip.LIMIT=50,t.Tooltip.mouseOutPid_=0,t.Tooltip.showPid_=0,t.Tooltip.lastX_=0,t.Tooltip.lastY_=0,t.Tooltip.element_=null,t.Tooltip.poisonedElement_=null,t.Tooltip.OFFSET_X=0,t.Tooltip.OFFSET_Y=10,t.Tooltip.RADIUS_OK=10,t.Tooltip.HOVER_MS=750,t.Tooltip.MARGINS=5,t.Tooltip.DIV=null,t.Tooltip.createDom=function(){t.Tooltip.DIV||(t.Tooltip.DIV=document.createElement("div"),t.Tooltip.DIV.className="blocklyTooltipDiv",(t.parentContainer||document.body).appendChild(t.Tooltip.DIV))},t.Tooltip.bindMouseEvents=function(e){e.mouseOverWrapper_=t.bindEvent_(e,"mouseover",null,t.Tooltip.onMouseOver_),e.mouseOutWrapper_=t.bindEvent_(e,"mouseout",null,t.Tooltip.onMouseOut_),e.addEventListener("mousemove",t.Tooltip.onMouseMove_,!1)},t.Tooltip.unbindMouseEvents=function(e){e&&(t.unbindEvent_(e.mouseOverWrapper_),t.unbindEvent_(e.mouseOutWrapper_),e.removeEventListener("mousemove",t.Tooltip.onMouseMove_))},t.Tooltip.onMouseOver_=function(e){if(!t.Tooltip.blocked_){for(e=e.currentTarget;"string"!=typeof e.tooltip&&"function"!=typeof e.tooltip;)e=e.tooltip;t.Tooltip.element_!=e&&(t.Tooltip.hide(),t.Tooltip.poisonedElement_=null,t.Tooltip.element_=e),clearTimeout(t.Tooltip.mouseOutPid_)}},t.Tooltip.onMouseOut_=function(e){t.Tooltip.blocked_||(t.Tooltip.mouseOutPid_=setTimeout((function(){t.Tooltip.element_=null,t.Tooltip.poisonedElement_=null,t.Tooltip.hide()}),1),clearTimeout(t.Tooltip.showPid_))},t.Tooltip.onMouseMove_=function(e){if(t.Tooltip.element_&&t.Tooltip.element_.tooltip&&!t.Tooltip.blocked_)if(t.Tooltip.visible){var o=t.Tooltip.lastX_-e.pageX;e=t.Tooltip.lastY_-e.pageY,Math.sqrt(o*o+e*e)>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;o<e.length;o++){var i=document.createElement("div");i.appendChild(document.createTextNode(e[o])),t.Tooltip.DIV.appendChild(i)}e=t.Tooltip.element_.RTL,o=document.documentElement.clientWidth,i=document.documentElement.clientHeight,t.Tooltip.DIV.style.direction=e?"rtl":"ltr",t.Tooltip.DIV.style.display="block",t.Tooltip.visible=!0;var n=t.Tooltip.lastX_;n=e?n-(t.Tooltip.OFFSET_X+t.Tooltip.DIV.offsetWidth):n+t.Tooltip.OFFSET_X;var s=t.Tooltip.lastY_+t.Tooltip.OFFSET_Y;s+t.Tooltip.DIV.offsetHeight>i+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;e<s.length;){if(s[e].isClickable()||t.ASTNode.NAVIGATE_ALL_FIELDS)return t.ASTNode.createFieldNode(s[e]);e++}if(e=0,o.connection)return t.ASTNode.createInputNode(o)}return null},t.ASTNode.prototype.findPrevForInput_=function(){for(var e,o=this.location_.getParentInput(),i=o.getSourceBlock(),n=i.inputList.indexOf(o);e=i.inputList[n];n--){if(e.connection&&e!==o)return t.ASTNode.createInputNode(e);for(var s,r=(e=e.fieldRow).length-1;s=e[r];r--)if(s.isClickable()||t.ASTNode.NAVIGATE_ALL_FIELDS)return t.ASTNode.createFieldNode(s)}return null},t.ASTNode.prototype.findPrevForField_=function(){var e,o=this.location_,i=o.getParentInput(),n=o.getSourceBlock(),s=n.inputList.indexOf(i);for(o=i.fieldRow.indexOf(o)-1;e=n.inputList[s];s--){if(e.connection&&e!==i)return t.ASTNode.createInputNode(e);for(e=e.fieldRow;-1<o;){if(e[o].isClickable()||t.ASTNode.NAVIGATE_ALL_FIELDS)return t.ASTNode.createFieldNode(e[o]);o--}0<=s-1&&(o=n.inputList[s-1].fieldRow.length-1)}return null},t.ASTNode.prototype.navigateBetweenStacks_=function(e){var o=this.getLocation();if(o instanceof t.Block||(o=o.getSourceBlock()),!o||!o.workspace)return null;var i=o.getRootBlock();o=i.workspace.getTopBlocks(!0);for(var n,s=0;n=o[s];s++)if(i.id==n.id)return-1==(e=s+(e?1:-1))||e==o.length?null:t.ASTNode.createStackNode(o[e]);throw Error("Couldn't find "+(e?"next":"previous")+" stack?!")},t.ASTNode.prototype.findTopASTNodeForBlock_=function(e){var o=e.previousConnection||e.outputConnection;return o?t.ASTNode.createConnectionNode(o):t.ASTNode.createBlockNode(e)},t.ASTNode.prototype.getOutAstNodeForBlock_=function(e){if(!e)return null;var o=(e=e.getTopStackBlock()).previousConnection||e.outputConnection;return o&&o.targetConnection&&o.targetConnection.getParentInput()?t.ASTNode.createInputNode(o.targetConnection.getParentInput()):t.ASTNode.createStackNode(e)},t.ASTNode.prototype.findFirstFieldOrInput_=function(e){e=e.inputList;for(var o,i=0;o=e[i];i++){for(var n,s=o.fieldRow,r=0;n=s[r];r++)if(n.isClickable()||t.ASTNode.NAVIGATE_ALL_FIELDS)return t.ASTNode.createFieldNode(n);if(o.connection)return t.ASTNode.createInputNode(o)}return null},t.ASTNode.prototype.getSourceBlock=function(){return this.getType()===t.ASTNode.types.BLOCK||this.getType()===t.ASTNode.types.STACK?this.getLocation():this.getType()===t.ASTNode.types.WORKSPACE?null:this.getLocation().getSourceBlock()},t.ASTNode.prototype.next=function(){switch(this.type_){case t.ASTNode.types.STACK:return this.navigateBetweenStacks_(!0);case t.ASTNode.types.OUTPUT:return t.ASTNode.createBlockNode(this.location_.getSourceBlock());case t.ASTNode.types.FIELD:return this.findNextForField_();case t.ASTNode.types.INPUT:return this.findNextForInput_();case t.ASTNode.types.BLOCK:return t.ASTNode.createConnectionNode(this.location_.nextConnection);case t.ASTNode.types.PREVIOUS:return t.ASTNode.createBlockNode(this.location_.getSourceBlock());case t.ASTNode.types.NEXT:return t.ASTNode.createConnectionNode(this.location_.targetConnection)}return null},t.ASTNode.prototype.in=function(){switch(this.type_){case t.ASTNode.types.WORKSPACE:var e=this.location_.getTopBlocks(!0);if(0<e.length)return t.ASTNode.createStackNode(e[0]);break;case t.ASTNode.types.STACK:return e=this.location_,this.findTopASTNodeForBlock_(e);case t.ASTNode.types.BLOCK:return e=this.location_,this.findFirstFieldOrInput_(e);case t.ASTNode.types.INPUT:return t.ASTNode.createConnectionNode(this.location_.targetConnection)}return null},t.ASTNode.prototype.prev=function(){switch(this.type_){case t.ASTNode.types.STACK:return this.navigateBetweenStacks_(!1);case t.ASTNode.types.FIELD:return this.findPrevForField_();case t.ASTNode.types.INPUT:return this.findPrevForInput_();case t.ASTNode.types.BLOCK:var e=this.location_;return t.ASTNode.createConnectionNode(e.previousConnection||e.outputConnection);case t.ASTNode.types.PREVIOUS:if((e=this.location_.targetConnection)&&!e.getParentInput())return t.ASTNode.createConnectionNode(e);break;case t.ASTNode.types.NEXT:return t.ASTNode.createBlockNode(this.location_.getSourceBlock())}return null},t.ASTNode.prototype.out=function(){switch(this.type_){case t.ASTNode.types.STACK:var e=this.location_.getRelativeToSurfaceXY();return e=new t.utils.Coordinate(e.x,e.y+t.ASTNode.DEFAULT_OFFSET_Y),t.ASTNode.createWorkspaceNode(this.location_.workspace,e);case t.ASTNode.types.OUTPUT:return(e=this.location_.targetConnection)?t.ASTNode.createConnectionNode(e):t.ASTNode.createStackNode(this.location_.getSourceBlock());case t.ASTNode.types.FIELD:case t.ASTNode.types.INPUT:return t.ASTNode.createBlockNode(this.location_.getSourceBlock());case t.ASTNode.types.BLOCK:return this.getOutAstNodeForBlock_(this.location_);case t.ASTNode.types.PREVIOUS:case t.ASTNode.types.NEXT:return this.getOutAstNodeForBlock_(this.location_.getSourceBlock())}return null},t.Blocks=Object.create(null),t.Connection=function(t,e){this.sourceBlock_=t,this.type=e},t.Connection.CAN_CONNECT=0,t.Connection.REASON_SELF_CONNECTION=1,t.Connection.REASON_WRONG_TYPE=2,t.Connection.REASON_TARGET_NULL=3,t.Connection.REASON_CHECKS_FAILED=4,t.Connection.REASON_DIFFERENT_WORKSPACES=5,t.Connection.REASON_SHADOW_PARENT=6,t.Connection.prototype.targetConnection=null,t.Connection.prototype.disposed=!1,t.Connection.prototype.check_=null,t.Connection.prototype.shadowDom_=null,t.Connection.prototype.x=0,t.Connection.prototype.y=0,t.Connection.prototype.connect_=function(e){var o,i=this,n=i.getSourceBlock(),s=e.getSourceBlock();if(e.isConnected()&&e.disconnect(),i.isConnected()){var r=i.targetBlock(),a=i.getShadowDom();if(i.setShadowDom(null),r.isShadow())a=t.Xml.blockToDom(r),r.dispose(!1),r=null;else if(i.type==t.INPUT_VALUE){if(!r.outputConnection)throw Error("Orphan block does not have an output connection.");var l=t.Connection.lastConnectionInRow(s,r);l&&(r.outputConnection.connect(l),r=null)}else if(i.type==t.NEXT_STATEMENT){if(!r.previousConnection)throw Error("Orphan block does not have a previous connection.");for(l=s;l.nextConnection;){var c=l.getNextBlock();if(!c||c.isShadow()){r.previousConnection.checkType(l.nextConnection)&&(l.nextConnection.connect(r.previousConnection),r=null);break}l=c}}if(r&&(i.disconnect(),t.Events.recordUndo)){var h=t.Events.getGroup();setTimeout((function(){r.workspace&&!r.getParent()&&(t.Events.setGroup(h),r.outputConnection?r.outputConnection.onFailedConnect(i):r.previousConnection&&r.previousConnection.onFailedConnect(i),t.Events.setGroup(!1))}),t.BUMP_DELAY)}i.setShadowDom(a)}t.Events.isEnabled()&&(o=new t.Events.BlockMove(s)),t.Connection.connectReciprocally_(i,e),s.setParent(n),o&&(o.recordNew(),t.Events.fire(o))},t.Connection.prototype.dispose=function(){if(this.isConnected()){this.setShadowDom(null);var t=this.targetBlock();t.isShadow()?t.dispose(!1):t.unplug()}this.disposed=!0},t.Connection.prototype.getSourceBlock=function(){return this.sourceBlock_},t.Connection.prototype.isSuperior=function(){return this.type==t.INPUT_VALUE||this.type==t.NEXT_STATEMENT},t.Connection.prototype.isConnected=function(){return!!this.targetConnection},t.Connection.prototype.canConnectWithReason=function(e){if(!e)return t.Connection.REASON_TARGET_NULL;if(this.isSuperior())var o=this.sourceBlock_,i=e.getSourceBlock();else i=this.sourceBlock_,o=e.getSourceBlock();return o&&o==i?t.Connection.REASON_SELF_CONNECTION:e.type!=t.OPPOSITE_TYPE[this.type]?t.Connection.REASON_WRONG_TYPE:o&&i&&o.workspace!==i.workspace?t.Connection.REASON_DIFFERENT_WORKSPACES:this.checkType(e)?o.isShadow()&&!i.isShadow()?t.Connection.REASON_SHADOW_PARENT:t.Connection.CAN_CONNECT:t.Connection.REASON_CHECKS_FAILED},t.Connection.prototype.checkConnection=function(e){switch(this.canConnectWithReason(e)){case t.Connection.CAN_CONNECT:break;case t.Connection.REASON_SELF_CONNECTION:throw Error("Attempted to connect a block to itself.");case t.Connection.REASON_DIFFERENT_WORKSPACES:throw Error("Blocks not on same workspace.");case t.Connection.REASON_WRONG_TYPE:throw Error("Attempt to connect incompatible types.");case t.Connection.REASON_TARGET_NULL:throw Error("Target connection is null.");case t.Connection.REASON_CHECKS_FAILED:throw Error("Connection checks failed. "+this+" expected "+this.check_+", found "+e.check_);case t.Connection.REASON_SHADOW_PARENT:throw Error("Connecting non-shadow to shadow block.");default:throw Error("Unknown connection failure: this should never happen!")}},t.Connection.prototype.canConnectToPrevious_=function(e){return!(this.targetConnection||-1!=t.draggingConnections.indexOf(e)||e.targetConnection&&(!(e=e.targetBlock()).isInsertionMarker()||e.getPreviousBlock()))},t.Connection.prototype.isConnectionAllowed=function(e){if(e.sourceBlock_.isInsertionMarker()||this.canConnectWithReason(e)!=t.Connection.CAN_CONNECT)return!1;switch(e.type){case t.PREVIOUS_STATEMENT:return this.canConnectToPrevious_(e);case t.OUTPUT_VALUE:if(e.isConnected()&&!e.targetBlock().isInsertionMarker()||this.isConnected())return!1;break;case t.INPUT_VALUE:if(e.isConnected()&&!e.targetBlock().isMovable()&&!e.targetBlock().isShadow())return!1;break;case t.NEXT_STATEMENT:if(e.isConnected()&&!this.sourceBlock_.nextConnection&&!e.targetBlock().isShadow()&&e.targetBlock().nextConnection)return!1;break;default:throw Error("Unknown connection type in isConnectionAllowed")}return-1==t.draggingConnections.indexOf(e)},t.Connection.prototype.onFailedConnect=function(t){},t.Connection.prototype.connect=function(e){if(this.targetConnection!=e){this.checkConnection(e);var o=t.Events.getGroup();o||t.Events.setGroup(!0),this.isSuperior()?this.connect_(e):e.connect_(this),o||t.Events.setGroup(!1)}},t.Connection.connectReciprocally_=function(t,e){if(!t||!e)throw Error("Cannot connect null connections.");t.targetConnection=e,e.targetConnection=t},t.Connection.singleConnection_=function(e,o){for(var i=null,n=0;n<e.inputList.length;n++){var s=e.inputList[n].connection;if(s&&s.type==t.INPUT_VALUE&&o.outputConnection.checkType(s)){if(i)return null;i=s}}return i},t.Connection.lastConnectionInRow=function(e,o){for(var i;i=t.Connection.singleConnection_(e,o);)if(!(e=i.targetBlock())||e.isShadow())return i;return null},t.Connection.prototype.disconnect=function(){var e=this.targetConnection;if(!e)throw Error("Source connection not connected.");if(e.targetConnection!=this)throw Error("Target connection not connected to source connection.");if(this.isSuperior()){var o=this.sourceBlock_,i=e.getSourceBlock();e=this}else o=e.getSourceBlock(),i=this.sourceBlock_;var n=t.Events.getGroup();n||t.Events.setGroup(!0),this.disconnectInternal_(o,i),e.respawnShadow_(),n||t.Events.setGroup(!1)},t.Connection.prototype.disconnectInternal_=function(e,o){var i;t.Events.isEnabled()&&(i=new t.Events.BlockMove(o)),this.targetConnection=this.targetConnection.targetConnection=null,o.setParent(null),i&&(i.recordNew(),t.Events.fire(i))},t.Connection.prototype.respawnShadow_=function(){var e=this.getSourceBlock(),o=this.getShadowDom();if(e.workspace&&o&&t.Events.recordUndo)if((e=t.Xml.domToBlock(o,e.workspace)).outputConnection)this.connect(e.outputConnection);else{if(!e.previousConnection)throw Error("Child block does not have output or previous statement.");this.connect(e.previousConnection)}},t.Connection.prototype.targetBlock=function(){return this.isConnected()?this.targetConnection.getSourceBlock():null},t.Connection.prototype.checkType=function(t){if(!this.check_||!t.check_)return!0;for(var e=0;e<this.check_.length;e++)if(-1!=t.check_.indexOf(this.check_[e]))return!0;return!1},t.Connection.prototype.checkType_=function(t){return console.warn("Deprecated call to Blockly.Connection.prototype.checkType_, use Blockly.Connection.prototype.checkType instead."),this.checkType(t)},t.Connection.prototype.onCheckChanged_=function(){!this.isConnected()||this.targetConnection&&this.checkType(this.targetConnection)||(this.isSuperior()?this.targetBlock():this.sourceBlock_).unplug()},t.Connection.prototype.setCheck=function(t){return t?(Array.isArray(t)||(t=[t]),this.check_=t,this.onCheckChanged_()):this.check_=null,this},t.Connection.prototype.getCheck=function(){return this.check_},t.Connection.prototype.setShadowDom=function(t){this.shadowDom_=t},t.Connection.prototype.getShadowDom=function(){return this.shadowDom_},t.Connection.prototype.neighbours=function(t){return[]},t.Connection.prototype.getParentInput=function(){for(var t=null,e=this.sourceBlock_,o=e.inputList,i=0;i<e.inputList.length;i++)if(o[i].connection===this){t=o[i];break}return t},t.Connection.prototype.toString=function(){var t=this.sourceBlock_;if(!t)return"Orphan Connection";if(t.outputConnection==this)var e="Output Connection of ";else if(t.previousConnection==this)e="Previous Connection of ";else if(t.nextConnection==this)e="Next Connection of ";else{e=null;for(var o,i=0;o=t.inputList[i];i++)if(o.connection==this){e=o;break}if(!e)return console.warn("Connection not actually connected to sourceBlock_"),"Orphan Connection";e='Input "'+e.name+'" connection on '}return e+t.toDevString()},t.Extensions={},t.Extensions.ALL_={},t.Extensions.register=function(e,o){if("string"!=typeof e||""==e.trim())throw Error('Error: Invalid extension name "'+e+'"');if(t.Extensions.ALL_[e])throw Error('Error: Extension "'+e+'" is already registered.');if("function"!=typeof o)throw Error('Error: Extension "'+e+'" must be a function');t.Extensions.ALL_[e]=o},t.Extensions.registerMixin=function(e,o){if(!o||"object"!=typeof o)throw Error('Error: Mixin "'+e+'" must be a object');t.Extensions.register(e,(function(){this.mixin(o)}))},t.Extensions.registerMutator=function(e,o,i,n){var s='Error when registering mutator "'+e+'": ';t.Extensions.checkHasFunction_(s,o.domToMutation,"domToMutation"),t.Extensions.checkHasFunction_(s,o.mutationToDom,"mutationToDom");var r=t.Extensions.checkMutatorDialog_(o,s);if(i&&"function"!=typeof i)throw Error('Extension "'+e+'" is not a function');t.Extensions.register(e,(function(){if(r){if(!t.Mutator)throw Error(s+"Missing require for Blockly.Mutator");this.setMutator(new t.Mutator(n||[]))}this.mixin(o),i&&i.apply(this)}))},t.Extensions.unregister=function(e){t.Extensions.ALL_[e]?delete t.Extensions.ALL_[e]:console.warn('No extension mapping for name "'+e+'" found to unregister')},t.Extensions.apply=function(e,o,i){var n=t.Extensions.ALL_[e];if("function"!=typeof n)throw Error('Error: Extension "'+e+'" not found.');if(i)t.Extensions.checkNoMutatorProperties_(e,o);else var s=t.Extensions.getMutatorProperties_(o);if(n.apply(o),i)t.Extensions.checkBlockHasMutatorProperties_('Error after applying mutator "'+e+'": ',o);else if(!t.Extensions.mutatorPropertiesMatch_(s,o))throw Error('Error when applying extension "'+e+'": mutation properties changed when applying a non-mutator extension.')},t.Extensions.checkHasFunction_=function(t,e,o){if(!e)throw Error(t+'missing required property "'+o+'"');if("function"!=typeof e)throw Error(t+'" required property "'+o+'" must be a function')},t.Extensions.checkNoMutatorProperties_=function(e,o){if(t.Extensions.getMutatorProperties_(o).length)throw Error('Error: tried to apply mutation "'+e+'" to a block that already has mutator functions.  Block id: '+o.id)},t.Extensions.checkMutatorDialog_=function(t,e){var o=void 0!==t.compose,i=void 0!==t.decompose;if(o&&i){if("function"!=typeof t.compose)throw Error(e+"compose must be a function.");if("function"!=typeof t.decompose)throw Error(e+"decompose must be a function.");return!0}if(o||i)throw Error(e+'Must have both or neither of "compose" and "decompose"');return!1},t.Extensions.checkBlockHasMutatorProperties_=function(e,o){if("function"!=typeof o.domToMutation)throw Error(e+'Applying a mutator didn\'t add "domToMutation"');if("function"!=typeof o.mutationToDom)throw Error(e+'Applying a mutator didn\'t add "mutationToDom"');t.Extensions.checkMutatorDialog_(o,e)},t.Extensions.getMutatorProperties_=function(t){var e=[];return void 0!==t.domToMutation&&e.push(t.domToMutation),void 0!==t.mutationToDom&&e.push(t.mutationToDom),void 0!==t.compose&&e.push(t.compose),void 0!==t.decompose&&e.push(t.decompose),e},t.Extensions.mutatorPropertiesMatch_=function(e,o){if((o=t.Extensions.getMutatorProperties_(o)).length!=e.length)return!1;for(var i=0;i<o.length;i++)if(e[i]!=o[i])return!1;return!0},t.Extensions.buildTooltipForDropdown=function(e,o){var i=[];return"object"==typeof document&&t.utils.runAfterPageLoad((function(){for(var e in o)t.utils.checkMessageReferences(o[e])})),function(){this.type&&-1==i.indexOf(this.type)&&(t.Extensions.checkDropdownOptionsInTable_(this,e,o),i.push(this.type)),this.setTooltip(function(){var n=String(this.getFieldValue(e)),s=o[n];return null==s?-1==i.indexOf(this.type)&&(n="No tooltip mapping for value "+n+" of field "+e,null!=this.type&&(n+=" of block type "+this.type),console.warn(n+".")):s=t.utils.replaceMessageReferences(s),s}.bind(this))}},t.Extensions.checkDropdownOptionsInTable_=function(t,e,o){var i=t.getField(e);if(!i.isOptionListDynamic()){i=i.getOptions();for(var n=0;n<i.length;++n){var s=i[n][1];null==o[s]&&console.warn("No tooltip mapping for value "+s+" of field "+e+" of block type "+t.type)}}},t.Extensions.buildTooltipWithFieldText=function(e,o){return"object"==typeof document&&t.utils.runAfterPageLoad((function(){t.utils.checkMessageReferences(e)})),function(){this.setTooltip(function(){var i=this.getField(o);return t.utils.replaceMessageReferences(e).replace("%1",i?i.getText():"")}.bind(this))}},t.Extensions.extensionParentTooltip_=function(){this.tooltipWhenNotConnected_=this.tooltip,this.setTooltip(function(){var t=this.getParent();return t&&t.getInputsInline()&&t.tooltip||this.tooltipWhenNotConnected_}.bind(this))},t.Extensions.register("parent_tooltip_when_inline",t.Extensions.extensionParentTooltip_),t.fieldRegistry={},t.fieldRegistry.typeMap_={},t.fieldRegistry.register=function(e,o){if("string"!=typeof e||""==e.trim())throw Error('Invalid field type "'+e+'". The type must be a non-empty string.');if(t.fieldRegistry.typeMap_[e])throw Error('Error: Field "'+e+'" is already registered.');if(!o||"function"!=typeof o.fromJson)throw Error('Field "'+o+'" must have a fromJson function');e=e.toLowerCase(),t.fieldRegistry.typeMap_[e]=o},t.fieldRegistry.unregister=function(e){t.fieldRegistry.typeMap_[e]?delete t.fieldRegistry.typeMap_[e]:console.warn('No field mapping for type "'+e+'" found to unregister')},t.fieldRegistry.fromJson=function(e){var o=e.type.toLowerCase();return(o=t.fieldRegistry.typeMap_[o])?o.fromJson(e):(console.warn("Blockly could not create a field of type "+e.type+". The field is probably not being registered. This could be because the file is not loaded, the field does not register itself (Issue #1584), or the registration is not being reached."),null)},t.blockAnimations={},t.blockAnimations.disconnectPid_=0,t.blockAnimations.disconnectGroup_=null,t.blockAnimations.disposeUiEffect=function(e){var o=e.workspace,i=e.getSvgRoot();o.getAudioManager().play("delete"),e=o.getSvgXY(i),(i=i.cloneNode(!0)).translateX_=e.x,i.translateY_=e.y,i.setAttribute("transform","translate("+e.x+","+e.y+")"),o.getParentSvg().appendChild(i),i.bBox_=i.getBBox(),t.blockAnimations.disposeUiStep_(i,o.RTL,new Date,o.scale)},t.blockAnimations.disposeUiStep_=function(e,o,i,n){var s=(new Date-i)/150;1<s?t.utils.dom.removeNode(e):(e.setAttribute("transform","translate("+(e.translateX_+(o?-1:1)*e.bBox_.width*n/2*s)+","+(e.translateY_+e.bBox_.height*n*s)+") scale("+(1-s)*n+")"),setTimeout(t.blockAnimations.disposeUiStep_,10,e,o,i,n))},t.blockAnimations.connectionUiEffect=function(e){var o=e.workspace,i=o.scale;if(o.getAudioManager().play("click"),!(1>i)){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;1<n?t.utils.dom.removeNode(e):(e.setAttribute("r",25*n*i),e.style.opacity=1-n,t.blockAnimations.disconnectPid_=setTimeout(t.blockAnimations.connectionUiStep_,10,e,o,i))},t.blockAnimations.disconnectUiEffect=function(e){if(e.workspace.getAudioManager().play("disconnect"),!(1>e.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;1<n?e.skew_="":(e.skew_="skewX("+Math.round(Math.sin(n*Math.PI*3)*(1-n)*o)+")",t.blockAnimations.disconnectGroup_=e,t.blockAnimations.disconnectPid_=setTimeout(t.blockAnimations.disconnectUiStep_,10,e,o,i)),e.setAttribute("transform",e.translate_+e.skew_)},t.blockAnimations.disconnectUiStop=function(){if(t.blockAnimations.disconnectGroup_){clearTimeout(t.blockAnimations.disconnectPid_);var e=t.blockAnimations.disconnectGroup_;e.skew_="",e.setAttribute("transform",e.translate_),t.blockAnimations.disconnectGroup_=null}},t.InsertionMarkerManager=function(e){this.topBlock_=t.selected=e,this.workspace_=e.workspace,this.lastMarker_=this.lastOnStack_=null,this.firstMarker_=this.createMarkerBlock_(this.topBlock_),this.localConnection_=this.closestConnection_=null,this.wouldDeleteBlock_=!1,this.fadedBlock_=this.highlightedBlock_=this.markerConnection_=null,this.availableConnections_=this.initAvailableConnections_()},t.InsertionMarkerManager.PREVIEW_TYPE={INSERTION_MARKER:0,INPUT_OUTLINE:1,REPLACEMENT_FADE:2},t.InsertionMarkerManager.prototype.dispose=function(){this.availableConnections_.length=0,t.Events.disable();try{this.firstMarker_&&this.firstMarker_.dispose(),this.lastMarker_&&this.lastMarker_.dispose()}finally{t.Events.enable()}},t.InsertionMarkerManager.prototype.wouldDeleteBlock=function(){return this.wouldDeleteBlock_},t.InsertionMarkerManager.prototype.wouldConnectBlock=function(){return!!this.closestConnection_},t.InsertionMarkerManager.prototype.applyConnections=function(){if(this.closestConnection_&&(t.Events.disable(),this.hidePreview_(),t.Events.enable(),this.localConnection_.connect(this.closestConnection_),this.topBlock_.rendered)){var e=this.localConnection_.isSuperior()?this.closestConnection_:this.localConnection_;t.blockAnimations.connectionUiEffect(e.getSourceBlock()),this.topBlock_.getRootBlock().bringToFront()}},t.InsertionMarkerManager.prototype.update=function(e,o){var i=this.getCandidate_(e);((this.wouldDeleteBlock_=this.shouldDelete_(i,o))||this.shouldUpdatePreviews_(i,e))&&(t.Events.disable(),this.maybeHidePreview_(i),this.maybeShowPreview_(i),t.Events.enable())},t.InsertionMarkerManager.prototype.createMarkerBlock_=function(e){var o=e.type;t.Events.disable();try{var i=this.workspace_.newBlock(o);if(i.setInsertionMarker(!0),e.mutationToDom){var n=e.mutationToDom();n&&i.domToMutation(n)}for(i.setCollapsed(e.isCollapsed()),i.setInputsInline(e.getInputsInline()),o=0;o<e.inputList.length;o++){var s=e.inputList[o];if(s.isVisible()){var r=i.inputList[o];for(n=0;n<s.fieldRow.length;n++)r.fieldRow[n].setValue(s.fieldRow[n].getValue())}}i.initSvg(),i.getSvgRoot().setAttribute("visibility","hidden")}finally{t.Events.enable()}return i},t.InsertionMarkerManager.prototype.initAvailableConnections_=function(){var t=this.topBlock_.getConnections_(!1),e=this.topBlock_.lastConnectionInStack();return e&&e!=this.topBlock_.nextConnection&&(t.push(e),this.lastOnStack_=e,this.lastMarker_=this.createMarkerBlock_(e.getSourceBlock())),t},t.InsertionMarkerManager.prototype.shouldUpdatePreviews_=function(e,o){var i=e.local,n=e.closest;return e=e.radius,i&&n?this.localConnection_&&this.closestConnection_?!(this.closestConnection_==n&&this.localConnection_==i||(i=this.localConnection_.x+o.x-this.closestConnection_.x,o=this.localConnection_.y+o.y-this.closestConnection_.y,o=Math.sqrt(i*i+o*o),n&&e>o-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;n<this.availableConnections_.length;n++){var s=this.availableConnections_[n],r=s.closest(e,t);r.connection&&(o=r.connection,i=s,e=r.radius)}return{closest:o,local:i,radius:e}},t.InsertionMarkerManager.prototype.getStartRadius_=function(){return this.closestConnection_&&this.localConnection_?t.CONNECTING_SNAP_RADIUS:t.SNAP_RADIUS},t.InsertionMarkerManager.prototype.shouldDelete_=function(e,o){return e=e&&!!e.closest&&o!=t.DELETE_AREA_TOOLBOX,!!o&&!this.topBlock_.getParent()&&this.topBlock_.isDeletable()&&!e},t.InsertionMarkerManager.prototype.maybeShowPreview_=function(t){if(!this.wouldDeleteBlock_){var e=t.closest;t=t.local,e&&(e==this.closestConnection_||e.getSourceBlock().isInsertionMarker()?console.log("Trying to connect to an insertion marker"):(this.closestConnection_=e,this.localConnection_=t,this.showPreview_()))}},t.InsertionMarkerManager.prototype.showPreview_=function(){var e=this.closestConnection_,o=this.workspace_.getRenderer();switch(o.getConnectionPreviewMethod(e,this.localConnection_,this.topBlock_)){case t.InsertionMarkerManager.PREVIEW_TYPE.INPUT_OUTLINE:this.showInsertionInputOutline_();break;case t.InsertionMarkerManager.PREVIEW_TYPE.INSERTION_MARKER:this.showInsertionMarker_();break;case t.InsertionMarkerManager.PREVIEW_TYPE.REPLACEMENT_FADE:this.showReplacementFade_()}e&&o.shouldHighlightConnection(e)&&e.highlight()},t.InsertionMarkerManager.prototype.maybeHidePreview_=function(t){if(t.closest){var e=this.closestConnection_!=t.closest;t=this.localConnection_!=t.local,this.closestConnection_&&this.localConnection_&&(e||t||this.wouldDeleteBlock_)&&this.hidePreview_()}else this.hidePreview_();this.localConnection_=this.closestConnection_=this.markerConnection_=null},t.InsertionMarkerManager.prototype.hidePreview_=function(){this.closestConnection_&&this.closestConnection_.targetBlock()&&this.workspace_.getRenderer().shouldHighlightConnection(this.closestConnection_)&&this.closestConnection_.unhighlight(),this.fadedBlock_?this.hideReplacementFade_():this.highlightedBlock_?this.hideInsertionInputOutline_():this.markerConnection_&&this.hideInsertionMarker_()},t.InsertionMarkerManager.prototype.showInsertionMarker_=function(){var t=this.localConnection_,e=this.closestConnection_,o=this.lastOnStack_&&t==this.lastOnStack_?this.lastMarker_:this.firstMarker_;if((t=o.getMatchingConnection(t.getSourceBlock(),t))==this.markerConnection_)throw Error("Made it to showInsertionMarker_ even though the marker isn't changing");o.render(),o.rendered=!0,o.getSvgRoot().setAttribute("visibility","visible"),t&&e&&o.positionNearConnection(t,e),e&&t.connect(e),this.markerConnection_=t},t.InsertionMarkerManager.prototype.hideInsertionMarker_=function(){if(this.markerConnection_){var e=this.markerConnection_,o=e.getSourceBlock(),i=o.nextConnection,n=o.previousConnection,s=o.outputConnection;if(s=e.type==t.INPUT_VALUE&&!(s&&s.targetConnection),!(e!=i||n&&n.targetConnection)||s?e.targetBlock().unplug(!1):e.type==t.NEXT_STATEMENT&&e!=i?((i=e.targetConnection).getSourceBlock().unplug(!1),n=n?n.targetConnection:null,o.unplug(!0),n&&n.connect(i)):o.unplug(!0),e.targetConnection)throw Error("markerConnection_ still connected at the end of disconnectInsertionMarker");this.markerConnection_=null,o.getSvgRoot().setAttribute("visibility","hidden")}else console.log("No insertion marker connection to disconnect")},t.InsertionMarkerManager.prototype.showInsertionInputOutline_=function(){var t=this.closestConnection_;this.highlightedBlock_=t.getSourceBlock(),this.highlightedBlock_.highlightShapeForInput(t,!0)},t.InsertionMarkerManager.prototype.hideInsertionInputOutline_=function(){this.highlightedBlock_.highlightShapeForInput(this.closestConnection_,!1),this.highlightedBlock_=null},t.InsertionMarkerManager.prototype.showReplacementFade_=function(){this.fadedBlock_=this.closestConnection_.targetBlock(),this.fadedBlock_.fadeForReplacement(!0)},t.InsertionMarkerManager.prototype.hideReplacementFade_=function(){this.fadedBlock_.fadeForReplacement(!1),this.fadedBlock_=null},t.InsertionMarkerManager.prototype.getInsertionMarkers=function(){var t=[];return this.firstMarker_&&t.push(this.firstMarker_),this.lastMarker_&&t.push(this.lastMarker_),t},t.BlockDragger=function(e,o){this.draggingBlock_=e,this.workspace_=o,this.draggedConnectionManager_=new t.InsertionMarkerManager(this.draggingBlock_),this.deleteArea_=null,this.wouldDeleteBlock_=!1,this.startXY_=this.draggingBlock_.getRelativeToSurfaceXY(),this.dragIconData_=t.BlockDragger.initIconData_(e)},t.BlockDragger.prototype.dispose=function(){this.dragIconData_.length=0,this.draggedConnectionManager_&&this.draggedConnectionManager_.dispose()},t.BlockDragger.initIconData_=function(t){var e=[];t=t.getDescendants(!1);for(var o,i=0;o=t[i];i++){o=o.getIcons();for(var n=0;n<o.length;n++){var s={location:o[n].getIconLocation(),icon:o[n]};e.push(s)}}return e},t.BlockDragger.prototype.startBlockDrag=function(e,o){t.Events.getGroup()||t.Events.setGroup(!0),this.fireDragStartEvent_(),this.workspace_.isMutator&&this.draggingBlock_.bringToFront(),t.utils.dom.startTextWidthCache(),this.workspace_.setResizesEnabled(!1),t.blockAnimations.disconnectUiStop(),(this.draggingBlock_.getParent()||o&&this.draggingBlock_.nextConnection&&this.draggingBlock_.nextConnection.targetBlock())&&(this.draggingBlock_.unplug(o),e=this.pixelsToWorkspaceUnits_(e),e=t.utils.Coordinate.sum(this.startXY_,e),this.draggingBlock_.translate(e.x,e.y),t.blockAnimations.disconnectUiEffect(this.draggingBlock_)),this.draggingBlock_.setDragging(!0),this.draggingBlock_.moveToDragSurface(),(e=this.workspace_.getToolbox())&&(o=this.draggingBlock_.isDeletable()?"blocklyToolboxDelete":"blocklyToolboxGrab",e.addStyle(o))},t.BlockDragger.prototype.fireDragStartEvent_=function(){var e=new t.Events.Ui(this.draggingBlock_,"dragStart",null,this.draggingBlock_.getDescendants(!1));t.Events.fire(e)},t.BlockDragger.prototype.dragBlock=function(e,o){o=this.pixelsToWorkspaceUnits_(o);var i=t.utils.Coordinate.sum(this.startXY_,o);this.draggingBlock_.moveDuringDrag(i),this.dragIcons_(o),this.deleteArea_=this.workspace_.isDeleteArea(e),this.draggedConnectionManager_.update(o,this.deleteArea_),this.updateCursorDuringBlockDrag_()},t.BlockDragger.prototype.endBlockDrag=function(e,o){this.dragBlock(e,o),this.dragIconData_=[],this.fireDragEndEvent_(),t.utils.dom.stopTextWidthCache(),t.blockAnimations.disconnectUiStop(),e=this.pixelsToWorkspaceUnits_(o),o=t.utils.Coordinate.sum(this.startXY_,e),this.draggingBlock_.moveOffDragSurface(o),this.maybeDeleteBlock_()||(this.draggingBlock_.moveConnections(e.x,e.y),this.draggingBlock_.setDragging(!1),this.fireMoveEvent_(),this.draggedConnectionManager_.wouldConnectBlock()?this.draggedConnectionManager_.applyConnections():this.draggingBlock_.render(),this.draggingBlock_.scheduleSnapAndBump()),this.workspace_.setResizesEnabled(!0),(e=this.workspace_.getToolbox())&&(o=this.draggingBlock_.isDeletable()?"blocklyToolboxDelete":"blocklyToolboxGrab",e.removeStyle(o)),t.Events.setGroup(!1)},t.BlockDragger.prototype.fireDragEndEvent_=function(){var e=new t.Events.Ui(this.draggingBlock_,"dragStop",this.draggingBlock_.getDescendants(!1),null);t.Events.fire(e)},t.BlockDragger.prototype.fireMoveEvent_=function(){var e=new t.Events.BlockMove(this.draggingBlock_);e.oldCoordinate=this.startXY_,e.recordNew(),t.Events.fire(e)},t.BlockDragger.prototype.maybeDeleteBlock_=function(){var e=this.workspace_.trashcan;return this.wouldDeleteBlock_?(e&&setTimeout(e.close.bind(e),100),this.fireMoveEvent_(),this.draggingBlock_.dispose(!1,!0),t.draggingConnections=[]):e&&e.close(),this.wouldDeleteBlock_},t.BlockDragger.prototype.updateCursorDuringBlockDrag_=function(){this.wouldDeleteBlock_=this.draggedConnectionManager_.wouldDeleteBlock();var e=this.workspace_.trashcan;this.wouldDeleteBlock_?(this.draggingBlock_.setDeleteStyle(!0),this.deleteArea_==t.DELETE_AREA_TRASH&&e&&e.setOpen(!0)):(this.draggingBlock_.setDeleteStyle(!1),e&&e.setOpen(!1))},t.BlockDragger.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.BlockDragger.prototype.dragIcons_=function(e){for(var o=0;o<this.dragIconData_.length;o++){var i=this.dragIconData_[o];i.icon.setIconLocation(t.utils.Coordinate.sum(i.location,e))}},t.BlockDragger.prototype.getInsertionMarkers=function(){return this.draggedConnectionManager_&&this.draggedConnectionManager_.getInsertionMarkers?this.draggedConnectionManager_.getInsertionMarkers():[]},t.VariableMap=function(t){this.variableMap_=Object.create(null),this.workspace=t},t.VariableMap.prototype.clear=function(){this.variableMap_=Object.create(null)},t.VariableMap.prototype.renameVariable=function(e,o){var i=this.getVariable(o,e.type),n=this.workspace.getAllBlocks(!1);t.Events.setGroup(!0);try{i&&i.getId()!=e.getId()?this.renameVariableWithConflict_(e,o,i,n):this.renameVariableAndUses_(e,o,n)}finally{t.Events.setGroup(!1)}},t.VariableMap.prototype.renameVariableById=function(t,e){var o=this.getVariableById(t);if(!o)throw Error("Tried to rename a variable that didn't exist. ID: "+t);this.renameVariable(o,e)},t.VariableMap.prototype.renameVariableAndUses_=function(e,o,i){for(t.Events.fire(new t.Events.VarRename(e,o)),e.name=o,o=0;o<i.length;o++)i[o].updateVarName(e)},t.VariableMap.prototype.renameVariableWithConflict_=function(e,o,i,n){var s=e.type;for(o!=i.name&&this.renameVariableAndUses_(i,o,n),o=0;o<n.length;o++)n[o].renameVarById(e.getId(),i.getId());t.Events.fire(new t.Events.VarDelete(e)),e=this.getVariablesOfType(s).indexOf(e),this.variableMap_[s].splice(e,1)},t.VariableMap.prototype.createVariable=function(e,o,i){var n=this.getVariable(e,o);if(n){if(i&&n.getId()!=i)throw Error('Variable "'+e+'" is already in use and its id is "'+n.getId()+'" which conflicts with the passed in id, "'+i+'".');return n}if(i&&this.getVariableById(i))throw Error('Variable id, "'+i+'", is already in use.');return n=i||t.utils.genUid(),o=o||"",n=new t.VariableModel(this.workspace,e,o,n),(e=this.variableMap_[o]||[]).push(n),delete this.variableMap_[o],this.variableMap_[o]=e,n},t.VariableMap.prototype.deleteVariable=function(e){for(var o,i=this.variableMap_[e.type],n=0;o=i[n];n++)if(o.getId()==e.getId()){i.splice(n,1),t.Events.fire(new t.Events.VarDelete(e));break}},t.VariableMap.prototype.deleteVariableById=function(e){var o=this.getVariableById(e);if(o){var i,n=o.name,s=this.getVariableUsesById(e);for(e=0;i=s[e];e++)if("procedures_defnoreturn"==i.type||"procedures_defreturn"==i.type)return e=i.getFieldValue("NAME"),n=t.Msg.CANNOT_DELETE_VARIABLE_PROCEDURE.replace("%1",n).replace("%2",e),void t.alert(n);var r=this;1<s.length?(n=t.Msg.DELETE_VARIABLE_CONFIRMATION.replace("%1",String(s.length)).replace("%2",n),t.confirm(n,(function(t){t&&o&&r.deleteVariableInternal(o,s)}))):r.deleteVariableInternal(o,s)}else console.warn("Can't delete non-existent variable: "+e)},t.VariableMap.prototype.deleteVariableInternal=function(e,o){var i=t.Events.getGroup();i||t.Events.setGroup(!0);try{for(var n=0;n<o.length;n++)o[n].dispose(!0);this.deleteVariable(e)}finally{i||t.Events.setGroup(!1)}},t.VariableMap.prototype.getVariable=function(e,o){if(o=this.variableMap_[o||""])for(var i,n=0;i=o[n];n++)if(t.Names.equals(i.name,e))return i;return null},t.VariableMap.prototype.getVariableById=function(t){for(var e=Object.keys(this.variableMap_),o=0;o<e.length;o++)for(var i,n=e[o],s=0;i=this.variableMap_[n][s];s++)if(i.getId()==t)return i;return null},t.VariableMap.prototype.getVariablesOfType=function(t){return(t=this.variableMap_[t||""])?t.slice():[]},t.VariableMap.prototype.getVariableTypes=function(e){var o={};t.utils.object.mixin(o,this.variableMap_),e&&e.getPotentialVariableMap()&&t.utils.object.mixin(o,e.getPotentialVariableMap().variableMap_),e=Object.keys(o),o=!1;for(var i=0;i<e.length;i++)""==e[i]&&(o=!0);return o||e.push(""),e},t.VariableMap.prototype.getAllVariables=function(){var t,e=[];for(t in this.variableMap_)e=e.concat(this.variableMap_[t]);return e},t.VariableMap.prototype.getAllVariableNames=function(){var t,e=[];for(t in this.variableMap_)for(var o,i=this.variableMap_[t],n=0;o=i[n];n++)e.push(o.name);return e},t.VariableMap.prototype.getVariableUsesById=function(t){for(var e=[],o=this.workspace.getAllBlocks(!1),i=0;i<o.length;i++){var n=o[i].getVarModels();if(n)for(var s=0;s<n.length;s++)n[s].getId()==t&&e.push(o[i])}return e},t.Workspace=function(e){this.id=t.utils.genUid(),t.Workspace.WorkspaceDB_[this.id]=this,this.options=e||new t.Options({}),this.RTL=!!this.options.RTL,this.horizontalLayout=!!this.options.horizontalLayout,this.toolboxPosition=this.options.toolboxPosition,this.topBlocks_=[],this.topComments_=[],this.commentDB_=Object.create(null),this.listeners_=[],this.undoStack_=[],this.redoStack_=[],this.blockDB_=Object.create(null),this.typedBlocksDB_=Object.create(null),this.variableMap_=new t.VariableMap(this),this.potentialVariableMap_=null},t.Workspace.prototype.rendered=!1,t.Workspace.prototype.isClearing=!1,t.Workspace.prototype.MAX_UNDO=1024,t.Workspace.prototype.connectionDBList=null,t.Workspace.prototype.dispose=function(){this.listeners_.length=0,this.clear(),delete t.Workspace.WorkspaceDB_[this.id]},t.Workspace.SCAN_ANGLE=3,t.Workspace.prototype.sortObjects_=function(e,o){return e=e.getRelativeToSurfaceXY(),o=o.getRelativeToSurfaceXY(),e.y+t.Workspace.prototype.sortObjects_.offset*e.x-(o.y+t.Workspace.prototype.sortObjects_.offset*o.x)},t.Workspace.prototype.addTopBlock=function(t){this.topBlocks_.push(t)},t.Workspace.prototype.removeTopBlock=function(e){if(!t.utils.arrayRemove(this.topBlocks_,e))throw Error("Block not present in workspace's list of top-most blocks.")},t.Workspace.prototype.getTopBlocks=function(e){var o=[].concat(this.topBlocks_);return e&&1<o.length&&(this.sortObjects_.offset=Math.sin(t.utils.math.toRadians(t.Workspace.SCAN_ANGLE)),this.RTL&&(this.sortObjects_.offset*=-1),o.sort(this.sortObjects_)),o},t.Workspace.prototype.addTypedBlock=function(t){this.typedBlocksDB_[t.type]||(this.typedBlocksDB_[t.type]=[]),this.typedBlocksDB_[t.type].push(t)},t.Workspace.prototype.removeTypedBlock=function(t){this.typedBlocksDB_[t.type].splice(this.typedBlocksDB_[t.type].indexOf(t),1),this.typedBlocksDB_[t.type].length||delete this.typedBlocksDB_[t.type]},t.Workspace.prototype.getBlocksByType=function(e,o){return this.typedBlocksDB_[e]?(e=this.typedBlocksDB_[e].slice(0),o&&1<e.length&&(this.sortObjects_.offset=Math.sin(t.utils.math.toRadians(t.Workspace.SCAN_ANGLE)),this.RTL&&(this.sortObjects_.offset*=-1),e.sort(this.sortObjects_)),e):[]},t.Workspace.prototype.addTopComment=function(t){this.topComments_.push(t),this.commentDB_[t.id]&&console.warn('Overriding an existing comment on this workspace, with id "'+t.id+'"'),this.commentDB_[t.id]=t},t.Workspace.prototype.removeTopComment=function(e){if(!t.utils.arrayRemove(this.topComments_,e))throw Error("Comment not present in workspace's list of top-most comments.");delete this.commentDB_[e.id]},t.Workspace.prototype.getTopComments=function(e){var o=[].concat(this.topComments_);return e&&1<o.length&&(this.sortObjects_.offset=Math.sin(t.utils.math.toRadians(t.Workspace.SCAN_ANGLE)),this.RTL&&(this.sortObjects_.offset*=-1),o.sort(this.sortObjects_)),o},t.Workspace.prototype.getAllBlocks=function(t){if(t){t=this.getTopBlocks(!0);for(var e=[],o=0;o<t.length;o++)e.push.apply(e,t[o].getDescendants(!0))}else for(e=this.getTopBlocks(!1),o=0;o<e.length;o++)e.push.apply(e,e[o].getChildren(!1));return e.filter((function(t){return!t.isInsertionMarker()}))},t.Workspace.prototype.clear=function(){this.isClearing=!0;try{var e=t.Events.getGroup();for(e||t.Events.setGroup(!0);this.topBlocks_.length;)this.topBlocks_[0].dispose(!1);for(;this.topComments_.length;)this.topComments_[this.topComments_.length-1].dispose(!1);e||t.Events.setGroup(!1),this.variableMap_.clear(),this.potentialVariableMap_&&this.potentialVariableMap_.clear()}finally{this.isClearing=!1}},t.Workspace.prototype.renameVariableById=function(t,e){this.variableMap_.renameVariableById(t,e)},t.Workspace.prototype.createVariable=function(t,e,o){return this.variableMap_.createVariable(t,e,o)},t.Workspace.prototype.getVariableUsesById=function(t){return this.variableMap_.getVariableUsesById(t)},t.Workspace.prototype.deleteVariableById=function(t){this.variableMap_.deleteVariableById(t)},t.Workspace.prototype.deleteVariableInternal_=function(t,e){this.variableMap_.deleteVariableInternal(t,e)},t.Workspace.prototype.variableIndexOf=function(t){return console.warn("Deprecated call to Blockly.Workspace.prototype.variableIndexOf"),-1},t.Workspace.prototype.getVariable=function(t,e){return this.variableMap_.getVariable(t,e)},t.Workspace.prototype.getVariableById=function(t){return this.variableMap_.getVariableById(t)},t.Workspace.prototype.getVariablesOfType=function(t){return this.variableMap_.getVariablesOfType(t)},t.Workspace.prototype.getVariableTypes=function(){return this.variableMap_.getVariableTypes(this)},t.Workspace.prototype.getAllVariables=function(){return this.variableMap_.getAllVariables()},t.Workspace.prototype.getAllVariableNames=function(){return this.variableMap_.getAllVariableNames()},t.Workspace.prototype.getWidth=function(){return 0},t.Workspace.prototype.newBlock=function(e,o){return new t.Block(this,e,o)},t.Workspace.prototype.remainingCapacity=function(){return isNaN(this.options.maxBlocks)?1/0:this.options.maxBlocks-this.getAllBlocks(!1).length},t.Workspace.prototype.remainingCapacityOfType=function(t){return this.options.maxInstances?(this.options.maxInstances[t]||1/0)-this.getBlocksByType(t,!1).length:1/0},t.Workspace.prototype.isCapacityAvailable=function(t){if(!this.hasBlockLimits())return!0;var e,o=0;for(e in t){if(t[e]>this.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.width<i.height?o:r,i=i.width<i.height?r:o,o=this.getOverlap_(n,t),r=this.getOverlap_(s,t);var a=this.getOverlap_(e,t);t=this.getOverlap_(i,t),o==(t=Math.max(o,r,a,t))?(this.relativeLeft_=n.x,this.relativeTop_=n.y):r==t?(this.relativeLeft_=s.x,this.relativeTop_=s.y):a==t?(this.relativeLeft_=e.x,this.relativeTop_=e.y):(this.relativeLeft_=i.x,this.relativeTop_=i.y)},t.Bubble.prototype.getOverlap_=function(t,e){var o=this.workspace_.RTL?this.anchorXY_.x-t.x-this.width_:t.x+this.anchorXY_.x;return t=t.y+this.anchorXY_.y,Math.max(0,Math.min(1,(Math.min(o+this.width_,e.viewLeft+e.viewWidth)-Math.max(o,e.viewLeft))*(Math.min(t+this.height_,e.viewTop+e.viewHeight)-Math.max(t,e.viewTop))/(this.width_*this.height_)))},t.Bubble.prototype.getOptimalRelativeLeft_=function(e){var o=-this.width_/4;if(this.width_>e.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?n<r?o=-(r-this.anchorXY_.x+this.width_):i>s&&(o=-(s-this.anchorXY_.x)):n<r?o=r-this.anchorXY_.x:i>s&&(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 i<s?o=s-r:n>e&&(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<n.length?o.setCurNode(t.navigation.getTopNode(n[0])):(i=new t.utils.Coordinate(100,100),e=t.ASTNode.createWorkspaceNode(e,i),o.setCurNode(e))},t.navigation.getFlyoutCursor_=function(){var e=t.getMainWorkspace(),o=null;return e.rendered&&(o=(e=(o=e.getToolbox())?o.flyout_:e.getFlyout())?e.workspace_.getCursor():null),o},t.navigation.insertFromFlyout=function(){var e=t.getMainWorkspace(),o=e.getFlyout();if(o&&o.isVisible()){var i=t.navigation.getFlyoutCursor_().getCurNode().getLocation();i.isEnabled()?((o=o.createBlock(i)).render(),o.setConnectionTracking(!0),e.getCursor().setCurNode(t.ASTNode.createBlockNode(o)),t.navigation.modify_()||t.navigation.warn_("Something went wrong while inserting a block from the flyout."),t.navigation.focusWorkspace_(),e.getCursor().setCurNode(t.navigation.getTopNode(o)),t.navigation.removeMark_()):t.navigation.warn_("Can't insert a disabled block.")}else t.navigation.warn_("Trying to insert from the flyout when the flyout does not  exist or is not visible")},t.navigation.resetFlyout_=function(e){t.navigation.getFlyoutCursor_()&&(t.navigation.getFlyoutCursor_().hide(),e&&t.getMainWorkspace().getFlyout().hide())},t.navigation.modifyWarn_=function(){var e=t.navigation.getMarker().getCurNode(),o=t.getMainWorkspace().getCursor().getCurNode();return e?o?(e=e.getType(),o=o.getType(),e==t.ASTNode.types.FIELD?(t.navigation.warn_("Should not have been able to mark a field."),!1):e==t.ASTNode.types.BLOCK?(t.navigation.warn_("Should not have been able to mark a block."),!1):e==t.ASTNode.types.STACK?(t.navigation.warn_("Should not have been able to mark a stack."),!1):o==t.ASTNode.types.FIELD?(t.navigation.warn_("Cannot attach a field to anything else."),!1):o!=t.ASTNode.types.WORKSPACE||(t.navigation.warn_("Cannot attach a workspace to anything else."),!1)):(t.navigation.warn_("Cannot insert with no cursor node."),!1):(t.navigation.warn_("Cannot insert with no marked node."),!1)},t.navigation.moveBlockToWorkspace_=function(e,o){return!!e&&(e.isShadow()?(t.navigation.warn_("Cannot move a shadow block to the workspace."),!1):(e.getParent()&&e.unplug(!1),e.moveTo(o.getWsCoordinate()),!0))},t.navigation.modify_=function(){var e=t.navigation.getMarker().getCurNode(),o=t.getMainWorkspace().getCursor().getCurNode();if(!t.navigation.modifyWarn_())return!1;var i=e.getType(),n=o.getType(),s=o.getLocation(),r=e.getLocation();return e.isConnection()&&o.isConnection()?t.navigation.connect_(s,r):!e.isConnection()||n!=t.ASTNode.types.BLOCK&&n!=t.ASTNode.types.STACK?i==t.ASTNode.types.WORKSPACE?(o=o?o.getSourceBlock():null,t.navigation.moveBlockToWorkspace_(o,e)):(t.navigation.warn_("Unexpected state in Blockly.navigation.modify_."),!1):t.navigation.insertBlock(s,r)},t.navigation.disconnectChild_=function(e,o){var i=e.getSourceBlock(),n=o.getSourceBlock();i.getRootBlock()==n.getRootBlock()&&(-1<i.getDescendants(!1).indexOf(n)?t.navigation.getInferiorConnection_(o).disconnect():t.navigation.getInferiorConnection_(e).disconnect())},t.navigation.moveAndConnect_=function(e,o){if(!e||!o)return!1;var i=e.getSourceBlock();return o.canConnectWithReason(e)==t.Connection.CAN_CONNECT&&(t.navigation.disconnectChild_(e,o),o.isSuperior()||i.getRootBlock().positionNearConnection(e,o),o.connect(e),!0)},t.navigation.getInferiorConnection_=function(t){var e=t.getSourceBlock();return t.isSuperior()?e.previousConnection?e.previousConnection:e.outputConnection?e.outputConnection:null:t},t.navigation.getSuperiorConnection_=function(t){return t.isSuperior()?t:t.targetConnection?t.targetConnection:null},t.navigation.connect_=function(e,o){if(!e||!o)return!1;var i=t.navigation.getInferiorConnection_(e),n=t.navigation.getSuperiorConnection_(o),s=t.navigation.getSuperiorConnection_(e),r=t.navigation.getInferiorConnection_(o);if(i&&n&&t.navigation.moveAndConnect_(i,n)||s&&r&&t.navigation.moveAndConnect_(s,r)||t.navigation.moveAndConnect_(e,o))return!0;try{o.checkConnection(e)}catch(e){t.navigation.warn_("Connection failed with error: "+e)}return!1},t.navigation.insertBlock=function(e,o){switch(o.type){case t.PREVIOUS_STATEMENT:if(t.navigation.connect_(e.nextConnection,o))return!0;break;case t.NEXT_STATEMENT:if(t.navigation.connect_(e.previousConnection,o))return!0;break;case t.INPUT_VALUE:if(t.navigation.connect_(e.outputConnection,o))return!0;break;case t.OUTPUT_VALUE:for(var i=0;i<e.inputList.length;i++){var n=e.inputList[i].connection;if(n&&n.type===t.INPUT_VALUE&&t.navigation.connect_(n,o))return!0}if(e.outputConnection&&t.navigation.connect_(e.outputConnection,o))return!0}return t.navigation.warn_("This block can not be inserted at the marked location."),!1},t.navigation.disconnectBlocks_=function(){var e=t.getMainWorkspace(),o=e.getCursor().getCurNode();if(o.isConnection()){var i=o.getLocation();i.isConnected()?(o=i.isSuperior()?i:i.targetConnection,(i=i.isSuperior()?i.targetConnection:i).getSourceBlock().isShadow()?t.navigation.log_("Cannot disconnect a shadow block"):(o.disconnect(),i.bumpAwayFrom(o),o.getSourceBlock().getRootBlock().bringToFront(),o=t.ASTNode.createConnectionNode(o),e.getCursor().setCurNode(o))):t.navigation.log_("Cannot disconnect unconnected connection")}else t.navigation.log_("Cannot disconnect blocks when the cursor is not on a connection")},t.navigation.markAtCursor_=function(){t.navigation.getMarker().setCurNode(t.getMainWorkspace().getCursor().getCurNode())},t.navigation.removeMark_=function(){var e=t.navigation.getMarker();e.setCurNode(null),e.hide()},t.navigation.setState=function(e){t.navigation.currentState_=e},t.navigation.getTopNode=function(e){var o=e.previousConnection||e.outputConnection;return o?t.ASTNode.createConnectionNode(o):t.ASTNode.createBlockNode(e)},t.navigation.moveCursorOnBlockDelete=function(e){var o=t.getMainWorkspace();if(o&&(o=o.getCursor())){var i=o.getCurNode();(i=i?i.getSourceBlock():null)===e?i.getParent()?(e=i.previousConnection||i.outputConnection)&&o.setCurNode(t.ASTNode.createConnectionNode(e.targetConnection)):o.setCurNode(t.ASTNode.createWorkspaceNode(i.workspace,i.getRelativeToSurfaceXY())):i&&-1<e.getChildren(!1).indexOf(i)&&o.setCurNode(t.ASTNode.createWorkspaceNode(i.workspace,i.getRelativeToSurfaceXY()))}},t.navigation.moveCursorOnBlockMutation=function(e){var o=t.getMainWorkspace().getCursor();if(o){var i=o.getCurNode();(i=i?i.getSourceBlock():null)===e&&o.setCurNode(t.ASTNode.createBlockNode(i))}},t.navigation.enableKeyboardAccessibility=function(){t.getMainWorkspace().keyboardAccessibilityMode||(t.getMainWorkspace().keyboardAccessibilityMode=!0,t.navigation.focusWorkspace_())},t.navigation.disableKeyboardAccessibility=function(){if(t.getMainWorkspace().keyboardAccessibilityMode){var e=t.getMainWorkspace();t.getMainWorkspace().keyboardAccessibilityMode=!1,e.getCursor().hide(),t.navigation.getMarker().hide(),t.navigation.getFlyoutCursor_()&&t.navigation.getFlyoutCursor_().hide()}},t.navigation.log_=function(e){t.navigation.loggingCallback?t.navigation.loggingCallback("log",e):console.log(e)},t.navigation.warn_=function(e){t.navigation.loggingCallback?t.navigation.loggingCallback("warn",e):console.warn(e)},t.navigation.error_=function(e){t.navigation.loggingCallback?t.navigation.loggingCallback("error",e):console.error(e)},t.navigation.onKeyPress=function(e){return e=t.user.keyMap.serializeKeyEvent(e),!!(e=t.user.keyMap.getActionByKeyCode(e))&&t.navigation.onBlocklyAction(e)},t.navigation.onBlocklyAction=function(e){var o=t.getMainWorkspace().options.readOnly,i=!1;return t.getMainWorkspace().keyboardAccessibilityMode?o?-1<t.navigation.READONLY_ACTION_LIST.indexOf(e)&&(i=t.navigation.handleActions_(e)):i=t.navigation.handleActions_(e):e.name===t.navigation.actionNames.TOGGLE_KEYBOARD_NAV&&(t.navigation.enableKeyboardAccessibility(),i=!0),i},t.navigation.handleActions_=function(e){return e.name==t.navigation.actionNames.TOOLBOX||t.navigation.currentState_==t.navigation.STATE_TOOLBOX?t.navigation.toolboxOnAction_(e):e.name==t.navigation.actionNames.TOGGLE_KEYBOARD_NAV?(t.navigation.disableKeyboardAccessibility(),!0):t.navigation.currentState_==t.navigation.STATE_WS?t.navigation.workspaceOnAction_(e):t.navigation.currentState_==t.navigation.STATE_FLYOUT&&t.navigation.flyoutOnAction_(e)},t.navigation.flyoutOnAction_=function(e){var o=t.getMainWorkspace(),i=o.getToolbox();if((o=i?i.flyout_:o.getFlyout())&&o.onBlocklyAction(e))return!0;switch(e.name){case t.navigation.actionNames.OUT:return t.navigation.focusToolbox_(),!0;case t.navigation.actionNames.MARK:return t.navigation.insertFromFlyout(),!0;case t.navigation.actionNames.EXIT:return t.navigation.focusWorkspace_(),!0;default:return!1}},t.navigation.toolboxOnAction_=function(e){var o=t.getMainWorkspace(),i=o.getToolbox();return!((!i||!i.onBlocklyAction(e))&&(e.name===t.navigation.actionNames.TOOLBOX?(o.getToolbox()?t.navigation.focusToolbox_():t.navigation.focusFlyout_(),0):e.name===t.navigation.actionNames.IN?(t.navigation.focusFlyout_(),0):e.name!==t.navigation.actionNames.EXIT||(t.navigation.focusWorkspace_(),0)))},t.navigation.moveWSCursor_=function(e,o){var i=t.getMainWorkspace().getCursor(),n=t.getMainWorkspace().getCursor().getCurNode();return n.getType()===t.ASTNode.types.WORKSPACE&&(n=n.getWsCoordinate(),e=e*t.navigation.WS_MOVE_DISTANCE+n.x,o=o*t.navigation.WS_MOVE_DISTANCE+n.y,i.setCurNode(t.ASTNode.createWorkspaceNode(t.getMainWorkspace(),new t.utils.Coordinate(e,o))),!0)},t.navigation.workspaceOnAction_=function(e){if(t.getMainWorkspace().getCursor().onBlocklyAction(e))return!0;switch(e.name){case t.navigation.actionNames.INSERT:return t.navigation.modify_(),!0;case t.navigation.actionNames.MARK:return t.navigation.handleEnterForWS_(),!0;case t.navigation.actionNames.DISCONNECT:return t.navigation.disconnectBlocks_(),!0;case t.navigation.actionNames.MOVE_WS_CURSOR_UP:return t.navigation.moveWSCursor_(0,-1);case t.navigation.actionNames.MOVE_WS_CURSOR_DOWN:return t.navigation.moveWSCursor_(0,1);case t.navigation.actionNames.MOVE_WS_CURSOR_LEFT:return t.navigation.moveWSCursor_(-1,0);case t.navigation.actionNames.MOVE_WS_CURSOR_RIGHT:return t.navigation.moveWSCursor_(1,0);default:return!1}},t.navigation.handleEnterForWS_=function(){var e=t.getMainWorkspace().getCursor().getCurNode(),o=e.getType();o==t.ASTNode.types.FIELD?e.getLocation().showEditor():e.isConnection()||o==t.ASTNode.types.WORKSPACE?t.navigation.markAtCursor_():o==t.ASTNode.types.BLOCK?t.navigation.warn_("Cannot mark a block."):o==t.ASTNode.types.STACK&&t.navigation.warn_("Cannot mark a stack.")},t.navigation.ACTION_PREVIOUS=new t.Action(t.navigation.actionNames.PREVIOUS,"Go to the previous location."),t.navigation.ACTION_OUT=new t.Action(t.navigation.actionNames.OUT,"Go to the parent of the current location."),t.navigation.ACTION_NEXT=new t.Action(t.navigation.actionNames.NEXT,"Go to the next location."),t.navigation.ACTION_IN=new t.Action(t.navigation.actionNames.IN,"Go to the first child of the current location."),t.navigation.ACTION_INSERT=new t.Action(t.navigation.actionNames.INSERT,"Connect the current location to the marked location."),t.navigation.ACTION_MARK=new t.Action(t.navigation.actionNames.MARK,"Mark the current location."),t.navigation.ACTION_DISCONNECT=new t.Action(t.navigation.actionNames.DISCONNECT,"Disconnect the block at the current location from its parent."),t.navigation.ACTION_TOOLBOX=new t.Action(t.navigation.actionNames.TOOLBOX,"Open the toolbox."),t.navigation.ACTION_EXIT=new t.Action(t.navigation.actionNames.EXIT,"Close the current modal, such as a toolbox or field editor."),t.navigation.ACTION_TOGGLE_KEYBOARD_NAV=new t.Action(t.navigation.actionNames.TOGGLE_KEYBOARD_NAV,"Turns on and off keyboard navigation."),t.navigation.ACTION_MOVE_WS_CURSOR_LEFT=new t.Action(t.navigation.actionNames.MOVE_WS_CURSOR_LEFT,"Move the workspace cursor to the lefts."),t.navigation.ACTION_MOVE_WS_CURSOR_RIGHT=new t.Action(t.navigation.actionNames.MOVE_WS_CURSOR_RIGHT,"Move the workspace cursor to the right."),t.navigation.ACTION_MOVE_WS_CURSOR_UP=new t.Action(t.navigation.actionNames.MOVE_WS_CURSOR_UP,"Move the workspace cursor up."),t.navigation.ACTION_MOVE_WS_CURSOR_DOWN=new t.Action(t.navigation.actionNames.MOVE_WS_CURSOR_DOWN,"Move the workspace cursor down."),t.navigation.READONLY_ACTION_LIST=[t.navigation.ACTION_PREVIOUS,t.navigation.ACTION_OUT,t.navigation.ACTION_IN,t.navigation.ACTION_NEXT,t.navigation.ACTION_TOGGLE_KEYBOARD_NAV],t.Gesture=function(e,o){this.mouseDownXY_=null,this.currentDragDeltaXY_=new t.utils.Coordinate(0,0),this.startWorkspace_=this.targetBlock_=this.startBlock_=this.startField_=this.startBubble_=null,this.creatorWorkspace_=o,this.isDraggingBubble_=this.isDraggingBlock_=this.isDraggingWorkspace_=this.hasExceededDragRadius_=!1,this.mostRecentEvent_=e,this.flyout_=this.workspaceDragger_=this.blockDragger_=this.bubbleDragger_=this.onUpWrapper_=this.onMoveWrapper_=null,this.isEnding_=this.hasStarted_=this.calledUpdateIsDragging_=!1,this.healStack_=!t.DRAG_STACK},t.Gesture.prototype.dispose=function(){t.Touch.clearTouchIdentifier(),t.Tooltip.unblock(),this.creatorWorkspace_.clearGesture(),this.onMoveWrapper_&&t.unbindEvent_(this.onMoveWrapper_),this.onUpWrapper_&&t.unbindEvent_(this.onUpWrapper_),this.blockDragger_&&this.blockDragger_.dispose(),this.workspaceDragger_&&this.workspaceDragger_.dispose(),this.bubbleDragger_&&this.bubbleDragger_.dispose()},t.Gesture.prototype.updateFromEvent_=function(e){var o=new t.utils.Coordinate(e.clientX,e.clientY);this.updateDragDelta_(o)&&(this.updateIsDragging_(),t.longStop_()),this.mostRecentEvent_=e},t.Gesture.prototype.updateDragDelta_=function(e){return this.currentDragDeltaXY_=t.utils.Coordinate.difference(e,this.mouseDownXY_),!this.hasExceededDragRadius_&&(this.hasExceededDragRadius_=t.utils.Coordinate.magnitude(this.currentDragDeltaXY_)>(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;i<e.inputList.length;i++)for(var n=o[i],s=n.fieldRow,r=0;r<s.length;r++)if(s[r]===this){t=n;break}return t},t.Field.prototype.getFlipRtl=function(){return!1},t.Field.prototype.isTabNavigable=function(){return!1},t.Field.prototype.onBlocklyAction=function(t){return!1},t.Field.prototype.setCursorSvg=function(t){t?(this.fieldGroup_.appendChild(t),this.cursorSvg_=t):this.cursorSvg_=null},t.Field.prototype.setMarkerSvg=function(t){t?(this.fieldGroup_.appendChild(t),this.markerSvg_=t):this.markerSvg_=null},t.Field.prototype.updateMarkers_=function(){var e=this.sourceBlock_.workspace;e.keyboardAccessibilityMode&&this.cursorSvg_&&e.getCursor().draw(),e.keyboardAccessibilityMode&&this.markerSvg_&&e.getMarker(t.navigation.MARKER_NAME).draw()},t.FieldLabel=function(e,o,i){this.class_=null,null==e&&(e=""),t.FieldLabel.superClass_.constructor.call(this,e,null,i),i||(this.class_=o||null)},t.utils.object.inherits(t.FieldLabel,t.Field),t.FieldLabel.fromJson=function(e){var o=t.utils.replaceMessageReferences(e.text);return new t.FieldLabel(o,void 0,e)},t.FieldLabel.prototype.EDITABLE=!1,t.FieldLabel.prototype.configure_=function(e){t.FieldLabel.superClass_.configure_.call(this,e),this.class_=e.class},t.FieldLabel.prototype.initView=function(){this.createTextElement_(),this.class_&&t.utils.dom.addClass(this.textElement_,this.class_)},t.FieldLabel.prototype.doClassValidation_=function(t){return null==t?null:String(t)},t.FieldLabel.prototype.setClass=function(e){this.textElement_&&(this.class_&&t.utils.dom.removeClass(this.textElement_,this.class_),e&&t.utils.dom.addClass(this.textElement_,e)),this.class_=e},t.fieldRegistry.register("field_label",t.FieldLabel),t.Input=function(e,o,i,n){if(e!=t.DUMMY_INPUT&&!o)throw Error("Value inputs and statement inputs must have non-empty name.");this.type=e,this.name=o,this.sourceBlock_=i,this.connection=n,this.fieldRow=[]},t.Input.prototype.align=t.ALIGN_LEFT,t.Input.prototype.visible_=!0,t.Input.prototype.getSourceBlock=function(){return this.sourceBlock_},t.Input.prototype.appendField=function(t,e){return this.insertFieldAt(this.fieldRow.length,t,e),this},t.Input.prototype.insertFieldAt=function(e,o,i){if(0>e||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;t<this.fieldRow.length;t++)this.fieldRow[t].init()},t.Input.prototype.dispose=function(){for(var t,e=0;t=this.fieldRow[e];e++)t.dispose();this.connection&&this.connection.dispose(),this.sourceBlock_=null},t.Block=function(e,o,i){if(t.Generator&&void 0!==t.Generator.prototype[o])throw Error('Block prototypeName "'+o+'" conflicts with Blockly.Generator members.');if(this.id=i&&!e.getBlockById(i)?i:t.utils.genUid(),e.setBlockById(this.id,this),this.previousConnection=this.nextConnection=this.outputConnection=null,this.inputList=[],this.inputsInline=void 0,this.disabled=!1,this.tooltip="",this.contextMenu=!0,this.parentBlock_=null,this.childBlocks_=[],this.editable_=this.movable_=this.deletable_=!0,this.collapsed_=this.isShadow_=!1,this.comment=this.outputShape_=null,this.commentModel={text:null,pinned:!1,size:new t.utils.Size(160,80)},this.xy_=new t.utils.Coordinate(0,0),this.workspace=e,this.isInFlyout=e.isFlyout,this.isInMutator=e.isMutator,this.RTL=e.RTL,this.isInsertionMarker_=!1,this.hat=void 0,this.statementInputCount=0,o){if(this.type=o,!(i=t.Blocks[o])||"object"!=typeof i)throw TypeError("Unknown block type: "+o);t.utils.object.mixin(this,i)}if(e.addTopBlock(this),e.addTypedBlock(this),"function"==typeof this.init&&this.init(),this.inputsInlineDefault=this.inputsInline,t.Events.isEnabled()){(e=t.Events.getGroup())||t.Events.setGroup(!0);try{t.Events.fire(new t.Events.BlockCreate(this))}finally{e||t.Events.setGroup(!1)}}"function"==typeof this.onchange&&this.setOnChange(this.onchange)},t.Block.prototype.data=null,t.Block.prototype.disposed=!1,t.Block.prototype.hue_=null,t.Block.prototype.colour_="#000000",t.Block.prototype.styleName_=null,t.Block.prototype.dispose=function(e){if(this.workspace){this.onchangeWrapper_&&this.workspace.removeChangeListener(this.onchangeWrapper_),this.unplug(e),t.Events.isEnabled()&&t.Events.fire(new t.Events.BlockDelete(this)),t.Events.disable();try{this.workspace&&(this.workspace.removeTopBlock(this),this.workspace.removeTypedBlock(this),this.workspace.removeBlockById(this.id),this.workspace=null),t.selected==this&&(t.selected=null);for(var o=this.childBlocks_.length-1;0<=o;o--)this.childBlocks_[o].dispose(!1);o=0;for(var i;i=this.inputList[o];o++)i.dispose();this.inputList.length=0;var n,s=this.getConnections_(!0);for(o=0;n=s[o];o++)n.dispose()}finally{t.Events.enable(),this.disposed=!0}}},t.Block.prototype.initModel=function(){for(var t,e=0;t=this.inputList[e];e++)for(var o,i=0;o=t.fieldRow[i];i++)o.initModel&&o.initModel()},t.Block.prototype.unplug=function(t){this.outputConnection?this.unplugFromRow_(t):this.previousConnection&&this.unplugFromStack_(t)},t.Block.prototype.unplugFromRow_=function(t){var e=null;this.outputConnection.isConnected()&&(e=this.outputConnection.targetConnection,this.outputConnection.disconnect()),e&&t&&(t=this.getOnlyValueConnection_())&&t.isConnected()&&!t.targetBlock().isShadow()&&((t=t.targetConnection).disconnect(),t.checkType(e)?e.connect(t):t.onFailedConnect(e))},t.Block.prototype.getOnlyValueConnection_=function(){for(var e=null,o=0;o<this.inputList.length;o++){var i=this.inputList[o].connection;if(i&&i.type==t.INPUT_VALUE&&i.targetConnection){if(e)return null;e=i}}return e},t.Block.prototype.unplugFromStack_=function(t){var e=null;this.previousConnection.isConnected()&&(e=this.previousConnection.targetConnection,this.previousConnection.disconnect());var o=this.getNextBlock();t&&o&&!o.isShadow()&&((t=this.nextConnection.targetConnection).disconnect(),e&&e.checkType(t)&&e.connect(t))},t.Block.prototype.getConnections_=function(t){t=[],this.outputConnection&&t.push(this.outputConnection),this.previousConnection&&t.push(this.previousConnection),this.nextConnection&&t.push(this.nextConnection);for(var e,o=0;e=this.inputList[o];o++)e.connection&&t.push(e.connection);return t},t.Block.prototype.lastConnectionInStack=function(){for(var t=this.nextConnection;t;){var e=t.targetBlock();if(!e)return t;t=e.nextConnection}return null},t.Block.prototype.bumpNeighbours=function(){console.warn("Not expected to reach Block.bumpNeighbours function. BlockSvg.bumpNeighbours was expected to be called instead.")},t.Block.prototype.getParent=function(){return this.parentBlock_},t.Block.prototype.getInputWithBlock=function(t){for(var e,o=0;e=this.inputList[o];o++)if(e.connection&&e.connection.targetBlock()==t)return e;return null},t.Block.prototype.getSurroundParent=function(){var t=this;do{var e=t;if(!(t=t.getParent()))return null}while(t.getNextBlock()==e);return t},t.Block.prototype.getNextBlock=function(){return this.nextConnection&&this.nextConnection.targetBlock()},t.Block.prototype.getPreviousBlock=function(){return this.previousConnection&&this.previousConnection.targetBlock()},t.Block.prototype.getFirstStatementConnection=function(){for(var e,o=0;e=this.inputList[o];o++)if(e.connection&&e.connection.type==t.NEXT_STATEMENT)return e.connection;return null},t.Block.prototype.getRootBlock=function(){var t=this;do{var e=t;t=e.parentBlock_}while(t);return e},t.Block.prototype.getTopStackBlock=function(){var t=this;do{var e=t.getPreviousBlock()}while(e&&e.getNextBlock()==t&&(t=e));return t},t.Block.prototype.getChildren=function(t){if(!t)return this.childBlocks_;t=[];for(var e,o=0;e=this.inputList[o];o++)e.connection&&(e=e.connection.targetBlock())&&t.push(e);return(o=this.getNextBlock())&&t.push(o),t},t.Block.prototype.setParent=function(e){if(e!=this.parentBlock_){if(this.parentBlock_){if(t.utils.arrayRemove(this.parentBlock_.childBlocks_,this),this.previousConnection&&this.previousConnection.isConnected())throw Error("Still connected to previous block.");if(this.outputConnection&&this.outputConnection.isConnected())throw Error("Still connected to parent block.");this.parentBlock_=null}else this.workspace.removeTopBlock(this);(this.parentBlock_=e)?e.childBlocks_.push(this):this.workspace.addTopBlock(this)}},t.Block.prototype.getDescendants=function(t){for(var e,o=[this],i=this.getChildren(t),n=0;e=i[n];n++)o.push.apply(o,e.getDescendants(t));return o},t.Block.prototype.isDeletable=function(){return this.deletable_&&!this.isShadow_&&!(this.workspace&&this.workspace.options.readOnly)},t.Block.prototype.setDeletable=function(t){this.deletable_=t},t.Block.prototype.isMovable=function(){return this.movable_&&!this.isShadow_&&!(this.workspace&&this.workspace.options.readOnly)},t.Block.prototype.setMovable=function(t){this.movable_=t},t.Block.prototype.isDuplicatable=function(){return!this.workspace.hasBlockLimits()||this.workspace.isCapacityAvailable(t.utils.getBlockTypeCounts(this,!0))},t.Block.prototype.isShadow=function(){return this.isShadow_},t.Block.prototype.setShadow=function(t){this.isShadow_=t},t.Block.prototype.isInsertionMarker=function(){return this.isInsertionMarker_},t.Block.prototype.setInsertionMarker=function(t){this.isInsertionMarker_=t},t.Block.prototype.isEditable=function(){return this.editable_&&!(this.workspace&&this.workspace.options.readOnly)},t.Block.prototype.setEditable=function(t){this.editable_=t,t=0;for(var e;e=this.inputList[t];t++)for(var o,i=0;o=e.fieldRow[i];i++)o.updateEditable()},t.Block.prototype.isDisposed=function(){return this.disposed},t.Block.prototype.getMatchingConnection=function(t,e){var o=this.getConnections_(!0);if(t=t.getConnections_(!0),o.length!=t.length)throw Error("Connection lists did not match in length.");for(var i=0;i<t.length;i++)if(t[i]==e)return o[i];return null},t.Block.prototype.setHelpUrl=function(t){this.helpUrl=t},t.Block.prototype.setTooltip=function(t){this.tooltip=t},t.Block.prototype.getColour=function(){return this.colour_},t.Block.prototype.getStyleName=function(){return this.styleName_},t.Block.prototype.getHue=function(){return this.hue_},t.Block.prototype.setColour=function(e){e=t.utils.parseBlockColour(e),this.hue_=e.hue,this.colour_=e.hex},t.Block.prototype.setStyle=function(t){this.styleName_=t},t.Block.prototype.setOnChange=function(t){if(t&&"function"!=typeof t)throw Error("onchange must be a function.");this.onchangeWrapper_&&this.workspace.removeChangeListener(this.onchangeWrapper_),(this.onchange=t)&&(this.onchangeWrapper_=t.bind(this),this.workspace.addChangeListener(this.onchangeWrapper_))},t.Block.prototype.getField=function(t){for(var e,o=0;e=this.inputList[o];o++)for(var i,n=0;i=e.fieldRow[n];n++)if(i.name==t)return i;return null},t.Block.prototype.getVars=function(){for(var t,e=[],o=0;t=this.inputList[o];o++)for(var i,n=0;i=t.fieldRow[n];n++)i.referencesVariables()&&e.push(i.getValue());return e},t.Block.prototype.getVarModels=function(){for(var t,e=[],o=0;t=this.inputList[o];o++)for(var i,n=0;i=t.fieldRow[n];n++)i.referencesVariables()&&(i=this.workspace.getVariableById(i.getValue()))&&e.push(i);return e},t.Block.prototype.updateVarName=function(t){for(var e,o=0;e=this.inputList[o];o++)for(var i,n=0;i=e.fieldRow[n];n++)i.referencesVariables()&&t.getId()==i.getValue()&&i.refreshVariableName()},t.Block.prototype.renameVarById=function(t,e){for(var o,i=0;o=this.inputList[i];i++)for(var n,s=0;n=o.fieldRow[s];s++)n.referencesVariables()&&t==n.getValue()&&n.setValue(e)},t.Block.prototype.getFieldValue=function(t){return(t=this.getField(t))?t.getValue():null},t.Block.prototype.setFieldValue=function(t,e){var o=this.getField(e);if(!o)throw Error('Field "'+e+'" not found.');o.setValue(t)},t.Block.prototype.setPreviousStatement=function(e,o){if(e){if(void 0===o&&(o=null),!this.previousConnection){if(this.outputConnection)throw Error("Remove output connection prior to adding previous connection.");this.previousConnection=this.makeConnection_(t.PREVIOUS_STATEMENT)}this.previousConnection.setCheck(o)}else if(this.previousConnection){if(this.previousConnection.isConnected())throw Error("Must disconnect previous statement before removing connection.");this.previousConnection.dispose(),this.previousConnection=null}},t.Block.prototype.setNextStatement=function(e,o){if(e)void 0===o&&(o=null),this.nextConnection||(this.nextConnection=this.makeConnection_(t.NEXT_STATEMENT)),this.nextConnection.setCheck(o);else if(this.nextConnection){if(this.nextConnection.isConnected())throw Error("Must disconnect next statement before removing connection.");this.nextConnection.dispose(),this.nextConnection=null}},t.Block.prototype.setOutput=function(e,o){if(e){if(void 0===o&&(o=null),!this.outputConnection){if(this.previousConnection)throw Error("Remove previous connection prior to adding output connection.");this.outputConnection=this.makeConnection_(t.OUTPUT_VALUE)}this.outputConnection.setCheck(o)}else if(this.outputConnection){if(this.outputConnection.isConnected())throw Error("Must disconnect output value before removing connection.");this.outputConnection.dispose(),this.outputConnection=null}},t.Block.prototype.setInputsInline=function(e){this.inputsInline!=e&&(t.Events.fire(new t.Events.BlockChange(this,"inline",null,this.inputsInline,e)),this.inputsInline=e)},t.Block.prototype.getInputsInline=function(){if(null!=this.inputsInline)return this.inputsInline;for(var e=1;e<this.inputList.length;e++)if(this.inputList[e-1].type==t.DUMMY_INPUT&&this.inputList[e].type==t.DUMMY_INPUT)return!1;for(e=1;e<this.inputList.length;e++)if(this.inputList[e-1].type==t.INPUT_VALUE&&this.inputList[e].type==t.DUMMY_INPUT)return!0;return!1},t.Block.prototype.setOutputShape=function(t){this.outputShape_=t},t.Block.prototype.getOutputShape=function(){return this.outputShape_},t.Block.prototype.setDisabled=function(t){console.warn("Deprecated call to Blockly.Block.prototype.setDisabled, use Blockly.Block.prototype.setEnabled instead."),this.setEnabled(!t)},t.Block.prototype.isEnabled=function(){return!this.disabled},t.Block.prototype.setEnabled=function(e){this.isEnabled()!=e&&(t.Events.fire(new t.Events.BlockChange(this,"disabled",null,this.disabled,!e)),this.disabled=!e)},t.Block.prototype.getInheritedDisabled=function(){for(var t=this.getSurroundParent();t;){if(t.disabled)return!0;t=t.getSurroundParent()}return!1},t.Block.prototype.isCollapsed=function(){return this.collapsed_},t.Block.prototype.setCollapsed=function(e){this.collapsed_!=e&&(t.Events.fire(new t.Events.BlockChange(this,"collapsed",null,this.collapsed_,e)),this.collapsed_=e)},t.Block.prototype.toString=function(t,e){var o=[],i=e||"?";if(this.collapsed_)o.push(this.getInput("_TEMP_COLLAPSED_INPUT").fieldRow[0].getText());else for(var n,s=0;n=this.inputList[s];s++){for(var r,a=0;r=n.fieldRow[a];a++)o.push(r.getText());n.connection&&((n=n.connection.targetBlock())?o.push(n.toString(void 0,e)):o.push(i))}return o=o.join(" ").trim()||"???",t&&o.length>t&&(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<e.length;++o)t.Extensions.apply(e[o],this,!1)},t.Block.prototype.jsonInitColour_=function(t,e){if("colour"in t)if(void 0===t.colour)console.warn(e+"Undefined colour value.");else{t=t.colour;try{this.setColour(t)}catch(o){console.warn(e+"Illegal colour value: ",t)}}},t.Block.prototype.jsonInitStyle_=function(t,e){t=t.style;try{this.setStyle(t)}catch(o){console.warn(e+"Style does not exist: ",t)}},t.Block.prototype.mixin=function(e,o){if(void 0!==o&&"boolean"!=typeof o)throw Error("opt_disableCheck must be a boolean if provided");if(!o){for(var i in o=[],e)void 0!==this[i]&&o.push(i);if(o.length)throw Error("Mixin will overwrite block members: "+JSON.stringify(o))}t.utils.object.mixin(this,e)},t.Block.prototype.interpolate_=function(e,o,i,n){var s=t.utils.tokenizeInterpolation(e),r=[],a=0;e=[];for(var l=0;l<s.length;l++){var c=s[l];if("number"==typeof c){if(0>=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<e.length;l++)if("string"==typeof(r=e[l]))o.push([r,void 0]);else{s=a=null;do{if(c=!1,"string"==typeof r)a=new t.FieldLabel(r);else switch(r.type){case"input_value":s=this.appendValueInput(r.name);break;case"input_statement":s=this.appendStatementInput(r.name);break;case"input_dummy":s=this.appendDummyInput(r.name);break;default:!(a=t.fieldRegistry.fromJson(r))&&r.alt&&(r=r.alt,c=!0)}}while(c);if(a)o.push([a,r.name]);else if(s){for(r.check&&s.setCheck(r.check),r.align&&(void 0===(a=i[r.align.toUpperCase()])?console.warn(n+"Illegal align value: ",r.align):s.setAlign(a)),r=0;r<o.length;r++)s.appendField(o[r][0],o[r][1]);o.length=0}}},t.Block.prototype.appendInput_=function(e,o){var i=null;return e!=t.INPUT_VALUE&&e!=t.NEXT_STATEMENT||(i=this.makeConnection_(e)),e==t.NEXT_STATEMENT&&this.statementInputCount++,e=new t.Input(e,o,this,i),this.inputList.push(e),e},t.Block.prototype.moveInputBefore=function(t,e){if(t!=e){for(var o,i=-1,n=e?-1:this.inputList.length,s=0;o=this.inputList[s];s++)if(o.name==t){if(i=s,-1!=n)break}else if(e&&o.name==e&&(n=s,-1!=i))break;if(-1==i)throw Error('Named input "'+t+'" not found.');if(-1==n)throw Error('Reference input "'+e+'" not found.');this.moveNumberedInputBefore(i,n)}},t.Block.prototype.moveNumberedInputBefore=function(t,e){if(t==e)throw Error("Can't move input to itself.");if(t>=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<e&&e--,this.inputList.splice(e,0,o)},t.Block.prototype.removeInput=function(e,o){for(var i,n=0;i=this.inputList[n];n++)if(i.name==e)return i.type==t.NEXT_STATEMENT&&this.statementInputCount--,i.dispose(),void this.inputList.splice(n,1);if(!o)throw Error("Input not found: "+e)},t.Block.prototype.getInput=function(t){for(var e,o=0;e=this.inputList[o];o++)if(e.name==t)return e;return null},t.Block.prototype.getInputTargetBlock=function(t){return(t=this.getInput(t))&&t.connection&&t.connection.targetBlock()},t.Block.prototype.getCommentText=function(){return this.commentModel.text},t.Block.prototype.setCommentText=function(e){this.commentModel.text!=e&&(t.Events.fire(new t.Events.BlockChange(this,"comment",null,this.commentModel.text,e)),this.comment=this.commentModel.text=e)},t.Block.prototype.setWarningText=function(t,e){},t.Block.prototype.setMutator=function(t){},t.Block.prototype.getRelativeToSurfaceXY=function(){return this.xy_},t.Block.prototype.moveBy=function(e,o){if(this.parentBlock_)throw Error("Block has parent.");var i=new t.Events.BlockMove(this);this.xy_.translate(e,o),i.recordNew(),t.Events.fire(i)},t.Block.prototype.makeConnection_=function(e){return new t.Connection(this,e)},t.Block.prototype.allInputsFilled=function(t){if(void 0===t&&(t=!0),!t&&this.isShadow())return!1;for(var e,o=0;e=this.inputList[o];o++)if(e.connection&&(!(e=e.connection.targetBlock())||!e.allInputsFilled(t)))return!1;return!(o=this.getNextBlock())||o.allInputsFilled(t)},t.Block.prototype.toDevString=function(){var t=this.type?'"'+this.type+'" block':"Block";return this.id&&(t+=' (id="'+this.id+'")'),t},t.blockRendering={},t.blockRendering.IPathObject=function(t,e){},t.utils.aria={},t.utils.aria.ARIA_PREFIX_="aria-",t.utils.aria.ROLE_ATTRIBUTE_="role",t.utils.aria.Role={GRID:"grid",GRIDCELL:"gridcell",GROUP:"group",LISTBOX:"listbox",MENU:"menu",MENUITEM:"menuitem",MENUITEMCHECKBOX:"menuitemcheckbox",OPTION:"option",PRESENTATION:"presentation",ROW:"row",TREE:"tree",TREEITEM:"treeitem"},t.utils.aria.State={ACTIVEDESCENDANT:"activedescendant",COLCOUNT:"colcount",EXPANDED:"expanded",INVALID:"invalid",LABEL:"label",LABELLEDBY:"labelledby",LEVEL:"level",ORIENTATION:"orientation",POSINSET:"posinset",ROWCOUNT:"rowcount",SELECTED:"selected",SETSIZE:"setsize",VALUEMAX:"valuemax",VALUEMIN:"valuemin"},t.utils.aria.setRole=function(e,o){e.setAttribute(t.utils.aria.ROLE_ATTRIBUTE_,o)},t.utils.aria.setState=function(e,o,i){Array.isArray(i)&&(i=i.join(" ")),e.setAttribute(t.utils.aria.ARIA_PREFIX_+o,i)},t.Menu=function(){t.Component.call(this),this.openingCoords=null,this.highlightedIndex_=-1,this.onKeyDownWrapper_=this.mouseLeaveHandler_=this.mouseEnterHandler_=this.clickHandler_=this.mouseOverHandler_=null},t.utils.object.inherits(t.Menu,t.Component),t.Menu.prototype.createDom=function(){var e=document.createElement("div");e.id=this.getId(),this.setElementInternal(e),e.className="goog-menu goog-menu-vertical blocklyNonSelectable",e.tabIndex=0,t.utils.aria.setRole(e,this.roleName_||t.utils.aria.Role.MENU)},t.Menu.prototype.focus=function(){var e=this.getElement();e&&(e.focus({preventScroll:!0}),t.utils.dom.addClass(e,"focused"))},t.Menu.prototype.blur=function(){var e=this.getElement();e&&(e.blur(),t.utils.dom.removeClass(e,"focused"))},t.Menu.prototype.setRole=function(t){this.roleName_=t},t.Menu.prototype.enterDocument=function(){t.Menu.superClass_.enterDocument.call(this),this.forEachChild((function(t){t.isInDocument()&&this.registerChildId_(t)}),this),this.attachEvents_()},t.Menu.prototype.exitDocument=function(){this.setHighlightedIndex(-1),t.Menu.superClass_.exitDocument.call(this)},t.Menu.prototype.disposeInternal=function(){t.Menu.superClass_.disposeInternal.call(this),this.detachEvents_()},t.Menu.prototype.attachEvents_=function(){var e=this.getElement();this.mouseOverHandler_=t.bindEventWithChecks_(e,"mouseover",this,this.handleMouseOver_,!0),this.clickHandler_=t.bindEventWithChecks_(e,"click",this,this.handleClick_,!0),this.mouseEnterHandler_=t.bindEventWithChecks_(e,"mouseenter",this,this.handleMouseEnter_,!0),this.mouseLeaveHandler_=t.bindEventWithChecks_(e,"mouseleave",this,this.handleMouseLeave_,!0),this.onKeyDownWrapper_=t.bindEventWithChecks_(e,"keydown",this,this.handleKeyEvent)},t.Menu.prototype.detachEvents_=function(){this.mouseOverHandler_&&(t.unbindEvent_(this.mouseOverHandler_),this.mouseOverHandler_=null),this.clickHandler_&&(t.unbindEvent_(this.clickHandler_),this.clickHandler_=null),this.mouseEnterHandler_&&(t.unbindEvent_(this.mouseEnterHandler_),this.mouseEnterHandler_=null),this.mouseLeaveHandler_&&(t.unbindEvent_(this.mouseLeaveHandler_),this.mouseLeaveHandler_=null),this.onKeyDownWrapper_&&(t.unbindEvent_(this.onKeyDownWrapper_),this.onKeyDownWrapper_=null)},t.Menu.prototype.childElementIdMap_=null,t.Menu.prototype.registerChildId_=function(t){var e=t.getElement();e=e.id||(e.id=t.getId()),this.childElementIdMap_||(this.childElementIdMap_={}),this.childElementIdMap_[e]=t},t.Menu.prototype.getMenuItem=function(t){if(this.childElementIdMap_)for(var e=this.getElement();t&&t!==e;){var o=t.id;if(o in this.childElementIdMap_)return this.childElementIdMap_[o];t=t.parentNode}return null},t.Menu.prototype.unhighlightCurrent=function(){var t=this.getHighlighted();t&&t.setHighlighted(!1)},t.Menu.prototype.clearHighlighted=function(){this.unhighlightCurrent(),this.setHighlightedIndex(-1)},t.Menu.prototype.getHighlighted=function(){return this.getChildAt(this.highlightedIndex_)},t.Menu.prototype.setHighlightedIndex=function(e){var o=this.getChildAt(e);o?(o.setHighlighted(!0),this.highlightedIndex_=e):-1<this.highlightedIndex_&&(this.getHighlighted().setHighlighted(!1),this.highlightedIndex_=-1),o&&t.utils.style.scrollIntoContainerView(o.getElement(),this.getElement())},t.Menu.prototype.setHighlighted=function(t){this.setHighlightedIndex(this.indexOfChild(t))},t.Menu.prototype.highlightNext=function(){this.unhighlightCurrent(),this.highlightHelper((function(t,e){return(t+1)%e}),this.highlightedIndex_)},t.Menu.prototype.highlightPrevious=function(){this.unhighlightCurrent(),this.highlightHelper((function(t,e){return 0>--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;e<t.length;e++){for(var o=t[e],i=o.getConnections_(!0),n=0;n<i.length;n++)i[n].setTracking(!1);for(o=o.getIcons(),n=0;n<o.length;n++)o[n].setVisible(!1)}},t.RenderedConnection.prototype.startTrackingAll=function(){this.setTracking(!0);var e=[];if(this.type!=t.INPUT_VALUE&&this.type!=t.NEXT_STATEMENT)return e;var o=this.targetBlock();if(o){if(o.isCollapsed()){var i=[];o.outputConnection&&i.push(o.outputConnection),o.nextConnection&&i.push(o.nextConnection),o.previousConnection&&i.push(o.previousConnection)}else i=o.getConnections_(!0);for(var n=0;n<i.length;n++)e.push.apply(e,i[n].startTrackingAll());e.length||(e[0]=o)}return e},t.RenderedConnection.prototype.isConnectionAllowed=function(e,o){return!(this.distanceFrom(e)>o)&&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<e.length;o++)e[o].createIcon();this.applyColour(),this.pathObject.updateMovable(this.isMovable()),o=this.getSvgRoot(),this.workspace.options.readOnly||this.eventsInit_||!o||t.bindEventWithChecks_(o,"mousedown",this,this.onMouseDown_),this.eventsInit_=!0,o.parentNode||this.workspace.getCanvas().appendChild(o)},t.BlockSvg.prototype.getColourSecondary=function(){return this.style.colourSecondary},t.BlockSvg.prototype.getColourTertiary=function(){return this.style.colourTertiary},t.BlockSvg.prototype.getColourShadow=function(){return this.getColourSecondary()},t.BlockSvg.prototype.getColourBorder=function(){return{colourBorder:this.getColourTertiary(),colourLight:null,colourDark:null}},t.BlockSvg.prototype.select=function(){if(this.isShadow()&&this.getParent())this.getParent().select();else if(t.selected!=this){var e=null;if(t.selected){e=t.selected.id,t.Events.disable();try{t.selected.unselect()}finally{t.Events.enable()}}(e=new t.Events.Ui(null,"selected",e,this.id)).workspaceId=this.workspace.id,t.Events.fire(e),t.selected=this,this.addSelect()}},t.BlockSvg.prototype.unselect=function(){if(t.selected==this){var e=new t.Events.Ui(null,"selected",this.id,null);e.workspaceId=this.workspace.id,t.Events.fire(e),t.selected=null,this.removeSelect()}},t.BlockSvg.prototype.mutator=null,t.BlockSvg.prototype.comment=null,t.BlockSvg.prototype.commentIcon_=null,t.BlockSvg.prototype.warning=null,t.BlockSvg.prototype.getIcons=function(){var t=[];return this.mutator&&t.push(this.mutator),this.commentIcon_&&t.push(this.commentIcon_),this.warning&&t.push(this.warning),t},t.BlockSvg.prototype.setParent=function(e){var o=this.parentBlock_;if(e!=o){t.utils.dom.startTextWidthCache(),t.BlockSvg.superClass_.setParent.call(this,e),t.utils.dom.stopTextWidthCache();var i=this.getSvgRoot();if(!this.workspace.isClearing&&i){var n=this.getRelativeToSurfaceXY();e?(e.getSvgRoot().appendChild(i),e=this.getRelativeToSurfaceXY(),this.moveConnections(e.x-n.x,e.y-n.y)):o&&(this.workspace.getCanvas().appendChild(i),this.translate(n.x,n.y)),this.applyColour()}}},t.BlockSvg.prototype.getRelativeToSurfaceXY=function(){var e=0,o=0,i=this.useDragSurface_?this.workspace.getBlockDragSurface().getGroup():null,n=this.getSvgRoot();if(n)do{var s=t.utils.getRelativeXY(n);e+=s.x,o+=s.y,this.useDragSurface_&&this.workspace.getBlockDragSurface().getCurrentBlock()==n&&(e+=(s=this.workspace.getBlockDragSurface().getSurfaceTranslation()).x,o+=s.y),n=n.parentNode}while(n&&n!=this.workspace.getCanvas()&&n!=i);return new t.utils.Coordinate(e,o)},t.BlockSvg.prototype.moveBy=function(e,o){if(this.parentBlock_)throw Error("Block has parent.");var i=t.Events.isEnabled();if(i)var n=new t.Events.BlockMove(this);var s=this.getRelativeToSurfaceXY();this.translate(s.x+e,s.y+o),this.moveConnections(e,o),i&&(n.recordNew(),t.Events.fire(n)),this.workspace.resizeContents()},t.BlockSvg.prototype.translate=function(t,e){this.getSvgRoot().setAttribute("transform","translate("+t+","+e+")")},t.BlockSvg.prototype.moveToDragSurface=function(){if(this.useDragSurface_){var t=this.getRelativeToSurfaceXY();this.clearTransformAttributes_(),this.workspace.getBlockDragSurface().translateSurface(t.x,t.y),(t=this.getSvgRoot())&&this.workspace.getBlockDragSurface().setBlocksAndShow(t)}},t.BlockSvg.prototype.moveTo=function(t){var e=this.getRelativeToSurfaceXY();this.moveBy(t.x-e.x,t.y-e.y)},t.BlockSvg.prototype.moveOffDragSurface=function(t){this.useDragSurface_&&(this.translate(t.x,t.y),this.workspace.getBlockDragSurface().clearAndHide(this.workspace.getCanvas()))},t.BlockSvg.prototype.moveDuringDrag=function(t){this.useDragSurface_?this.workspace.getBlockDragSurface().translateSurface(t.x,t.y):(this.svgGroup_.translate_="translate("+t.x+","+t.y+")",this.svgGroup_.setAttribute("transform",this.svgGroup_.translate_+this.svgGroup_.skew_))},t.BlockSvg.prototype.clearTransformAttributes_=function(){this.getSvgRoot().removeAttribute("transform")},t.BlockSvg.prototype.snapToGrid=function(){if(this.workspace&&!this.workspace.isDragging()&&!this.getParent()&&!this.isInFlyout){var t=this.workspace.getGrid();if(t&&t.shouldSnap()){var e=t.getSpacing(),o=e/2,i=this.getRelativeToSurfaceXY();t=Math.round((i.x-o)/e)*e+o-i.x,e=Math.round((i.y-o)/e)*e+o-i.y,t=Math.round(t),e=Math.round(e),0==t&&0==e||this.moveBy(t,e)}}},t.BlockSvg.prototype.getBoundingRectangle=function(){var e=this.getRelativeToSurfaceXY(),o=this.getHeightWidth();if(this.RTL)var i=e.x-o.width,n=e.x;else i=e.x,n=e.x+o.width;return new t.utils.Rect(e.y,e.y+o.height,i,n)},t.BlockSvg.prototype.markDirty=function(){this.pathObject.constants=this.workspace.getRenderer().getConstants();for(var t,e=0;t=this.inputList[e];e++)t.markDirty()},t.BlockSvg.prototype.setCollapsed=function(e){if(this.collapsed_!=e){for(var o,i=[],n=0;o=this.inputList[n];n++)i.push.apply(i,o.setVisible(!e));if(e){for(o=this.getIcons(),n=0;n<o.length;n++)o[n].setVisible(!1);n=this.toString(t.COLLAPSE_CHARS),this.appendDummyInput("_TEMP_COLLAPSED_INPUT").appendField(n).init(),o=this.getDescendants(!0),(n=this.getNextBlock())&&(n=o.indexOf(n),o.splice(n,o.length-n)),n=1;for(var s;s=o[n];n++)if(s.warning){this.setWarningText(t.Msg.COLLAPSED_WARNINGS_WARNING,t.BlockSvg.COLLAPSED_WARNING_ID);break}}else this.removeInput("_TEMP_COLLAPSED_INPUT"),this.warning&&(this.warning.setText("",t.BlockSvg.COLLAPSED_WARNING_ID),Object.keys(this.warning.text_).length||this.setWarningText(null));if(t.BlockSvg.superClass_.setCollapsed.call(this,e),i.length||(i[0]=this),this.rendered)for(n=0;s=i[n];n++)s.render()}},t.BlockSvg.prototype.tab=function(e,o){var i=new t.TabNavigateCursor;i.setCurNode(t.ASTNode.createFieldNode(e)),e=i.getCurNode(),i.onBlocklyAction(o?t.navigation.ACTION_NEXT:t.navigation.ACTION_PREVIOUS),(o=i.getCurNode())&&o!==e&&(o.getLocation().showEditor(),this.workspace.keyboardAccessibilityMode&&this.workspace.getCursor().setCurNode(o))},t.BlockSvg.prototype.onMouseDown_=function(t){var e=this.workspace&&this.workspace.getGesture(t);e&&e.handleBlockStart(t,this)},t.BlockSvg.prototype.showHelp=function(){var t="function"==typeof this.helpUrl?this.helpUrl():this.helpUrl;t&&window.open(t)},t.BlockSvg.prototype.generateContextMenu=function(){if(this.workspace.options.readOnly||!this.contextMenu)return null;var e=this,o=[];if(!this.isInFlyout){if(this.isDeletable()&&this.isMovable()&&o.push(t.ContextMenu.blockDuplicateOption(e)),this.workspace.options.comments&&!this.collapsed_&&this.isEditable()&&o.push(t.ContextMenu.blockCommentOption(e)),this.isMovable())if(this.collapsed_)this.workspace.options.collapse&&((i={enabled:!0}).text=t.Msg.EXPAND_BLOCK,i.callback=function(){e.setCollapsed(!1)},o.push(i));else{for(var i=1;i<this.inputList.length;i++)if(this.inputList[i-1].type!=t.NEXT_STATEMENT&&this.inputList[i].type!=t.NEXT_STATEMENT){i={enabled:!0};var n=this.getInputsInline();i.text=n?t.Msg.EXTERNAL_INPUTS:t.Msg.INLINE_INPUTS,i.callback=function(){e.setInputsInline(!n)},o.push(i);break}this.workspace.options.collapse&&((i={enabled:!0}).text=t.Msg.COLLAPSE_BLOCK,i.callback=function(){e.setCollapsed(!0)},o.push(i))}this.workspace.options.disable&&this.isEditable()&&(i={text:this.isEnabled()?t.Msg.DISABLE_BLOCK:t.Msg.ENABLE_BLOCK,enabled:!this.getInheritedDisabled(),callback:function(){var o=t.Events.getGroup();o||t.Events.setGroup(!0),e.setEnabled(!e.isEnabled()),o||t.Events.setGroup(!1)}},o.push(i)),this.isDeletable()&&o.push(t.ContextMenu.blockDeleteOption(e))}return o.push(t.ContextMenu.blockHelpOption(e)),this.customContextMenu&&this.customContextMenu(o),o},t.BlockSvg.prototype.showContextMenu=function(e){var o=this.generateContextMenu();o&&o.length&&(t.ContextMenu.show(e,o,this.RTL),t.ContextMenu.currentBlock=this)},t.BlockSvg.prototype.moveConnections=function(t,e){if(this.rendered){for(var o=this.getConnections_(!1),i=0;i<o.length;i++)o[i].moveBy(t,e);for(o=this.getIcons(),i=0;i<o.length;i++)o[i].computeIconLocation();for(i=0;i<this.childBlocks_.length;i++)this.childBlocks_[i].moveConnections(t,e)}},t.BlockSvg.prototype.setDragging=function(e){if(e){var o=this.getSvgRoot();o.translate_="",o.skew_="",t.draggingConnections=t.draggingConnections.concat(this.getConnections_(!0)),t.utils.dom.addClass(this.svgGroup_,"blocklyDragging")}else t.draggingConnections=[],t.utils.dom.removeClass(this.svgGroup_,"blocklyDragging");for(o=0;o<this.childBlocks_.length;o++)this.childBlocks_[o].setDragging(e)},t.BlockSvg.prototype.setMovable=function(e){t.BlockSvg.superClass_.setMovable.call(this,e),this.pathObject.updateMovable(e)},t.BlockSvg.prototype.setEditable=function(e){t.BlockSvg.superClass_.setEditable.call(this,e),e=this.getIcons();for(var o=0;o<e.length;o++)e[o].updateEditable()},t.BlockSvg.prototype.setShadow=function(e){t.BlockSvg.superClass_.setShadow.call(this,e),this.applyColour()},t.BlockSvg.prototype.setInsertionMarker=function(t){this.isInsertionMarker_!=t&&(this.isInsertionMarker_=t)&&(this.setColour(this.workspace.getRenderer().getConstants().INSERTION_MARKER_COLOUR),this.pathObject.updateInsertionMarker(!0))},t.BlockSvg.prototype.getSvgRoot=function(){return this.svgGroup_},t.BlockSvg.prototype.dispose=function(e,o){if(this.workspace){t.Tooltip.dispose(),t.Tooltip.unbindMouseEvents(this.pathObject.svgPath),t.utils.dom.startTextWidthCache();var i=this.workspace;if(t.selected==this&&(this.unselect(),this.workspace.cancelCurrentGesture()),t.ContextMenu.currentBlock==this&&t.ContextMenu.hide(),this.workspace.keyboardAccessibilityMode&&t.navigation.moveCursorOnBlockDelete(this),o&&this.rendered&&(this.unplug(e),t.blockAnimations.disposeUiEffect(this)),this.rendered=!1,this.warningTextDb_){for(var n in this.warningTextDb_)clearTimeout(this.warningTextDb_[n]);this.warningTextDb_=null}for(o=this.getIcons(),n=0;n<o.length;n++)o[n].dispose();t.BlockSvg.superClass_.dispose.call(this,!!e),t.utils.dom.removeNode(this.svgGroup_),i.resizeContents(),this.svgGroup_=null,t.utils.dom.stopTextWidthCache()}},t.BlockSvg.prototype.applyColour=function(){this.pathObject.applyColour(this);for(var t=this.getIcons(),e=0;e<t.length;e++)t[e].applyColour();for(t=0;e=this.inputList[t];t++)for(var o,i=0;o=e.fieldRow[i];i++)o.applyColour()},t.BlockSvg.prototype.updateDisabled=function(){var t=this.getChildren(!1);this.applyColour();for(var e,o=0;e=t[o];o++)e.updateDisabled()},t.BlockSvg.prototype.getCommentIcon=function(){return this.commentIcon_},t.BlockSvg.prototype.setCommentText=function(e){if(!t.Comment)throw Error("Missing require for Blockly.Comment");this.commentModel.text!=e&&(t.BlockSvg.superClass_.setCommentText.call(this,e),e=null!=e,!!this.commentIcon_==e?this.commentIcon_.updateText():(e?this.comment=this.commentIcon_=new t.Comment(this):(this.commentIcon_.dispose(),this.comment=this.commentIcon_=null),this.rendered&&(this.render(),this.bumpNeighbours())))},t.BlockSvg.prototype.setWarningText=function(e,o){if(!t.Warning)throw Error("Missing require for Blockly.Warning");this.warningTextDb_||(this.warningTextDb_=Object.create(null));var i=o||"";if(i)this.warningTextDb_[i]&&(clearTimeout(this.warningTextDb_[i]),delete this.warningTextDb_[i]);else for(var n in this.warningTextDb_)clearTimeout(this.warningTextDb_[n]),delete this.warningTextDb_[n];if(this.workspace.isDragging()){var s=this;this.warningTextDb_[i]=setTimeout((function(){s.workspace&&(delete s.warningTextDb_[i],s.setWarningText(e,i))}),100)}else{for(this.isInFlyout&&(e=null),o=this.getSurroundParent(),n=null;o;)o.isCollapsed()&&(n=o),o=o.getSurroundParent();n&&n.setWarningText(t.Msg.COLLAPSED_WARNINGS_WARNING,t.BlockSvg.COLLAPSED_WARNING_ID),o=!1,"string"==typeof e?(this.warning||(this.warning=new t.Warning(this),o=!0),this.warning.setText(e,i)):this.warning&&!i?(this.warning.dispose(),o=!0):this.warning&&(o=this.warning.getText(),this.warning.setText("",i),(n=this.warning.getText())||this.warning.dispose(),o=o!=n),o&&this.rendered&&(this.render(),this.bumpNeighbours())}},t.BlockSvg.prototype.setMutator=function(t){this.mutator&&this.mutator!==t&&this.mutator.dispose(),t&&(t.setBlock(this),this.mutator=t,t.createIcon()),this.rendered&&(this.render(),this.bumpNeighbours())},t.BlockSvg.prototype.setDisabled=function(t){console.warn("Deprecated call to Blockly.BlockSvg.prototype.setDisabled, use Blockly.BlockSvg.prototype.setEnabled instead."),this.setEnabled(!t)},t.BlockSvg.prototype.setEnabled=function(e){this.isEnabled()!=e&&(t.BlockSvg.superClass_.setEnabled.call(this,e),this.rendered&&!this.getInheritedDisabled()&&this.updateDisabled())},t.BlockSvg.prototype.setHighlighted=function(t){this.rendered&&this.pathObject.updateHighlighted(t)},t.BlockSvg.prototype.addSelect=function(){this.pathObject.updateSelected(!0)},t.BlockSvg.prototype.removeSelect=function(){this.pathObject.updateSelected(!1)},t.BlockSvg.prototype.setDeleteStyle=function(t){this.pathObject.updateDraggingDelete(t)},t.BlockSvg.prototype.getColour=function(){return this.style.colourPrimary},t.BlockSvg.prototype.setColour=function(e){t.BlockSvg.superClass_.setColour.call(this,e),e=this.workspace.getRenderer().getConstants().getBlockStyleForColour(this.colour_),this.pathObject.setStyle(e.style),this.style=e.style,this.styleName_=e.name,this.applyColour()},t.BlockSvg.prototype.setStyle=function(t){var e=this.workspace.getRenderer().getConstants().getBlockStyle(t);if(this.styleName_=t,!e)throw Error("Invalid style name: "+t);this.hat=e.hat,this.pathObject.setStyle(e),this.colour_=e.colourPrimary,this.style=e,this.applyColour()},t.BlockSvg.prototype.bringToFront=function(){var t=this;do{var e=t.getSvgRoot(),o=e.parentNode,i=o.childNodes;i[i.length-1]!==e&&o.appendChild(e),t=t.getParent()}while(t)},t.BlockSvg.prototype.setPreviousStatement=function(e,o){t.BlockSvg.superClass_.setPreviousStatement.call(this,e,o),this.rendered&&(this.render(),this.bumpNeighbours())},t.BlockSvg.prototype.setNextStatement=function(e,o){t.BlockSvg.superClass_.setNextStatement.call(this,e,o),this.rendered&&(this.render(),this.bumpNeighbours())},t.BlockSvg.prototype.setOutput=function(e,o){t.BlockSvg.superClass_.setOutput.call(this,e,o),this.rendered&&(this.render(),this.bumpNeighbours())},t.BlockSvg.prototype.setInputsInline=function(e){t.BlockSvg.superClass_.setInputsInline.call(this,e),this.rendered&&(this.render(),this.bumpNeighbours())},t.BlockSvg.prototype.removeInput=function(e,o){t.BlockSvg.superClass_.removeInput.call(this,e,o),this.rendered&&(this.render(),this.bumpNeighbours())},t.BlockSvg.prototype.moveNumberedInputBefore=function(e,o){t.BlockSvg.superClass_.moveNumberedInputBefore.call(this,e,o),this.rendered&&(this.render(),this.bumpNeighbours())},t.BlockSvg.prototype.appendInput_=function(e,o){return e=t.BlockSvg.superClass_.appendInput_.call(this,e,o),this.rendered&&(this.render(),this.bumpNeighbours()),e},t.BlockSvg.prototype.setConnectionTracking=function(t){if(this.previousConnection&&this.previousConnection.setTracking(t),this.outputConnection&&this.outputConnection.setTracking(t),this.nextConnection){this.nextConnection.setTracking(t);var e=this.nextConnection.targetBlock();e&&e.setConnectionTracking(t)}if(!this.collapsed_)for(e=0;e<this.inputList.length;e++){var o=this.inputList[e].connection;o&&(o.setTracking(t),(o=o.targetBlock())&&o.setConnectionTracking(t))}},t.BlockSvg.prototype.getConnections_=function(t){var e=[];if((t||this.rendered)&&(this.outputConnection&&e.push(this.outputConnection),this.previousConnection&&e.push(this.previousConnection),this.nextConnection&&e.push(this.nextConnection),t||!this.collapsed_)){t=0;for(var o;o=this.inputList[t];t++)o.connection&&e.push(o.connection)}return e},t.BlockSvg.prototype.lastConnectionInStack=function(){return t.BlockSvg.superClass_.lastConnectionInStack.call(this)},t.BlockSvg.prototype.getMatchingConnection=function(e,o){return t.BlockSvg.superClass_.getMatchingConnection.call(this,e,o)},t.BlockSvg.prototype.makeConnection_=function(e){return new t.RenderedConnection(this,e)},t.BlockSvg.prototype.bumpNeighbours=function(){if(this.workspace&&!this.workspace.isDragging()){var e=this.getRootBlock();if(!e.isInFlyout)for(var o,i=this.getConnections_(!1),n=0;o=i[n];n++){o.isConnected()&&o.isSuperior()&&o.targetBlock().bumpNeighbours();for(var s,r=o.neighbours(t.SNAP_RADIUS),a=0;s=r[a];a++)o.isConnected()&&s.isConnected()||s.getSourceBlock().getRootBlock()!=e&&(o.isSuperior()?s.bumpAwayFrom(o):o.bumpAwayFrom(s))}}},t.BlockSvg.prototype.scheduleSnapAndBump=function(){var e=this,o=t.Events.getGroup();setTimeout((function(){t.Events.setGroup(o),e.snapToGrid(),t.Events.setGroup(!1)}),t.BUMP_DELAY/2),setTimeout((function(){t.Events.setGroup(o),e.bumpNeighbours(),t.Events.setGroup(!1)}),t.BUMP_DELAY)},t.BlockSvg.prototype.positionNearConnection=function(e,o){e.type!=t.NEXT_STATEMENT&&e.type!=t.INPUT_VALUE||this.moveBy(o.x-e.x,o.y-e.y)},t.BlockSvg.prototype.getParent=function(){return t.BlockSvg.superClass_.getParent.call(this)},t.BlockSvg.prototype.getRootBlock=function(){return t.BlockSvg.superClass_.getRootBlock.call(this)},t.BlockSvg.prototype.render=function(e){t.utils.dom.startTextWidthCache(),this.rendered=!0,this.workspace.getRenderer().render(this),this.updateConnectionLocations_(),!1!==e&&((e=this.getParent())?e.render(!0):this.workspace.resizeContents()),t.utils.dom.stopTextWidthCache(),this.updateMarkers_()},t.BlockSvg.prototype.updateMarkers_=function(){this.workspace.keyboardAccessibilityMode&&this.pathObject.cursorSvg&&this.workspace.getCursor().draw(),this.workspace.keyboardAccessibilityMode&&this.pathObject.markerSvg&&this.workspace.getMarker(t.navigation.MARKER_NAME).draw()},t.BlockSvg.prototype.updateConnectionLocations_=function(){var t=this.getRelativeToSurfaceXY();this.previousConnection&&this.previousConnection.moveToOffset(t),this.outputConnection&&this.outputConnection.moveToOffset(t);for(var e=0;e<this.inputList.length;e++){var o=this.inputList[e].connection;o&&(o.moveToOffset(t),o.isConnected()&&o.tighten())}this.nextConnection&&(this.nextConnection.moveToOffset(t),this.nextConnection.isConnected()&&this.nextConnection.tighten())},t.BlockSvg.prototype.setCursorSvg=function(t){this.pathObject.setCursorSvg(t)},t.BlockSvg.prototype.setMarkerSvg=function(t){this.pathObject.setMarkerSvg(t)},t.BlockSvg.prototype.getHeightWidth=function(){var t=this.height,e=this.width,o=this.getNextBlock();if(o){o=o.getHeightWidth();var i=this.workspace.getRenderer().getConstants().NOTCH_HEIGHT;t+=o.height-i,e=Math.max(e,o.width)}return{height:t,width:e}},t.BlockSvg.prototype.fadeForReplacement=function(t){this.pathObject.updateReplacementFade(t)},t.BlockSvg.prototype.highlightShapeForInput=function(t,e){this.pathObject.updateShapeForInputHighlight(t,e)},t.blockRendering.rendererMap_={},t.blockRendering.useDebugger=!1,t.blockRendering.register=function(e,o){if(t.blockRendering.rendererMap_[e])throw Error("Renderer has already been registered.");t.blockRendering.rendererMap_[e]=o},t.blockRendering.unregister=function(e){t.blockRendering.rendererMap_[e]?delete t.blockRendering.rendererMap_[e]:console.warn('No renderer mapping for name "'+e+'" found to unregister')},t.blockRendering.startDebugger=function(){t.blockRendering.useDebugger=!0},t.blockRendering.stopDebugger=function(){t.blockRendering.useDebugger=!1},t.blockRendering.init=function(e,o,i){if(!t.blockRendering.rendererMap_[e])throw Error("Renderer not registered: ",e);return(e=new t.blockRendering.rendererMap_[e](e)).init(o,i),e},t.ConnectionDB=function(){this.connections_=[]},t.ConnectionDB.prototype.addConnection=function(t,e){e=this.calculateIndexForYPos_(e),this.connections_.splice(e,0,t)},t.ConnectionDB.prototype.findIndexOfConnection_=function(t,e){if(!this.connections_.length)return-1;var o=this.calculateIndexForYPos_(e);if(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(;o<this.connections_.length&&this.connections_[o].y==e;){if(this.connections_[o]==t)return o;o++}return-1},t.ConnectionDB.prototype.calculateIndexForYPos_=function(t){if(!this.connections_.length)return 0;for(var e=0,o=this.connections_.length;e<o;){var i=Math.floor((e+o)/2);if(this.connections_[i].y<t)e=i+1;else{if(!(this.connections_[i].y>t)){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<e}var i=this.connections_,n=t.x,s=t.y;t=0;for(var r=i.length-2,a=r;t<a;)i[a].y<s?t=a:r=a,a=Math.floor((t+r)/2);var l=[];if(r=t=a,i.length){for(;0<=t&&o(t);)t--;do{r++}while(r<i.length&&o(r))}return l},t.ConnectionDB.prototype.isInYRange_=function(t,e,o){return Math.abs(this.connections_[t].y-e)<=o},t.ConnectionDB.prototype.searchForClosest=function(t,e,o){if(!this.connections_.length)return{connection:null,radius:e};var i=t.y,n=t.x;t.x=n+o.x,t.y=i+o.y;var s=this.calculateIndexForYPos_(t.y);o=null;for(var r,a=e,l=s-1;0<=l&&this.isInYRange_(l,t.y,e);)r=this.connections_[l],t.isConnectionAllowed(r,a)&&(o=r,a=r.distanceFrom(t)),l--;for(;s<this.connections_.length&&this.isInYRange_(s,t.y,e);)r=this.connections_[s],t.isConnectionAllowed(r,a)&&(o=r,a=r.distanceFrom(t)),s++;return t.x=n,t.y=i,{connection:o,radius:a}},t.ConnectionDB.init=function(){var e=[];return e[t.INPUT_VALUE]=new t.ConnectionDB,e[t.OUTPUT_VALUE]=new t.ConnectionDB,e[t.NEXT_STATEMENT]=new t.ConnectionDB,e[t.PREVIOUS_STATEMENT]=new t.ConnectionDB,e},t.MarkerManager=function(t){this.cursorSvg_=this.cursor_=null,this.markers_={},this.workspace_=t},t.MarkerManager.prototype.registerMarker=function(t,e){this.markers_[t]&&this.unregisterMarker(t),e.setDrawer(this.workspace_.getRenderer().makeMarkerDrawer(this.workspace_,e)),this.setMarkerSvg(e.getDrawer().createDom()),this.markers_[t]=e},t.MarkerManager.prototype.unregisterMarker=function(t){var e=this.markers_[t];if(!e)throw Error("Marker with id "+t+" does not exist. Can only unregistermarkers that exist.");e.dispose(),delete this.markers_[t]},t.MarkerManager.prototype.getCursor=function(){return this.cursor_},t.MarkerManager.prototype.getMarker=function(t){return this.markers_[t]},t.MarkerManager.prototype.setCursor=function(t){this.cursor_&&this.cursor_.getDrawer()&&this.cursor_.getDrawer().dispose(),(this.cursor_=t)&&(t=this.workspace_.getRenderer().makeMarkerDrawer(this.workspace_,this.cursor_),this.cursor_.setDrawer(t),this.setCursorSvg(this.cursor_.getDrawer().createDom()))},t.MarkerManager.prototype.setCursorSvg=function(t){t?(this.workspace_.getBlockCanvas().appendChild(t),this.cursorSvg_=t):this.cursorSvg_=null},t.MarkerManager.prototype.setMarkerSvg=function(t){t?this.workspace_.getBlockCanvas()&&(this.cursorSvg_?this.workspace_.getBlockCanvas().insertBefore(t,this.cursorSvg_):this.workspace_.getBlockCanvas().appendChild(t)):this.markerSvg_=null},t.MarkerManager.prototype.updateMarkers=function(){this.workspace_.keyboardAccessibilityMode&&this.cursorSvg_&&this.workspace_.getCursor().draw()},t.MarkerManager.prototype.dispose=function(){for(var t,e=Object.keys(this.markers_),o=0;t=e[o];o++)this.unregisterMarker(t);this.markers_=null,this.cursor_.dispose(),this.cursor_=null},t.ThemeManager=function(t,e){this.workspace_=t,this.theme_=e,this.subscribedWorkspaces_=[],this.componentDB_=Object.create(null)},t.ThemeManager.prototype.getTheme=function(){return this.theme_},t.ThemeManager.prototype.setTheme=function(e){var o,i=this.theme_;for(this.theme_=e,(e=this.workspace_.getInjectionDiv())&&(i&&t.utils.dom.removeClass(e,i.getClassName()),t.utils.dom.addClass(e,this.theme_.getClassName())),i=0;e=this.subscribedWorkspaces_[i];i++)e.refreshTheme();for(i=0,e=Object.keys(this.componentDB_);o=e[i];i++)for(var n,s=0;n=this.componentDB_[o][s];s++){var r=n.element;n=n.propertyName;var a=this.theme_&&this.theme_.getComponentStyle(o);r.style[n]=a||""}t.hideChaff()},t.ThemeManager.prototype.subscribeWorkspace=function(t){this.subscribedWorkspaces_.push(t)},t.ThemeManager.prototype.unsubscribeWorkspace=function(t){if(0>(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_,0<this.previousScale_&&1/0>this.previousScale_){var i=o-this.previousScale_;i=0<i?i*t.TouchGesture.ZOOM_IN_MULTIPLIER:i*t.TouchGesture.ZOOM_OUT_MULTIPLIER;var n=this.startWorkspace_,s=t.utils.mouseToSvg(e,n.getParentSvg(),n.getInverseScreenCTM());n.zoom(s.x,s.y,i)}this.previousScale_=o,e.preventDefault()},t.TouchGesture.prototype.handleTouchEnd=function(e){e=t.Touch.getTouchIdentifierFromEvent(e),this.cachedPoints_[e]&&delete this.cachedPoints_[e],2>Object.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<e.length;s++){var r=e[s],a=r.match(/\.(\w+)$/);if(a&&i.canPlayType("audio/"+a[1])){n=new t.utils.global.Audio(r);break}}n&&n.play&&(this.SOUNDS_[o]=n)}},t.WorkspaceAudio.prototype.preload=function(){for(var e in this.SOUNDS_){var o=this.SOUNDS_[e];o.volume=.01;var i=o.play();if(void 0!==i?i.then(o.pause).catch((function(){})):o.pause(),t.utils.userAgent.IPAD||t.utils.userAgent.IPHONE)break}},t.WorkspaceAudio.prototype.play=function(e,o){var i=this.SOUNDS_[e];i?(e=new Date,null!=this.lastSound_&&e-this.lastSound_<t.SOUND_LIMIT||(this.lastSound_=e,(i=t.utils.userAgent.IPAD||t.utils.userAgent.ANDROID?i:i.cloneNode()).volume=void 0===o?1:o,i.play())):this.parentWorkspace_&&this.parentWorkspace_.getAudioManager().play(e,o)},t.WorkspaceSvg=function(e,o,i){t.WorkspaceSvg.superClass_.constructor.call(this,e),this.getMetrics=e.getMetrics||t.WorkspaceSvg.getTopLevelWorkspaceMetrics_,this.setMetrics=e.setMetrics||t.WorkspaceSvg.setTopLevelWorkspaceMetrics_,this.connectionDBList=t.ConnectionDB.init(),o&&(this.blockDragSurface_=o),i&&(this.workspaceDragSurface_=i),this.useWorkspaceDragSurface_=!!this.workspaceDragSurface_&&t.utils.is3dSupported(),this.highlightedBlocks_=[],this.audioManager_=new t.WorkspaceAudio(e.parentWorkspace),this.grid_=this.options.gridPattern?new t.Grid(e.gridPattern,e.gridOptions):null,this.markerManager_=new t.MarkerManager(this),this.toolboxCategoryCallbacks_={},this.flyoutButtonCallbacks_={},t.Variables&&t.Variables.flyoutCategory&&this.registerToolboxCategoryCallback(t.VARIABLE_CATEGORY_NAME,t.Variables.flyoutCategory),t.VariablesDynamic&&t.VariablesDynamic.flyoutCategory&&this.registerToolboxCategoryCallback(t.VARIABLE_DYNAMIC_CATEGORY_NAME,t.VariablesDynamic.flyoutCategory),t.Procedures&&t.Procedures.flyoutCategory&&(this.registerToolboxCategoryCallback(t.PROCEDURE_CATEGORY_NAME,t.Procedures.flyoutCategory),this.addChangeListener(t.Procedures.mutatorOpenListener)),this.themeManager_=this.options.parentWorkspace?this.options.parentWorkspace.getThemeManager():new t.ThemeManager(this,this.options.theme||t.Themes.Classic),this.themeManager_.subscribeWorkspace(this),this.renderer_=t.blockRendering.init(this.options.renderer||"geras",this.getTheme(),this.options.rendererOverrides),this.cachedParentSvg_=null,this.keyboardAccessibilityMode=!1},t.utils.object.inherits(t.WorkspaceSvg,t.Workspace),t.WorkspaceSvg.prototype.resizeHandlerWrapper_=null,t.WorkspaceSvg.prototype.rendered=!0,t.WorkspaceSvg.prototype.isVisible_=!0,t.WorkspaceSvg.prototype.isFlyout=!1,t.WorkspaceSvg.prototype.isMutator=!1,t.WorkspaceSvg.prototype.resizesEnabled_=!0,t.WorkspaceSvg.prototype.scrollX=0,t.WorkspaceSvg.prototype.scrollY=0,t.WorkspaceSvg.prototype.startScrollX=0,t.WorkspaceSvg.prototype.startScrollY=0,t.WorkspaceSvg.prototype.dragDeltaXY_=null,t.WorkspaceSvg.prototype.scale=1,t.WorkspaceSvg.prototype.trashcan=null,t.WorkspaceSvg.prototype.scrollbar=null,t.WorkspaceSvg.prototype.flyout_=null,t.WorkspaceSvg.prototype.toolbox_=null,t.WorkspaceSvg.prototype.currentGesture_=null,t.WorkspaceSvg.prototype.blockDragSurface_=null,t.WorkspaceSvg.prototype.workspaceDragSurface_=null,t.WorkspaceSvg.prototype.useWorkspaceDragSurface_=!1,t.WorkspaceSvg.prototype.isDragSurfaceActive_=!1,t.WorkspaceSvg.prototype.injectionDiv_=null,t.WorkspaceSvg.prototype.lastRecordedPageScroll_=null,t.WorkspaceSvg.prototype.targetWorkspace=null,t.WorkspaceSvg.prototype.inverseScreenCTM_=null,t.WorkspaceSvg.prototype.inverseScreenCTMDirty_=!0,t.WorkspaceSvg.prototype.getMarkerManager=function(){return this.markerManager_},t.WorkspaceSvg.prototype.setCursorSvg=function(t){this.markerManager_.setCursorSvg(t)},t.WorkspaceSvg.prototype.setMarkerSvg=function(t){this.markerManager_.setMarkerSvg(t)},t.WorkspaceSvg.prototype.getMarker=function(t){return this.markerManager_?this.markerManager_.getMarker(t):null},t.WorkspaceSvg.prototype.getCursor=function(){return this.markerManager_?this.markerManager_.getCursor():null},t.WorkspaceSvg.prototype.getRenderer=function(){return this.renderer_},t.WorkspaceSvg.prototype.getThemeManager=function(){return this.themeManager_},t.WorkspaceSvg.prototype.getTheme=function(){return this.themeManager_.getTheme()},t.WorkspaceSvg.prototype.setTheme=function(e){e||(e=t.Themes.Classic),this.themeManager_.setTheme(e)},t.WorkspaceSvg.prototype.refreshTheme=function(){this.svgGroup_&&this.renderer_.refreshDom(this.svgGroup_,this.getTheme()),this.updateBlockStyles_(this.getAllBlocks(!1).filter((function(t){return void 0!==t.getStyleName()}))),this.refreshToolboxSelection(),this.toolbox_&&this.toolbox_.updateColourFromTheme(),this.isVisible()&&this.setVisible(!0);var e=new t.Events.Ui(null,"theme",null,null);e.workspaceId=this.id,t.Events.fire(e)},t.WorkspaceSvg.prototype.updateBlockStyles_=function(t){for(var e,o=0;e=t[o];o++){var i=e.getStyleName();i&&(e.setStyle(i),e.mutator&&e.mutator.updateBlockStyle())}},t.WorkspaceSvg.prototype.getInverseScreenCTM=function(){if(this.inverseScreenCTMDirty_){var t=this.getParentSvg().getScreenCTM();t&&(this.inverseScreenCTM_=t.inverse(),this.inverseScreenCTMDirty_=!1)}return this.inverseScreenCTM_},t.WorkspaceSvg.prototype.updateInverseScreenCTM=function(){this.inverseScreenCTMDirty_=!0},t.WorkspaceSvg.prototype.isVisible=function(){return this.isVisible_},t.WorkspaceSvg.prototype.getSvgXY=function(e){var o=0,i=0,n=1;(t.utils.dom.containsNode(this.getCanvas(),e)||t.utils.dom.containsNode(this.getBubbleCanvas(),e))&&(n=this.scale);do{var s=t.utils.getRelativeXY(e);e!=this.getCanvas()&&e!=this.getBubbleCanvas()||(n=1),o+=s.x*n,i+=s.y*n,e=e.parentNode}while(e&&e!=this.getParentSvg());return new t.utils.Coordinate(o,i)},t.WorkspaceSvg.prototype.getOriginOffsetInPixels=function(){return t.utils.getInjectionDivXY_(this.getCanvas())},t.WorkspaceSvg.prototype.getInjectionDiv=function(){if(!this.injectionDiv_)for(var t=this.svgGroup_;t;){if(-1!=(" "+(t.getAttribute("class")||"")+" ").indexOf(" injectionDiv ")){this.injectionDiv_=t;break}t=t.parentNode}return this.injectionDiv_},t.WorkspaceSvg.prototype.getBlockCanvas=function(){return this.svgBlockCanvas_},t.WorkspaceSvg.prototype.setResizeHandlerWrapper=function(t){this.resizeHandlerWrapper_=t},t.WorkspaceSvg.prototype.createDom=function(e){if(this.svgGroup_=t.utils.dom.createSvgElement("g",{class:"blocklyWorkspace"},null),e&&(this.svgBackground_=t.utils.dom.createSvgElement("rect",{height:"100%",width:"100%",class:e},this.svgGroup_),"blocklyMainBackground"==e&&this.grid_?this.svgBackground_.style.fill="url(#"+this.grid_.getPatternId()+")":this.themeManager_.subscribe(this.svgBackground_,"workspaceBackgroundColour","fill")),this.svgBlockCanvas_=t.utils.dom.createSvgElement("g",{class:"blocklyBlockCanvas"},this.svgGroup_),this.svgBubbleCanvas_=t.utils.dom.createSvgElement("g",{class:"blocklyBubbleCanvas"},this.svgGroup_),this.isFlyout||(t.bindEventWithChecks_(this.svgGroup_,"mousedown",this,this.onMouseDown_,!1,!0),t.bindEventWithChecks_(this.svgGroup_,"wheel",this,this.onMouseWheel_)),this.options.hasCategories){if(!t.Toolbox)throw Error("Missing require for Blockly.Toolbox");this.toolbox_=new t.Toolbox(this)}return this.grid_&&this.grid_.update(this.scale),this.recordDeleteAreas(),this.markerManager_.setCursor(new t.Cursor),this.markerManager_.registerMarker(t.navigation.MARKER_NAME,new t.Marker),this.renderer_.createDom(this.svgGroup_,this.getTheme()),this.svgGroup_},t.WorkspaceSvg.prototype.dispose=function(){if(this.rendered=!1,this.currentGesture_&&this.currentGesture_.cancel(),this.svgGroup_&&(t.utils.dom.removeNode(this.svgGroup_),this.svgGroup_=null),this.svgBubbleCanvas_=this.svgBlockCanvas_=null,this.toolbox_&&(this.toolbox_.dispose(),this.toolbox_=null),this.flyout_&&(this.flyout_.dispose(),this.flyout_=null),this.trashcan&&(this.trashcan.dispose(),this.trashcan=null),this.scrollbar&&(this.scrollbar.dispose(),this.scrollbar=null),this.zoomControls_&&(this.zoomControls_.dispose(),this.zoomControls_=null),this.audioManager_&&(this.audioManager_.dispose(),this.audioManager_=null),this.grid_&&(this.grid_.dispose(),this.grid_=null),this.renderer_.dispose(),this.themeManager_&&(this.themeManager_.unsubscribeWorkspace(this),this.themeManager_.unsubscribe(this.svgBackground_),this.options.parentWorkspace||(this.themeManager_.dispose(),this.themeManager_=null)),this.markerManager_&&(this.markerManager_.dispose(),this.markerManager_=null),t.WorkspaceSvg.superClass_.dispose.call(this),this.flyoutButtonCallbacks_=this.toolboxCategoryCallbacks_=this.connectionDBList=null,!this.options.parentWorkspace){var e=this.getParentSvg().parentNode;e&&t.utils.dom.removeNode(e)}this.resizeHandlerWrapper_&&(t.unbindEvent_(this.resizeHandlerWrapper_),this.resizeHandlerWrapper_=null)},t.WorkspaceSvg.prototype.newBlock=function(e,o){return new t.BlockSvg(this,e,o)},t.WorkspaceSvg.prototype.addTrashcan=function(){if(!t.Trashcan)throw Error("Missing require for Blockly.Trashcan");this.trashcan=new t.Trashcan(this);var e=this.trashcan.createDom();this.svgGroup_.insertBefore(e,this.svgBlockCanvas_)},t.WorkspaceSvg.prototype.addZoomControls=function(){if(!t.ZoomControls)throw Error("Missing require for Blockly.ZoomControls");this.zoomControls_=new t.ZoomControls(this);var e=this.zoomControls_.createDom();this.svgGroup_.appendChild(e)},t.WorkspaceSvg.prototype.addFlyout=function(e){var o=new t.Options({parentWorkspace:this,rtl:this.RTL,oneBasedIndex:this.options.oneBasedIndex,horizontalLayout:this.horizontalLayout,renderer:this.options.renderer,rendererOverrides:this.options.rendererOverrides});if(o.toolboxPosition=this.options.toolboxPosition,this.horizontalLayout){if(!t.HorizontalFlyout)throw Error("Missing require for Blockly.HorizontalFlyout");this.flyout_=new t.HorizontalFlyout(o)}else{if(!t.VerticalFlyout)throw Error("Missing require for Blockly.VerticalFlyout");this.flyout_=new t.VerticalFlyout(o)}return this.flyout_.autoClose=!1,this.flyout_.getWorkspace().setVisible(!0),this.flyout_.createDom(e)},t.WorkspaceSvg.prototype.getFlyout=function(t){return this.flyout_||t?this.flyout_:this.toolbox_?this.toolbox_.getFlyout():null},t.WorkspaceSvg.prototype.getToolbox=function(){return this.toolbox_},t.WorkspaceSvg.prototype.updateScreenCalculations_=function(){this.updateInverseScreenCTM(),this.recordDeleteAreas()},t.WorkspaceSvg.prototype.resizeContents=function(){this.resizesEnabled_&&this.rendered&&(this.scrollbar&&this.scrollbar.resize(),this.updateInverseScreenCTM())},t.WorkspaceSvg.prototype.resize=function(){this.toolbox_&&this.toolbox_.position(),this.flyout_&&this.flyout_.position(),this.trashcan&&this.trashcan.position(),this.zoomControls_&&this.zoomControls_.position(),this.scrollbar&&this.scrollbar.resize(),this.updateScreenCalculations_()},t.WorkspaceSvg.prototype.updateScreenCalculationsIfScrolled=function(){var e=t.utils.getDocumentScroll();t.utils.Coordinate.equals(this.lastRecordedPageScroll_,e)||(this.lastRecordedPageScroll_=e,this.updateScreenCalculations_())},t.WorkspaceSvg.prototype.getCanvas=function(){return this.svgBlockCanvas_},t.WorkspaceSvg.prototype.getBubbleCanvas=function(){return this.svgBubbleCanvas_},t.WorkspaceSvg.prototype.getParentSvg=function(){if(!this.cachedParentSvg_)for(var t=this.svgGroup_;t;){if("svg"==t.tagName){this.cachedParentSvg_=t;break}t=t.parentNode}return this.cachedParentSvg_},t.WorkspaceSvg.prototype.translate=function(t,e){if(this.useWorkspaceDragSurface_&&this.isDragSurfaceActive_)this.workspaceDragSurface_.translateSurface(t,e);else{var o="translate("+t+","+e+") scale("+this.scale+")";this.svgBlockCanvas_.setAttribute("transform",o),this.svgBubbleCanvas_.setAttribute("transform",o)}this.blockDragSurface_&&this.blockDragSurface_.translateAndScaleGroup(t,e,this.scale),this.grid_&&this.grid_.moveTo(t,e)},t.WorkspaceSvg.prototype.resetDragSurface=function(){if(this.useWorkspaceDragSurface_){this.isDragSurfaceActive_=!1;var t=this.workspaceDragSurface_.getSurfaceTranslation();this.workspaceDragSurface_.clearAndHide(this.svgGroup_),t="translate("+t.x+","+t.y+") scale("+this.scale+")",this.svgBlockCanvas_.setAttribute("transform",t),this.svgBubbleCanvas_.setAttribute("transform",t)}},t.WorkspaceSvg.prototype.setupDragSurface=function(){if(this.useWorkspaceDragSurface_&&!this.isDragSurfaceActive_){this.isDragSurfaceActive_=!0;var e=this.svgBlockCanvas_.previousSibling,o=parseInt(this.getParentSvg().getAttribute("width"),10),i=parseInt(this.getParentSvg().getAttribute("height"),10),n=t.utils.getRelativeXY(this.getCanvas());this.workspaceDragSurface_.setContentsAndShow(this.getCanvas(),this.getBubbleCanvas(),e,o,i,this.scale),this.workspaceDragSurface_.translateSurface(n.x,n.y)}},t.WorkspaceSvg.prototype.getBlockDragSurface=function(){return this.blockDragSurface_},t.WorkspaceSvg.prototype.getWidth=function(){var t=this.getMetrics();return t?t.viewWidth/this.scale:0},t.WorkspaceSvg.prototype.setVisible=function(e){if(this.isVisible_=e,this.svgGroup_)if(this.scrollbar&&this.scrollbar.setContainerVisible(e),this.getFlyout()&&this.getFlyout().setContainerVisible(e),this.getParentSvg().style.display=e?"block":"none",this.toolbox_&&(this.toolbox_.HtmlDiv.style.display=e?"block":"none"),e){for(var o=(e=this.getAllBlocks(!1)).length-1;0<=o;o--)e[o].markDirty();this.render(),this.toolbox_&&this.toolbox_.position()}else t.hideChaff(!0)},t.WorkspaceSvg.prototype.render=function(){for(var t=this.getAllBlocks(!1),e=t.length-1;0<=e;e--)t[e].render(!1);if(this.currentGesture_)for(t=this.currentGesture_.getInsertionMarkers(),e=0;e<t.length;e++)t[e].render(!1);this.markerManager_.updateMarkers()},t.WorkspaceSvg.prototype.traceOn=function(){console.warn("Deprecated call to traceOn, delete this.")},t.WorkspaceSvg.prototype.highlightBlock=function(e,o){if(void 0===o){for(var i,n=0;i=this.highlightedBlocks_[n];n++)i.setHighlighted(!1);this.highlightedBlocks_.length=0}(i=e?this.getBlockById(e):null)&&((e=void 0===o||o)?-1==this.highlightedBlocks_.indexOf(i)&&this.highlightedBlocks_.push(i):t.utils.arrayRemove(this.highlightedBlocks_,i),i.setHighlighted(e))},t.WorkspaceSvg.prototype.paste=function(t){!this.rendered||t.getElementsByTagName("block").length>=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;i<e.length;i++){var n=e[i].getBoundingRectangle();n.top<o.top&&(o.top=n.top),n.bottom>o.bottom&&(o.bottom=n.bottom),n.left<o.left&&(o.left=n.left),n.right>o.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<t.length;e++)o(t[e])}}function i(){t.Events.setGroup(r);var e=_.shift();e&&(e.workspace?(e.dispose(!1,!0),setTimeout(i,10)):i()),t.Events.setGroup(!1)}if(!this.options.readOnly&&!this.isFlyout){var n=[],s=this.getTopBlocks(!0),r=t.utils.genUid(),a=this,l={};if(l.text=t.Msg.UNDO,l.enabled=0<this.undoStack_.length,l.callback=this.undo.bind(this,!1),n.push(l),(l={}).text=t.Msg.REDO,l.enabled=0<this.redoStack_.length,l.callback=this.undo.bind(this,!0),n.push(l),this.isMovable()&&((l={}).text=t.Msg.CLEAN_UP,l.enabled=1<s.length,l.callback=this.cleanUp.bind(this),n.push(l)),this.options.collapse){for(var c=l=!1,h=0;h<s.length;h++)for(var u=s[h];u;)u.isCollapsed()?l=!0:c=!0,u=u.getNextBlock();var p=function(t){for(var e=0,o=0;o<s.length;o++)for(var i=s[o];i;)setTimeout(i.setCollapsed.bind(i,t),e),i=i.getNextBlock(),e+=10};(c={enabled:c}).text=t.Msg.COLLAPSE_ALL,c.callback=function(){p(!0)},n.push(c),(l={enabled:l}).text=t.Msg.EXPAND_ALL,l.callback=function(){p(!1)},n.push(l)}var _=[];for(h=0;h<s.length;h++)o(s[h]);l={text:1==_.length?t.Msg.DELETE_BLOCK:t.Msg.DELETE_X_BLOCKS.replace("%1",String(_.length)),enabled:0<_.length,callback:function(){a.currentGesture_&&a.currentGesture_.cancel(),2>_.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:i<this.options.zoomOptions.minScale&&(o=this.options.zoomOptions.minScale/this.scale);var n=this.getCanvas().getCTM(),s=this.getParentSvg().createSVGPoint();s.x=t,s.y=e,t=(s=s.matrixTransform(n.inverse())).x,e=s.y,n=n.translate(t*(1-o),e*(1-o)).scale(o),this.scrollX=n.e,this.scrollY=n.f,this.setScale(i)}},t.WorkspaceSvg.prototype.zoomCenter=function(t){var e=this.getMetrics();if(this.flyout_){var o=e.svgWidth/2;e=e.svgHeight/2}else o=e.viewWidth/2+e.absoluteLeft,e=e.viewHeight/2+e.absoluteTop;this.zoom(o,e,t)},t.WorkspaceSvg.prototype.zoomToFit=function(){if(this.isMovable()){var t=this.getMetrics(),e=t.viewWidth;t=t.viewHeight;var o=this.getBlocksBoundingBox(),i=o.right-o.left;o=o.bottom-o.top,i&&(this.flyout_&&(this.horizontalLayout?(t+=this.flyout_.getHeight(),o+=this.flyout_.getHeight()/this.scale):(e+=this.flyout_.getWidth(),i+=this.flyout_.getWidth()/this.scale)),this.setScale(Math.min(e/i,t/o)),this.scrollCenter())}else console.warn("Tried to move a non-movable workspace. This could result in blocks becoming inaccessible.")},t.WorkspaceSvg.prototype.beginCanvasTransition=function(){t.utils.dom.addClass(this.svgBlockCanvas_,"blocklyCanvasTransitioning"),t.utils.dom.addClass(this.svgBubbleCanvas_,"blocklyCanvasTransitioning")},t.WorkspaceSvg.prototype.endCanvasTransition=function(){t.utils.dom.removeClass(this.svgBlockCanvas_,"blocklyCanvasTransitioning"),t.utils.dom.removeClass(this.svgBubbleCanvas_,"blocklyCanvasTransitioning")},t.WorkspaceSvg.prototype.scrollCenter=function(){if(this.isMovable()){var t=this.getMetrics(),e=(t.contentWidth-t.viewWidth)/2,o=(t.contentHeight-t.viewHeight)/2;e=-e-t.contentLeft,o=-o-t.contentTop,this.scroll(e,o)}else console.warn("Tried to move a non-movable workspace. This could result in blocks becoming inaccessible.")},t.WorkspaceSvg.prototype.centerOnBlock=function(t){if(this.isMovable()){if(t=t?this.getBlockById(t):null){var e=t.getRelativeToSurfaceXY(),o=t.getHeightWidth(),i=this.scale;t=(e.x+(this.RTL?-1:1)*o.width/2)*i,e=(e.y+o.height/2)*i,o=this.getMetrics(),this.scroll(-(t-o.viewWidth/2),-(e-o.viewHeight/2))}}else console.warn("Tried to move a non-movable workspace. This could result in blocks becoming inaccessible.")},t.WorkspaceSvg.prototype.setScale=function(e){this.options.zoomOptions.maxScale&&e>this.options.zoomOptions.maxScale?e=this.options.zoomOptions.maxScale:this.options.zoomOptions.minScale&&e<this.options.zoomOptions.minScale&&(e=this.options.zoomOptions.minScale),this.scale=e,t.hideChaff(!1),this.flyout_&&(this.flyout_.reflow(),this.recordDeleteAreas()),this.grid_&&this.grid_.update(this.scale),e=this.getMetrics(),this.scrollX-=e.absoluteLeft,this.scrollY-=e.absoluteTop,e.viewLeft+=e.absoluteLeft,e.viewTop+=e.absoluteTop,this.scroll(this.scrollX,this.scrollY),this.scrollbar&&(this.flyout_?(this.scrollbar.hScroll.resizeViewHorizontal(e),this.scrollbar.vScroll.resizeViewVertical(e)):(this.scrollbar.hScroll.resizeContentHorizontal(e),this.scrollbar.vScroll.resizeContentVertical(e)))},t.WorkspaceSvg.prototype.getScale=function(){return this.options.parentWorkspace?this.options.parentWorkspace.getScale():this.scale},t.WorkspaceSvg.prototype.scroll=function(e,o){t.hideChaff(!0);var i=this.getMetrics(),n=i.contentWidth+i.contentLeft-i.viewWidth,s=i.contentHeight+i.contentTop-i.viewHeight;e=Math.min(e,-i.contentLeft),o=Math.min(o,-i.contentTop),e=Math.max(e,-n),o=Math.max(o,-s),this.scrollX=e,this.scrollY=o,this.scrollbar&&(this.scrollbar.hScroll.setHandlePosition(-(e+i.contentLeft)*this.scrollbar.hScroll.ratio_),this.scrollbar.vScroll.setHandlePosition(-(o+i.contentTop)*this.scrollbar.vScroll.ratio_)),e+=i.absoluteLeft,o+=i.absoluteTop,this.translate(e,o)},t.WorkspaceSvg.getDimensionsPx_=function(t){var e=0,o=0;return t&&(e=t.getWidth(),o=t.getHeight()),{width:e,height:o}},t.WorkspaceSvg.getContentDimensions_=function(e,o){return e.isContentBounded()?t.WorkspaceSvg.getContentDimensionsBounded_(e,o):t.WorkspaceSvg.getContentDimensionsExact_(e)},t.WorkspaceSvg.getContentDimensionsExact_=function(t){var e=t.getBlocksBoundingBox(),o=t.scale;t=e.top*o;var i=e.bottom*o,n=e.left*o;return{top:t,bottom:i,left:n,right:e=e.right*o,width:e-n,height:i-t}},t.WorkspaceSvg.getContentDimensionsBounded_=function(e,o){e=t.WorkspaceSvg.getContentDimensionsExact_(e);var i=o.width,n=i/2,s=(o=o.height)/2,r=Math.min(e.left-n,e.right-i),a=Math.min(e.top-s,e.bottom-o);return{left:r,top:a,height:Math.max(e.bottom+s,e.top+o)-a,width:Math.max(e.right+n,e.left+i)-r}},t.WorkspaceSvg.getTopLevelWorkspaceMetrics_=function(){var e=t.WorkspaceSvg.getDimensionsPx_(this.toolbox_),o=t.WorkspaceSvg.getDimensionsPx_(this.flyout_),i=t.svgSize(this.getParentSvg()),n={height:i.height,width:i.width};this.toolbox_?this.toolboxPosition==t.TOOLBOX_AT_TOP||this.toolboxPosition==t.TOOLBOX_AT_BOTTOM?n.height-=e.height:this.toolboxPosition!=t.TOOLBOX_AT_LEFT&&this.toolboxPosition!=t.TOOLBOX_AT_RIGHT||(n.width-=e.width):this.flyout_&&(this.toolboxPosition==t.TOOLBOX_AT_TOP||this.toolboxPosition==t.TOOLBOX_AT_BOTTOM?n.height-=o.height:this.toolboxPosition!=t.TOOLBOX_AT_LEFT&&this.toolboxPosition!=t.TOOLBOX_AT_RIGHT||(n.width-=o.width));var s=t.WorkspaceSvg.getContentDimensions_(this,n),r=0;this.toolbox_&&this.toolboxPosition==t.TOOLBOX_AT_LEFT?r=e.width:this.flyout_&&this.toolboxPosition==t.TOOLBOX_AT_LEFT&&(r=o.width);var a=0;return this.toolbox_&&this.toolboxPosition==t.TOOLBOX_AT_TOP?a=e.height:this.flyout_&&this.toolboxPosition==t.TOOLBOX_AT_TOP&&(a=o.height),{contentHeight:s.height,contentWidth:s.width,contentTop:s.top,contentLeft:s.left,viewHeight:n.height,viewWidth:n.width,viewTop:-this.scrollY,viewLeft:-this.scrollX,absoluteTop:a,absoluteLeft:r,svgHeight:i.height,svgWidth:i.width,toolboxWidth:e.width,toolboxHeight:e.height,flyoutWidth:o.width,flyoutHeight:o.height,toolboxPosition:this.toolboxPosition}},t.WorkspaceSvg.setTopLevelWorkspaceMetrics_=function(t){var e=this.getMetrics();"number"==typeof t.x&&(this.scrollX=-e.contentWidth*t.x-e.contentLeft),"number"==typeof t.y&&(this.scrollY=-e.contentHeight*t.y-e.contentTop),this.translate(this.scrollX+e.absoluteLeft,this.scrollY+e.absoluteTop)},t.WorkspaceSvg.prototype.getBlockById=function(e){return t.WorkspaceSvg.superClass_.getBlockById.call(this,e)},t.WorkspaceSvg.prototype.getTopBlocks=function(e){return t.WorkspaceSvg.superClass_.getTopBlocks.call(this,e)},t.WorkspaceSvg.prototype.setResizesEnabled=function(t){var e=!this.resizesEnabled_&&t;this.resizesEnabled_=t,e&&this.resizeContents()},t.WorkspaceSvg.prototype.clear=function(){this.setResizesEnabled(!1),t.WorkspaceSvg.superClass_.clear.call(this),this.setResizesEnabled(!0)},t.WorkspaceSvg.prototype.registerButtonCallback=function(t,e){if("function"!=typeof e)throw TypeError("Button callbacks must be functions.");this.flyoutButtonCallbacks_[t]=e},t.WorkspaceSvg.prototype.getButtonCallback=function(t){return(t=this.flyoutButtonCallbacks_[t])?t:null},t.WorkspaceSvg.prototype.removeButtonCallback=function(t){this.flyoutButtonCallbacks_[t]=null},t.WorkspaceSvg.prototype.registerToolboxCategoryCallback=function(t,e){if("function"!=typeof e)throw TypeError("Toolbox category callbacks must be functions.");this.toolboxCategoryCallbacks_[t]=e},t.WorkspaceSvg.prototype.getToolboxCategoryCallback=function(t){return this.toolboxCategoryCallbacks_[t]||null},t.WorkspaceSvg.prototype.removeToolboxCategoryCallback=function(t){this.toolboxCategoryCallbacks_[t]=null},t.WorkspaceSvg.prototype.getGesture=function(e){var o="mousedown"==e.type||"touchstart"==e.type||"pointerdown"==e.type,i=this.currentGesture_;return i?o&&i.hasStarted()?(console.warn("Tried to start the same gesture twice."),i.cancel(),null):i:o?this.currentGesture_=new t.TouchGesture(e,this):null},t.WorkspaceSvg.prototype.clearGesture=function(){this.currentGesture_=null},t.WorkspaceSvg.prototype.cancelCurrentGesture=function(){this.currentGesture_&&this.currentGesture_.cancel()},t.WorkspaceSvg.prototype.getAudioManager=function(){return this.audioManager_},t.WorkspaceSvg.prototype.getGrid=function(){return this.grid_},t.inject=function(e,o){if(t.checkBlockColourConstants(),"string"==typeof e&&(e=document.getElementById(e)||document.querySelector(e)),!e||!t.utils.dom.containsNode(document,e))throw Error("Error: container is not in current document.");o=new t.Options(o||{});var i=document.createElement("div");i.className="injectionDiv",i.tabIndex=0,t.utils.aria.setState(i,t.utils.aria.State.LABEL,t.Msg.WORKSPACE_ARIA_LABEL),e.appendChild(i),e=t.createDom_(i,o);var n=new t.BlockDragSurfaceSvg(i),s=new t.WorkspaceDragSurfaceSvg(i),r=t.createMainWorkspace_(e,o,n,s);return t.user.keyMap.setKeyMap(o.keyMap),t.init_(r),t.mainWorkspace=r,t.svgResize(r),i.addEventListener("focusin",(function(){t.mainWorkspace=r})),r},t.createDom_=function(e,o){e.setAttribute("dir","LTR"),t.Component.defaultRightToLeft=o.RTL,t.Css.inject(o.hasCss,o.pathToMedia),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",class:"blocklySvg",tabindex:"0"},e);var i=t.utils.dom.createSvgElement("defs",{},e),n=String(Math.random()).substring(2);return o.gridPattern=t.Grid.createDom(n,o.gridOptions,i),e},t.createMainWorkspace_=function(e,o,i,n){o.parentWorkspace=null;var s=new t.WorkspaceSvg(o,i,n);return o=s.options,s.scale=o.zoomOptions.startScale,e.appendChild(s.createDom("blocklyMainBackground")),t.utils.dom.addClass(s.getInjectionDiv(),s.getRenderer().getClassName()),t.utils.dom.addClass(s.getInjectionDiv(),s.getTheme().getClassName()),!o.hasCategories&&o.languageTree&&(i=s.addFlyout("svg"),t.utils.dom.insertAfter(i,e)),o.hasTrashcan&&s.addTrashcan(),o.zoomOptions&&o.zoomOptions.controls&&s.addZoomControls(),s.getThemeManager().subscribe(e,"workspaceBackgroundColour","background-color"),s.translate(0,0),o.readOnly||s.isMovable()||s.addChangeListener((function(e){if(!s.isDragging()&&!s.isMovable()&&-1!=t.Events.BUMP_EVENTS.indexOf(e.type)){var o=Object.create(null),i=s.getMetrics(),n=s.scale;if(o.RTL=s.RTL,o.viewLeft=i.viewLeft/n,o.viewTop=i.viewTop/n,o.viewRight=(i.viewLeft+i.viewWidth)/n,o.viewBottom=(i.viewTop+i.viewHeight)/n,s.isContentBounded()?(i=s.getBlocksBoundingBox(),o.contentLeft=i.left,o.contentTop=i.top,o.contentRight=i.right,o.contentBottom=i.bottom):(o.contentLeft=i.contentLeft/n,o.contentTop=i.contentTop/n,o.contentRight=(i.contentLeft+i.contentWidth)/n,o.contentBottom=(i.contentTop+i.contentHeight)/n),o.contentTop<o.viewTop||o.contentBottom>o.viewBottom||o.contentLeft<o.viewLeft||o.contentRight>o.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;e<t.length;e++)this.reservedDict_[t[e]]=!0;this.reset()},t.Names.DEVELOPER_VARIABLE_TYPE="DEVELOPER_VARIABLE",t.Names.prototype.reset=function(){this.db_=Object.create(null),this.dbReverse_=Object.create(null),this.variableMap_=null},t.Names.prototype.setVariableMap=function(t){this.variableMap_=t},t.Names.prototype.getNameForUserVariable_=function(t){return this.variableMap_?(t=this.variableMap_.getVariableById(t))?t.name:null:(console.log("Deprecated call to Blockly.Names.prototype.getName without defining a variable map. To fix, add the following code in your generator's init() function:\nBlockly.YourGeneratorName.variableDB_.setVariableMap(workspace.getVariableMap());"),null)},t.Names.prototype.getName=function(e,o){if(o==t.VARIABLE_CATEGORY_NAME){var i=this.getNameForUserVariable_(e);i&&(e=i)}i=e.toLowerCase()+"_"+o;var n=o==t.VARIABLE_CATEGORY_NAME||o==t.Names.DEVELOPER_VARIABLE_TYPE?this.variablePrefix_:"";return i in this.db_?n+this.db_[i]:(e=this.getDistinctName(e,o),this.db_[i]=e.substr(n.length),e)},t.Names.prototype.getDistinctName=function(e,o){e=this.safeName_(e);for(var i="";this.dbReverse_[e+i]||e+i in this.reservedDict_;)i=i?i+1:2;return e+=i,this.dbReverse_[e]=!0,(o==t.VARIABLE_CATEGORY_NAME||o==t.Names.DEVELOPER_VARIABLE_TYPE?this.variablePrefix_:"")+e},t.Names.prototype.safeName_=function(e){return e?(e=encodeURI(e.replace(/ /g,"_")).replace(/[^\w]/g,"_"),-1!="0123456789".indexOf(e[0])&&(e="my_"+e)):e=t.Msg.UNNAMED_KEY||"unnamed",e},t.Names.equals=function(t,e){return t.toLowerCase()==e.toLowerCase()},t.Procedures={},t.Procedures.NAME_TYPE=t.PROCEDURE_CATEGORY_NAME,t.Procedures.DEFAULT_ARG="x",t.Procedures.allProcedures=function(e){e=e.getAllBlocks(!1);for(var o=[],i=[],n=0;n<e.length;n++)if(e[n].getProcedureDef){var s=e[n].getProcedureDef();s&&(s[2]?o.push(s):i.push(s))}return i.sort(t.Procedures.procTupleComparator_),o.sort(t.Procedures.procTupleComparator_),[i,o]},t.Procedures.procTupleComparator_=function(t,e){return t[0].toLowerCase().localeCompare(e[0].toLowerCase())},t.Procedures.findLegalName=function(e,o){if(o.isInFlyout)return e;for(e=e||t.Msg.UNNAMED_KEY||"unnamed";!t.Procedures.isLegalName_(e,o.workspace,o);){var i=e.match(/^(.*?)(\d+)$/);e=i?i[1]+(parseInt(i[2],10)+1):e+"2"}return e},t.Procedures.isLegalName_=function(e,o,i){return!t.Procedures.isNameUsed(e,o,i)},t.Procedures.isNameUsed=function(e,o,i){o=o.getAllBlocks(!1);for(var n=0;n<o.length;n++)if(o[n]!=i&&o[n].getProcedureDef){var s=o[n].getProcedureDef();if(t.Names.equals(s[0],e))return!0}return!1},t.Procedures.rename=function(e){e=e.trim();var o=t.Procedures.findLegalName(e,this.getSourceBlock()),i=this.getValue();if(i!=e&&i!=o){e=this.getSourceBlock().workspace.getAllBlocks(!1);for(var n=0;n<e.length;n++)e[n].renameProcedure&&e[n].renameProcedure(i,o)}return o},t.Procedures.flyoutCategory=function(e){function o(e,o){for(var n=0;n<e.length;n++){var s=e[n][0],r=e[n][1],a=t.utils.xml.createElement("block");a.setAttribute("type",o),a.setAttribute("gap",16);var l=t.utils.xml.createElement("mutation");for(l.setAttribute("name",s),a.appendChild(l),s=0;s<r.length;s++){var c=t.utils.xml.createElement("arg");c.setAttribute("name",r[s]),l.appendChild(c)}i.push(a)}}var i=[];if(t.Blocks.procedures_defnoreturn){var n=t.utils.xml.createElement("block");n.setAttribute("type","procedures_defnoreturn"),n.setAttribute("gap",16);var s=t.utils.xml.createElement("field");s.setAttribute("name","NAME"),s.appendChild(t.utils.xml.createTextNode(t.Msg.PROCEDURES_DEFNORETURN_PROCEDURE)),n.appendChild(s),i.push(n)}return t.Blocks.procedures_defreturn&&((n=t.utils.xml.createElement("block")).setAttribute("type","procedures_defreturn"),n.setAttribute("gap",16),(s=t.utils.xml.createElement("field")).setAttribute("name","NAME"),s.appendChild(t.utils.xml.createTextNode(t.Msg.PROCEDURES_DEFRETURN_PROCEDURE)),n.appendChild(s),i.push(n)),t.Blocks.procedures_ifreturn&&((n=t.utils.xml.createElement("block")).setAttribute("type","procedures_ifreturn"),n.setAttribute("gap",16),i.push(n)),i.length&&i[i.length-1].setAttribute("gap",24),o((e=t.Procedures.allProcedures(e))[0],"procedures_callnoreturn"),o(e[1],"procedures_callreturn"),i},t.Procedures.updateMutatorFlyout_=function(e){for(var o,i=[],n=e.getBlocksByType("procedures_mutatorarg",!1),s=0;o=n[s];s++)i.push(o.getFieldValue("NAME"));n=t.utils.xml.createElement("xml"),(s=t.utils.xml.createElement("block")).setAttribute("type","procedures_mutatorarg"),(o=t.utils.xml.createElement("field")).setAttribute("name","NAME"),i=t.Variables.generateUniqueNameFromOptions(t.Procedures.DEFAULT_ARG,i),i=t.utils.xml.createTextNode(i),o.appendChild(i),s.appendChild(o),n.appendChild(s),e.updateToolbox(n)},t.Procedures.mutatorOpenListener=function(e){if(e.type==t.Events.UI&&"mutatorOpen"==e.element&&e.newValue){var o=(e=t.Workspace.getById(e.workspaceId).getBlockById(e.blockId)).type;"procedures_defnoreturn"!=o&&"procedures_defreturn"!=o||(e=e.mutator.getWorkspace(),t.Procedures.updateMutatorFlyout_(e),e.addChangeListener(t.Procedures.mutatorChangeListener_))}},t.Procedures.mutatorChangeListener_=function(e){e.type!=t.Events.BLOCK_CREATE&&e.type!=t.Events.BLOCK_DELETE&&e.type!=t.Events.BLOCK_CHANGE||(e=t.Workspace.getById(e.workspaceId),t.Procedures.updateMutatorFlyout_(e))},t.Procedures.getCallers=function(e,o){var i=[];o=o.getAllBlocks(!1);for(var n=0;n<o.length;n++)if(o[n].getProcedureCall){var s=o[n].getProcedureCall();s&&t.Names.equals(s,e)&&i.push(o[n])}return i},t.Procedures.mutateCallers=function(e){var o,i=t.Events.recordUndo,n=e.getProcedureDef()[0],s=e.mutationToDom(!0);for(e=t.Procedures.getCallers(n,e.workspace),n=0;o=e[n];n++){var r=o.mutationToDom();r=r&&t.Xml.domToText(r),o.domToMutation(s);var a=o.mutationToDom();r!=(a=a&&t.Xml.domToText(a))&&(t.Events.recordUndo=!1,t.Events.fire(new t.Events.BlockChange(o,"mutation",null,r,a)),t.Events.recordUndo=i)}},t.Procedures.getDefinition=function(e,o){o=o.getTopBlocks(!1);for(var i=0;i<o.length;i++)if(o[i].getProcedureDef){var n=o[i].getProcedureDef();if(n&&t.Names.equals(n[0],e))return o[i]}return null},t.VariableModel=function(e,o,i,n){this.workspace=e,this.name=o,this.type=i||"",this.id_=n||t.utils.genUid(),t.Events.fire(new t.Events.VarCreate(this))},t.VariableModel.prototype.getId=function(){return this.id_},t.VariableModel.compareByName=function(t,e){return(t=t.name.toLowerCase())<(e=e.name.toLowerCase())?-1:t==e?0:1},t.Variables={},t.Variables.NAME_TYPE=t.VARIABLE_CATEGORY_NAME,t.Variables.allUsedVarModels=function(t){var e=t.getAllBlocks(!1);t=Object.create(null);for(var o=0;o<e.length;o++){var i=e[o].getVarModels();if(i)for(var n=0;n<i.length;n++){var s=i[n],r=s.getId();r&&(t[r]=s)}}for(r in e=[],t)e.push(t[r]);return e},t.Variables.allUsedVariables=function(){console.warn("Deprecated call to Blockly.Variables.allUsedVariables. Use Blockly.Variables.allUsedVarModels instead.\nIf this is a major issue please file a bug on GitHub.")},t.Variables.ALL_DEVELOPER_VARS_WARNINGS_BY_BLOCK_TYPE_={},t.Variables.allDeveloperVariables=function(e){e=e.getAllBlocks(!1);for(var o,i=Object.create(null),n=0;o=e[n];n++){var s=o.getDeveloperVariables;if(!s&&o.getDeveloperVars&&(s=o.getDeveloperVars,t.Variables.ALL_DEVELOPER_VARS_WARNINGS_BY_BLOCK_TYPE_[o.type]||(console.warn("Function getDeveloperVars() deprecated. Use getDeveloperVariables() (block type '"+o.type+"')"),t.Variables.ALL_DEVELOPER_VARS_WARNINGS_BY_BLOCK_TYPE_[o.type]=!0)),s)for(o=s(),s=0;s<o.length;s++)i[o[s]]=!0}return Object.keys(i)},t.Variables.flyoutCategory=function(e){var o=[],i=document.createElement("button");return i.setAttribute("text","%{BKY_NEW_VARIABLE}"),i.setAttribute("callbackKey","CREATE_VARIABLE"),e.registerButtonCallback("CREATE_VARIABLE",(function(e){t.Variables.createVariableButtonHandler(e.getTargetWorkspace())})),o.push(i),e=t.Variables.flyoutCategoryBlocks(e),o.concat(e)},t.Variables.flyoutCategoryBlocks=function(e){var o=[];if(0<(e=e.getVariablesOfType("")).length){var i=e[e.length-1];if(t.Blocks.variables_set){var n=t.utils.xml.createElement("block");n.setAttribute("type","variables_set"),n.setAttribute("gap",t.Blocks.math_change?8:24),n.appendChild(t.Variables.generateVariableFieldDom(i)),o.push(n)}if(t.Blocks.math_change&&((n=t.utils.xml.createElement("block")).setAttribute("type","math_change"),n.setAttribute("gap",t.Blocks.variables_get?20:8),n.appendChild(t.Variables.generateVariableFieldDom(i)),i=t.Xml.textToDom('<value name="DELTA"><shadow type="math_number"><field name="NUM">1</field></shadow></value>'),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;a<o.length;a++)if(o[a].toLowerCase()==e){r=!0;break}if(!r)return e;++s==i.length&&(s=0,n=Number(n)+1),e=i.charAt(s)+n}},t.Variables.createVariableButtonHandler=function(e,o,i){var n=i||"",s=function(i){t.Variables.promptName(t.Msg.NEW_VARIABLE_TITLE,i,(function(i){if(i){var r=t.Variables.nameUsedWithAnyType_(i,e);if(r){if(r.type==n)var a=t.Msg.VARIABLE_ALREADY_EXISTS.replace("%1",r.name);else a=(a=t.Msg.VARIABLE_ALREADY_EXISTS_FOR_ANOTHER_TYPE).replace("%1",r.name).replace("%2",r.type);t.alert(a,(function(){s(i)}))}else e.createVariable(i,n),o&&o(i)}else o&&o(null)}))};s("")},t.Variables.createVariable=t.Variables.createVariableButtonHandler,t.Variables.renameVariable=function(e,o,i){var n=function(s){var r=t.Msg.RENAME_VARIABLE_TITLE.replace("%1",o.name);t.Variables.promptName(r,s,(function(s){if(s){var r=t.Variables.nameUsedWithOtherType_(s,o.type,e);r?(r=t.Msg.VARIABLE_ALREADY_EXISTS_FOR_ANOTHER_TYPE.replace("%1",r.name).replace("%2",r.type),t.alert(r,(function(){n(s)}))):(e.renameVariableById(o.getId(),s),i&&i(s))}else i&&i(null)}))};n("")},t.Variables.promptName=function(e,o,i){t.prompt(e,o,(function(e){e&&((e=e.replace(/[\s\xa0]+/g," ").trim())==t.Msg.RENAME_VARIABLE||e==t.Msg.NEW_VARIABLE)&&(e=null),i(e)}))},t.Variables.nameUsedWithOtherType_=function(t,e,o){o=o.getVariableMap().getAllVariables(),t=t.toLowerCase();for(var i,n=0;i=o[n];n++)if(i.name.toLowerCase()==t&&i.type!=e)return i;return null},t.Variables.nameUsedWithAnyType_=function(t,e){e=e.getVariableMap().getAllVariables(),t=t.toLowerCase();for(var o,i=0;o=e[i];i++)if(o.name.toLowerCase()==t)return o;return null},t.Variables.generateVariableFieldDom=function(e){var o=t.utils.xml.createElement("field");return o.setAttribute("name","VAR"),o.setAttribute("id",e.getId()),o.setAttribute("variabletype",e.type),e=t.utils.xml.createTextNode(e.name),o.appendChild(e),o},t.Variables.getOrCreateVariablePackage=function(e,o,i,n){var s=t.Variables.getVariable(e,o,i,n);return s||(s=t.Variables.createVariable_(e,o,i,n)),s},t.Variables.getVariable=function(t,e,o,i){var n=t.getPotentialVariableMap(),s=null;if(e&&(!(s=t.getVariableById(e))&&n&&(s=n.getVariableById(e)),s))return s;if(o){if(null==i)throw Error("Tried to look up a variable by name without a type");!(s=t.getVariable(o,i))&&n&&(s=n.getVariable(o,i))}return s},t.Variables.createVariable_=function(e,o,i,n){var s=e.getPotentialVariableMap();return i||(i=t.Variables.generateUniqueName(e.isFlyout?e.targetWorkspace:e)),s?s.createVariable(i,n,o):e.createVariable(i,n,o)},t.Variables.getAddedVariables=function(t,e){t=t.getAllVariables();var o=[];if(e.length!=t.length)for(var i=0;i<t.length;i++){var n=t[i];-1==e.indexOf(n)&&o.push(n)}return o},t.WidgetDiv={},t.WidgetDiv.owner_=null,t.WidgetDiv.dispose_=null,t.WidgetDiv.rendererClassName_="",t.WidgetDiv.themeClassName_="",t.WidgetDiv.createDom=function(){t.WidgetDiv.DIV||(t.WidgetDiv.DIV=document.createElement("div"),t.WidgetDiv.DIV.className="blocklyWidgetDiv",(t.parentContainer||document.body).appendChild(t.WidgetDiv.DIV))},t.WidgetDiv.show=function(e,o,i){t.WidgetDiv.hide(),t.WidgetDiv.owner_=e,t.WidgetDiv.dispose_=i,(e=t.WidgetDiv.DIV).style.direction=o?"rtl":"ltr",e.style.display="block",t.WidgetDiv.rendererClassName_=t.getMainWorkspace().getRenderer().getClassName(),t.WidgetDiv.themeClassName_=t.getMainWorkspace().getTheme().getClassName(),t.utils.dom.addClass(e,t.WidgetDiv.rendererClassName_),t.utils.dom.addClass(e,t.WidgetDiv.themeClassName_)},t.WidgetDiv.hide=function(){if(t.WidgetDiv.isVisible()){t.WidgetDiv.owner_=null;var e=t.WidgetDiv.DIV;e.style.display="none",e.style.left="",e.style.top="",t.WidgetDiv.dispose_&&t.WidgetDiv.dispose_(),t.WidgetDiv.dispose_=null,e.textContent="",t.WidgetDiv.rendererClassName_&&(t.utils.dom.removeClass(e,t.WidgetDiv.rendererClassName_),t.WidgetDiv.rendererClassName_=""),t.WidgetDiv.themeClassName_&&(t.utils.dom.removeClass(e,t.WidgetDiv.themeClassName_),t.WidgetDiv.themeClassName_=""),t.getMainWorkspace().markFocused()}},t.WidgetDiv.isVisible=function(){return!!t.WidgetDiv.owner_},t.WidgetDiv.hideIfOwner=function(e){t.WidgetDiv.owner_==e&&t.WidgetDiv.hide()},t.WidgetDiv.positionInternal_=function(e,o,i){t.WidgetDiv.DIV.style.left=e+"px",t.WidgetDiv.DIV.style.top=o+"px",t.WidgetDiv.DIV.style.height=i+"px"},t.WidgetDiv.positionWithAnchor=function(e,o,i,n){var s=t.WidgetDiv.calculateY_(e,o,i);e=t.WidgetDiv.calculateX_(e,o,i,n),0>s?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;o<e.length;o++){var i=e[o];if(i){var n=i.type;null==n||""===n?console.warn("Block definition #"+o+" in JSON array is missing a type attribute. Skipping."):(t.Blocks[n]&&console.warn("Block definition #"+o+' in JSON array overwrites prior definition of "'+n+'".'),t.Blocks[n]={init:t.jsonInitFactory_(i)})}else console.warn("Block definition #"+o+" in JSON array is "+i+". Skipping.")}},t.bindEventWithChecks_=function(e,o,i,n,s,r){var a=!1,l=function(e){var o=!s;e=t.Touch.splitEventByTouches(e);for(var r,l=0;r=e[l];l++)o&&!t.Touch.shouldHandleEvent(r)||(t.Touch.setClientFromTouch(r),i?n.call(i,r):n(r),a=!0)},c=[];if(t.utils.global.PointerEvent&&o in t.Touch.TOUCH_MAP)for(var h,u=0;h=t.Touch.TOUCH_MAP[o][u];u++)e.addEventListener(h,l,!1),c.push([e,h,l]);else if(e.addEventListener(o,l,!1),c.push([e,o,l]),o in t.Touch.TOUCH_MAP){var p=function(t){l(t),a&&!r&&t.preventDefault()};for(u=0;h=t.Touch.TOUCH_MAP[o][u];u++)e.addEventListener(h,p,!1),c.push([e,h,p])}return c},t.bindEvent_=function(e,o,i,n){var s=function(t){i?n.call(i,t):n(t)},r=[];if(t.utils.global.PointerEvent&&o in t.Touch.TOUCH_MAP)for(var a,l=0;a=t.Touch.TOUCH_MAP[o][l];l++)e.addEventListener(a,s,!1),r.push([e,a,s]);else if(e.addEventListener(o,s,!1),r.push([e,o,s]),o in t.Touch.TOUCH_MAP){var c=function(t){if(t.changedTouches&&1==t.changedTouches.length){var e=t.changedTouches[0];t.clientX=e.clientX,t.clientY=e.clientY}s(t),t.preventDefault()};for(l=0;a=t.Touch.TOUCH_MAP[o][l];l++)e.addEventListener(a,c,!1),r.push([e,a,c])}return r},t.unbindEvent_=function(t){for(;t.length;){var e=t.pop(),o=e[2];e[0].removeEventListener(e[1],o,!1)}return o},t.isNumber=function(t){return/^\s*-?\d+(\.\d+)?\s*$/.test(t)},t.hueToHex=function(e){return t.utils.colour.hsvToHex(e,t.HSV_SATURATION,255*t.HSV_VALUE)},t.checkBlockColourConstants=function(){t.checkBlockColourConstant_("LOGIC_HUE",["Blocks","logic","HUE"],void 0),t.checkBlockColourConstant_("LOGIC_HUE",["Constants","Logic","HUE"],210),t.checkBlockColourConstant_("LOOPS_HUE",["Blocks","loops","HUE"],void 0),t.checkBlockColourConstant_("LOOPS_HUE",["Constants","Loops","HUE"],120),t.checkBlockColourConstant_("MATH_HUE",["Blocks","math","HUE"],void 0),t.checkBlockColourConstant_("MATH_HUE",["Constants","Math","HUE"],230),t.checkBlockColourConstant_("TEXTS_HUE",["Blocks","texts","HUE"],void 0),t.checkBlockColourConstant_("TEXTS_HUE",["Constants","Text","HUE"],160),t.checkBlockColourConstant_("LISTS_HUE",["Blocks","lists","HUE"],void 0),t.checkBlockColourConstant_("LISTS_HUE",["Constants","Lists","HUE"],260),t.checkBlockColourConstant_("COLOUR_HUE",["Blocks","colour","HUE"],void 0),t.checkBlockColourConstant_("COLOUR_HUE",["Constants","Colour","HUE"],20),t.checkBlockColourConstant_("VARIABLES_HUE",["Blocks","variables","HUE"],void 0),t.checkBlockColourConstant_("VARIABLES_HUE",["Constants","Variables","HUE"],330),t.checkBlockColourConstant_("VARIABLES_DYNAMIC_HUE",["Constants","VariablesDynamic","HUE"],310),t.checkBlockColourConstant_("PROCEDURES_HUE",["Blocks","procedures","HUE"],void 0)},t.checkBlockColourConstant_=function(e,o,i){for(var n="Blockly",s=t,r=0;r<o.length;++r)n+="."+o[r],s&&(s=s[o[r]]);s&&s!==i&&(e=(void 0===i?'%1 has been removed. Use Blockly.Msg["%2"].':'%1 is deprecated and unused. Override Blockly.Msg["%2"].').replace("%1",n).replace("%2",e),console.warn(e))},t.setParentContainer=function(e){t.parentContainer=e},t.Icon=function(t){this.block_=t},t.Icon.prototype.collapseHidden=!0,t.Icon.prototype.SIZE=17,t.Icon.prototype.bubble_=null,t.Icon.prototype.iconXY_=null,t.Icon.prototype.createIcon=function(){this.iconGroup_||(this.iconGroup_=t.utils.dom.createSvgElement("g",{class:"blocklyIconGroup"},null),this.block_.isInFlyout&&t.utils.dom.addClass(this.iconGroup_,"blocklyIconGroupReadonly"),this.drawIcon_(this.iconGroup_),this.block_.getSvgRoot().appendChild(this.iconGroup_),t.bindEventWithChecks_(this.iconGroup_,"mouseup",this,this.iconClick_),this.updateEditable())},t.Icon.prototype.dispose=function(){t.utils.dom.removeNode(this.iconGroup_),this.iconGroup_=null,this.setVisible(!1),this.block_=null},t.Icon.prototype.updateEditable=function(){},t.Icon.prototype.isVisible=function(){return!!this.bubble_},t.Icon.prototype.iconClick_=function(e){this.block_.workspace.isDragging()||this.block_.isInFlyout||t.utils.isRightButton(e)||this.setVisible(!this.isVisible())},t.Icon.prototype.applyColour=function(){this.isVisible()&&this.bubble_.setColour(this.block_.style.colourPrimary)},t.Icon.prototype.setIconLocation=function(t){this.iconXY_=t,this.isVisible()&&this.bubble_.setAnchorLocation(t)},t.Icon.prototype.computeIconLocation=function(){var e=this.block_.getRelativeToSurfaceXY(),o=t.utils.getRelativeXY(this.iconGroup_);e=new t.utils.Coordinate(e.x+o.x+this.SIZE/2,e.y+o.y+this.SIZE/2),t.utils.Coordinate.equals(this.getIconLocation(),e)||this.setIconLocation(e)},t.Icon.prototype.getIconLocation=function(){return this.iconXY_},t.Icon.prototype.getCorrectedSize=function(){return new t.utils.Size(t.Icon.prototype.SIZE,t.Icon.prototype.SIZE-2)},t.Warning=function(e){t.Warning.superClass_.constructor.call(this,e),this.createIcon(),this.text_={}},t.utils.object.inherits(t.Warning,t.Icon),t.Warning.prototype.collapseHidden=!1,t.Warning.prototype.drawIcon_=function(e){t.utils.dom.createSvgElement("path",{class:"blocklyIconShape",d:"M2,15Q-1,15 0.5,12L6.5,1.7Q8,-1 9.5,1.7L15.5,12Q17,15 14,15z"},e),t.utils.dom.createSvgElement("path",{class:"blocklyIconSymbol",d:"m7,4.8v3.16l0.27,2.27h1.46l0.27,-2.27v-3.16z"},e),t.utils.dom.createSvgElement("rect",{class:"blocklyIconSymbol",x:"7",y:"11",height:"2",width:"2"},e)},t.Warning.textToDom_=function(e){var o=t.utils.dom.createSvgElement("text",{class:"blocklyText blocklyBubbleText blocklyNoPointerEvents",y:t.Bubble.BORDER_WIDTH},null);e=e.split("\n");for(var i=0;i<e.length;i++){var n=t.utils.dom.createSvgElement("tspan",{dy:"1em",x:t.Bubble.BORDER_WIDTH},o),s=document.createTextNode(e[i]);n.appendChild(s)}return o},t.Warning.prototype.setVisible=function(e){e!=this.isVisible()&&(t.Events.fire(new t.Events.Ui(this.block_,"warningOpen",!e,e)),e?this.createBubble():this.disposeBubble())},t.Warning.prototype.createBubble=function(){if(this.paragraphElement_=t.Warning.textToDom_(this.getText()),this.bubble_=new t.Bubble(this.block_.workspace,this.paragraphElement_,this.block_.pathObject.svgPath,this.iconXY_,null,null),this.bubble_.setSvgId(this.block_.id),this.block_.RTL)for(var e,o=this.paragraphElement_.getBBox().width,i=0;e=this.paragraphElement_.childNodes[i];i++)e.setAttribute("text-anchor","end"),e.setAttribute("x",o+t.Bubble.BORDER_WIDTH);this.applyColour()},t.Warning.prototype.disposeBubble=function(){this.bubble_.dispose(),this.paragraphElement_=this.body_=this.bubble_=null},t.Warning.prototype.bodyFocus_=function(t){this.bubble_.promote()},t.Warning.prototype.setText=function(t,e){this.text_[e]!=t&&(t?this.text_[e]=t:delete this.text_[e],this.isVisible()&&(this.setVisible(!1),this.setVisible(!0)))},t.Warning.prototype.getText=function(){var t,e=[];for(t in this.text_)e.push(this.text_[t]);return e.join("\n")},t.Warning.prototype.dispose=function(){this.block_.warning=null,t.Icon.prototype.dispose.call(this)},t.Comment=function(e){t.Comment.superClass_.constructor.call(this,e),this.model_=e.commentModel,this.model_.text=this.model_.text||"",this.cachedText_="",this.onInputWrapper_=this.onChangeWrapper_=this.onWheelWrapper_=this.onMouseUpWrapper_=null,this.createIcon()},t.utils.object.inherits(t.Comment,t.Icon),t.Comment.prototype.drawIcon_=function(e){t.utils.dom.createSvgElement("circle",{class:"blocklyIconShape",r:"8",cx:"8",cy:"8"},e),t.utils.dom.createSvgElement("path",{class:"blocklyIconSymbol",d:"m6.8,10h2c0.003,-0.617 0.271,-0.962 0.633,-1.266 2.875,-2.4050.607,-5.534 -3.765,-3.874v1.7c3.12,-1.657 3.698,0.118 2.336,1.25-1.201,0.998 -1.201,1.528 -1.204,2.19z"},e),t.utils.dom.createSvgElement("rect",{class:"blocklyIconSymbol",x:"6.8",y:"10.78",height:"2",width:"2"},e)},t.Comment.prototype.createEditor_=function(){this.foreignObject_=t.utils.dom.createSvgElement("foreignObject",{x:t.Bubble.BORDER_WIDTH,y:t.Bubble.BORDER_WIDTH},null);var e=document.createElementNS(t.utils.dom.HTML_NS,"body");e.setAttribute("xmlns",t.utils.dom.HTML_NS),e.className="blocklyMinimalBody";var o=this.textarea_=document.createElementNS(t.utils.dom.HTML_NS,"textarea");return o.className="blocklyCommentTextarea",o.setAttribute("dir",this.block_.RTL?"RTL":"LTR"),o.value=this.model_.text,this.resizeTextarea_(),e.appendChild(o),this.foreignObject_.appendChild(e),this.onMouseUpWrapper_=t.bindEventWithChecks_(o,"mouseup",this,this.startEdit_,!0,!0),this.onWheelWrapper_=t.bindEventWithChecks_(o,"wheel",this,(function(t){t.stopPropagation()})),this.onChangeWrapper_=t.bindEventWithChecks_(o,"change",this,(function(e){this.cachedText_!=this.model_.text&&t.Events.fire(new t.Events.BlockChange(this.block_,"comment",null,this.cachedText_,this.model_.text))})),this.onInputWrapper_=t.bindEventWithChecks_(o,"input",this,(function(t){this.model_.text=o.value})),setTimeout(o.focus.bind(o),0),this.foreignObject_},t.Comment.prototype.updateEditable=function(){t.Comment.superClass_.updateEditable.call(this),this.isVisible()&&(this.disposeBubble_(),this.createBubble_())},t.Comment.prototype.onBubbleResize_=function(){this.isVisible()&&(this.model_.size=this.bubble_.getBubbleSize(),this.resizeTextarea_())},t.Comment.prototype.resizeTextarea_=function(){var e=this.model_.size,o=2*t.Bubble.BORDER_WIDTH,i=e.width-o;e=e.height-o,this.foreignObject_.setAttribute("width",i),this.foreignObject_.setAttribute("height",e),this.textarea_.style.width=i-4+"px",this.textarea_.style.height=e-4+"px"},t.Comment.prototype.setVisible=function(e){e!=this.isVisible()&&(t.Events.fire(new t.Events.Ui(this.block_,"commentOpen",!e,e)),(this.model_.pinned=e)?this.createBubble_():this.disposeBubble_())},t.Comment.prototype.createBubble_=function(){!this.block_.isEditable()||t.utils.userAgent.IE?this.createNonEditableBubble_():this.createEditableBubble_()},t.Comment.prototype.createEditableBubble_=function(){this.bubble_=new t.Bubble(this.block_.workspace,this.createEditor_(),this.block_.pathObject.svgPath,this.iconXY_,this.model_.size.width,this.model_.size.height),this.bubble_.setSvgId(this.block_.id),this.bubble_.registerResizeEvent(this.onBubbleResize_.bind(this)),this.applyColour()},t.Comment.prototype.createNonEditableBubble_=function(){t.Warning.prototype.createBubble.call(this)},t.Comment.prototype.disposeBubble_=function(){this.paragraphElement_?t.Warning.prototype.disposeBubble.call(this):(this.onMouseUpWrapper_&&(t.unbindEvent_(this.onMouseUpWrapper_),this.onMouseUpWrapper_=null),this.onWheelWrapper_&&(t.unbindEvent_(this.onWheelWrapper_),this.onWheelWrapper_=null),this.onChangeWrapper_&&(t.unbindEvent_(this.onChangeWrapper_),this.onChangeWrapper_=null),this.onInputWrapper_&&(t.unbindEvent_(this.onInputWrapper_),this.onInputWrapper_=null),this.bubble_.dispose(),this.foreignObject_=this.textarea_=this.bubble_=null)},t.Comment.prototype.startEdit_=function(t){this.bubble_.promote()&&this.textarea_.focus(),this.cachedText_=this.model_.text},t.Comment.prototype.getBubbleSize=function(){return this.model_.size},t.Comment.prototype.setBubbleSize=function(t,e){this.bubble_?this.bubble_.setBubbleSize(t,e):(this.model_.size.width=t,this.model_.size.height=e)},t.Comment.prototype.getText=function(){return this.model_.text||""},t.Comment.prototype.setText=function(t){this.model_.text!=t&&(this.model_.text=t,this.updateText())},t.Comment.prototype.updateText=function(){this.textarea_?this.textarea_.value=this.model_.text:this.paragraphElement_&&(this.paragraphElement_.firstChild.textContent=this.model_.text)},t.Comment.prototype.dispose=function(){this.block_.comment=null,t.Icon.prototype.dispose.call(this)},t.Css.register(".blocklyCommentTextarea {,background-color: #fef49c;,border: 0;,outline: 0;,margin: 0;,padding: 3px;,resize: none;,display: block;,overflow: hidden;,}".split(",")),t.FlyoutCursor=function(){t.FlyoutCursor.superClass_.constructor.call(this)},t.utils.object.inherits(t.FlyoutCursor,t.Cursor),t.FlyoutCursor.prototype.onBlocklyAction=function(e){switch(e.name){case t.navigation.actionNames.PREVIOUS:return this.prev(),!0;case t.navigation.actionNames.NEXT:return this.next(),!0;default:return!1}},t.FlyoutCursor.prototype.next=function(){var t=this.getCurNode();return t?((t=t.next())&&this.setCurNode(t),t):null},t.FlyoutCursor.prototype.in=function(){return null},t.FlyoutCursor.prototype.prev=function(){var t=this.getCurNode();return t?((t=t.prev())&&this.setCurNode(t),t):null},t.FlyoutCursor.prototype.out=function(){return null},t.Flyout=function(e){e.getMetrics=this.getMetrics_.bind(this),e.setMetrics=this.setMetrics_.bind(this),this.workspace_=new t.WorkspaceSvg(e),this.workspace_.isFlyout=!0,this.workspace_.setVisible(this.isVisible_),this.RTL=!!e.RTL,this.toolboxPosition_=e.toolboxPosition,this.eventWrappers_=[],this.mats_=[],this.buttons_=[],this.listeners_=[],this.permanentlyDisabled_=[],this.tabWidth_=this.workspace_.getRenderer().getConstants().TAB_WIDTH},t.Flyout.prototype.autoClose=!0,t.Flyout.prototype.isVisible_=!1,t.Flyout.prototype.containerVisible_=!0,t.Flyout.prototype.CORNER_RADIUS=8,t.Flyout.prototype.MARGIN=t.Flyout.prototype.CORNER_RADIUS,t.Flyout.prototype.GAP_X=3*t.Flyout.prototype.MARGIN,t.Flyout.prototype.GAP_Y=3*t.Flyout.prototype.MARGIN,t.Flyout.prototype.SCROLLBAR_PADDING=2,t.Flyout.prototype.width_=0,t.Flyout.prototype.height_=0,t.Flyout.prototype.dragAngleRange_=70,t.Flyout.prototype.createDom=function(e){return this.svgGroup_=t.utils.dom.createSvgElement(e,{class:"blocklyFlyout",style:"display: none"},null),this.svgBackground_=t.utils.dom.createSvgElement("path",{class:"blocklyFlyoutBackground"},this.svgGroup_),this.svgGroup_.appendChild(this.workspace_.createDom()),this.workspace_.getThemeManager().subscribe(this.svgBackground_,"flyoutBackgroundColour","fill"),this.workspace_.getThemeManager().subscribe(this.svgBackground_,"flyoutOpacity","fill-opacity"),this.workspace_.getMarkerManager().setCursor(new t.FlyoutCursor),this.svgGroup_},t.Flyout.prototype.init=function(e){this.targetWorkspace_=e,this.workspace_.targetWorkspace=e,this.scrollbar_=new t.Scrollbar(this.workspace_,this.horizontalLayout_,!1,"blocklyFlyoutScrollbar"),this.hide(),Array.prototype.push.apply(this.eventWrappers_,t.bindEventWithChecks_(this.svgGroup_,"wheel",this,this.wheel_)),this.autoClose||(this.filterWrapper_=this.filterForCapacity_.bind(this),this.targetWorkspace_.addChangeListener(this.filterWrapper_)),Array.prototype.push.apply(this.eventWrappers_,t.bindEventWithChecks_(this.svgBackground_,"mousedown",this,this.onMouseDown_)),this.workspace_.getGesture=this.targetWorkspace_.getGesture.bind(this.targetWorkspace_),this.workspace_.setVariableMap(this.targetWorkspace_.getVariableMap()),this.workspace_.createPotentialVariableMap()},t.Flyout.prototype.dispose=function(){this.hide(),t.unbindEvent_(this.eventWrappers_),this.filterWrapper_&&(this.targetWorkspace_.removeChangeListener(this.filterWrapper_),this.filterWrapper_=null),this.scrollbar_&&(this.scrollbar_.dispose(),this.scrollbar_=null),this.workspace_&&(this.workspace_.getThemeManager().unsubscribe(this.svgBackground_),this.workspace_.targetWorkspace=null,this.workspace_.dispose(),this.workspace_=null),this.svgGroup_&&(t.utils.dom.removeNode(this.svgGroup_),this.svgGroup_=null),this.targetWorkspace_=this.svgBackground_=null},t.Flyout.prototype.getWidth=function(){return this.width_},t.Flyout.prototype.getHeight=function(){return this.height_},t.Flyout.prototype.getWorkspace=function(){return this.workspace_},t.Flyout.prototype.isVisible=function(){return this.isVisible_},t.Flyout.prototype.setVisible=function(t){var e=t!=this.isVisible();this.isVisible_=t,e&&this.updateDisplay_()},t.Flyout.prototype.setContainerVisible=function(t){var e=t!=this.containerVisible_;this.containerVisible_=t,e&&this.updateDisplay_()},t.Flyout.prototype.updateDisplay_=function(){var t=!!this.containerVisible_&&this.isVisible();this.svgGroup_.style.display=t?"block":"none",this.scrollbar_.setContainerVisible(t)},t.Flyout.prototype.positionAt_=function(e,o,i,n){this.svgGroup_.setAttribute("width",e),this.svgGroup_.setAttribute("height",o),"svg"==this.svgGroup_.tagName?t.utils.dom.setCssTransform(this.svgGroup_,"translate("+i+"px,"+n+"px)"):this.svgGroup_.setAttribute("transform","translate("+i+","+n+")"),this.scrollbar_&&(this.scrollbar_.setOrigin(i,n),this.scrollbar_.resize(),this.scrollbar_.setPosition_(this.scrollbar_.position_.x,this.scrollbar_.position_.y))},t.Flyout.prototype.hide=function(){if(this.isVisible()){this.setVisible(!1);for(var e,o=0;e=this.listeners_[o];o++)t.unbindEvent_(e);this.listeners_.length=0,this.reflowWrapper_&&(this.workspace_.removeChangeListener(this.reflowWrapper_),this.reflowWrapper_=null)}},t.Flyout.prototype.show=function(e){if(this.workspace_.setResizesEnabled(!1),this.hide(),this.clearOldBlocks_(),"string"==typeof e){if("function"!=typeof(e=this.workspace_.targetWorkspace.getToolboxCategoryCallback(e)))throw TypeError("Couldn't find a callback function when opening a toolbox category.");if(e=e(this.workspace_.targetWorkspace),!Array.isArray(e))throw TypeError("Result of toolbox category callback must be an array.")}this.setVisible(!0);var o=[],i=[];this.permanentlyDisabled_.length=0;for(var n,s=this.horizontalLayout_?this.GAP_X:this.GAP_Y,r=0;n=e[r];r++)if(n.tagName)switch(n.tagName.toUpperCase()){case"BLOCK":var a=t.Xml.domToBlock(n,this.workspace_);a.isEnabled()||this.permanentlyDisabled_.push(a),o.push({type:"block",block:a}),n=parseInt(n.getAttribute("gap"),10),i.push(isNaN(n)?s:n);break;case"SEP":n=parseInt(n.getAttribute("gap"),10),!isNaN(n)&&0<i.length?i[i.length-1]=n:i.push(s);break;case"LABEL":case"BUTTON":if(a="LABEL"==n.tagName.toUpperCase(),!t.FlyoutButton)throw Error("Missing require for Blockly.FlyoutButton");n=new t.FlyoutButton(this.workspace_,this.targetWorkspace_,n,a),o.push({type:"button",button:n}),i.push(s)}this.layout_(o,i),this.listeners_.push(t.bindEventWithChecks_(this.svgBackground_,"mouseover",this,(function(){for(var t,e=this.workspace_.getTopBlocks(!1),o=0;t=e[o];o++)t.removeSelect()}))),this.horizontalLayout_?this.height_=0:this.width_=0,this.workspace_.setResizesEnabled(!0),this.reflow(),this.filterForCapacity_(),this.position(),this.reflowWrapper_=this.reflow.bind(this),this.workspace_.addChangeListener(this.reflowWrapper_)},t.Flyout.prototype.clearOldBlocks_=function(){for(var e,o=this.workspace_.getTopBlocks(!1),i=0;e=o[i];i++)e.workspace==this.workspace_&&e.dispose(!1,!1);for(i=0;i<this.mats_.length;i++)(o=this.mats_[i])&&(t.Tooltip.unbindMouseEvents(o),t.utils.dom.removeNode(o));for(i=this.mats_.length=0;o=this.buttons_[i];i++)o.dispose();this.buttons_.length=0,this.workspace_.getPotentialVariableMap().clear()},t.Flyout.prototype.addBlockListeners_=function(e,o,i){this.listeners_.push(t.bindEventWithChecks_(e,"mousedown",null,this.blockMouseDown_(o))),this.listeners_.push(t.bindEventWithChecks_(i,"mousedown",null,this.blockMouseDown_(o))),this.listeners_.push(t.bindEvent_(e,"mouseenter",o,o.addSelect)),this.listeners_.push(t.bindEvent_(e,"mouseleave",o,o.removeSelect)),this.listeners_.push(t.bindEvent_(i,"mouseenter",o,o.addSelect)),this.listeners_.push(t.bindEvent_(i,"mouseleave",o,o.removeSelect))},t.Flyout.prototype.blockMouseDown_=function(t){var e=this;return function(o){var i=e.targetWorkspace_.getGesture(o);i&&(i.setStartBlock(t),i.handleFlyoutStart(o,e))}},t.Flyout.prototype.onMouseDown_=function(t){var e=this.targetWorkspace_.getGesture(t);e&&e.handleFlyoutStart(t,this)},t.Flyout.prototype.isBlockCreatable_=function(t){return t.isEnabled()},t.Flyout.prototype.createBlock=function(e){var o=null;t.Events.disable();var i=this.targetWorkspace_.getAllVariables();this.targetWorkspace_.setResizesEnabled(!1);try{o=this.placeNewBlock_(e),t.hideChaff()}finally{t.Events.enable()}if(e=t.Variables.getAddedVariables(this.targetWorkspace_,i),t.Events.isEnabled())for(t.Events.setGroup(!0),t.Events.fire(new t.Events.Create(o)),i=0;i<e.length;i++)t.Events.fire(new t.Events.VarCreate(e[i]));return this.autoClose?this.hide():this.filterForCapacity_(),o},t.Flyout.prototype.initFlyoutButton_=function(e,o,i){var n=e.createDom();e.moveTo(o,i),e.show(),this.listeners_.push(t.bindEventWithChecks_(n,"mousedown",this,this.onMouseDown_)),this.buttons_.push(e)},t.Flyout.prototype.createRect_=function(e,o,i,n,s){return(o=t.utils.dom.createSvgElement("rect",{"fill-opacity":0,x:o,y:i,height:n.height,width:n.width},null)).tooltip=e,t.Tooltip.bindMouseEvents(o),this.workspace_.getCanvas().insertBefore(o,e.getSvgRoot()),e.flyoutRect_=o,this.mats_[s]=o},t.Flyout.prototype.moveRectToBlock_=function(t,e){var o=e.getHeightWidth();t.setAttribute("width",o.width),t.setAttribute("height",o.height),e=e.getRelativeToSurfaceXY(),t.setAttribute("y",e.y),t.setAttribute("x",this.RTL?e.x-o.width:e.x)},t.Flyout.prototype.filterForCapacity_=function(){for(var e,o=this.workspace_.getTopBlocks(!1),i=0;e=o[i];i++)if(-1==this.permanentlyDisabled_.indexOf(e))for(var n=this.targetWorkspace_.isCapacityAvailable(t.utils.getBlockTypeCounts(e));e;)e.setEnabled(n),e=e.getNextBlock()},t.Flyout.prototype.reflow=function(){this.reflowWrapper_&&this.workspace_.removeChangeListener(this.reflowWrapper_),this.reflowInternal_(),this.reflowWrapper_&&this.workspace_.addChangeListener(this.reflowWrapper_)},t.Flyout.prototype.isScrollable=function(){return!!this.scrollbar_&&this.scrollbar_.isVisible()},t.Flyout.prototype.placeNewBlock_=function(e){var o=this.targetWorkspace_;if(!e.getSvgRoot())throw Error("oldBlock is not rendered.");var i=t.Xml.blockToDom(e,!0);if(o.setResizesEnabled(!1),!(i=t.Xml.domToBlock(i,o)).getSvgRoot())throw Error("block is not rendered.");var n=o.getOriginOffsetInPixels(),s=this.workspace_.getOriginOffsetInPixels();return(e=e.getRelativeToSurfaceXY()).scale(this.workspace_.scale),e=t.utils.Coordinate.sum(s,e),(n=t.utils.Coordinate.difference(e,n)).scale(1/o.scale),i.moveBy(n.x,n.y),i},t.Flyout.prototype.onBlocklyAction=function(t){return this.workspace_.getCursor().onBlocklyAction(t)},t.HorizontalFlyout=function(e){e.getMetrics=this.getMetrics_.bind(this),e.setMetrics=this.setMetrics_.bind(this),t.HorizontalFlyout.superClass_.constructor.call(this,e),this.horizontalLayout_=!0},t.utils.object.inherits(t.HorizontalFlyout,t.Flyout),t.HorizontalFlyout.prototype.getMetrics_=function(){if(!this.isVisible())return null;try{var e=this.workspace_.getCanvas().getBBox()}catch(t){e={height:0,y:0,width:0,x:0}}var o=this.SCROLLBAR_PADDING,i=this.SCROLLBAR_PADDING;this.toolboxPosition_==t.TOOLBOX_AT_BOTTOM&&(o=0);var n=this.height_;return this.toolboxPosition_==t.TOOLBOX_AT_TOP&&(n-=this.SCROLLBAR_PADDING),{viewHeight:n,viewWidth:this.width_-2*this.SCROLLBAR_PADDING,contentHeight:(e.height+2*this.MARGIN)*this.workspace_.scale,contentWidth:(e.width+2*this.MARGIN)*this.workspace_.scale,viewTop:-this.workspace_.scrollY,viewLeft:-this.workspace_.scrollX,contentTop:0,contentLeft:0,absoluteTop:o,absoluteLeft:i}},t.HorizontalFlyout.prototype.setMetrics_=function(t){var e=this.getMetrics_();e&&("number"==typeof t.x&&(this.workspace_.scrollX=-e.contentWidth*t.x),this.workspace_.translate(this.workspace_.scrollX+e.absoluteLeft,this.workspace_.scrollY+e.absoluteTop))},t.HorizontalFlyout.prototype.position=function(){if(this.isVisible()){var e=this.targetWorkspace_.getMetrics();e&&(this.width_=e.viewWidth,this.setBackgroundPath_(e.viewWidth-2*this.CORNER_RADIUS,this.height_-this.CORNER_RADIUS),this.positionAt_(this.width_,this.height_,0,this.targetWorkspace_.toolboxPosition==this.toolboxPosition_?e.toolboxHeight?this.toolboxPosition_==t.TOOLBOX_AT_TOP?e.toolboxHeight:e.viewHeight-this.height_:this.toolboxPosition_==t.TOOLBOX_AT_TOP?0:e.viewHeight:this.toolboxPosition_==t.TOOLBOX_AT_TOP?0:e.viewHeight+e.absoluteTop-this.height_))}},t.HorizontalFlyout.prototype.setBackgroundPath_=function(e,o){var i=this.toolboxPosition_==t.TOOLBOX_AT_TOP,n=["M 0,"+(i?0:this.CORNER_RADIUS)];i?(n.push("h",e+2*this.CORNER_RADIUS),n.push("v",o),n.push("a",this.CORNER_RADIUS,this.CORNER_RADIUS,0,0,1,-this.CORNER_RADIUS,this.CORNER_RADIUS),n.push("h",-e),n.push("a",this.CORNER_RADIUS,this.CORNER_RADIUS,0,0,1,-this.CORNER_RADIUS,-this.CORNER_RADIUS)):(n.push("a",this.CORNER_RADIUS,this.CORNER_RADIUS,0,0,1,this.CORNER_RADIUS,-this.CORNER_RADIUS),n.push("h",e),n.push("a",this.CORNER_RADIUS,this.CORNER_RADIUS,0,0,1,this.CORNER_RADIUS,this.CORNER_RADIUS),n.push("v",o),n.push("h",-e-2*this.CORNER_RADIUS)),n.push("z"),this.svgBackground_.setAttribute("d",n.join(" "))},t.HorizontalFlyout.prototype.scrollToStart=function(){this.scrollbar_.set(this.RTL?1/0:0)},t.HorizontalFlyout.prototype.wheel_=function(e){var o=t.utils.getScrollDeltaPixels(e),i=o.x||o.y;i&&(i=(o=this.getMetrics_()).viewLeft+i,i=Math.min(i,o.contentWidth-o.viewWidth),i=Math.max(i,0),this.scrollbar_.set(i),t.WidgetDiv.hide()),e.preventDefault(),e.stopPropagation()},t.HorizontalFlyout.prototype.layout_=function(t,e){this.workspace_.scale=this.targetWorkspace_.scale;var o=this.MARGIN,i=o+this.tabWidth_;this.RTL&&(t=t.reverse());for(var n,s=0;n=t[s];s++)if("block"==n.type){for(var r,a=(n=n.block).getDescendants(!1),l=0;r=a[l];l++)r.isInFlyout=!0;n.render(),a=n.getSvgRoot(),l=n.getHeightWidth(),r=n.outputConnection?this.tabWidth_:0,r=this.RTL?i+l.width:i-r,n.moveBy(r,o),r=this.createRect_(n,r,o,l,s),i+=l.width+e[s],this.addBlockListeners_(a,n,r)}else"button"==n.type&&(this.initFlyoutButton_(n.button,i,o),i+=n.button.width+e[s])},t.HorizontalFlyout.prototype.isDragTowardWorkspace=function(t){t=Math.atan2(t.y,t.x)/Math.PI*180;var e=this.dragAngleRange_;return t<90+e&&t>90-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>-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;o<t.length;o++){var i=t[o].getCommentText();i&&e.push(i)}return e.length&&e.push(""),e.join("\n")},t.Generator.prototype.blockToCode=function(t,e){if(!t)return"";if(!t.isEnabled())return e?"":this.blockToCode(t.getNextBlock());var o=this[t.type];if("function"!=typeof o)throw Error('Language "'+this.name_+'" does not know how to generate  code for block type "'+t.type+'".');if(o=o.call(t,t),Array.isArray(o)){if(!t.outputConnection)throw TypeError("Expecting string from statement block: "+t.type);return[this.scrub_(t,o[0],e),o[1]]}if("string"==typeof o)return this.STATEMENT_PREFIX&&!t.suppressPrefixSuffix&&(o=this.injectId(this.STATEMENT_PREFIX,t)+o),this.STATEMENT_SUFFIX&&!t.suppressPrefixSuffix&&(o+=this.injectId(this.STATEMENT_SUFFIX,t)),this.scrub_(t,o,e);if(null===o)return"";throw SyntaxError("Invalid code generated: "+o)},t.Generator.prototype.valueToCode=function(t,e,o){if(isNaN(o))throw TypeError("Expecting valid order from block: "+t.type);var i=t.getInputTargetBlock(e);if(!i)return"";if(""===(e=this.blockToCode(i)))return"";if(!Array.isArray(e))throw TypeError("Expecting tuple from value block: "+i.type);if(t=e[0],e=e[1],isNaN(e))throw TypeError("Expecting valid order from value block: "+i.type);if(!t)return"";i=!1;var n=Math.floor(o),s=Math.floor(e);if(n<=s&&(n!=s||0!=n&&99!=n))for(i=!0,n=0;n<this.ORDER_OVERRIDES.length;n++)if(this.ORDER_OVERRIDES[n][0]==o&&this.ORDER_OVERRIDES[n][1]==e){i=!1;break}return i&&(t="("+t+")"),t},t.Generator.prototype.statementToCode=function(t,e){if(t=t.getInputTargetBlock(e),"string"!=typeof(e=this.blockToCode(t)))throw TypeError("Expecting code from statement block: "+(t&&t.type));return e&&(e=this.prefixLines(e,this.INDENT)),e},t.Generator.prototype.addLoopTrap=function(t,e){return this.INFINITE_LOOP_TRAP&&(t=this.prefixLines(this.injectId(this.INFINITE_LOOP_TRAP,e),this.INDENT)+t),this.STATEMENT_SUFFIX&&!e.suppressPrefixSuffix&&(t=this.prefixLines(this.injectId(this.STATEMENT_SUFFIX,e),this.INDENT)+t),this.STATEMENT_PREFIX&&!e.suppressPrefixSuffix&&(t+=this.prefixLines(this.injectId(this.STATEMENT_PREFIX,e),this.INDENT)),t},t.Generator.prototype.injectId=function(t,e){return e=e.id.replace(/\$/g,"$$$$"),t.replace(/%1/g,"'"+e+"'")},t.Generator.prototype.RESERVED_WORDS_="",t.Generator.prototype.addReservedWords=function(t){this.RESERVED_WORDS_+=t+","},t.Generator.prototype.FUNCTION_NAME_PLACEHOLDER_="{leCUI8hutHZI4480Dc}",t.Generator.prototype.provideFunction_=function(e,o){if(!this.definitions_[e]){var i,n=this.variableDB_.getDistinctName(e,t.PROCEDURE_CATEGORY_NAME);for(this.functionNames_[e]=n,o=o.join("\n").replace(this.FUNCTION_NAME_PLACEHOLDER_REGEXP_,n);i!=o;)i=o,o=o.replace(/^(( {2})*) {2}/gm,"$1\0");o=o.replace(/\0/g,this.INDENT),this.definitions_[e]=o}return this.functionNames_[e]},t.Generator.prototype.init=function(t){},t.Generator.prototype.scrub_=function(t,e,o){return e},t.Generator.prototype.finish=function(t){return t},t.Generator.prototype.scrubNakedValue=function(t){return t},t.tree={},t.tree.BaseNode=function(e,o){t.Component.call(this),this.content=e,this.config_=o,this.expanded_=this.selected_=!1,this.isUserCollapsible_=!0,this.depth_=-1},t.utils.object.inherits(t.tree.BaseNode,t.Component),t.tree.BaseNode.allNodes={},t.tree.BaseNode.prototype.disposeInternal=function(){t.tree.BaseNode.superClass_.disposeInternal.call(this),this.tree&&(this.tree=null),this.setElementInternal(null)},t.tree.BaseNode.prototype.initAccessibility=function(){var e=this.getElement();if(e){var o=this.getLabelElement();if(o&&!o.id&&(o.id=this.getId()+".label"),t.utils.aria.setRole(e,t.utils.aria.Role.TREEITEM),t.utils.aria.setState(e,t.utils.aria.State.SELECTED,!1),t.utils.aria.setState(e,t.utils.aria.State.LEVEL,this.getDepth()),o&&t.utils.aria.setState(e,t.utils.aria.State.LABELLEDBY,o.id),(o=this.getIconElement())&&t.utils.aria.setRole(o,t.utils.aria.Role.PRESENTATION),(o=this.getChildrenElement())&&(t.utils.aria.setRole(o,t.utils.aria.Role.GROUP),o.hasChildNodes()))for(t.utils.aria.setState(e,t.utils.aria.State.EXPANDED,!1),e=this.getChildCount(),o=1;o<=e;o++){var i=this.getChildAt(o-1).getElement();t.utils.aria.setState(i,t.utils.aria.State.SETSIZE,e),t.utils.aria.setState(i,t.utils.aria.State.POSINSET,o)}}},t.tree.BaseNode.prototype.createDom=function(){var t=document.createElement("div");t.appendChild(this.toDom()),this.setElementInternal(t)},t.tree.BaseNode.prototype.enterDocument=function(){t.tree.BaseNode.superClass_.enterDocument.call(this),t.tree.BaseNode.allNodes[this.getId()]=this,this.initAccessibility()},t.tree.BaseNode.prototype.exitDocument=function(){t.tree.BaseNode.superClass_.exitDocument.call(this),delete t.tree.BaseNode.allNodes[this.getId()]},t.tree.BaseNode.prototype.addChildAt=function(e,o){var i=this.getChildAt(o-1),n=this.getChildAt(o);if(t.tree.BaseNode.superClass_.addChildAt.call(this,e,o),e.previousSibling_=i,e.nextSibling_=n,i&&(i.nextSibling_=e),n&&(n.previousSibling_=e),(o=this.getTree())&&e.setTreeInternal(o),e.setDepth_(this.getDepth()+1),(o=this.getElement())&&(this.updateExpandIcon(),t.utils.aria.setState(o,t.utils.aria.State.EXPANDED,this.expanded_),this.expanded_)){o=this.getChildrenElement(),e.getElement()||e.createDom();var s=e.getElement(),r=n&&n.getElement();o.insertBefore(s,r),this.isInDocument()&&e.enterDocument(),n||(i?i.updateExpandIcon():(t.utils.style.setElementShown(o,!0),this.setExpanded(this.expanded_)))}},t.tree.BaseNode.prototype.add=function(e){if(e.getParent())throw Error(t.Component.Error.PARENT_UNABLE_TO_BE_SET);this.addChildAt(e,this.getChildCount())},t.tree.BaseNode.prototype.getTree=function(){return null},t.tree.BaseNode.prototype.getDepth=function(){var t=this.depth_;return 0>t&&(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("<<<PATH>>>/handdelete.cur"), auto;',"}",".blocklyToolboxGrab {",'cursor: url("<<<PATH>>>/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(<<<PATH>>>/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("<<<PATH>>>/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 0<this.workspace_.options.maxTrashcanContents&&(t.utils.dom.insertAfter(this.flyout.createDom("svg"),this.workspace_.getParentSvg()),this.flyout.init(this.workspace_)),this.verticalSpacing_=this.MARGIN_BOTTOM_+e,this.setOpen(!1),this.verticalSpacing_+this.BODY_HEIGHT_+this.LID_HEIGHT_},t.Trashcan.prototype.dispose=function(){this.svgGroup_&&(t.utils.dom.removeNode(this.svgGroup_),this.svgGroup_=null),this.workspace_=this.svgLid_=null,clearTimeout(this.lidTask_)},t.Trashcan.prototype.contentsIsOpen=function(){return this.flyout.isVisible()},t.Trashcan.prototype.emptyContents=function(){this.contents_.length&&(this.contents_.length=0,this.setMinOpenness_(0),this.contentsIsOpen()&&this.flyout.hide())},t.Trashcan.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,this.top_=e.toolboxPosition==t.TOOLBOX_AT_BOTTOM?this.verticalSpacing_:e.viewHeight+e.absoluteTop-(this.BODY_HEIGHT_+this.LID_HEIGHT_)-this.verticalSpacing_,this.svgGroup_.setAttribute("transform","translate("+this.left_+","+this.top_+")"))}},t.Trashcan.prototype.getClientRect=function(){if(!this.svgGroup_)return null;var e=this.svgGroup_.getBoundingClientRect(),o=e.top+this.SPRITE_TOP_-this.MARGIN_HOTSPOT_;return e=e.left+this.SPRITE_LEFT_-this.MARGIN_HOTSPOT_,new t.utils.Rect(o,o+this.LID_HEIGHT_+this.BODY_HEIGHT_+2*this.MARGIN_HOTSPOT_,e,e+this.WIDTH_+2*this.MARGIN_HOTSPOT_)},t.Trashcan.prototype.setOpen=function(t){this.isOpen!=t&&(clearTimeout(this.lidTask_),this.isOpen=t,this.animateLid_())},t.Trashcan.prototype.animateLid_=function(){var e=t.Trashcan.ANIMATION_FRAMES_,o=1/(e+1);this.lidOpen_+=this.isOpen?o:-o,this.lidOpen_=Math.min(Math.max(this.lidOpen_,this.minOpenness_),1),this.setLidAngle_(this.lidOpen_*t.Trashcan.MAX_LID_ANGLE_),o=t.Trashcan.OPACITY_MIN_,this.svgGroup_.style.opacity=o+this.lidOpen_*(t.Trashcan.OPACITY_MAX_-o),this.lidOpen_>this.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.length;o++){var i=e[o];i.setStyle(i.getStyleName())}for(t=t.getFlyout().workspace_.getAllBlocks(!1),o=0;o<t.length;o++)(i=t[o]).setStyle(i.getStyleName())}},t.Mutator.reconnect=function(t,e,o){if(!t||!t.getSourceBlock().workspace)return!1;o=e.getInput(o).connection;var i=t.targetBlock();return!(i&&i!=e||o.targetConnection==t||(o.isConnected()&&o.disconnect(),o.connect(t),0))},t.Mutator.findParentWs=function(t){var e=null;if(t&&t.options){var o=t.options.parentWorkspace;t.isFlyout?o&&o.options&&(e=o.options.parentWorkspace):o&&(e=o)}return e},t.FieldTextInput=function(e,o,i){this.spellcheck_=!0,null==e&&(e=""),t.FieldTextInput.superClass_.constructor.call(this,e,o,i),this.onKeyInputWrapper_=this.onKeyDownWrapper_=this.htmlInput_=null,this.fullBlockClickTarget_=!1},t.utils.object.inherits(t.FieldTextInput,t.Field),t.FieldTextInput.fromJson=function(e){var o=t.utils.replaceMessageReferences(e.text);return new t.FieldTextInput(o,void 0,e)},t.FieldTextInput.prototype.SERIALIZABLE=!0,t.FieldTextInput.BORDERRADIUS=4,t.FieldTextInput.prototype.CURSOR="text",t.FieldTextInput.prototype.configure_=function(e){t.FieldTextInput.superClass_.configure_.call(this,e),"boolean"==typeof e.spellcheck&&(this.spellcheck_=e.spellcheck)},t.FieldTextInput.prototype.initView=function(){if(this.getConstants().FULL_BLOCK_FIELDS){for(var t,e=0,o=0,i=0;t=this.sourceBlock_.inputList[i];i++){for(var n=0;t.fieldRow[n];n++)e++;t.connection&&o++}this.fullBlockClickTarget_=1>=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<e&&(o+=360),o=this.clockwise_?this.offset_+360-o:360-(this.offset_-o),this.displayMouseOrKeyboardValue_(o))},t.FieldAngle.prototype.displayMouseOrKeyboardValue_=function(t){this.round_&&(t=Math.round(t/this.round_)*this.round_),(t=this.wrapValue_(t))!=this.value_&&this.setEditorValue_(t)},t.FieldAngle.prototype.updateGraph_=function(){if(this.gauge_){var e=Number(this.getText())+this.offset_,o=t.utils.math.toRadians(e%360);e=["M ",t.FieldAngle.HALF,",",t.FieldAngle.HALF];var i=t.FieldAngle.HALF,n=t.FieldAngle.HALF;if(!isNaN(o)){var s=Number(this.clockwise_),r=t.utils.math.toRadians(this.offset_),a=Math.cos(r)*t.FieldAngle.RADIUS,l=Math.sin(r)*-t.FieldAngle.RADIUS;s&&(o=2*r-o),i+=Math.cos(o)*t.FieldAngle.RADIUS,n-=Math.sin(o)*t.FieldAngle.RADIUS,o=Math.abs(Math.floor((o-r)/Math.PI)%2),s&&(o=1-o),e.push(" l ",a,",",l," A ",t.FieldAngle.RADIUS,",",t.FieldAngle.RADIUS," 0 ",o," ",s," ",i,",",n," z")}this.gauge_.setAttribute("d",e.join("")),this.line_.setAttribute("x2",i),this.line_.setAttribute("y2",n)}},t.FieldAngle.prototype.onHtmlInputKeyDown_=function(e){var o;if(t.FieldAngle.superClass_.onHtmlInputKeyDown_.call(this,e),e.keyCode===t.utils.KeyCodes.LEFT?o=this.sourceBlock_.RTL?1:-1:e.keyCode===t.utils.KeyCodes.RIGHT?o=this.sourceBlock_.RTL?-1:1:e.keyCode===t.utils.KeyCodes.DOWN?o=-1:e.keyCode===t.utils.KeyCodes.UP&&(o=1),o){var i=this.getValue();this.displayMouseOrKeyboardValue_(i+o*this.round_),e.preventDefault(),e.stopPropagation()}},t.FieldAngle.prototype.doClassValidation_=function(t){return t=Number(t),isNaN(t)||!isFinite(t)?null:this.wrapValue_(t)},t.FieldAngle.prototype.wrapValue_=function(t){return 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&&0<r?(s=n-1,r--):0>s&&(s=0):0<e?s>n-1&&r<Math.floor(i.length/n)-1?(s=0,r++):s>n-1&&s--:0>o?0>r&&(r=0):0<o&&r>Math.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;a<o.length;a++){0==a%e&&(r=document.createElement("tr"),t.utils.aria.setRole(r,t.utils.aria.Role.ROW),s.appendChild(r));var l=document.createElement("td");r.appendChild(l),l.label=o[a],l.title=i[a]||o[a],l.id=t.utils.IdGenerator.getNextUniqueId(),l.setAttribute("data-index",a),t.utils.aria.setRole(l,t.utils.aria.Role.GRIDCELL),t.utils.aria.setState(l,t.utils.aria.State.LABEL,o[a]),t.utils.aria.setState(l,t.utils.aria.State.SELECTED,o[a]==n),l.style.backgroundColor=o[a],o[a]==n&&(l.className="blocklyColourSelected",this.highlightedIndex_=a)}return this.onClickWrapper_=t.bindEventWithChecks_(s,"click",this,this.onClick_,!0),this.onMouseMoveWrapper_=t.bindEventWithChecks_(s,"mousemove",this,this.onMouseMove_,!0),this.onMouseEnterWrapper_=t.bindEventWithChecks_(s,"mouseenter",this,this.onMouseEnter_,!0),this.onMouseLeaveWrapper_=t.bindEventWithChecks_(s,"mouseleave",this,this.onMouseLeave_,!0),this.onKeyDownWrapper_=t.bindEventWithChecks_(s,"keydown",this,this.onKeyDown_),s},t.FieldColour.prototype.dropdownDispose_=function(){this.onClickWrapper_&&(t.unbindEvent_(this.onClickWrapper_),this.onClickWrapper_=null),this.onMouseMoveWrapper_&&(t.unbindEvent_(this.onMouseMoveWrapper_),this.onMouseMoveWrapper_=null),this.onMouseEnterWrapper_&&(t.unbindEvent_(this.onMouseEnterWrapper_),this.onMouseEnterWrapper_=null),this.onMouseLeaveWrapper_&&(t.unbindEvent_(this.onMouseLeaveWrapper_),this.onMouseLeaveWrapper_=null),this.onKeyDownWrapper_&&(t.unbindEvent_(this.onKeyDownWrapper_),this.onKeyDownWrapper_=null),this.highlightedIndex_=this.picker_=null},t.Css.register([".blocklyColourTable {","border-collapse: collapse;","display: block;","outline: none;","padding: 1px;","}",".blocklyColourTable>tr>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;i<o.length;i++){var n=o[i][0],s=o[i][1];if("object"==typeof n){var r=new Image(n.width,n.height);r.src=n.src,r.alt=n.alt||"",n=r}(n=new t.MenuItem(n)).setRole(t.utils.aria.Role.OPTION),n.setRightToLeft(this.sourceBlock_.RTL),n.setValue(s),n.setCheckable(!0),e.addChild(n,!0),n.setChecked(s==this.value_),s==this.value_&&(this.selectedMenuItem_=n),n.onAction(this.handleMenuActionEvent_,this)}return t.utils.aria.setState(e.getElement(),t.utils.aria.State.ACTIVEDESCENDANT,this.selectedMenuItem_?this.selectedMenuItem_.getId():""),e},t.FieldDropdown.prototype.dropdownDispose_=function(){this.menu_&&this.menu_.dispose(),this.selectedMenuItem_=this.menu_=null,this.applyColour()},t.FieldDropdown.prototype.handleMenuActionEvent_=function(e){t.DropDownDiv.hideIfOwner(this,!0),this.onItemSelected_(this.menu_,e)},t.FieldDropdown.prototype.onItemSelected_=function(t,e){this.setValue(e.getValue())},t.FieldDropdown.prototype.trimOptions_=function(){this.suffixField=this.prefixField=null;var e=this.menuGenerator_;if(Array.isArray(e)){for(var o=!1,i=0;i<e.length;i++){var n=e[i][0];"string"==typeof n?e[i][0]=t.utils.replaceMessageReferences(n):(null!=n.alt&&(e[i][0].alt=t.utils.replaceMessageReferences(n.alt)),o=!0)}if(!(o||2>e.length)){for(o=[],i=0;i<e.length;i++)o.push(e[i][0]);i=t.utils.string.shortestStringLength(o),n=t.utils.string.commonWordPrefix(o,i);var s=t.utils.string.commonWordSuffix(o,i);!n&&!s||i<=n+s||(n&&(this.prefixField=o[0].substring(0,n-1)),s&&(this.suffixField=o[0].substr(1-s)),this.menuGenerator_=t.FieldDropdown.applyTrim_(e,n,s))}}},t.FieldDropdown.applyTrim_=function(t,e,o){for(var i=[],n=0;n<t.length;n++){var s=t[n][0],r=t[n][1];s=s.substring(e,s.length-o),i[n]=[s,r]}return i},t.FieldDropdown.prototype.isOptionListDynamic=function(){return"function"==typeof this.menuGenerator_},t.FieldDropdown.prototype.getOptions=function(e){return this.isOptionListDynamic()?(this.generatedOptions_&&e||(this.generatedOptions_=this.menuGenerator_.call(this),t.FieldDropdown.validateOptions_(this.generatedOptions_)),this.generatedOptions_):this.menuGenerator_},t.FieldDropdown.prototype.doClassValidation_=function(t){for(var e,o=!1,i=this.getOptions(!0),n=0;e=i[n];n++)if(e[1]==t){o=!0;break}return o?t:(this.sourceBlock_&&console.warn("Cannot set the dropdown's value to an unavailable option. Block type: "+this.sourceBlock_.type+", Field name: "+this.name+", Value: "+t),null)},t.FieldDropdown.prototype.doValueUpdate_=function(e){t.FieldDropdown.superClass_.doValueUpdate_.call(this,e),e=this.getOptions(!0);for(var o,i=0;o=e[i];i++)o[1]==this.value_&&(this.selectedOption_=o)},t.FieldDropdown.prototype.applyColour=function(){this.borderRect_&&(this.borderRect_.setAttribute("stroke",this.sourceBlock_.style.colourTertiary),this.menu_?this.borderRect_.setAttribute("fill",this.sourceBlock_.style.colourTertiary):this.borderRect_.setAttribute("fill","transparent")),this.sourceBlock_&&this.arrow_&&(this.sourceBlock_.isShadow()?this.arrow_.style.fill=this.sourceBlock_.style.colourSecondary:this.arrow_.style.fill=this.sourceBlock_.style.colourPrimary)},t.FieldDropdown.prototype.render_=function(){this.textContent_.nodeValue="",this.imageElement_.style.display="none";var t=this.selectedOption_&&this.selectedOption_[0];t&&"object"==typeof t?this.renderSelectedImage_(t):this.renderSelectedText_(),this.positionBorderRect_()},t.FieldDropdown.prototype.renderSelectedImage_=function(e){this.imageElement_.style.display="",this.imageElement_.setAttributeNS(t.utils.dom.XLINK_NS,"xlink:href",e.src),this.imageElement_.setAttribute("height",e.height),this.imageElement_.setAttribute("width",e.width);var o=Number(e.height);e=Number(e.width);var i=!!this.borderRect_,n=Math.max(i?this.getConstants().FIELD_DROPDOWN_BORDER_RECT_HEIGHT:0,o+t.FieldDropdown.IMAGE_Y_PADDING);i=i?this.getConstants().FIELD_BORDER_RECT_X_PADDING:0;var s=this.svgArrow_?this.positionSVGArrow_(e+i,n/2-this.getConstants().FIELD_DROPDOWN_SVG_ARROW_SIZE/2):t.utils.dom.getFastTextWidth(this.arrow_,this.getConstants().FIELD_TEXT_FONTSIZE,this.getConstants().FIELD_TEXT_FONTWEIGHT,this.getConstants().FIELD_TEXT_FONTFAMILY);this.size_.width=e+s+2*i,this.size_.height=n;var r=0;this.sourceBlock_.RTL?this.imageElement_.setAttribute("x",i+s):(r=e+s,this.textElement_.setAttribute("text-anchor","end"),this.imageElement_.setAttribute("x",i)),this.imageElement_.setAttribute("y",n/2-o/2),this.positionTextElement_(r+i,e+s)},t.FieldDropdown.prototype.renderSelectedText_=function(){this.textContent_.nodeValue=this.getDisplayText_(),t.utils.dom.addClass(this.textElement_,"blocklyDropdownText"),this.textElement_.setAttribute("text-anchor","start");var e=!!this.borderRect_,o=Math.max(e?this.getConstants().FIELD_DROPDOWN_BORDER_RECT_HEIGHT:0,this.getConstants().FIELD_TEXT_HEIGHT),i=t.utils.dom.getFastTextWidth(this.textElement_,this.getConstants().FIELD_TEXT_FONTSIZE,this.getConstants().FIELD_TEXT_FONTWEIGHT,this.getConstants().FIELD_TEXT_FONTFAMILY);e=e?this.getConstants().FIELD_BORDER_RECT_X_PADDING:0;var n=0;this.svgArrow_&&(n=this.positionSVGArrow_(i+e,o/2-this.getConstants().FIELD_DROPDOWN_SVG_ARROW_SIZE/2)),this.size_.width=i+n+2*e,this.size_.height=o,this.positionTextElement_(e,i)},t.FieldDropdown.prototype.positionSVGArrow_=function(t,e){if(!this.svgArrow_)return 0;var o=this.borderRect_?this.getConstants().FIELD_BORDER_RECT_X_PADDING:0,i=this.getConstants().FIELD_DROPDOWN_SVG_ARROW_PADDING,n=this.getConstants().FIELD_DROPDOWN_SVG_ARROW_SIZE;return this.svgArrow_.setAttribute("transform","translate("+(this.sourceBlock_.RTL?o:t+i)+","+e+")"),n+i},t.FieldDropdown.prototype.getText_=function(){if(!this.selectedOption_)return null;var t=this.selectedOption_[0];return"object"==typeof t?t.alt:t},t.FieldDropdown.validateOptions_=function(t){if(!Array.isArray(t))throw TypeError("FieldDropdown options must be an array.");if(!t.length)throw TypeError("FieldDropdown options must not be an empty array.");for(var e=!1,o=0;o<t.length;++o){var i=t[o];Array.isArray(i)?"string"!=typeof i[1]?(e=!0,console.error("Invalid option["+o+"]: Each FieldDropdown option id must be a string. Found "+i[1]+" in: ",i)):i[0]&&"string"!=typeof i[0]&&"string"!=typeof i[0].src&&(e=!0,console.error("Invalid option["+o+"]: Each FieldDropdown option must have a string label or image description. Found"+i[0]+" in: ",i)):(e=!0,console.error("Invalid option["+o+"]: Each FieldDropdown option must be an array. Found: ",i))}if(e)throw TypeError("Found invalid FieldDropdown options.")},t.FieldDropdown.prototype.onBlocklyAction=function(e){if(this.menu_){if(e===t.navigation.ACTION_PREVIOUS)return this.menu_.highlightPrevious(),!0;if(e===t.navigation.ACTION_NEXT)return this.menu_.highlightNext(),!0}return t.FieldDropdown.superClass_.onBlocklyAction.call(this,e)},t.fieldRegistry.register("field_dropdown",t.FieldDropdown),t.FieldLabelSerializable=function(e,o,i){t.FieldLabelSerializable.superClass_.constructor.call(this,e,o,i)},t.utils.object.inherits(t.FieldLabelSerializable,t.FieldLabel),t.FieldLabelSerializable.fromJson=function(e){var o=t.utils.replaceMessageReferences(e.text);return new t.FieldLabelSerializable(o,void 0,e)},t.FieldLabelSerializable.prototype.EDITABLE=!1,t.FieldLabelSerializable.prototype.SERIALIZABLE=!0,t.fieldRegistry.register("field_label_serializable",t.FieldLabelSerializable),t.FieldImage=function(e,o,i,n,s,r,a){if(!e)throw Error("Src value of an image field is required");if(e=t.utils.replaceMessageReferences(e),i=Number(t.utils.replaceMessageReferences(i)),o=Number(t.utils.replaceMessageReferences(o)),isNaN(i)||isNaN(o))throw Error("Height and width values of an image field must cast to numbers.");if(0>=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;i<o.length;i++){var n=o[i];n.length>this.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;i<e.length;i++){var n=this.getConstants().FIELD_TEXT_HEIGHT+this.getConstants().FIELD_BORDER_RECT_Y_PADDING;t.utils.dom.createSvgElement("text",{class:"blocklyText blocklyMultilineText",x:this.getConstants().FIELD_BORDER_RECT_X_PADDING,y:o+this.getConstants().FIELD_BORDER_RECT_Y_PADDING,dy:this.getConstants().FIELD_TEXT_BASELINE},this.textGroup_).appendChild(document.createTextNode(e[i])),o+=n}this.updateSize_(),this.isBeingEdited_&&(this.sourceBlock_.RTL?setTimeout(this.resizeEditor_.bind(this),0):this.resizeEditor_(),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.FieldMultilineInput.prototype.updateSize_=function(){for(var e=this.textGroup_.childNodes,o=0,i=0,n=0;n<e.length;n++){var s=t.utils.dom.getTextWidth(e[n]);s>o&&(o=s),i+=this.getConstants().FIELD_TEXT_HEIGHT+(0<n?this.getConstants().FIELD_BORDER_RECT_Y_PADDING:0)}this.borderRect_&&(i+=2*this.getConstants().FIELD_BORDER_RECT_Y_PADDING,o+=2*this.getConstants().FIELD_BORDER_RECT_X_PADDING,this.borderRect_.setAttribute("width",o),this.borderRect_.setAttribute("height",i)),this.size_.width=o,this.size_.height=i,this.positionBorderRect_()},t.FieldMultilineInput.prototype.widgetCreate_=function(){var e=t.WidgetDiv.DIV,o=this.workspace_.getScale(),i=document.createElement("textarea");i.className="blocklyHtmlInput blocklyHtmlTextAreaInput",i.setAttribute("spellcheck",this.spellcheck_);var n=this.getConstants().FIELD_TEXT_FONTSIZE*o+"pt";e.style.fontSize=n,i.style.fontSize=n,i.style.borderRadius=t.FieldTextInput.BORDERRADIUS*o+"px",n=this.getConstants().FIELD_BORDER_RECT_X_PADDING*o;var s=this.getConstants().FIELD_BORDER_RECT_Y_PADDING*o/2;return i.style.padding=s+"px "+n+"px "+s+"px "+n+"px",n=this.getConstants().FIELD_TEXT_HEIGHT+this.getConstants().FIELD_BORDER_RECT_Y_PADDING,i.style.lineHeight=n*o+"px",e.appendChild(i),i.value=i.defaultValue=this.getEditorText_(this.value_),i.untypedDefaultValue_=this.value_,i.oldValue_=null,t.utils.userAgent.GECKO?setTimeout(this.resizeEditor_.bind(this),0):this.resizeEditor_(),this.bindInputEvents_(i),i},t.FieldMultilineInput.prototype.onHtmlInputKeyDown_=function(e){e.keyCode!==t.utils.KeyCodes.ENTER&&t.FieldMultilineInput.superClass_.onHtmlInputKeyDown_.call(this,e)},t.Css.register(".blocklyHtmlTextAreaInput {,font-family: monospace;,resize: none;,overflow: hidden;,height: 100%;,text-align: left;,}".split(",")),t.fieldRegistry.register("field_multilinetext",t.FieldMultilineInput),t.FieldNumber=function(e,o,i,n,s,r){this.min_=-1/0,this.max_=1/0,this.precision_=0,this.decimalPlaces_=null,t.FieldNumber.superClass_.constructor.call(this,e||0,s,r),r||this.setConstraints(o,i,n)},t.utils.object.inherits(t.FieldNumber,t.FieldTextInput),t.FieldNumber.fromJson=function(e){return new t.FieldNumber(e.value,void 0,void 0,void 0,void 0,e)},t.FieldNumber.prototype.SERIALIZABLE=!0,t.FieldNumber.prototype.configure_=function(e){t.FieldNumber.superClass_.configure_.call(this,e),this.setMinInternal_(e.min),this.setMaxInternal_(e.max),this.setPrecisionInternal_(e.precision)},t.FieldNumber.prototype.setConstraints=function(t,e,o){this.setMinInternal_(t),this.setMaxInternal_(e),this.setPrecisionInternal_(o),this.setValue(this.getValue())},t.FieldNumber.prototype.setMin=function(t){this.setMinInternal_(t),this.setValue(this.getValue())},t.FieldNumber.prototype.setMinInternal_=function(t){null==t?this.min_=-1/0:(t=Number(t),isNaN(t)||(this.min_=t))},t.FieldNumber.prototype.getMin=function(){return this.min_},t.FieldNumber.prototype.setMax=function(t){this.setMaxInternal_(t),this.setValue(this.getValue())},t.FieldNumber.prototype.setMaxInternal_=function(t){null==t?this.max_=1/0:(t=Number(t),isNaN(t)||(this.max_=t))},t.FieldNumber.prototype.getMax=function(){return this.max_},t.FieldNumber.prototype.setPrecision=function(t){this.setPrecisionInternal_(t),this.setValue(this.getValue())},t.FieldNumber.prototype.setPrecisionInternal_=function(t){null==t?this.precision_=0:(t=Number(t),isNaN(t)||(this.precision_=t));var e=this.precision_.toString(),o=e.indexOf(".");this.decimalPlaces_=-1==o?t?0:null:e.length-o-1},t.FieldNumber.prototype.getPrecision=function(){return this.precision_},t.FieldNumber.prototype.doClassValidation_=function(t){return null===t?null:(t=(t=(t=(t=String(t)).replace(/O/gi,"0")).replace(/,/g,"")).replace(/infinity/i,"Infinity"),t=Number(t||0),isNaN(t)?null:(t=Math.min(Math.max(t,this.min_),this.max_),this.precision_&&isFinite(t)&&(t=Math.round(t/this.precision_)*this.precision_),null!=this.decimalPlaces_&&(t=Number(t.toFixed(this.decimalPlaces_))),t))},t.FieldNumber.prototype.widgetCreate_=function(){var e=t.FieldNumber.superClass_.widgetCreate_.call(this);return-1/0<this.min_&&t.utils.aria.setState(e,t.utils.aria.State.VALUEMIN,this.min_),1/0>this.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;o<e.length;o++)if(t==e[o])return!0;return!1},t.FieldVariable.prototype.getVariableTypes_=function(){var t=this.variableTypes;if(null===t&&this.sourceBlock_&&this.sourceBlock_.workspace)return this.sourceBlock_.workspace.getVariableTypes();if(0==(t=t||[""]).length)throw t=this.getText(),Error("'variableTypes' of field variable "+t+" was an empty list");return t},t.FieldVariable.prototype.setTypes_=function(t,e){if(e=e||"",null==t||null==t)t=null;else{if(!Array.isArray(t))throw Error("'variableTypes' was not an array in the definition of a FieldVariable");for(var o=!1,i=0;i<t.length;i++)t[i]==e&&(o=!0);if(!o)throw Error("Invalid default type '"+e+"' in the definition of a FieldVariable")}this.defaultType_=e,this.variableTypes=t},t.FieldVariable.prototype.refreshVariableName=function(){this.forceRerender()},t.FieldVariable.dropdownCreate=function(){if(!this.variable_)throw Error("Tried to call dropdownCreate on a variable field with no variable selected.");var e=this.getText(),o=[];if(this.sourceBlock_&&this.sourceBlock_.workspace)for(var i=this.getVariableTypes_(),n=0;n<i.length;n++){var s=this.sourceBlock_.workspace.getVariablesOfType(i[n]);o=o.concat(s)}for(o.sort(t.VariableModel.compareByName),i=[],n=0;n<o.length;n++)i[n]=[o[n].name,o[n].getId()];return i.push([t.Msg.RENAME_VARIABLE,t.RENAME_VARIABLE_ID]),t.Msg.DELETE_VARIABLE&&i.push([t.Msg.DELETE_VARIABLE.replace("%1",e),t.DELETE_VARIABLE_ID]),i},t.FieldVariable.prototype.onItemSelected_=function(e,o){if(e=o.getValue(),this.sourceBlock_&&this.sourceBlock_.workspace){if(e==t.RENAME_VARIABLE_ID)return void t.Variables.renameVariable(this.sourceBlock_.workspace,this.variable_);if(e==t.DELETE_VARIABLE_ID)return void this.sourceBlock_.workspace.deleteVariableById(this.variable_.getId())}this.setValue(e)},t.FieldVariable.prototype.referencesVariables=function(){return!0},t.fieldRegistry.register("field_variable",t.FieldVariable),t.utils.svgPaths={},t.utils.svgPaths.point=function(t,e){return" "+t+","+e+" "},t.utils.svgPaths.curve=function(t,e){return" "+t+e.join("")},t.utils.svgPaths.moveTo=function(t,e){return" M "+t+","+e+" "},t.utils.svgPaths.moveBy=function(t,e){return" m "+t+","+e+" "},t.utils.svgPaths.lineTo=function(t,e){return" l "+t+","+e+" "},t.utils.svgPaths.line=function(t){return" l"+t.join("")},t.utils.svgPaths.lineOnAxis=function(t,e){return" "+t+" "+e+" "},t.utils.svgPaths.arc=function(t,e,o,i){return t+" "+o+" "+o+" "+e+i},t.blockRendering.ConstantProvider=function(){this.NO_PADDING=0,this.SMALL_PADDING=3,this.MEDIUM_PADDING=5,this.MEDIUM_LARGE_PADDING=8,this.LARGE_PADDING=10,this.TALL_INPUT_FIELD_OFFSET_Y=this.MEDIUM_PADDING,this.TAB_HEIGHT=15,this.TAB_OFFSET_FROM_TOP=5,this.TAB_VERTICAL_OVERLAP=2.5,this.TAB_WIDTH=8,this.NOTCH_WIDTH=15,this.NOTCH_HEIGHT=4,this.MIN_BLOCK_WIDTH=12,this.EMPTY_BLOCK_SPACER_HEIGHT=16,this.DUMMY_INPUT_SHADOW_MIN_HEIGHT=this.DUMMY_INPUT_MIN_HEIGHT=this.TAB_HEIGHT,this.CORNER_RADIUS=8,this.STATEMENT_INPUT_NOTCH_OFFSET=this.NOTCH_OFFSET_LEFT=15,this.STATEMENT_BOTTOM_SPACER=0,this.STATEMENT_INPUT_PADDING_LEFT=20,this.BETWEEN_STATEMENT_PADDING_Y=4,this.TOP_ROW_MIN_HEIGHT=this.MEDIUM_PADDING,this.TOP_ROW_PRECEDES_STATEMENT_MIN_HEIGHT=this.LARGE_PADDING,this.BOTTOM_ROW_MIN_HEIGHT=this.MEDIUM_PADDING,this.BOTTOM_ROW_AFTER_STATEMENT_MIN_HEIGHT=this.LARGE_PADDING,this.ADD_START_HATS=!1,this.START_HAT_HEIGHT=15,this.START_HAT_WIDTH=100,this.SPACER_DEFAULT_HEIGHT=15,this.MIN_BLOCK_HEIGHT=24,this.EMPTY_INLINE_INPUT_PADDING=14.5,this.EMPTY_INLINE_INPUT_HEIGHT=this.TAB_HEIGHT+11,this.EXTERNAL_VALUE_INPUT_PADDING=2,this.EMPTY_STATEMENT_INPUT_HEIGHT=this.MIN_BLOCK_HEIGHT,this.START_POINT=t.utils.svgPaths.moveBy(0,0),this.JAGGED_TEETH_HEIGHT=12,this.JAGGED_TEETH_WIDTH=6,this.FIELD_TEXT_FONTSIZE=11,this.FIELD_TEXT_FONTWEIGHT="normal",this.FIELD_TEXT_FONTFAMILY="sans-serif",this.FIELD_TEXT_BASELINE=this.FIELD_TEXT_HEIGHT=-1,this.FIELD_BORDER_RECT_RADIUS=4,this.FIELD_BORDER_RECT_HEIGHT=16,this.FIELD_BORDER_RECT_X_PADDING=5,this.FIELD_BORDER_RECT_Y_PADDING=3,this.FIELD_BORDER_RECT_COLOUR="#fff",this.FIELD_TEXT_BASELINE_CENTER=!t.utils.userAgent.IE&&!t.utils.userAgent.EDGE,this.FIELD_DROPDOWN_BORDER_RECT_HEIGHT=this.FIELD_BORDER_RECT_HEIGHT,this.FIELD_DROPDOWN_SVG_ARROW=this.FIELD_DROPDOWN_COLOURED_DIV=this.FIELD_DROPDOWN_NO_BORDER_RECT_SHADOW=!1,this.FIELD_DROPDOWN_SVG_ARROW_PADDING=this.FIELD_BORDER_RECT_X_PADDING,this.FIELD_DROPDOWN_SVG_ARROW_SIZE=12,this.FIELD_DROPDOWN_SVG_ARROW_DATAURI="data:image/svg+xml;base64,PHN2ZyBpZD0iTGF5ZXJfMSIgZGF0YS1uYW1lPSJMYXllciAxIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxMi43MSIgaGVpZ2h0PSI4Ljc5IiB2aWV3Qm94PSIwIDAgMTIuNzEgOC43OSI+PHRpdGxlPmRyb3Bkb3duLWFycm93PC90aXRsZT48ZyBvcGFjaXR5PSIwLjEiPjxwYXRoIGQ9Ik0xMi43MSwyLjQ0QTIuNDEsMi40MSwwLDAsMSwxMiw0LjE2TDguMDgsOC4wOGEyLjQ1LDIuNDUsMCwwLDEtMy40NSwwTDAuNzIsNC4xNkEyLjQyLDIuNDIsMCwwLDEsMCwyLjQ0LDIuNDgsMi40OCwwLDAsMSwuNzEuNzFDMSwwLjQ3LDEuNDMsMCw2LjM2LDBTMTEuNzUsMC40NiwxMiwuNzFBMi40NCwyLjQ0LDAsMCwxLDEyLjcxLDIuNDRaIiBmaWxsPSIjMjMxZjIwIi8+PC9nPjxwYXRoIGQ9Ik02LjM2LDcuNzlhMS40MywxLjQzLDAsMCwxLTEtLjQyTDEuNDIsMy40NWExLjQ0LDEuNDQsMCwwLDEsMC0yYzAuNTYtLjU2LDkuMzEtMC41Niw5Ljg3LDBhMS40NCwxLjQ0LDAsMCwxLDAsMkw3LjM3LDcuMzdBMS40MywxLjQzLDAsMCwxLDYuMzYsNy43OVoiIGZpbGw9IiNmZmYiLz48L3N2Zz4=",this.FIELD_COLOUR_FULL_BLOCK=this.FIELD_TEXTINPUT_BOX_SHADOW=!1,this.FIELD_COLOUR_DEFAULT_WIDTH=26,this.FIELD_COLOUR_DEFAULT_HEIGHT=this.FIELD_BORDER_RECT_HEIGHT,this.FIELD_CHECKBOX_X_OFFSET=this.FIELD_BORDER_RECT_X_PADDING-3,this.randomIdentifier=String(Math.random()).substring(2),this.embossFilterId="",this.embossFilter_=null,this.disabledPatternId="",this.disabledPattern_=null,this.debugFilterId="",this.cssNode_=this.debugFilter_=null,this.CURSOR_COLOUR="#cc0a0a",this.MARKER_COLOUR="#4286f4",this.CURSOR_WS_WIDTH=100,this.WS_CURSOR_HEIGHT=5,this.CURSOR_STACK_PADDING=10,this.CURSOR_BLOCK_PADDING=2,this.CURSOR_STROKE_WIDTH=4,this.FULL_BLOCK_FIELDS=!1,this.INSERTION_MARKER_COLOUR="#000000",this.INSERTION_MARKER_OPACITY=.2,this.SHAPES={PUZZLE:1,NOTCH:2}},t.blockRendering.ConstantProvider.prototype.init=function(){this.JAGGED_TEETH=this.makeJaggedTeeth(),this.NOTCH=this.makeNotch(),this.START_HAT=this.makeStartHat(),this.PUZZLE_TAB=this.makePuzzleTab(),this.INSIDE_CORNERS=this.makeInsideCorners(),this.OUTSIDE_CORNERS=this.makeOutsideCorners()},t.blockRendering.ConstantProvider.prototype.setTheme=function(t){this.blockStyles={};var e,o=t.blockStyles;for(e in o)this.blockStyles[e]=this.validatedBlockStyle_(o[e]);this.setDynamicProperties_(t)},t.blockRendering.ConstantProvider.prototype.setDynamicProperties_=function(t){this.setFontConstants_(t),this.setComponentConstants_(t),this.ADD_START_HATS=null!=t.startHats?t.startHats:this.ADD_START_HATS},t.blockRendering.ConstantProvider.prototype.setFontConstants_=function(e){this.FIELD_TEXT_FONTFAMILY=e.fontStyle&&null!=e.fontStyle.family?e.fontStyle.family:this.FIELD_TEXT_FONTFAMILY,this.FIELD_TEXT_FONTWEIGHT=e.fontStyle&&null!=e.fontStyle.weight?e.fontStyle.weight:this.FIELD_TEXT_FONTWEIGHT,this.FIELD_TEXT_FONTSIZE=e.fontStyle&&null!=e.fontStyle.size?e.fontStyle.size:this.FIELD_TEXT_FONTSIZE,e=t.utils.dom.measureFontMetrics("Hg",this.FIELD_TEXT_FONTSIZE+"pt",this.FIELD_TEXT_FONTWEIGHT,this.FIELD_TEXT_FONTFAMILY),this.FIELD_TEXT_HEIGHT=e.height,this.FIELD_TEXT_BASELINE=e.baseline},t.blockRendering.ConstantProvider.prototype.setComponentConstants_=function(t){this.CURSOR_COLOUR=t.getComponentStyle("cursorColour")||this.CURSOR_COLOUR,this.MARKER_COLOUR=t.getComponentStyle("markerColour")||this.MARKER_COLOUR,this.INSERTION_MARKER_COLOUR=t.getComponentStyle("insertionMarkerColour")||this.INSERTION_MARKER_COLOUR,this.INSERTION_MARKER_OPACITY=Number(t.getComponentStyle("insertionMarkerOpacity"))||this.INSERTION_MARKER_OPACITY},t.blockRendering.ConstantProvider.prototype.getBlockStyleForColour=function(t){var e="auto_"+t;return this.blockStyles[e]||(this.blockStyles[e]=this.createBlockStyle_(t)),{style:this.blockStyles[e],name:e}},t.blockRendering.ConstantProvider.prototype.getBlockStyle=function(t){return this.blockStyles[t||""]||(t&&0==t.indexOf("auto_")?this.getBlockStyleForColour(t.substring(5)).style:this.createBlockStyle_("#000000"))},t.blockRendering.ConstantProvider.prototype.createBlockStyle_=function(t){return this.validatedBlockStyle_({colourPrimary:t})},t.blockRendering.ConstantProvider.prototype.validatedBlockStyle_=function(e){var o={};return e&&t.utils.object.mixin(o,e),e=t.utils.parseBlockColour(o.colourPrimary||"#000"),o.colourPrimary=e.hex,o.colourSecondary=o.colourSecondary?t.utils.parseBlockColour(o.colourSecondary).hex:this.generateSecondaryColour_(o.colourPrimary),o.colourTertiary=o.colourTertiary?t.utils.parseBlockColour(o.colourTertiary).hex:this.generateTertiaryColour_(o.colourPrimary),o.hat=o.hat||"",o},t.blockRendering.ConstantProvider.prototype.generateSecondaryColour_=function(e){return t.utils.colour.blend("#fff",e,.6)||e},t.blockRendering.ConstantProvider.prototype.generateTertiaryColour_=function(e){return t.utils.colour.blend("#fff",e,.3)||e},t.blockRendering.ConstantProvider.prototype.dispose=function(){this.embossFilter_&&t.utils.dom.removeNode(this.embossFilter_),this.disabledPattern_&&t.utils.dom.removeNode(this.disabledPattern_),this.debugFilter_&&t.utils.dom.removeNode(this.debugFilter_),this.cssNode_=null},t.blockRendering.ConstantProvider.prototype.makeJaggedTeeth=function(){var e=this.JAGGED_TEETH_HEIGHT,o=this.JAGGED_TEETH_WIDTH;return{height:e,width:o,path:t.utils.svgPaths.line([t.utils.svgPaths.point(o,e/4),t.utils.svgPaths.point(2*-o,e/2),t.utils.svgPaths.point(o,e/4)])}},t.blockRendering.ConstantProvider.prototype.makeStartHat=function(){var e=this.START_HAT_HEIGHT,o=this.START_HAT_WIDTH;return{height:e,width:o,path:t.utils.svgPaths.curve("c",[t.utils.svgPaths.point(30,-e),t.utils.svgPaths.point(70,-e),t.utils.svgPaths.point(o,0)])}},t.blockRendering.ConstantProvider.prototype.makePuzzleTab=function(){function e(e){var n=-(e=e?-1:1),s=i/2,r=s+2.5,a=s+.5,l=t.utils.svgPaths.point(-o,e*s);return s=t.utils.svgPaths.point(o,e*s),t.utils.svgPaths.curve("c",[t.utils.svgPaths.point(0,e*r),t.utils.svgPaths.point(-o,n*a),l])+t.utils.svgPaths.curve("s",[t.utils.svgPaths.point(o,2.5*n),s])}var o=this.TAB_WIDTH,i=this.TAB_HEIGHT,n=e(!0),s=e(!1);return{type:this.SHAPES.PUZZLE,width:o,height:i,pathDown:s,pathUp:n}},t.blockRendering.ConstantProvider.prototype.makeNotch=function(){function e(e){return t.utils.svgPaths.line([t.utils.svgPaths.point(e*n,i),t.utils.svgPaths.point(3*e,0),t.utils.svgPaths.point(e*n,-i)])}var o=this.NOTCH_WIDTH,i=this.NOTCH_HEIGHT,n=(o-3)/2,s=e(1),r=e(-1);return{type:this.SHAPES.NOTCH,width:o,height:i,pathLeft:s,pathRight:r}},t.blockRendering.ConstantProvider.prototype.makeInsideCorners=function(){var e=this.CORNER_RADIUS;return{width:e,height:e,pathTop:t.utils.svgPaths.arc("a","0 0,0",e,t.utils.svgPaths.point(-e,e)),pathBottom:t.utils.svgPaths.arc("a","0 0,0",e,t.utils.svgPaths.point(e,e))}},t.blockRendering.ConstantProvider.prototype.makeOutsideCorners=function(){var e=this.CORNER_RADIUS,o=t.utils.svgPaths.moveBy(0,e)+t.utils.svgPaths.arc("a","0 0,1",e,t.utils.svgPaths.point(e,-e)),i=t.utils.svgPaths.arc("a","0 0,1",e,t.utils.svgPaths.point(e,e)),n=t.utils.svgPaths.arc("a","0 0,1",e,t.utils.svgPaths.point(-e,-e));return{topLeft:o,topRight:i,bottomRight:t.utils.svgPaths.arc("a","0 0,1",e,t.utils.svgPaths.point(-e,e)),bottomLeft:n,rightHeight:e}},t.blockRendering.ConstantProvider.prototype.shapeFor=function(e){switch(e.type){case t.INPUT_VALUE:case t.OUTPUT_VALUE:return this.PUZZLE_TAB;case t.PREVIOUS_STATEMENT:case t.NEXT_STATEMENT:return this.NOTCH;default:throw Error("Unknown connection type")}},t.blockRendering.ConstantProvider.prototype.createDom=function(e,o,i){this.injectCSS_(o,i),e=t.utils.dom.createSvgElement("defs",{},e),o=t.utils.dom.createSvgElement("filter",{id:"blocklyEmbossFilter"+this.randomIdentifier},e),t.utils.dom.createSvgElement("feGaussianBlur",{in:"SourceAlpha",stdDeviation:1,result:"blur"},o),i=t.utils.dom.createSvgElement("feSpecularLighting",{in:"blur",surfaceScale:1,specularConstant:.5,specularExponent:10,"lighting-color":"white",result:"specOut"},o),t.utils.dom.createSvgElement("fePointLight",{x:-5e3,y:-1e4,z:2e4},i),t.utils.dom.createSvgElement("feComposite",{in:"specOut",in2:"SourceAlpha",operator:"in",result:"specOut"},o),t.utils.dom.createSvgElement("feComposite",{in:"SourceGraphic",in2:"specOut",operator:"arithmetic",k1:0,k2:1,k3:1,k4:0},o),this.embossFilterId=o.id,this.embossFilter_=o,o=t.utils.dom.createSvgElement("pattern",{id:"blocklyDisabledPattern"+this.randomIdentifier,patternUnits:"userSpaceOnUse",width:10,height:10},e),t.utils.dom.createSvgElement("rect",{width:10,height:10,fill:"#aaa"},o),t.utils.dom.createSvgElement("path",{d:"M 0 0 L 10 10 M 10 0 L 0 10",stroke:"#cc0"},o),this.disabledPatternId=o.id,this.disabledPattern_=o,t.blockRendering.Debug&&(e=t.utils.dom.createSvgElement("filter",{id:"blocklyDebugFilter"+this.randomIdentifier,height:"160%",width:"180%",y:"-30%",x:"-40%"},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":"#ff0000","flood-opacity":.5,result:"outColor"},e),t.utils.dom.createSvgElement("feComposite",{in:"outColor",in2:"outBlur",operator:"in",result:"outGlow"},e),this.debugFilterId=e.id,this.debugFilter_=e)},t.blockRendering.ConstantProvider.prototype.injectCSS_=function(t,e){e=this.getCSS_(e),t="blockly-renderer-style-"+t,this.cssNode_=document.getElementById(t);var o=e.join("\n");this.cssNode_?this.cssNode_.firstChild.textContent=o:((e=document.createElement("style")).id=t,t=document.createTextNode(o),e.appendChild(t),document.head.insertBefore(e,document.head.firstChild),this.cssNode_=e)},t.blockRendering.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,",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<i.length-1;n++){e.elements.push(i[n]);var s=this.getInRowSpacing_(i[n],i[n+1]);e.elements.push(new t.blockRendering.InRowSpacer(this.constants_,s))}e.elements.push(i[i.length-1]),e.endsWithElemSpacer()&&e.elements.push(new t.blockRendering.InRowSpacer(this.constants_,this.getInRowSpacing_(i[i.length-1],null)))}}},t.blockRendering.RenderInfo.prototype.getInRowSpacing_=function(e,o){if(!e&&o&&t.blockRendering.Types.isStatementInput(o))return this.constants_.STATEMENT_INPUT_PADDING_LEFT;if(e&&t.blockRendering.Types.isInput(e)&&!o){if(t.blockRendering.Types.isExternalInput(e))return this.constants_.NO_PADDING;if(t.blockRendering.Types.isInlineInput(e))return this.constants_.LARGE_PADDING;if(t.blockRendering.Types.isStatementInput(e))return this.constants_.NO_PADDING}return e&&t.blockRendering.Types.isLeftSquareCorner(e)&&o&&(t.blockRendering.Types.isPreviousConnection(o)||t.blockRendering.Types.isNextConnection(o))?o.notchOffset:e&&t.blockRendering.Types.isLeftRoundedCorner(e)&&o&&(t.blockRendering.Types.isPreviousConnection(o)||t.blockRendering.Types.isNextConnection(o))?o.notchOffset-this.constants_.CORNER_RADIUS:this.constants_.MEDIUM_PADDING},t.blockRendering.RenderInfo.prototype.computeBounds_=function(){for(var t,e=0,o=0,i=0,n=0;t=this.rows[n];n++){if(t.measure(),o=Math.max(o,t.width),t.hasStatement){var s=t.getLastInput();e=Math.max(e,t.width-s.width)}i=Math.max(i,t.widthWithConnectedBlocks)}for(this.statementEdge=e,this.width=o,n=0;t=this.rows[n];n++)t.hasStatement&&(t.statementEdge=this.statementEdge);this.widthWithChildren=Math.max(o,i),this.outputConnection&&(this.startX=this.outputConnection.width,this.width+=this.outputConnection.width,this.widthWithChildren+=this.outputConnection.width)},t.blockRendering.RenderInfo.prototype.alignRowElements_=function(){for(var e,o=0;e=this.rows[o];o++)if(e.hasStatement)this.alignStatementRow_(e);else{var i=e.width;0<(i=this.getDesiredRowWidth_(e)-i)&&this.addAlignmentPadding_(e,i),t.blockRendering.Types.isTopOrBottomRow(e)&&(e.widthWithConnectedBlocks=e.width)}},t.blockRendering.RenderInfo.prototype.getDesiredRowWidth_=function(t){return this.width-this.startX},t.blockRendering.RenderInfo.prototype.addAlignmentPadding_=function(e,o){var i=e.getFirstSpacer(),n=e.getLastSpacer();(e.hasExternalInput||e.hasStatement)&&(e.widthWithConnectedBlocks+=o),e.align==t.ALIGN_LEFT?n.width+=o:e.align==t.ALIGN_CENTRE?(i.width+=o/2,n.width+=o/2):e.align==t.ALIGN_RIGHT?i.width+=o:n.width+=o,e.width+=o},t.blockRendering.RenderInfo.prototype.alignStatementRow_=function(t){var e=t.getLastInput(),o=t.width-e.width,i=this.statementEdge;0<(o=i-o)&&this.addAlignmentPadding_(t,o),o=t.width,i=this.getDesiredRowWidth_(t),e.width+=i-o,e.height=Math.max(e.height,t.height),t.width+=i-o,t.widthWithConnectedBlocks=Math.max(t.width,this.statementEdge+t.connectedBlockWidths)},t.blockRendering.RenderInfo.prototype.addRowSpacing_=function(){var t=this.rows;this.rows=[];for(var e=0;e<t.length;e++)this.rows.push(t[e]),e!=t.length-1&&this.rows.push(this.makeSpacerRow_(t[e],t[e+1]))},t.blockRendering.RenderInfo.prototype.makeSpacerRow_=function(e,o){var i=this.getSpacerRowHeight_(e,o),n=this.getSpacerRowWidth_(e,o);return i=new t.blockRendering.SpacerRow(this.constants_,i,n),e.hasStatement&&(i.followsStatement=!0),o.hasStatement&&(i.precedesStatement=!0),i},t.blockRendering.RenderInfo.prototype.getSpacerRowWidth_=function(t,e){return this.width-this.startX},t.blockRendering.RenderInfo.prototype.getSpacerRowHeight_=function(t,e){return this.constants_.MEDIUM_PADDING},t.blockRendering.RenderInfo.prototype.getElemCenterline_=function(e,o){return t.blockRendering.Types.isSpacer(o)?e.yPos+o.height/2:t.blockRendering.Types.isBottomRow(e)?(e=e.yPos+e.height-e.descenderHeight,t.blockRendering.Types.isNextConnection(o)?e+o.height/2:e-o.height/2):t.blockRendering.Types.isTopRow(e)?t.blockRendering.Types.isHat(o)?e.capline-o.height/2:e.capline+o.height/2:e.yPos+e.height/2},t.blockRendering.RenderInfo.prototype.recordElemPositions_=function(e){for(var o,i=e.xPos,n=0;o=e.elements[n];n++)t.blockRendering.Types.isSpacer(o)&&(o.height=e.height),o.xPos=i,o.centerline=this.getElemCenterline_(e,o),i+=o.width},t.blockRendering.RenderInfo.prototype.finalize_=function(){for(var t,e=0,o=0,i=0;t=this.rows[i];i++)t.yPos=o,t.xPos=this.startX,o+=t.height,e=Math.max(e,t.widthWithConnectedBlocks),this.recordElemPositions_(t);this.outputConnection&&this.block_.nextConnection&&this.block_.nextConnection.isConnected()&&(e=Math.max(e,this.block_.nextConnection.targetBlock().getHeightWidth().width)),this.widthWithChildren=e+this.startX,this.height=o,this.startY=this.topRow.capline,this.bottomRow.baseline=o-this.bottomRow.descenderHeight},t.blockRendering.Drawer=function(t,e){this.block_=t,this.info_=e,this.topLeft_=t.getRelativeToSurfaceXY(),this.inlinePath_=this.outlinePath_="",this.constants_=e.getRenderer().getConstants()},t.blockRendering.Drawer.prototype.draw=function(){this.hideHiddenIcons_(),this.drawOutline_(),this.drawInternals_(),this.block_.pathObject.setPath(this.outlinePath_+"\n"+this.inlinePath_),this.info_.RTL&&this.block_.pathObject.flipRTL(),t.blockRendering.useDebugger&&this.block_.renderingDebugger.drawDebug(this.block_,this.info_),this.recordSizeOnBlock_()},t.blockRendering.Drawer.prototype.recordSizeOnBlock_=function(){this.block_.height=this.info_.height,this.block_.width=this.info_.widthWithChildren},t.blockRendering.Drawer.prototype.hideHiddenIcons_=function(){for(var t,e=0;t=this.info_.hiddenIcons[e];e++)t.icon.iconGroup_.setAttribute("display","none")},t.blockRendering.Drawer.prototype.drawOutline_=function(){this.drawTop_();for(var t=1;t<this.info_.rows.length-1;t++){var e=this.info_.rows[t];e.hasJaggedEdge?this.drawJaggedEdge_(e):e.hasStatement?this.drawStatementInput_(e):e.hasExternalInput?this.drawValueInput_(e):this.drawRightSideRow_(e)}this.drawBottom_(),this.drawLeft_()},t.blockRendering.Drawer.prototype.drawTop_=function(){var e=this.info_.topRow,o=e.elements;this.positionPreviousConnection_(),this.outlinePath_+=t.utils.svgPaths.moveBy(e.xPos,this.info_.startY);for(var i,n=0;i=o[n];n++)t.blockRendering.Types.isLeftRoundedCorner(i)?this.outlinePath_+=this.constants_.OUTSIDE_CORNERS.topLeft:t.blockRendering.Types.isRightRoundedCorner(i)?this.outlinePath_+=this.constants_.OUTSIDE_CORNERS.topRight:t.blockRendering.Types.isPreviousConnection(i)?this.outlinePath_+=i.shape.pathLeft:t.blockRendering.Types.isHat(i)?this.outlinePath_+=this.constants_.START_HAT.path:t.blockRendering.Types.isSpacer(i)&&(this.outlinePath_+=t.utils.svgPaths.lineOnAxis("h",i.width));this.outlinePath_+=t.utils.svgPaths.lineOnAxis("v",e.height)},t.blockRendering.Drawer.prototype.drawJaggedEdge_=function(e){this.outlinePath_+=this.constants_.JAGGED_TEETH.path+t.utils.svgPaths.lineOnAxis("v",e.height-this.constants_.JAGGED_TEETH.height)},t.blockRendering.Drawer.prototype.drawValueInput_=function(e){var o=e.getLastInput();this.positionExternalValueConnection_(e);var i="function"==typeof o.shape.pathDown?o.shape.pathDown(o.height):o.shape.pathDown;this.outlinePath_+=t.utils.svgPaths.lineOnAxis("H",o.xPos+o.width)+i+t.utils.svgPaths.lineOnAxis("v",e.height-o.connectionHeight)},t.blockRendering.Drawer.prototype.drawStatementInput_=function(e){var o=e.getLastInput(),i=o.xPos+o.notchOffset+o.shape.width;o=o.shape.pathRight+t.utils.svgPaths.lineOnAxis("h",-(o.notchOffset-this.constants_.INSIDE_CORNERS.width))+this.constants_.INSIDE_CORNERS.pathTop;var n=e.height-2*this.constants_.INSIDE_CORNERS.height;this.outlinePath_+=t.utils.svgPaths.lineOnAxis("H",i)+o+t.utils.svgPaths.lineOnAxis("v",n)+this.constants_.INSIDE_CORNERS.pathBottom+t.utils.svgPaths.lineOnAxis("H",e.xPos+e.width),this.positionStatementInputConnection_(e)},t.blockRendering.Drawer.prototype.drawRightSideRow_=function(e){this.outlinePath_+=t.utils.svgPaths.lineOnAxis("V",e.yPos+e.height)},t.blockRendering.Drawer.prototype.drawBottom_=function(){var e=this.info_.bottomRow,o=e.elements;this.positionNextConnection_();for(var i,n=0,s="",r=o.length-1;i=o[r];r--)t.blockRendering.Types.isNextConnection(i)?s+=i.shape.pathRight:t.blockRendering.Types.isLeftSquareCorner(i)?s+=t.utils.svgPaths.lineOnAxis("H",e.xPos):t.blockRendering.Types.isLeftRoundedCorner(i)?s+=this.constants_.OUTSIDE_CORNERS.bottomLeft:t.blockRendering.Types.isRightRoundedCorner(i)?(s+=this.constants_.OUTSIDE_CORNERS.bottomRight,n=this.constants_.OUTSIDE_CORNERS.rightHeight):t.blockRendering.Types.isSpacer(i)&&(s+=t.utils.svgPaths.lineOnAxis("h",-1*i.width));this.outlinePath_+=t.utils.svgPaths.lineOnAxis("V",e.baseline-n),this.outlinePath_+=s},t.blockRendering.Drawer.prototype.drawLeft_=function(){var e=this.info_.outputConnection;if(this.positionOutputConnection_(),e){var o=e.connectionOffsetY+e.height;e="function"==typeof e.shape.pathUp?e.shape.pathUp(e.height):e.shape.pathUp,this.outlinePath_+=t.utils.svgPaths.lineOnAxis("V",o)+e}this.outlinePath_+="z"},t.blockRendering.Drawer.prototype.drawInternals_=function(){for(var e,o=0;e=this.info_.rows[o];o++)for(var i,n=0;i=e.elements[n];n++)t.blockRendering.Types.isInlineInput(i)?this.drawInlineInput_(i):(t.blockRendering.Types.isIcon(i)||t.blockRendering.Types.isField(i))&&this.layoutField_(i)},t.blockRendering.Drawer.prototype.layoutField_=function(e){if(t.blockRendering.Types.isField(e))var o=e.field.getSvgRoot();else t.blockRendering.Types.isIcon(e)&&(o=e.icon.iconGroup_);var i=e.centerline-e.height/2,n=e.xPos,s="";this.info_.RTL&&(n=-(n+e.width),e.flipRtl&&(n+=e.width,s="scale(-1 1)")),t.blockRendering.Types.isIcon(e)?(o.setAttribute("display","block"),o.setAttribute("transform","translate("+n+","+i+")"),e.icon.computeIconLocation()):o.setAttribute("transform","translate("+n+","+i+")"+s),this.info_.isInsertionMarker&&o.setAttribute("display","none")},t.blockRendering.Drawer.prototype.drawInlineInput_=function(e){var o=e.width,i=e.height,n=e.connectionOffsetY,s=e.connectionHeight+n;this.inlinePath_+=t.utils.svgPaths.moveTo(e.xPos+e.connectionWidth,e.centerline-i/2)+t.utils.svgPaths.lineOnAxis("v",n)+e.shape.pathDown+t.utils.svgPaths.lineOnAxis("v",i-s)+t.utils.svgPaths.lineOnAxis("h",o-e.connectionWidth)+t.utils.svgPaths.lineOnAxis("v",-i)+"z",this.positionInlineInputConnection_(e)},t.blockRendering.Drawer.prototype.positionInlineInputConnection_=function(t){var e=t.centerline-t.height/2;if(t.connectionModel){var o=t.xPos+t.connectionWidth+t.connectionOffsetX;this.info_.RTL&&(o*=-1),t.connectionModel.setOffsetInBlock(o,e+t.connectionOffsetY)}},t.blockRendering.Drawer.prototype.positionStatementInputConnection_=function(t){var e=t.getLastInput();if(e.connectionModel){var o=t.xPos+t.statementEdge+e.notchOffset;this.info_.RTL&&(o*=-1),e.connectionModel.setOffsetInBlock(o,t.yPos)}},t.blockRendering.Drawer.prototype.positionExternalValueConnection_=function(t){var e=t.getLastInput();if(e.connectionModel){var o=t.xPos+t.width;this.info_.RTL&&(o*=-1),e.connectionModel.setOffsetInBlock(o,t.yPos)}},t.blockRendering.Drawer.prototype.positionPreviousConnection_=function(){var t=this.info_.topRow;if(t.connection){var e=t.xPos+t.notchOffset;t.connection.connectionModel.setOffsetInBlock(this.info_.RTL?-e:e,0)}},t.blockRendering.Drawer.prototype.positionNextConnection_=function(){var t=this.info_.bottomRow;if(t.connection){var e=t.connection,o=e.xPos;e.connectionModel.setOffsetInBlock(this.info_.RTL?-o:o,t.baseline)}},t.blockRendering.Drawer.prototype.positionOutputConnection_=function(){if(this.info_.outputConnection){var t=this.info_.startX+this.info_.outputConnection.connectionOffsetX;this.block_.outputConnection.setOffsetInBlock(this.info_.RTL?-t:t,this.info_.outputConnection.connectionOffsetY)}},t.blockRendering.PathObject=function(e,o,i){this.constants=i,this.svgRoot=e,this.svgPath=t.utils.dom.createSvgElement("path",{class:"blocklyPath"},this.svgRoot),this.style=o,this.markerSvg=this.cursorSvg=null},t.blockRendering.PathObject.prototype.setPath=function(t){this.svgPath.setAttribute("d",t)},t.blockRendering.PathObject.prototype.flipRTL=function(){this.svgPath.setAttribute("transform","scale(-1 1)")},t.blockRendering.PathObject.prototype.setCursorSvg=function(t){t?(this.svgRoot.appendChild(t),this.cursorSvg=t):this.cursorSvg=null},t.blockRendering.PathObject.prototype.setMarkerSvg=function(t){t?(this.cursorSvg?this.svgRoot.insertBefore(t,this.cursorSvg):this.svgRoot.appendChild(t),this.markerSvg=t):this.markerSvg=null},t.blockRendering.PathObject.prototype.applyColour=function(t){this.svgPath.setAttribute("stroke",this.style.colourTertiary),this.svgPath.setAttribute("fill",this.style.colourPrimary),this.updateShadow_(t.isShadow()),this.updateDisabled_(!t.isEnabled()||t.getInheritedDisabled())},t.blockRendering.PathObject.prototype.setStyle=function(t){this.style=t},t.blockRendering.PathObject.prototype.setClass_=function(e,o){o?t.utils.dom.addClass(this.svgRoot,e):t.utils.dom.removeClass(this.svgRoot,e)},t.blockRendering.PathObject.prototype.updateHighlighted=function(t){t?this.svgPath.setAttribute("filter","url(#"+this.constants.embossFilterId+")"):this.svgPath.setAttribute("filter","none")},t.blockRendering.PathObject.prototype.updateShadow_=function(t){t&&(this.svgPath.setAttribute("stroke","none"),this.svgPath.setAttribute("fill",this.style.colourSecondary))},t.blockRendering.PathObject.prototype.updateDisabled_=function(t){this.setClass_("blocklyDisabled",t),t&&this.svgPath.setAttribute("fill","url(#"+this.constants.disabledPatternId+")")},t.blockRendering.PathObject.prototype.updateSelected=function(t){this.setClass_("blocklySelected",t)},t.blockRendering.PathObject.prototype.updateDraggingDelete=function(t){this.setClass_("blocklyDraggingDelete",t)},t.blockRendering.PathObject.prototype.updateInsertionMarker=function(t){this.setClass_("blocklyInsertionMarker",t)},t.blockRendering.PathObject.prototype.updateMovable=function(t){this.setClass_("blocklyDraggable",t)},t.blockRendering.PathObject.prototype.updateReplacementFade=function(t){this.setClass_("blocklyReplaceable",t)},t.blockRendering.PathObject.prototype.updateShapeForInputHighlight=function(t,e){},t.blockRendering.Renderer=function(t){this.name=t,this.overrides=this.constants_=null},t.blockRendering.Renderer.prototype.getClassName=function(){return this.name+"-renderer"},t.blockRendering.Renderer.prototype.init=function(e,o){this.constants_=this.makeConstants_(),o&&(this.overrides=o,t.utils.object.mixin(this.constants_,o)),this.constants_.setTheme(e),this.constants_.init()},t.blockRendering.Renderer.prototype.createDom=function(t,e){this.constants_.createDom(t,this.name+"-"+e.name,"."+this.getClassName()+"."+e.getClassName())},t.blockRendering.Renderer.prototype.refreshDom=function(e,o){var i=this.getConstants();i.dispose(),this.constants_=this.makeConstants_(),this.overrides&&t.utils.object.mixin(this.constants_,this.overrides),this.constants_.randomIdentifier=i.randomIdentifier,this.constants_.setTheme(o),this.constants_.init(),this.createDom(e,o)},t.blockRendering.Renderer.prototype.dispose=function(){this.constants_&&this.constants_.dispose()},t.blockRendering.Renderer.prototype.makeConstants_=function(){return new t.blockRendering.ConstantProvider},t.blockRendering.Renderer.prototype.makeRenderInfo_=function(e){return new t.blockRendering.RenderInfo(this,e)},t.blockRendering.Renderer.prototype.makeDrawer_=function(e,o){return new t.blockRendering.Drawer(e,o)},t.blockRendering.Renderer.prototype.makeDebugger_=function(){if(!t.blockRendering.Debug)throw Error("Missing require for Blockly.blockRendering.Debug");return new t.blockRendering.Debug(this.getConstants())},t.blockRendering.Renderer.prototype.makeMarkerDrawer=function(e,o){return new t.blockRendering.MarkerSvg(e,this.getConstants(),o)},t.blockRendering.Renderer.prototype.makePathObject=function(e,o){return new t.blockRendering.PathObject(e,o,this.constants_)},t.blockRendering.Renderer.prototype.getConstants=function(){return this.constants_},t.blockRendering.Renderer.prototype.shouldHighlightConnection=function(t){return!0},t.blockRendering.Renderer.prototype.orphanCanConnectAtEnd=function(e,o,i){return i==t.OUTPUT_VALUE?(i=o.outputConnection,e=t.Connection.lastConnectionInRow(e,o)):(i=o.previousConnection,e=e.lastConnectionInStack()),!!e&&i.checkType(e)},t.blockRendering.Renderer.prototype.getConnectionPreviewMethod=function(e,o,i){return o.type==t.OUTPUT_VALUE||o.type==t.PREVIOUS_STATEMENT?!e.isConnected()||this.orphanCanConnectAtEnd(i,e.targetBlock(),o.type)?t.InsertionMarkerManager.PREVIEW_TYPE.INSERTION_MARKER:t.InsertionMarkerManager.PREVIEW_TYPE.REPLACEMENT_FADE:t.InsertionMarkerManager.PREVIEW_TYPE.INSERTION_MARKER},t.blockRendering.Renderer.prototype.render=function(e){t.blockRendering.useDebugger&&!e.renderingDebugger&&(e.renderingDebugger=this.makeDebugger_());var o=this.makeRenderInfo_(e);o.measure(),this.makeDrawer_(e,o).draw()},t.geras={},t.geras.ConstantProvider=function(){t.geras.ConstantProvider.superClass_.constructor.call(this),this.FIELD_TEXT_BASELINE_CENTER=!1,this.DARK_PATH_OFFSET=1,this.MAX_BOTTOM_WIDTH=30},t.utils.object.inherits(t.geras.ConstantProvider,t.blockRendering.ConstantProvider),t.geras.ConstantProvider.prototype.getCSS_=function(e){return t.geras.ConstantProvider.superClass_.getCSS_.call(this,e).concat([e+" .blocklyInsertionMarker>.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;s<n.length-1;s++){e.elements.push(n[s]);var r=this.getInRowSpacing_(n[s],n[s+1]);e.elements.push(new t.blockRendering.InRowSpacer(this.constants_,r))}e.elements.push(n[n.length-1]),e.endsWithElemSpacer()&&(r=this.getInRowSpacing_(n[n.length-1],null),o&&e.hasDummyInput&&(r+=this.constants_.TAB_WIDTH),e.elements.push(new t.blockRendering.InRowSpacer(this.constants_,r)))}}},t.geras.RenderInfo.prototype.getInRowSpacing_=function(e,o){if(!e)return o&&t.blockRendering.Types.isField(o)&&o.isEditable?this.constants_.MEDIUM_PADDING:o&&t.blockRendering.Types.isInlineInput(o)?this.constants_.MEDIUM_LARGE_PADDING:o&&t.blockRendering.Types.isStatementInput(o)?this.constants_.STATEMENT_INPUT_PADDING_LEFT:this.constants_.LARGE_PADDING;if(!t.blockRendering.Types.isInput(e)&&(!o||t.blockRendering.Types.isStatementInput(o)))return t.blockRendering.Types.isField(e)&&e.isEditable?this.constants_.MEDIUM_PADDING:t.blockRendering.Types.isIcon(e)?2*this.constants_.LARGE_PADDING+1:t.blockRendering.Types.isHat(e)?this.constants_.NO_PADDING:t.blockRendering.Types.isPreviousOrNextConnection(e)?this.constants_.LARGE_PADDING:t.blockRendering.Types.isLeftRoundedCorner(e)?this.constants_.MIN_BLOCK_WIDTH:t.blockRendering.Types.isJaggedEdge(e)?this.constants_.NO_PADDING:this.constants_.LARGE_PADDING;if(t.blockRendering.Types.isInput(e)&&!o){if(t.blockRendering.Types.isExternalInput(e))return this.constants_.NO_PADDING;if(t.blockRendering.Types.isInlineInput(e))return this.constants_.LARGE_PADDING;if(t.blockRendering.Types.isStatementInput(e))return this.constants_.NO_PADDING}if(!t.blockRendering.Types.isInput(e)&&o&&t.blockRendering.Types.isInput(o)){if(t.blockRendering.Types.isField(e)&&e.isEditable){if(t.blockRendering.Types.isInlineInput(o)||t.blockRendering.Types.isExternalInput(o))return this.constants_.SMALL_PADDING}else{if(t.blockRendering.Types.isInlineInput(o)||t.blockRendering.Types.isExternalInput(o))return this.constants_.MEDIUM_LARGE_PADDING;if(t.blockRendering.Types.isStatementInput(o))return this.constants_.LARGE_PADDING}return this.constants_.LARGE_PADDING-1}if(t.blockRendering.Types.isIcon(e)&&o&&!t.blockRendering.Types.isInput(o))return this.constants_.LARGE_PADDING;if(t.blockRendering.Types.isInlineInput(e)&&o&&t.blockRendering.Types.isField(o))return o.isEditable?this.constants_.MEDIUM_PADDING:this.constants_.LARGE_PADDING;if(t.blockRendering.Types.isLeftSquareCorner(e)&&o){if(t.blockRendering.Types.isHat(o))return this.constants_.NO_PADDING;if(t.blockRendering.Types.isPreviousConnection(o))return o.notchOffset;if(t.blockRendering.Types.isNextConnection(o))return e=(this.RTL?1:-1)*this.constants_.DARK_PATH_OFFSET/2,o.notchOffset+e}if(t.blockRendering.Types.isLeftRoundedCorner(e)&&o){if(t.blockRendering.Types.isPreviousConnection(o))return o.notchOffset-this.constants_.CORNER_RADIUS;if(t.blockRendering.Types.isNextConnection(o))return e=(this.RTL?1:-1)*this.constants_.DARK_PATH_OFFSET/2,o.notchOffset-this.constants_.CORNER_RADIUS+e}return t.blockRendering.Types.isField(e)&&o&&t.blockRendering.Types.isField(o)&&e.isEditable==o.isEditable||o&&t.blockRendering.Types.isJaggedEdge(o)?this.constants_.LARGE_PADDING:this.constants_.MEDIUM_PADDING},t.geras.RenderInfo.prototype.getSpacerRowHeight_=function(e,o){return t.blockRendering.Types.isTopRow(e)&&t.blockRendering.Types.isBottomRow(o)?this.constants_.EMPTY_BLOCK_SPACER_HEIGHT:t.blockRendering.Types.isTopRow(e)||t.blockRendering.Types.isBottomRow(o)?this.constants_.NO_PADDING:e.hasExternalInput&&o.hasExternalInput?this.constants_.LARGE_PADDING:!e.hasStatement&&o.hasStatement?this.constants_.BETWEEN_STATEMENT_PADDING_Y:e.hasStatement&&o.hasStatement||!e.hasStatement&&o.hasDummyInput||e.hasDummyInput?this.constants_.LARGE_PADDING:this.constants_.MEDIUM_PADDING},t.geras.RenderInfo.prototype.getElemCenterline_=function(e,o){if(t.blockRendering.Types.isSpacer(o))return e.yPos+o.height/2;if(t.blockRendering.Types.isBottomRow(e))return e=e.yPos+e.height-e.descenderHeight,t.blockRendering.Types.isNextConnection(o)?e+o.height/2:e-o.height/2;if(t.blockRendering.Types.isTopRow(e))return t.blockRendering.Types.isHat(o)?e.capline-o.height/2:e.capline+o.height/2;var i=e.yPos;return t.blockRendering.Types.isField(o)||t.blockRendering.Types.isIcon(o)?(i+=o.height/2,(e.hasInlineInput||e.hasStatement)&&o.height+this.constants_.TALL_INPUT_FIELD_OFFSET_Y<=e.height&&(i+=this.constants_.TALL_INPUT_FIELD_OFFSET_Y)):i=t.blockRendering.Types.isInlineInput(o)?i+o.height/2:i+e.height/2,i},t.geras.RenderInfo.prototype.alignRowElements_=function(){if(this.isInline){for(var e,o=0,i=null,n=this.rows.length-1;e=this.rows[n];n--)e.nextRightEdge=o,t.blockRendering.Types.isInputRow(e)&&(e.hasStatement&&this.alignStatementRow_(e),i&&i.hasStatement&&e.width<i.width?e.nextRightEdge=i.width:o=e.width,i=e);for(n=o=0;e=this.rows[n];n++)e.hasStatement?o=this.getDesiredRowWidth_(e):t.blockRendering.Types.isSpacer(e)?e.width=Math.max(o,e.nextRightEdge):(0<(o=Math.max(o,e.nextRightEdge)-e.width)&&this.addAlignmentPadding_(e,o),o=e.width)}else t.geras.RenderInfo.superClass_.alignRowElements_.call(this)},t.geras.RenderInfo.prototype.getDesiredRowWidth_=function(e){return this.isInline&&e.hasStatement?this.statementEdge+this.constants_.MAX_BOTTOM_WIDTH+this.startX:t.geras.RenderInfo.superClass_.getDesiredRowWidth_.call(this,e)},t.geras.RenderInfo.prototype.finalize_=function(){for(var t,e=0,o=0,i=0;t=this.rows[i];i++){t.yPos=o,t.xPos=this.startX,o+=t.height,e=Math.max(e,t.widthWithConnectedBlocks);var n=o-this.topRow.ascenderHeight;t==this.bottomRow&&n<this.constants_.MIN_BLOCK_HEIGHT&&(n=this.constants_.MIN_BLOCK_HEIGHT-n,this.bottomRow.height+=n,o+=n),this.recordElemPositions_(t)}this.outputConnection&&this.block_.nextConnection&&this.block_.nextConnection.isConnected()&&(e=Math.max(e,this.block_.nextConnection.targetBlock().getHeightWidth().width-this.constants_.DARK_PATH_OFFSET)),this.bottomRow.baseline=o-this.bottomRow.descenderHeight,this.widthWithChildren=e+this.startX+this.constants_.DARK_PATH_OFFSET,this.width+=this.constants_.DARK_PATH_OFFSET,this.height=o+this.constants_.DARK_PATH_OFFSET,this.startY=this.topRow.capline},t.geras.Drawer=function(e,o){t.geras.Drawer.superClass_.constructor.call(this,e,o),this.highlighter_=new t.geras.Highlighter(o)},t.utils.object.inherits(t.geras.Drawer,t.blockRendering.Drawer),t.geras.Drawer.prototype.draw=function(){this.hideHiddenIcons_(),this.drawOutline_(),this.drawInternals_();var e=this.block_.pathObject;e.setPath(this.outlinePath_+"\n"+this.inlinePath_),e.setHighlightPath(this.highlighter_.getPath()),this.info_.RTL&&e.flipRTL(),t.blockRendering.useDebugger&&this.block_.renderingDebugger.drawDebug(this.block_,this.info_),this.recordSizeOnBlock_()},t.geras.Drawer.prototype.drawTop_=function(){this.highlighter_.drawTopCorner(this.info_.topRow),this.highlighter_.drawRightSideRow(this.info_.topRow),t.geras.Drawer.superClass_.drawTop_.call(this)},t.geras.Drawer.prototype.drawJaggedEdge_=function(e){this.highlighter_.drawJaggedEdge_(e),t.geras.Drawer.superClass_.drawJaggedEdge_.call(this,e)},t.geras.Drawer.prototype.drawValueInput_=function(e){this.highlighter_.drawValueInput(e),t.geras.Drawer.superClass_.drawValueInput_.call(this,e)},t.geras.Drawer.prototype.drawStatementInput_=function(e){this.highlighter_.drawStatementInput(e),t.geras.Drawer.superClass_.drawStatementInput_.call(this,e)},t.geras.Drawer.prototype.drawRightSideRow_=function(e){this.highlighter_.drawRightSideRow(e),this.outlinePath_+=t.utils.svgPaths.lineOnAxis("H",e.xPos+e.width)+t.utils.svgPaths.lineOnAxis("V",e.yPos+e.height)},t.geras.Drawer.prototype.drawBottom_=function(){this.highlighter_.drawBottomRow(this.info_.bottomRow),t.geras.Drawer.superClass_.drawBottom_.call(this)},t.geras.Drawer.prototype.drawLeft_=function(){this.highlighter_.drawLeft(),t.geras.Drawer.superClass_.drawLeft_.call(this)},t.geras.Drawer.prototype.drawInlineInput_=function(e){this.highlighter_.drawInlineInput(e),t.geras.Drawer.superClass_.drawInlineInput_.call(this,e)},t.geras.Drawer.prototype.positionInlineInputConnection_=function(t){var e=t.centerline-t.height/2;if(t.connectionModel){var o=t.xPos+t.connectionWidth+this.constants_.DARK_PATH_OFFSET;this.info_.RTL&&(o*=-1),t.connectionModel.setOffsetInBlock(o,e+t.connectionOffsetY+this.constants_.DARK_PATH_OFFSET)}},t.geras.Drawer.prototype.positionStatementInputConnection_=function(t){var e=t.getLastInput();if(e.connectionModel){var o=t.xPos+t.statementEdge+e.notchOffset;o=this.info_.RTL?-1*o:o+this.constants_.DARK_PATH_OFFSET,e.connectionModel.setOffsetInBlock(o,t.yPos+this.constants_.DARK_PATH_OFFSET)}},t.geras.Drawer.prototype.positionExternalValueConnection_=function(t){var e=t.getLastInput();if(e.connectionModel){var o=t.xPos+t.width+this.constants_.DARK_PATH_OFFSET;this.info_.RTL&&(o*=-1),e.connectionModel.setOffsetInBlock(o,t.yPos)}},t.geras.Drawer.prototype.positionNextConnection_=function(){var t=this.info_.bottomRow;if(t.connection){var e=t.connection,o=e.xPos;e.connectionModel.setOffsetInBlock((this.info_.RTL?-o:o)+this.constants_.DARK_PATH_OFFSET/2,t.baseline+this.constants_.DARK_PATH_OFFSET)}},t.geras.HighlightConstantProvider=function(e){this.constantProvider=e,this.OFFSET=.5,this.START_POINT=t.utils.svgPaths.moveBy(this.OFFSET,this.OFFSET)},t.geras.HighlightConstantProvider.prototype.init=function(){this.INSIDE_CORNER=this.makeInsideCorner(),this.OUTSIDE_CORNER=this.makeOutsideCorner(),this.PUZZLE_TAB=this.makePuzzleTab(),this.NOTCH=this.makeNotch(),this.JAGGED_TEETH=this.makeJaggedTeeth(),this.START_HAT=this.makeStartHat()},t.geras.HighlightConstantProvider.prototype.makeInsideCorner=function(){var e=this.constantProvider.CORNER_RADIUS,o=this.OFFSET,i=(1-Math.SQRT1_2)*(e+o)-o,n=t.utils.svgPaths.moveBy(i,i)+t.utils.svgPaths.arc("a","0 0,0",e,t.utils.svgPaths.point(-i-o,e-i)),s=t.utils.svgPaths.arc("a","0 0,0",e+o,t.utils.svgPaths.point(e+o,e+o)),r=t.utils.svgPaths.moveBy(i,-i)+t.utils.svgPaths.arc("a","0 0,0",e+o,t.utils.svgPaths.point(e-i,i+o));return{width:e+o,height:e,pathTop:function(t){return t?n:""},pathBottom:function(t){return t?s:r}}},t.geras.HighlightConstantProvider.prototype.makeOutsideCorner=function(){var e=this.constantProvider.CORNER_RADIUS,o=this.OFFSET,i=(1-Math.SQRT1_2)*(e-o)+o,n=t.utils.svgPaths.moveBy(i,i)+t.utils.svgPaths.arc("a","0 0,1",e-o,t.utils.svgPaths.point(e-i,-i+o)),s=t.utils.svgPaths.moveBy(o,e)+t.utils.svgPaths.arc("a","0 0,1",e-o,t.utils.svgPaths.point(e,-e+o)),r=-i,a=t.utils.svgPaths.moveBy(i,r)+t.utils.svgPaths.arc("a","0 0,1",e-o,t.utils.svgPaths.point(-i+o,-r-e));return{height:e,topLeft:function(t){return t?n:s},bottomLeft:function(){return a}}},t.geras.HighlightConstantProvider.prototype.makePuzzleTab=function(){var e=this.constantProvider.TAB_WIDTH,o=this.constantProvider.TAB_HEIGHT,i=t.utils.svgPaths.moveBy(-2,3.4-o)+t.utils.svgPaths.lineTo(-.45*e,-2.1),n=t.utils.svgPaths.lineOnAxis("v",2.5)+t.utils.svgPaths.moveBy(.97*-e,2.5)+t.utils.svgPaths.curve("q",[t.utils.svgPaths.point(.05*-e,10),t.utils.svgPaths.point(.3*e,9.5)])+t.utils.svgPaths.moveBy(.67*e,-1.9)+t.utils.svgPaths.lineOnAxis("v",2.5),s=t.utils.svgPaths.lineOnAxis("v",-1.5)+t.utils.svgPaths.moveBy(-.92*e,-.5)+t.utils.svgPaths.curve("q",[t.utils.svgPaths.point(-.19*e,-5.5),t.utils.svgPaths.point(0,-11)])+t.utils.svgPaths.moveBy(.92*e,1),r=t.utils.svgPaths.moveBy(-5,o-.7)+t.utils.svgPaths.lineTo(.46*e,-2.1);return{width:e,height:o,pathUp:function(t){return t?i:s},pathDown:function(t){return t?n:r}}},t.geras.HighlightConstantProvider.prototype.makeNotch=function(){return{pathLeft:t.utils.svgPaths.lineOnAxis("h",this.OFFSET)+this.constantProvider.NOTCH.pathLeft}},t.geras.HighlightConstantProvider.prototype.makeJaggedTeeth=function(){return{pathLeft:t.utils.svgPaths.lineTo(5.1,2.6)+t.utils.svgPaths.moveBy(-10.2,6.8)+t.utils.svgPaths.lineTo(5.1,2.6),height:12,width:10.2}},t.geras.HighlightConstantProvider.prototype.makeStartHat=function(){var e=this.constantProvider.START_HAT.height,o=t.utils.svgPaths.moveBy(25,-8.7)+t.utils.svgPaths.curve("c",[t.utils.svgPaths.point(29.7,-6.2),t.utils.svgPaths.point(57.2,-.5),t.utils.svgPaths.point(75,8.7)]),i=t.utils.svgPaths.curve("c",[t.utils.svgPaths.point(17.8,-9.2),t.utils.svgPaths.point(45.3,-14.9),t.utils.svgPaths.point(75,-8.7)])+t.utils.svgPaths.moveTo(100.5,e+.5);return{path:function(t){return t?o:i}}},t.geras.PathObject=function(e,o,i){this.constants=i,this.svgRoot=e,this.svgPathDark=t.utils.dom.createSvgElement("path",{class:"blocklyPathDark",transform:"translate(1,1)"},this.svgRoot),this.svgPath=t.utils.dom.createSvgElement("path",{class:"blocklyPath"},this.svgRoot),this.svgPathLight=t.utils.dom.createSvgElement("path",{class:"blocklyPathLight"},this.svgRoot),this.colourDark="#000000",this.style=o},t.utils.object.inherits(t.geras.PathObject,t.blockRendering.PathObject),t.geras.PathObject.prototype.setPath=function(t){this.svgPath.setAttribute("d",t),this.svgPathDark.setAttribute("d",t)},t.geras.PathObject.prototype.setHighlightPath=function(t){this.svgPathLight.setAttribute("d",t)},t.geras.PathObject.prototype.flipRTL=function(){this.svgPath.setAttribute("transform","scale(-1 1)"),this.svgPathLight.setAttribute("transform","scale(-1 1)"),this.svgPathDark.setAttribute("transform","translate(1,1) scale(-1 1)")},t.geras.PathObject.prototype.applyColour=function(e){this.svgPathLight.style.display="",this.svgPathDark.style.display="",this.svgPathLight.setAttribute("stroke",this.style.colourTertiary),this.svgPathDark.setAttribute("fill",this.colourDark),t.geras.PathObject.superClass_.applyColour.call(this,e),this.svgPath.setAttribute("stroke","none")},t.geras.PathObject.prototype.setStyle=function(e){this.style=e,this.colourDark=t.utils.colour.blend("#000",this.style.colourPrimary,.2)||this.colourDark},t.geras.PathObject.prototype.updateHighlighted=function(t){t?(this.svgPath.setAttribute("filter","url(#"+this.constants.embossFilterId+")"),this.svgPathLight.style.display="none"):(this.svgPath.setAttribute("filter","none"),this.svgPathLight.style.display="inline")},t.geras.PathObject.prototype.updateShadow_=function(t){t&&(this.svgPathLight.style.display="none",this.svgPathDark.setAttribute("fill",this.style.colourSecondary),this.svgPath.setAttribute("stroke","none"),this.svgPath.setAttribute("fill",this.style.colourSecondary))},t.geras.PathObject.prototype.updateDisabled_=function(e){t.geras.PathObject.superClass_.updateDisabled_.call(this,e),e&&this.svgPath.setAttribute("stroke","none")},t.geras.Renderer=function(e){t.geras.Renderer.superClass_.constructor.call(this,e),this.highlightConstants_=null},t.utils.object.inherits(t.geras.Renderer,t.blockRendering.Renderer),t.geras.Renderer.prototype.init=function(e,o){t.geras.Renderer.superClass_.init.call(this,e,o),this.highlightConstants_=this.makeHighlightConstants_(),this.highlightConstants_.init()},t.geras.Renderer.prototype.refreshDom=function(e,o){t.geras.Renderer.superClass_.refreshDom.call(this,e,o),this.getHighlightConstants().init()},t.geras.Renderer.prototype.makeConstants_=function(){return new t.geras.ConstantProvider},t.geras.Renderer.prototype.makeRenderInfo_=function(e){return new t.geras.RenderInfo(this,e)},t.geras.Renderer.prototype.makeDrawer_=function(e,o){return new t.geras.Drawer(e,o)},t.geras.Renderer.prototype.makePathObject=function(e,o){return new t.geras.PathObject(e,o,this.getConstants())},t.geras.Renderer.prototype.makeHighlightConstants_=function(){return new t.geras.HighlightConstantProvider(this.getConstants())},t.geras.Renderer.prototype.getHighlightConstants=function(){return this.highlightConstants_},t.blockRendering.register("geras",t.geras.Renderer),t.thrasos={},t.thrasos.RenderInfo=function(e,o){t.thrasos.RenderInfo.superClass_.constructor.call(this,e,o)},t.utils.object.inherits(t.thrasos.RenderInfo,t.blockRendering.RenderInfo),t.thrasos.RenderInfo.prototype.getRenderer=function(){return this.renderer_},t.thrasos.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;e.elements=[],e.startsWithElemSpacer()&&e.elements.push(new t.blockRendering.InRowSpacer(this.constants_,this.getInRowSpacing_(null,n[0])));for(var s=0;s<n.length-1;s++){e.elements.push(n[s]);var r=this.getInRowSpacing_(n[s],n[s+1]);e.elements.push(new t.blockRendering.InRowSpacer(this.constants_,r))}e.elements.push(n[n.length-1]),e.endsWithElemSpacer()&&(r=this.getInRowSpacing_(n[n.length-1],null),o&&e.hasDummyInput&&(r+=this.constants_.TAB_WIDTH),e.elements.push(new t.blockRendering.InRowSpacer(this.constants_,r)))}},t.thrasos.RenderInfo.prototype.getInRowSpacing_=function(e,o){if(!e)return o&&t.blockRendering.Types.isField(o)&&o.isEditable?this.constants_.MEDIUM_PADDING:o&&t.blockRendering.Types.isInlineInput(o)?this.constants_.MEDIUM_LARGE_PADDING:o&&t.blockRendering.Types.isStatementInput(o)?this.constants_.STATEMENT_INPUT_PADDING_LEFT:this.constants_.LARGE_PADDING;if(!t.blockRendering.Types.isInput(e)&&!o)return t.blockRendering.Types.isField(e)&&e.isEditable?this.constants_.MEDIUM_PADDING:t.blockRendering.Types.isIcon(e)?2*this.constants_.LARGE_PADDING+1:t.blockRendering.Types.isHat(e)?this.constants_.NO_PADDING:t.blockRendering.Types.isPreviousOrNextConnection(e)?this.constants_.LARGE_PADDING:t.blockRendering.Types.isLeftRoundedCorner(e)?this.constants_.MIN_BLOCK_WIDTH:t.blockRendering.Types.isJaggedEdge(e)?this.constants_.NO_PADDING:this.constants_.LARGE_PADDING;if(t.blockRendering.Types.isInput(e)&&!o){if(t.blockRendering.Types.isExternalInput(e))return this.constants_.NO_PADDING;if(t.blockRendering.Types.isInlineInput(e))return this.constants_.LARGE_PADDING;if(t.blockRendering.Types.isStatementInput(e))return this.constants_.NO_PADDING}if(!t.blockRendering.Types.isInput(e)&&o&&t.blockRendering.Types.isInput(o)){if(t.blockRendering.Types.isField(e)&&e.isEditable){if(t.blockRendering.Types.isInlineInput(o)||t.blockRendering.Types.isExternalInput(o))return this.constants_.SMALL_PADDING}else{if(t.blockRendering.Types.isInlineInput(o)||t.blockRendering.Types.isExternalInput(o))return this.constants_.MEDIUM_LARGE_PADDING;if(t.blockRendering.Types.isStatementInput(o))return this.constants_.LARGE_PADDING}return this.constants_.LARGE_PADDING-1}if(t.blockRendering.Types.isIcon(e)&&o&&!t.blockRendering.Types.isInput(o))return this.constants_.LARGE_PADDING;if(t.blockRendering.Types.isInlineInput(e)&&o&&t.blockRendering.Types.isField(o))return o.isEditable?this.constants_.MEDIUM_PADDING:this.constants_.LARGE_PADDING;if(t.blockRendering.Types.isLeftSquareCorner(e)&&o){if(t.blockRendering.Types.isHat(o))return this.constants_.NO_PADDING;if(t.blockRendering.Types.isPreviousConnection(o)||t.blockRendering.Types.isNextConnection(o))return o.notchOffset}return t.blockRendering.Types.isLeftRoundedCorner(e)&&o?o.notchOffset-this.constants_.CORNER_RADIUS:t.blockRendering.Types.isField(e)&&o&&t.blockRendering.Types.isField(o)&&e.isEditable==o.isEditable||o&&t.blockRendering.Types.isJaggedEdge(o)?this.constants_.LARGE_PADDING:this.constants_.MEDIUM_PADDING},t.thrasos.RenderInfo.prototype.getSpacerRowHeight_=function(e,o){return t.blockRendering.Types.isTopRow(e)&&t.blockRendering.Types.isBottomRow(o)?this.constants_.EMPTY_BLOCK_SPACER_HEIGHT:t.blockRendering.Types.isTopRow(e)||t.blockRendering.Types.isBottomRow(o)?this.constants_.NO_PADDING:e.hasExternalInput&&o.hasExternalInput?this.constants_.LARGE_PADDING:!e.hasStatement&&o.hasStatement?this.constants_.BETWEEN_STATEMENT_PADDING_Y:e.hasStatement&&o.hasStatement||e.hasDummyInput||o.hasDummyInput?this.constants_.LARGE_PADDING:this.constants_.MEDIUM_PADDING},t.thrasos.RenderInfo.prototype.getElemCenterline_=function(e,o){if(t.blockRendering.Types.isSpacer(o))return e.yPos+o.height/2;if(t.blockRendering.Types.isBottomRow(e))return e=e.yPos+e.height-e.descenderHeight,t.blockRendering.Types.isNextConnection(o)?e+o.height/2:e-o.height/2;if(t.blockRendering.Types.isTopRow(e))return t.blockRendering.Types.isHat(o)?e.capline-o.height/2:e.capline+o.height/2;var i=e.yPos;return t.blockRendering.Types.isField(o)&&e.hasStatement?i+(this.constants_.TALL_INPUT_FIELD_OFFSET_Y+o.height/2):i+e.height/2},t.thrasos.RenderInfo.prototype.finalize_=function(){for(var t,e=0,o=0,i=0;t=this.rows[i];i++){t.yPos=o,t.xPos=this.startX,o+=t.height,e=Math.max(e,t.widthWithConnectedBlocks);var n=o-this.topRow.ascenderHeight;t==this.bottomRow&&n<this.constants_.MIN_BLOCK_HEIGHT&&(n=this.constants_.MIN_BLOCK_HEIGHT-n,this.bottomRow.height+=n,o+=n),this.recordElemPositions_(t)}this.outputConnection&&this.block_.nextConnection&&this.block_.nextConnection.isConnected()&&(e=Math.max(e,this.block_.nextConnection.targetBlock().getHeightWidth().width)),this.bottomRow.baseline=o-this.bottomRow.descenderHeight,this.widthWithChildren=e+this.startX,this.height=o,this.startY=this.topRow.capline},t.thrasos.Renderer=function(e){t.thrasos.Renderer.superClass_.constructor.call(this,e)},t.utils.object.inherits(t.thrasos.Renderer,t.blockRendering.Renderer),t.thrasos.Renderer.prototype.makeRenderInfo_=function(e){return new t.thrasos.RenderInfo(this,e)},t.blockRendering.register("thrasos",t.thrasos.Renderer),t.zelos={},t.zelos.ConstantProvider=function(){t.zelos.ConstantProvider.superClass_.constructor.call(this),this.SMALL_PADDING=this.GRID_UNIT=4,this.MEDIUM_PADDING=2*this.GRID_UNIT,this.MEDIUM_LARGE_PADDING=3*this.GRID_UNIT,this.LARGE_PADDING=4*this.GRID_UNIT,this.CORNER_RADIUS=1*this.GRID_UNIT,this.NOTCH_WIDTH=9*this.GRID_UNIT,this.NOTCH_HEIGHT=2*this.GRID_UNIT,this.STATEMENT_INPUT_NOTCH_OFFSET=this.NOTCH_OFFSET_LEFT=3*this.GRID_UNIT,this.MIN_BLOCK_WIDTH=2*this.GRID_UNIT,this.MIN_BLOCK_HEIGHT=12*this.GRID_UNIT,this.EMPTY_STATEMENT_INPUT_HEIGHT=6*this.GRID_UNIT,this.TAB_OFFSET_FROM_TOP=0,this.TOP_ROW_MIN_HEIGHT=this.CORNER_RADIUS,this.TOP_ROW_PRECEDES_STATEMENT_MIN_HEIGHT=this.LARGE_PADDING,this.BOTTOM_ROW_MIN_HEIGHT=this.CORNER_RADIUS,this.BOTTOM_ROW_AFTER_STATEMENT_MIN_HEIGHT=6*this.GRID_UNIT,this.STATEMENT_BOTTOM_SPACER=-this.NOTCH_HEIGHT,this.STATEMENT_INPUT_SPACER_MIN_WIDTH=40*this.GRID_UNIT,this.STATEMENT_INPUT_PADDING_LEFT=4*this.GRID_UNIT,this.EMPTY_INLINE_INPUT_PADDING=4*this.GRID_UNIT,this.EMPTY_INLINE_INPUT_HEIGHT=8*this.GRID_UNIT,this.DUMMY_INPUT_MIN_HEIGHT=8*this.GRID_UNIT,this.DUMMY_INPUT_SHADOW_MIN_HEIGHT=6*this.GRID_UNIT,this.CURSOR_WS_WIDTH=20*this.GRID_UNIT,this.CURSOR_COLOUR="#ffa200",this.CURSOR_RADIUS=5,this.JAGGED_TEETH_WIDTH=this.JAGGED_TEETH_HEIGHT=0,this.START_HAT_HEIGHT=22,this.START_HAT_WIDTH=96,this.SHAPES={HEXAGONAL:1,ROUND:2,SQUARE:3,PUZZLE:4,NOTCH:5},this.SHAPE_IN_SHAPE_PADDING={1:{0:5*this.GRID_UNIT,1:2*this.GRID_UNIT,2:5*this.GRID_UNIT,3:5*this.GRID_UNIT},2:{0:3*this.GRID_UNIT,1:3*this.GRID_UNIT,2:1*this.GRID_UNIT,3:2*this.GRID_UNIT},3:{0:2*this.GRID_UNIT,1:2*this.GRID_UNIT,2:2*this.GRID_UNIT,3:2*this.GRID_UNIT}},this.FULL_BLOCK_FIELDS=!0,this.FIELD_TEXT_FONTSIZE=3*this.GRID_UNIT,this.FIELD_TEXT_FONTWEIGHT="bold",this.FIELD_TEXT_FONTFAMILY='"Helvetica Neue", "Segoe UI", Helvetica, sans-serif',this.FIELD_BORDER_RECT_RADIUS=this.CORNER_RADIUS,this.FIELD_BORDER_RECT_X_PADDING=2*this.GRID_UNIT,this.FIELD_BORDER_RECT_Y_PADDING=1.625*this.GRID_UNIT,this.FIELD_BORDER_RECT_HEIGHT=8*this.GRID_UNIT,this.FIELD_DROPDOWN_BORDER_RECT_HEIGHT=8*this.GRID_UNIT,this.FIELD_DROPDOWN_SVG_ARROW=this.FIELD_DROPDOWN_COLOURED_DIV=this.FIELD_DROPDOWN_NO_BORDER_RECT_SHADOW=!0,this.FIELD_DROPDOWN_SVG_ARROW_PADDING=this.FIELD_BORDER_RECT_X_PADDING,this.FIELD_COLOUR_FULL_BLOCK=this.FIELD_TEXTINPUT_BOX_SHADOW=!0,this.FIELD_COLOUR_DEFAULT_WIDTH=2*this.GRID_UNIT,this.FIELD_COLOUR_DEFAULT_HEIGHT=4*this.GRID_UNIT,this.FIELD_CHECKBOX_X_OFFSET=1*this.GRID_UNIT,this.MAX_DYNAMIC_CONNECTION_SHAPE_WIDTH=12*this.GRID_UNIT,this.SELECTED_GLOW_COLOUR="#fff200",this.SELECTED_GLOW_SIZE=.5,this.REPLACEMENT_GLOW_COLOUR="#fff200",this.REPLACEMENT_GLOW_SIZE=2,this.selectedGlowFilterId="",this.selectedGlowFilter_=null,this.replacementGlowFilterId="",this.replacementGlowFilter_=null},t.utils.object.inherits(t.zelos.ConstantProvider,t.blockRendering.ConstantProvider),t.zelos.ConstantProvider.prototype.setFontConstants_=function(e){t.zelos.ConstantProvider.superClass_.setFontConstants_.call(this,e),this.FIELD_DROPDOWN_BORDER_RECT_HEIGHT=this.FIELD_BORDER_RECT_HEIGHT=this.FIELD_TEXT_HEIGHT+2*this.FIELD_BORDER_RECT_Y_PADDING},t.zelos.ConstantProvider.prototype.init=function(){t.zelos.ConstantProvider.superClass_.init.call(this),this.HEXAGONAL=this.makeHexagonal(),this.ROUNDED=this.makeRounded(),this.SQUARED=this.makeSquared(),this.STATEMENT_INPUT_NOTCH_OFFSET=this.NOTCH_OFFSET_LEFT+this.INSIDE_CORNERS.rightWidth},t.zelos.ConstantProvider.prototype.setDynamicProperties_=function(e){t.zelos.ConstantProvider.superClass_.setDynamicProperties_.call(this,e),this.SELECTED_GLOW_COLOUR=e.getComponentStyle("selectedGlowColour")||this.SELECTED_GLOW_COLOUR;var o=Number(e.getComponentStyle("selectedGlowSize"));this.SELECTED_GLOW_SIZE=o&&!isNaN(o)?o:this.SELECTED_GLOW_SIZE,this.REPLACEMENT_GLOW_COLOUR=e.getComponentStyle("replacementGlowColour")||this.REPLACEMENT_GLOW_COLOUR,this.REPLACEMENT_GLOW_SIZE=(e=Number(e.getComponentStyle("replacementGlowSize")))&&!isNaN(e)?e:this.REPLACEMENT_GLOW_SIZE},t.zelos.ConstantProvider.prototype.dispose=function(){t.zelos.ConstantProvider.superClass_.dispose.call(this),this.selectedGlowFilter_&&t.utils.dom.removeNode(this.selectedGlowFilter_),this.replacementGlowFilter_&&t.utils.dom.removeNode(this.replacementGlowFilter_)},t.zelos.ConstantProvider.prototype.makeStartHat=function(){var e=this.START_HAT_HEIGHT,o=this.START_HAT_WIDTH;return{height:e,width:o,path:t.utils.svgPaths.curve("c",[t.utils.svgPaths.point(25,-e),t.utils.svgPaths.point(71,-e),t.utils.svgPaths.point(o,0)])}},t.zelos.ConstantProvider.prototype.makeHexagonal=function(){function e(e,i,n){var s=e/2;return s=s>o?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<o.statementInputCount,this.rightSide=this.outputConnection?new t.zelos.RightConnectionShape(this.constants_):null},t.utils.object.inherits(t.zelos.RenderInfo,t.blockRendering.RenderInfo),t.zelos.RenderInfo.prototype.getRenderer=function(){return this.renderer_},t.zelos.RenderInfo.prototype.measure=function(){this.createRows_(),this.addElemSpacing_(),this.addRowSpacing_(),this.adjustXPosition_(),this.computeBounds_(),this.alignRowElements_(),this.finalize_()},t.zelos.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||this.isMultiRow))},t.zelos.RenderInfo.prototype.getDesiredRowWidth_=function(e){return e.hasStatement?this.width-this.startX-(this.constants_.INSIDE_CORNERS.rightWidth||0):t.zelos.RenderInfo.superClass_.getDesiredRowWidth_.call(this,e)},t.zelos.RenderInfo.prototype.getInRowSpacing_=function(e,o){return e&&o||!this.outputConnection||!this.outputConnection.isDynamicShape||this.hasStatementInput||this.bottomRow.hasNextConnection?!e&&o&&t.blockRendering.Types.isStatementInput(o)?this.constants_.STATEMENT_INPUT_PADDING_LEFT:e&&t.blockRendering.Types.isLeftRoundedCorner(e)&&o&&(t.blockRendering.Types.isPreviousConnection(o)||t.blockRendering.Types.isNextConnection(o))?o.notchOffset-this.constants_.CORNER_RADIUS:e&&t.blockRendering.Types.isLeftSquareCorner(e)&&o&&t.blockRendering.Types.isHat(o)?this.constants_.NO_PADDING:this.constants_.MEDIUM_PADDING:this.constants_.NO_PADDING},t.zelos.RenderInfo.prototype.getSpacerRowHeight_=function(e,o){if(t.blockRendering.Types.isTopRow(e)&&t.blockRendering.Types.isBottomRow(o))return this.constants_.EMPTY_BLOCK_SPACER_HEIGHT;var i=t.blockRendering.Types.isInputRow(e)&&e.hasStatement,n=t.blockRendering.Types.isInputRow(o)&&o.hasStatement;return n||i?(e=Math.max(this.constants_.NOTCH_HEIGHT,this.constants_.INSIDE_CORNERS.rightHeight||0),n&&i?Math.max(e,this.constants_.DUMMY_INPUT_MIN_HEIGHT):e):t.blockRendering.Types.isTopRow(e)?e.hasPreviousConnection||this.outputConnection&&!this.hasStatementInput?this.constants_.NO_PADDING:Math.abs(this.constants_.NOTCH_HEIGHT-this.constants_.CORNER_RADIUS):t.blockRendering.Types.isBottomRow(o)?this.outputConnection?!o.hasNextConnection&&this.hasStatementInput?Math.abs(this.constants_.NOTCH_HEIGHT-this.constants_.CORNER_RADIUS):this.constants_.NO_PADDING:Math.max(this.topRow.minHeight,Math.max(this.constants_.NOTCH_HEIGHT,this.constants_.CORNER_RADIUS))-this.constants_.CORNER_RADIUS:this.constants_.MEDIUM_PADDING},t.zelos.RenderInfo.prototype.getSpacerRowWidth_=function(e,o){var i=this.width-this.startX;return t.blockRendering.Types.isInputRow(e)&&e.hasStatement||t.blockRendering.Types.isInputRow(o)&&o.hasStatement?Math.max(i,this.constants_.STATEMENT_INPUT_SPACER_MIN_WIDTH):i},t.zelos.RenderInfo.prototype.getElemCenterline_=function(e,o){if(e.hasStatement&&!t.blockRendering.Types.isSpacer(o)&&!t.blockRendering.Types.isStatementInput(o))return e.yPos+this.constants_.EMPTY_STATEMENT_INPUT_HEIGHT/2;if(t.blockRendering.Types.isInlineInput(o)){var i=o.connectedBlock;if(i&&i.outputConnection&&i.nextConnection)return e.yPos+i.height/2}return t.zelos.RenderInfo.superClass_.getElemCenterline_.call(this,e,o)},t.zelos.RenderInfo.prototype.addInput_=function(e,o){e.type==t.DUMMY_INPUT&&o.hasDummyInput&&o.align==t.ALIGN_LEFT&&e.align==t.ALIGN_RIGHT&&(o.rightAlignedDummyInput=e),t.zelos.RenderInfo.superClass_.addInput_.call(this,e,o)},t.zelos.RenderInfo.prototype.addAlignmentPadding_=function(e,o){if(e.rightAlignedDummyInput){for(var i,n,s=0;(n=e.elements[s])&&(t.blockRendering.Types.isSpacer(n)&&(i=n),!t.blockRendering.Types.isField(n)||n.parentInput!=e.rightAlignedDummyInput);s++);if(i)return i.width+=o,void(e.width+=o)}t.zelos.RenderInfo.superClass_.addAlignmentPadding_.call(this,e,o)},t.zelos.RenderInfo.prototype.adjustXPosition_=function(){for(var e=this.constants_.NOTCH_OFFSET_LEFT+this.constants_.NOTCH_WIDTH,o=e,i=2;i<this.rows.length-1;i+=2){var n=this.rows[i-1],s=this.rows[i],r=this.rows[i+1];if(n=2==i?!!this.topRow.hasPreviousConnection:!!n.followsStatement,r=i+2>=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))&&r<o)||t.blockRendering.Types.isField(a)&&(a.field instanceof t.FieldLabel||a.field instanceof t.FieldImage)||(n.width+=o-r),r+=a.width}}},t.zelos.RenderInfo.prototype.finalizeOutputConnection_=function(){if(this.outputConnection&&this.outputConnection.isDynamicShape){for(var t,e=0,o=0;t=this.rows[o];o++)t.yPos=e,e+=t.height;this.height=e,o=this.bottomRow.hasNextConnection?this.height-this.bottomRow.descenderHeight:this.height,e=this.outputConnection.shape.height(o),o=this.outputConnection.shape.width(o),this.outputConnection.height=e,this.outputConnection.width=o,this.outputConnection.startX=o,this.outputConnection.connectionOffsetY=this.outputConnection.shape.connectionOffsetY(e),this.outputConnection.connectionOffsetX=this.outputConnection.shape.connectionOffsetX(o),t=0,this.hasStatementInput||this.bottomRow.hasNextConnection||(t=o,this.rightSide.height=e,this.rightSide.width=t,this.rightSide.centerline=e/2,this.rightSide.xPos=this.width+t),this.startX=o,this.width+=o+t,this.widthWithChildren+=o+t}},t.zelos.RenderInfo.prototype.finalizeHorizontalAlignment_=function(){if(this.outputConnection&&!this.hasStatementInput&&!this.bottomRow.hasNextConnection){for(var e,o=0,i=0;e=this.rows[i];i++)if(t.blockRendering.Types.isInputRow(e)){o=e.elements[e.elements.length-2];var n=this.getNegativeSpacing_(e.elements[1]),s=this.getNegativeSpacing_(o);o=n+s;var r=this.constants_.MIN_BLOCK_WIDTH+2*this.outputConnection.width;this.width-o<r&&(n=(o=this.width-r)/2,s=o/2),e.elements.unshift(new t.blockRendering.InRowSpacer(this.constants_,-n)),e.elements.push(new t.blockRendering.InRowSpacer(this.constants_,-s))}if(o)for(this.width-=o,this.widthWithChildren-=o,this.rightSide.xPos-=o,i=0;e=this.rows[i];i++)t.blockRendering.Types.isTopOrBottomRow(e)&&(e.elements[1].width-=o,e.elements[1].widthWithConnectedBlocks-=o),e.width-=o,e.widthWithConnectedBlocks-=o}},t.zelos.RenderInfo.prototype.getNegativeSpacing_=function(e){if(!e)return 0;var o=this.outputConnection.width,i=this.outputConnection.shape.type,n=this.constants_;if(this.isMultiRow&&1<this.inputRows.length)switch(i){case n.SHAPES.ROUND:return i=this.constants_.MAX_DYNAMIC_CONNECTION_SHAPE_WIDTH,o-(i=this.height/2>i?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;e+=2){var o=this.rows[e-1],i=this.rows[e],n=this.rows[e+1],s=2==e,r=e+2>=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<o?t.utils.svgPaths.lineOnAxis("V",e.yPos+o):"")+(e.precedesStatement?this.constants_.INSIDE_CORNERS.pathTopRight:"")}else this.outlinePath_+=t.utils.svgPaths.lineOnAxis("V",e.yPos+e.height)},t.zelos.Drawer.prototype.drawRightDynamicConnection_=function(){this.outlinePath_+=this.info_.outputConnection.shape.pathRightDown(this.info_.outputConnection.height)},t.zelos.Drawer.prototype.drawLeftDynamicConnection_=function(){this.positionOutputConnection_(),this.outlinePath_+=this.info_.outputConnection.shape.pathUp(this.info_.outputConnection.height),this.outlinePath_+="z"},t.zelos.Drawer.prototype.drawFlatTop_=function(){var e=this.info_.topRow;this.positionPreviousConnection_(),this.outlinePath_+=t.utils.svgPaths.moveBy(e.xPos,this.info_.startY),this.outlinePath_+=t.utils.svgPaths.lineOnAxis("h",e.width)},t.zelos.Drawer.prototype.drawFlatBottom_=function(){var e=this.info_.bottomRow;this.positionNextConnection_(),this.outlinePath_+=t.utils.svgPaths.lineOnAxis("V",e.baseline),this.outlinePath_+=t.utils.svgPaths.lineOnAxis("h",-e.width)},t.zelos.Drawer.prototype.drawInlineInput_=function(e){this.positionInlineInputConnection_(e);var o=e.input.name;if(!e.connectedBlock&&!this.info_.isInsertionMarker){var i=e.width-2*e.connectionWidth;e=t.utils.svgPaths.moveTo(e.xPos+e.connectionWidth,e.centerline-e.height/2)+t.utils.svgPaths.lineOnAxis("h",i)+e.shape.pathRightDown(e.height)+t.utils.svgPaths.lineOnAxis("h",-i)+e.shape.pathUp(e.height)+"z",this.block_.pathObject.setOutlinePath(o,e)}},t.zelos.Drawer.prototype.drawStatementInput_=function(e){var o=e.getLastInput(),i=o.xPos+o.notchOffset+o.shape.width,n=o.shape.pathRight+t.utils.svgPaths.lineOnAxis("h",-(o.notchOffset-this.constants_.INSIDE_CORNERS.width))+this.constants_.INSIDE_CORNERS.pathTop,s=e.height-2*this.constants_.INSIDE_CORNERS.height;o=this.constants_.INSIDE_CORNERS.pathBottom+t.utils.svgPaths.lineOnAxis("h",o.notchOffset-this.constants_.INSIDE_CORNERS.width)+(o.connectedBottomNextConnection?"":o.shape.pathLeft),this.outlinePath_+=t.utils.svgPaths.lineOnAxis("H",i)+n+t.utils.svgPaths.lineOnAxis("v",s)+o+t.utils.svgPaths.lineOnAxis("H",e.xPos+e.width),this.positionStatementInputConnection_(e)},t.zelos.PathObject=function(e,o,i){t.zelos.PathObject.superClass_.constructor.call(this,e,o,i),this.constants=i,this.svgPathSelected_=null,this.outlines_={},this.outputShapeType=this.remainingOutlines_=null},t.utils.object.inherits(t.zelos.PathObject,t.blockRendering.PathObject),t.zelos.PathObject.prototype.setPath=function(e){t.zelos.PathObject.superClass_.setPath.call(this,e),this.svgPathSelected_&&this.svgPathSelected_.setAttribute("d",e)},t.zelos.PathObject.prototype.applyColour=function(e){t.zelos.PathObject.superClass_.applyColour.call(this,e),e.isShadow()&&e.getParent()&&this.svgPath.setAttribute("stroke",e.getParent().style.colourTertiary),e=0;for(var o,i=Object.keys(this.outlines_);o=i[e];e++)this.outlines_[o].setAttribute("fill",this.style.colourTertiary)},t.zelos.PathObject.prototype.flipRTL=function(){t.zelos.PathObject.superClass_.flipRTL.call(this);for(var e,o=0,i=Object.keys(this.outlines_);e=i[o];o++)this.outlines_[e].setAttribute("transform","scale(-1 1)")},t.zelos.PathObject.prototype.updateSelected=function(t){this.setClass_("blocklySelected",t),t?this.svgPathSelected_||(this.svgPathSelected_=this.svgPath.cloneNode(!0),this.svgPathSelected_.setAttribute("fill","none"),this.svgPathSelected_.setAttribute("filter","url(#"+this.constants.selectedGlowFilterId+")"),this.svgRoot.appendChild(this.svgPathSelected_)):this.svgPathSelected_&&(this.svgRoot.removeChild(this.svgPathSelected_),this.svgPathSelected_=null)},t.zelos.PathObject.prototype.updateReplacementFade=function(t){this.setClass_("blocklyReplaceable",t),t?this.svgPath.setAttribute("filter","url(#"+this.constants.replacementGlowFilterId+")"):this.svgPath.removeAttribute("filter")},t.zelos.PathObject.prototype.updateShapeForInputHighlight=function(t,e){t=t.getParentInput().name,(t=this.getOutlinePath_(t))&&(e?t.setAttribute("filter","url(#"+this.constants.replacementGlowFilterId+")"):t.removeAttribute("filter"))},t.zelos.PathObject.prototype.beginDrawing=function(){this.remainingOutlines_={};for(var t,e=0,o=Object.keys(this.outlines_);t=o[e];e++)this.remainingOutlines_[t]=1},t.zelos.PathObject.prototype.endDrawing=function(){if(this.remainingOutlines_)for(var t,e=0,o=Object.keys(this.remainingOutlines_);t=o[e];e++)this.removeOutlinePath_(t);this.remainingOutlines_=null},t.zelos.PathObject.prototype.setOutlinePath=function(t,e){(t=this.getOutlinePath_(t)).setAttribute("d",e),t.setAttribute("fill",this.style.colourTertiary)},t.zelos.PathObject.prototype.getOutlinePath_=function(e){return this.outlines_[e]||(this.outlines_[e]=t.utils.dom.createSvgElement("path",{class:"blocklyOutlinePath",d:""},this.svgRoot)),this.remainingOutlines_&&delete this.remainingOutlines_[e],this.outlines_[e]},t.zelos.PathObject.prototype.removeOutlinePath_=function(t){this.outlines_[t].parentNode.removeChild(this.outlines_[t]),delete this.outlines_[t]},t.zelos.MarkerSvg=function(e,o,i){t.zelos.MarkerSvg.superClass_.constructor.call(this,e,o,i)},t.utils.object.inherits(t.zelos.MarkerSvg,t.blockRendering.MarkerSvg),t.zelos.MarkerSvg.prototype.showWithInput_=function(t){var e=t.getSourceBlock();t=t.getLocation().getOffsetInBlock(),this.positionCircle_(t.x,t.y),this.setParent_(e),this.showCurrent_()},t.zelos.MarkerSvg.prototype.showWithBlock_=function(t){var e=(t=t.getLocation()).getHeightWidth();this.positionRect_(0,0,e.width,e.height),this.setParent_(t),this.showCurrent_()},t.zelos.MarkerSvg.prototype.positionCircle_=function(t,e){this.markerCircle_.setAttribute("cx",t),this.markerCircle_.setAttribute("cy",e),this.currentMarkerSvg=this.markerCircle_},t.zelos.MarkerSvg.prototype.showAtLocation_=function(e){var o=!1;e.getType()==t.ASTNode.types.OUTPUT?(this.showWithInput_(e),o=!0):e.getType()==t.ASTNode.types.BLOCK&&(this.showWithBlock_(e),o=!0),o||t.zelos.MarkerSvg.superClass_.showAtLocation_.call(this,e)},t.zelos.MarkerSvg.prototype.hide=function(){t.zelos.MarkerSvg.superClass_.hide.call(this),this.markerCircle_.style.display="none"},t.zelos.MarkerSvg.prototype.createDomInternal_=function(){if(t.zelos.MarkerSvg.superClass_.createDomInternal_.call(this),this.markerCircle_=t.utils.dom.createSvgElement("circle",{r:this.constants_.CURSOR_RADIUS,style:"display: none","stroke-width":this.constants_.CURSOR_STROKE_WIDTH},this.markerSvg_),this.isCursor()){var e=this.getBlinkProperties_();t.utils.dom.createSvgElement("animate",e,this.markerCircle_)}return this.markerSvg_},t.zelos.MarkerSvg.prototype.applyColour_=function(){t.zelos.MarkerSvg.superClass_.applyColour_.call(this),this.markerCircle_.setAttribute("fill",this.colour_),this.markerCircle_.setAttribute("stroke",this.colour_),this.isCursor()&&this.markerCircle_.firstChild.setAttribute("values",this.colour_+";transparent;transparent;")},t.zelos.Renderer=function(e){t.zelos.Renderer.superClass_.constructor.call(this,e)},t.utils.object.inherits(t.zelos.Renderer,t.blockRendering.Renderer),t.zelos.Renderer.prototype.makeConstants_=function(){return new t.zelos.ConstantProvider},t.zelos.Renderer.prototype.makeRenderInfo_=function(e){return new t.zelos.RenderInfo(this,e)},t.zelos.Renderer.prototype.makeDrawer_=function(e,o){return new t.zelos.Drawer(e,o)},t.zelos.Renderer.prototype.makeMarkerDrawer=function(e,o){return new t.zelos.MarkerSvg(e,this.getConstants(),o)},t.zelos.Renderer.prototype.makePathObject=function(e,o){return new t.zelos.PathObject(e,o,this.getConstants())},t.zelos.Renderer.prototype.shouldHighlightConnection=function(e){return e.type!=t.INPUT_VALUE&&e.type!==t.OUTPUT_VALUE},t.zelos.Renderer.prototype.getConnectionPreviewMethod=function(e,o,i){return o.type==t.OUTPUT_VALUE?e.isConnected()?t.InsertionMarkerManager.PREVIEW_TYPE.REPLACEMENT_FADE:t.InsertionMarkerManager.PREVIEW_TYPE.INPUT_OUTLINE:t.zelos.Renderer.superClass_.getConnectionPreviewMethod(e,o,i)},t.blockRendering.register("zelos",t.zelos.Renderer),t.Themes.Dark=t.Theme.defineTheme("dark",{base:t.Themes.Classic,componentStyles:{workspaceBackgroundColour:"#1e1e1e",toolboxBackgroundColour:"#333",toolboxForegroundColour:"#fff",flyoutBackgroundColour:"#252526",flyoutForegroundColour:"#ccc",flyoutOpacity:1,scrollbarColour:"#797979",insertionMarkerColour:"#fff",insertionMarkerOpacity:.3,scrollbarOpacity:.4,cursorColour:"#d0d0d0"}}),t.Themes.Deuteranopia={},t.Themes.Deuteranopia.defaultBlockStyles={colour_blocks:{colourPrimary:"#f2a72c",colourSecondary:"#f1c172",colourTertiary:"#da921c"},list_blocks:{colourPrimary:"#7d65ab",colourSecondary:"#a88be0",colourTertiary:"#66518e"},logic_blocks:{colourPrimary:"#9fd2f1",colourSecondary:"#c0e0f4",colourTertiary:"#74bae5"},loop_blocks:{colourPrimary:"#795a07",colourSecondary:"#ac8726",colourTertiary:"#c4a03f"},math_blocks:{colourPrimary:"#e6da39",colourSecondary:"#f3ec8e",colourTertiary:"#f2eeb7"},procedure_blocks:{colourPrimary:"#590721",colourSecondary:"#8c475d",colourTertiary:"#885464"},text_blocks:{colourPrimary:"#058863",colourSecondary:"#5ecfaf",colourTertiary:"#04684c"},variable_blocks:{colourPrimary:"#47025a",colourSecondary:"#820fa1",colourTertiary:"#8e579d"},variable_dynamic_blocks:{colourPrimary:"#47025a",colourSecondary:"#820fa1",colourTertiary:"#8e579d"}},t.Themes.Deuteranopia.categoryStyles={colour_category:{colour:"#f2a72c"},list_category:{colour:"#7d65ab"},logic_category:{colour:"#9fd2f1"},loop_category:{colour:"#795a07"},math_category:{colour:"#e6da39"},procedure_category:{colour:"#590721"},text_category:{colour:"#058863"},variable_category:{colour:"#47025a"},variable_dynamic_category:{colour:"#47025a"}},t.Themes.Deuteranopia=new t.Theme("deuteranopia",t.Themes.Deuteranopia.defaultBlockStyles,t.Themes.Deuteranopia.categoryStyles),t.Themes.HighContrast={},t.Themes.HighContrast.defaultBlockStyles={colour_blocks:{colourPrimary:"#a52714",colourSecondary:"#FB9B8C",colourTertiary:"#FBE1DD"},list_blocks:{colourPrimary:"#4a148c",colourSecondary:"#AD7BE9",colourTertiary:"#CDB6E9"},logic_blocks:{colourPrimary:"#01579b",colourSecondary:"#64C7FF",colourTertiary:"#C5EAFF"},loop_blocks:{colourPrimary:"#33691e",colourSecondary:"#9AFF78",colourTertiary:"#E1FFD7"},math_blocks:{colourPrimary:"#1a237e",colourSecondary:"#8A9EFF",colourTertiary:"#DCE2FF"},procedure_blocks:{colourPrimary:"#006064",colourSecondary:"#77E6EE",colourTertiary:"#CFECEE"},text_blocks:{colourPrimary:"#004d40",colourSecondary:"#5ae27c",colourTertiary:"#D2FFDD"},variable_blocks:{colourPrimary:"#880e4f",colourSecondary:"#FF73BE",colourTertiary:"#FFD4EB"},variable_dynamic_blocks:{colourPrimary:"#880e4f",colourSecondary:"#FF73BE",colourTertiary:"#FFD4EB"},hat_blocks:{colourPrimary:"#880e4f",colourSecondary:"#FF73BE",colourTertiary:"#FFD4EB",hat:"cap"}},t.Themes.HighContrast.categoryStyles={colour_category:{colour:"#a52714"},list_category:{colour:"#4a148c"},logic_category:{colour:"#01579b"},loop_category:{colour:"#33691e"},math_category:{colour:"#1a237e"},procedure_category:{colour:"#006064"},text_category:{colour:"#004d40"},variable_category:{colour:"#880e4f"},variable_dynamic_category:{colour:"#880e4f"}},t.Themes.HighContrast=new t.Theme("highcontrast",t.Themes.HighContrast.defaultBlockStyles,t.Themes.HighContrast.categoryStyles),t.Themes.HighContrast.setComponentStyle("selectedGlowColour","#000000"),t.Themes.HighContrast.setComponentStyle("selectedGlowSize",1),t.Themes.HighContrast.setComponentStyle("replacementGlowColour","#000000"),t.Themes.HighContrast.setFontStyle({family:null,weight:null,size:16}),t.Themes.Tritanopia={},t.Themes.Tritanopia.defaultBlockStyles={colour_blocks:{colourPrimary:"#05427f",colourSecondary:"#2974c0",colourTertiary:"#2d74bb"},list_blocks:{colourPrimary:"#b69ce8",colourSecondary:"#ccbaef",colourTertiary:"#9176c5"},logic_blocks:{colourPrimary:"#9fd2f1",colourSecondary:"#c0e0f4",colourTertiary:"#74bae5"},loop_blocks:{colourPrimary:"#aa1846",colourSecondary:"#d36185",colourTertiary:"#7c1636"},math_blocks:{colourPrimary:"#e6da39",colourSecondary:"#f3ec8e",colourTertiary:"#f2eeb7"},procedure_blocks:{colourPrimary:"#590721",colourSecondary:"#8c475d",colourTertiary:"#885464"},text_blocks:{colourPrimary:"#058863",colourSecondary:"#5ecfaf",colourTertiary:"#04684c"},variable_blocks:{colourPrimary:"#4b2d84",colourSecondary:"#816ea7",colourTertiary:"#83759e"},variable_dynamic_blocks:{colourPrimary:"#4b2d84",colourSecondary:"#816ea7",colourTertiary:"#83759e"}},t.Themes.Tritanopia.categoryStyles={colour_category:{colour:"#05427f"},list_category:{colour:"#b69ce8"},logic_category:{colour:"#9fd2f1"},loop_category:{colour:"#aa1846"},math_category:{colour:"#e6da39"},procedure_category:{colour:"#590721"},text_category:{colour:"#058863"},variable_category:{colour:"#4b2d84"},variable_dynamic_category:{colour:"#4b2d84"}},t.Themes.Tritanopia=new t.Theme("tritanopia",t.Themes.Tritanopia.defaultBlockStyles,t.Themes.Tritanopia.categoryStyles),t.requires={},t})?i.apply(e,n):i)||(t.exports=s)}).call(this,o(7))},function(t,e){var o;o=function(){return this}();try{o=o||new Function("return this")()}catch(t){"object"==typeof window&&(o=window)}t.exports=o},function(t,e,o){var i,n,s;n=[o(3)],void 0===(s="function"==typeof(i=function(t){return(t={Msg:{}}).Msg.ADD_COMMENT="Add Comment",t.Msg.CANNOT_DELETE_VARIABLE_PROCEDURE="Can't delete the variable '%1' because it's part of the definition of the function '%2'",t.Msg.CHANGE_VALUE_TITLE="Change value:",t.Msg.CLEAN_UP="Clean up Blocks",t.Msg.COLLAPSED_WARNINGS_WARNING="Collapsed blocks contain warnings.",t.Msg.COLLAPSE_ALL="Collapse Blocks",t.Msg.COLLAPSE_BLOCK="Collapse Block",t.Msg.COLOUR_BLEND_COLOUR1="colour 1",t.Msg.COLOUR_BLEND_COLOUR2="colour 2",t.Msg.COLOUR_BLEND_HELPURL="https://meyerweb.com/eric/tools/color-blend/#:::rgbp",t.Msg.COLOUR_BLEND_RATIO="ratio",t.Msg.COLOUR_BLEND_TITLE="blend",t.Msg.COLOUR_BLEND_TOOLTIP="Blends two colours together with a given ratio (0.0 - 1.0).",t.Msg.COLOUR_PICKER_HELPURL="https://en.wikipedia.org/wiki/Color",t.Msg.COLOUR_PICKER_TOOLTIP="Choose a colour from the palette.",t.Msg.COLOUR_RANDOM_HELPURL="http://randomcolour.com",t.Msg.COLOUR_RANDOM_TITLE="random colour",t.Msg.COLOUR_RANDOM_TOOLTIP="Choose a colour at random.",t.Msg.COLOUR_RGB_BLUE="blue",t.Msg.COLOUR_RGB_GREEN="green",t.Msg.COLOUR_RGB_HELPURL="https://www.december.com/html/spec/colorpercompact.html",t.Msg.COLOUR_RGB_RED="red",t.Msg.COLOUR_RGB_TITLE="colour with",t.Msg.COLOUR_RGB_TOOLTIP="Create a colour with the specified amount of red, green, and blue. All values must be between 0 and 100.",t.Msg.CONTROLS_FLOW_STATEMENTS_HELPURL="https://github.com/google/blockly/wiki/Loops#loop-termination-blocks",t.Msg.CONTROLS_FLOW_STATEMENTS_OPERATOR_BREAK="break out of loop",t.Msg.CONTROLS_FLOW_STATEMENTS_OPERATOR_CONTINUE="continue with next iteration of loop",t.Msg.CONTROLS_FLOW_STATEMENTS_TOOLTIP_BREAK="Break out of the containing loop.",t.Msg.CONTROLS_FLOW_STATEMENTS_TOOLTIP_CONTINUE="Skip the rest of this loop, and continue with the next iteration.",t.Msg.CONTROLS_FLOW_STATEMENTS_WARNING="Warning: This block may only be used within a loop.",t.Msg.CONTROLS_FOREACH_HELPURL="https://github.com/google/blockly/wiki/Loops#for-each",t.Msg.CONTROLS_FOREACH_TITLE="for each item %1 in list %2",t.Msg.CONTROLS_FOREACH_TOOLTIP="For each item in a list, set the variable '%1' to the item, and then do some statements.",t.Msg.CONTROLS_FOR_HELPURL="https://github.com/google/blockly/wiki/Loops#count-with",t.Msg.CONTROLS_FOR_TITLE="count with %1 from %2 to %3 by %4",t.Msg.CONTROLS_FOR_TOOLTIP="Have the variable '%1' take on the values from the start number to the end number, counting by the specified interval, and do the specified blocks.",t.Msg.CONTROLS_IF_ELSEIF_TOOLTIP="Add a condition to the if block.",t.Msg.CONTROLS_IF_ELSE_TOOLTIP="Add a final, catch-all condition to the if block.",t.Msg.CONTROLS_IF_HELPURL="https://github.com/google/blockly/wiki/IfElse",t.Msg.CONTROLS_IF_IF_TOOLTIP="Add, remove, or reorder sections to reconfigure this if block.",t.Msg.CONTROLS_IF_MSG_ELSE="else",t.Msg.CONTROLS_IF_MSG_ELSEIF="else if",t.Msg.CONTROLS_IF_MSG_IF="if",t.Msg.CONTROLS_IF_TOOLTIP_1="If a value is true, then do some statements.",t.Msg.CONTROLS_IF_TOOLTIP_2="If a value is true, then do the first block of statements. Otherwise, do the second block of statements.",t.Msg.CONTROLS_IF_TOOLTIP_3="If the first value is true, then do the first block of statements. Otherwise, if the second value is true, do the second block of statements.",t.Msg.CONTROLS_IF_TOOLTIP_4="If the first value is true, then do the first block of statements. Otherwise, if the second value is true, do the second block of statements. If none of the values are true, do the last block of statements.",t.Msg.CONTROLS_REPEAT_HELPURL="https://en.wikipedia.org/wiki/For_loop",t.Msg.CONTROLS_REPEAT_INPUT_DO="do",t.Msg.CONTROLS_REPEAT_TITLE="repeat %1 times",t.Msg.CONTROLS_REPEAT_TOOLTIP="Do some statements several times.",t.Msg.CONTROLS_WHILEUNTIL_HELPURL="https://github.com/google/blockly/wiki/Loops#repeat",t.Msg.CONTROLS_WHILEUNTIL_OPERATOR_UNTIL="repeat until",t.Msg.CONTROLS_WHILEUNTIL_OPERATOR_WHILE="repeat while",t.Msg.CONTROLS_WHILEUNTIL_TOOLTIP_UNTIL="While a value is false, then do some statements.",t.Msg.CONTROLS_WHILEUNTIL_TOOLTIP_WHILE="While a value is true, then do some statements.",t.Msg.DELETE_ALL_BLOCKS="Delete all %1 blocks?",t.Msg.DELETE_BLOCK="Delete Block",t.Msg.DELETE_VARIABLE="Delete the '%1' variable",t.Msg.DELETE_VARIABLE_CONFIRMATION="Delete %1 uses of the '%2' variable?",t.Msg.DELETE_X_BLOCKS="Delete %1 Blocks",t.Msg.DISABLE_BLOCK="Disable Block",t.Msg.DUPLICATE_BLOCK="Duplicate",t.Msg.DUPLICATE_COMMENT="Duplicate Comment",t.Msg.ENABLE_BLOCK="Enable Block",t.Msg.EXPAND_ALL="Expand Blocks",t.Msg.EXPAND_BLOCK="Expand Block",t.Msg.EXTERNAL_INPUTS="External Inputs",t.Msg.HELP="Help",t.Msg.INLINE_INPUTS="Inline Inputs",t.Msg.IOS_CANCEL="Cancel",t.Msg.IOS_ERROR="Error",t.Msg.IOS_OK="OK",t.Msg.IOS_PROCEDURES_ADD_INPUT="+ Add Input",t.Msg.IOS_PROCEDURES_ALLOW_STATEMENTS="Allow statements",t.Msg.IOS_PROCEDURES_DUPLICATE_INPUTS_ERROR="This function has duplicate inputs.",t.Msg.IOS_PROCEDURES_INPUTS="INPUTS",t.Msg.IOS_VARIABLES_ADD_BUTTON="Add",t.Msg.IOS_VARIABLES_ADD_VARIABLE="+ Add Variable",t.Msg.IOS_VARIABLES_DELETE_BUTTON="Delete",t.Msg.IOS_VARIABLES_EMPTY_NAME_ERROR="You can't use an empty variable name.",t.Msg.IOS_VARIABLES_RENAME_BUTTON="Rename",t.Msg.IOS_VARIABLES_VARIABLE_NAME="Variable name",t.Msg.LISTS_CREATE_EMPTY_HELPURL="https://github.com/google/blockly/wiki/Lists#create-empty-list",t.Msg.LISTS_CREATE_EMPTY_TITLE="create empty list",t.Msg.LISTS_CREATE_EMPTY_TOOLTIP="Returns a list, of length 0, containing no data records",t.Msg.LISTS_CREATE_WITH_CONTAINER_TITLE_ADD="list",t.Msg.LISTS_CREATE_WITH_CONTAINER_TOOLTIP="Add, remove, or reorder sections to reconfigure this list block.",t.Msg.LISTS_CREATE_WITH_HELPURL="https://github.com/google/blockly/wiki/Lists#create-list-with",t.Msg.LISTS_CREATE_WITH_INPUT_WITH="create list with",t.Msg.LISTS_CREATE_WITH_ITEM_TOOLTIP="Add an item to the list.",t.Msg.LISTS_CREATE_WITH_TOOLTIP="Create a list with any number of items.",t.Msg.LISTS_GET_INDEX_FIRST="first",t.Msg.LISTS_GET_INDEX_FROM_END="# from end",t.Msg.LISTS_GET_INDEX_FROM_START="#",t.Msg.LISTS_GET_INDEX_GET="get",t.Msg.LISTS_GET_INDEX_GET_REMOVE="get and remove",t.Msg.LISTS_GET_INDEX_LAST="last",t.Msg.LISTS_GET_INDEX_RANDOM="random",t.Msg.LISTS_GET_INDEX_REMOVE="remove",t.Msg.LISTS_GET_INDEX_TAIL="",t.Msg.LISTS_GET_INDEX_TOOLTIP_GET_FIRST="Returns the first item in a list.",t.Msg.LISTS_GET_INDEX_TOOLTIP_GET_FROM="Returns the item at the specified position in a list.",t.Msg.LISTS_GET_INDEX_TOOLTIP_GET_LAST="Returns the last item in a list.",t.Msg.LISTS_GET_INDEX_TOOLTIP_GET_RANDOM="Returns a random item in a list.",t.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_FIRST="Removes and returns the first item in a list.",t.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_FROM="Removes and returns the item at the specified position in a list.",t.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_LAST="Removes and returns the last item in a list.",t.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_RANDOM="Removes and returns a random item in a list.",t.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_FIRST="Removes the first item in a list.",t.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_FROM="Removes the item at the specified position in a list.",t.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_LAST="Removes the last item in a list.",t.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_RANDOM="Removes a random item in a list.",t.Msg.LISTS_GET_SUBLIST_END_FROM_END="to # from end",t.Msg.LISTS_GET_SUBLIST_END_FROM_START="to #",t.Msg.LISTS_GET_SUBLIST_END_LAST="to last",t.Msg.LISTS_GET_SUBLIST_HELPURL="https://github.com/google/blockly/wiki/Lists#getting-a-sublist",t.Msg.LISTS_GET_SUBLIST_START_FIRST="get sub-list from first",t.Msg.LISTS_GET_SUBLIST_START_FROM_END="get sub-list from # from end",t.Msg.LISTS_GET_SUBLIST_START_FROM_START="get sub-list from #",t.Msg.LISTS_GET_SUBLIST_TAIL="",t.Msg.LISTS_GET_SUBLIST_TOOLTIP="Creates a copy of the specified portion of a list.",t.Msg.LISTS_INDEX_FROM_END_TOOLTIP="%1 is the last item.",t.Msg.LISTS_INDEX_FROM_START_TOOLTIP="%1 is the first item.",t.Msg.LISTS_INDEX_OF_FIRST="find first occurrence of item",t.Msg.LISTS_INDEX_OF_HELPURL="https://github.com/google/blockly/wiki/Lists#getting-items-from-a-list",t.Msg.LISTS_INDEX_OF_LAST="find last occurrence of item",t.Msg.LISTS_INDEX_OF_TOOLTIP="Returns the index of the first/last occurrence of the item in the list. Returns %1 if item is not found.",t.Msg.LISTS_INLIST="in list",t.Msg.LISTS_ISEMPTY_HELPURL="https://github.com/google/blockly/wiki/Lists#is-empty",t.Msg.LISTS_ISEMPTY_TITLE="%1 is empty",t.Msg.LISTS_ISEMPTY_TOOLTIP="Returns true if the list is empty.",t.Msg.LISTS_LENGTH_HELPURL="https://github.com/google/blockly/wiki/Lists#length-of",t.Msg.LISTS_LENGTH_TITLE="length of %1",t.Msg.LISTS_LENGTH_TOOLTIP="Returns the length of a list.",t.Msg.LISTS_REPEAT_HELPURL="https://github.com/google/blockly/wiki/Lists#create-list-with",t.Msg.LISTS_REPEAT_TITLE="create list with item %1 repeated %2 times",t.Msg.LISTS_REPEAT_TOOLTIP="Creates a list consisting of the given value repeated the specified number of times.",t.Msg.LISTS_REVERSE_HELPURL="https://github.com/google/blockly/wiki/Lists#reversing-a-list",t.Msg.LISTS_REVERSE_MESSAGE0="reverse %1",t.Msg.LISTS_REVERSE_TOOLTIP="Reverse a copy of a list.",t.Msg.LISTS_SET_INDEX_HELPURL="https://github.com/google/blockly/wiki/Lists#in-list--set",t.Msg.LISTS_SET_INDEX_INPUT_TO="as",t.Msg.LISTS_SET_INDEX_INSERT="insert at",t.Msg.LISTS_SET_INDEX_SET="set",t.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_FIRST="Inserts the item at the start of a list.",t.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_FROM="Inserts the item at the specified position in a list.",t.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_LAST="Append the item to the end of a list.",t.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_RANDOM="Inserts the item randomly in a list.",t.Msg.LISTS_SET_INDEX_TOOLTIP_SET_FIRST="Sets the first item in a list.",t.Msg.LISTS_SET_INDEX_TOOLTIP_SET_FROM="Sets the item at the specified position in a list.",t.Msg.LISTS_SET_INDEX_TOOLTIP_SET_LAST="Sets the last item in a list.",t.Msg.LISTS_SET_INDEX_TOOLTIP_SET_RANDOM="Sets a random item in a list.",t.Msg.LISTS_SORT_HELPURL="https://github.com/google/blockly/wiki/Lists#sorting-a-list",t.Msg.LISTS_SORT_ORDER_ASCENDING="ascending",t.Msg.LISTS_SORT_ORDER_DESCENDING="descending",t.Msg.LISTS_SORT_TITLE="sort %1 %2 %3",t.Msg.LISTS_SORT_TOOLTIP="Sort a copy of a list.",t.Msg.LISTS_SORT_TYPE_IGNORECASE="alphabetic, ignore case",t.Msg.LISTS_SORT_TYPE_NUMERIC="numeric",t.Msg.LISTS_SORT_TYPE_TEXT="alphabetic",t.Msg.LISTS_SPLIT_HELPURL="https://github.com/google/blockly/wiki/Lists#splitting-strings-and-joining-lists",t.Msg.LISTS_SPLIT_LIST_FROM_TEXT="make list from text",t.Msg.LISTS_SPLIT_TEXT_FROM_LIST="make text from list",t.Msg.LISTS_SPLIT_TOOLTIP_JOIN="Join a list of texts into one text, separated by a delimiter.",t.Msg.LISTS_SPLIT_TOOLTIP_SPLIT="Split text into a list of texts, breaking at each delimiter.",t.Msg.LISTS_SPLIT_WITH_DELIMITER="with delimiter",t.Msg.LOGIC_BOOLEAN_FALSE="false",t.Msg.LOGIC_BOOLEAN_HELPURL="https://github.com/google/blockly/wiki/Logic#values",t.Msg.LOGIC_BOOLEAN_TOOLTIP="Returns either true or false.",t.Msg.LOGIC_BOOLEAN_TRUE="true",t.Msg.LOGIC_COMPARE_HELPURL="https://en.wikipedia.org/wiki/Inequality_(mathematics)",t.Msg.LOGIC_COMPARE_TOOLTIP_EQ="Return true if both inputs equal each other.",t.Msg.LOGIC_COMPARE_TOOLTIP_GT="Return true if the first input is greater than the second input.",t.Msg.LOGIC_COMPARE_TOOLTIP_GTE="Return true if the first input is greater than or equal to the second input.",t.Msg.LOGIC_COMPARE_TOOLTIP_LT="Return true if the first input is smaller than the second input.",t.Msg.LOGIC_COMPARE_TOOLTIP_LTE="Return true if the first input is smaller than or equal to the second input.",t.Msg.LOGIC_COMPARE_TOOLTIP_NEQ="Return true if both inputs are not equal to each other.",t.Msg.LOGIC_NEGATE_HELPURL="https://github.com/google/blockly/wiki/Logic#not",t.Msg.LOGIC_NEGATE_TITLE="not %1",t.Msg.LOGIC_NEGATE_TOOLTIP="Returns true if the input is false. Returns false if the input is true.",t.Msg.LOGIC_NULL="null",t.Msg.LOGIC_NULL_HELPURL="https://en.wikipedia.org/wiki/Nullable_type",t.Msg.LOGIC_NULL_TOOLTIP="Returns null.",t.Msg.LOGIC_OPERATION_AND="and",t.Msg.LOGIC_OPERATION_HELPURL="https://github.com/google/blockly/wiki/Logic#logical-operations",t.Msg.LOGIC_OPERATION_OR="or",t.Msg.LOGIC_OPERATION_TOOLTIP_AND="Return true if both inputs are true.",t.Msg.LOGIC_OPERATION_TOOLTIP_OR="Return true if at least one of the inputs is true.",t.Msg.LOGIC_TERNARY_CONDITION="test",t.Msg.LOGIC_TERNARY_HELPURL="https://en.wikipedia.org/wiki/%3F:",t.Msg.LOGIC_TERNARY_IF_FALSE="if false",t.Msg.LOGIC_TERNARY_IF_TRUE="if true",t.Msg.LOGIC_TERNARY_TOOLTIP="Check the condition in 'test'. If the condition is true, returns the 'if true' value; otherwise returns the 'if false' value.",t.Msg.MATH_ADDITION_SYMBOL="+",t.Msg.MATH_ARITHMETIC_HELPURL="https://en.wikipedia.org/wiki/Arithmetic",t.Msg.MATH_ARITHMETIC_TOOLTIP_ADD="Return the sum of the two numbers.",t.Msg.MATH_ARITHMETIC_TOOLTIP_DIVIDE="Return the quotient of the two numbers.",t.Msg.MATH_ARITHMETIC_TOOLTIP_MINUS="Return the difference of the two numbers.",t.Msg.MATH_ARITHMETIC_TOOLTIP_MULTIPLY="Return the product of the two numbers.",t.Msg.MATH_ARITHMETIC_TOOLTIP_POWER="Return the first number raised to the power of the second number.",t.Msg.MATH_ATAN2_HELPURL="https://en.wikipedia.org/wiki/Atan2",t.Msg.MATH_ATAN2_TITLE="atan2 of X:%1 Y:%2",t.Msg.MATH_ATAN2_TOOLTIP="Return the arctangent of point (X, Y) in degrees from -180 to 180.",t.Msg.MATH_CHANGE_HELPURL="https://en.wikipedia.org/wiki/Programming_idiom#Incrementing_a_counter",t.Msg.MATH_CHANGE_TITLE="change %1 by %2",t.Msg.MATH_CHANGE_TOOLTIP="Add a number to variable '%1'.",t.Msg.MATH_CONSTANT_HELPURL="https://en.wikipedia.org/wiki/Mathematical_constant",t.Msg.MATH_CONSTANT_TOOLTIP="Return one of the common constants: π (3.141…), e (2.718…), φ (1.618…), sqrt(2) (1.414…), sqrt(½) (0.707…), or ∞ (infinity).",t.Msg.MATH_CONSTRAIN_HELPURL="https://en.wikipedia.org/wiki/Clamping_(graphics)",t.Msg.MATH_CONSTRAIN_TITLE="constrain %1 low %2 high %3",t.Msg.MATH_CONSTRAIN_TOOLTIP="Constrain a number to be between the specified limits (inclusive).",t.Msg.MATH_DIVISION_SYMBOL="÷",t.Msg.MATH_IS_DIVISIBLE_BY="is divisible by",t.Msg.MATH_IS_EVEN="is even",t.Msg.MATH_IS_NEGATIVE="is negative",t.Msg.MATH_IS_ODD="is odd",t.Msg.MATH_IS_POSITIVE="is positive",t.Msg.MATH_IS_PRIME="is prime",t.Msg.MATH_IS_TOOLTIP="Check if a number is an even, odd, prime, whole, positive, negative, or if it is divisible by certain number. Returns true or false.",t.Msg.MATH_IS_WHOLE="is whole",t.Msg.MATH_MODULO_HELPURL="https://en.wikipedia.org/wiki/Modulo_operation",t.Msg.MATH_MODULO_TITLE="remainder of %1 ÷ %2",t.Msg.MATH_MODULO_TOOLTIP="Return the remainder from dividing the two numbers.",t.Msg.MATH_MULTIPLICATION_SYMBOL="×",t.Msg.MATH_NUMBER_HELPURL="https://en.wikipedia.org/wiki/Number",t.Msg.MATH_NUMBER_TOOLTIP="A number.",t.Msg.MATH_ONLIST_HELPURL="",t.Msg.MATH_ONLIST_OPERATOR_AVERAGE="average of list",t.Msg.MATH_ONLIST_OPERATOR_MAX="max of list",t.Msg.MATH_ONLIST_OPERATOR_MEDIAN="median of list",t.Msg.MATH_ONLIST_OPERATOR_MIN="min of list",t.Msg.MATH_ONLIST_OPERATOR_MODE="modes of list",t.Msg.MATH_ONLIST_OPERATOR_RANDOM="random item of list",t.Msg.MATH_ONLIST_OPERATOR_STD_DEV="standard deviation of list",t.Msg.MATH_ONLIST_OPERATOR_SUM="sum of list",t.Msg.MATH_ONLIST_TOOLTIP_AVERAGE="Return the average (arithmetic mean) of the numeric values in the list.",t.Msg.MATH_ONLIST_TOOLTIP_MAX="Return the largest number in the list.",t.Msg.MATH_ONLIST_TOOLTIP_MEDIAN="Return the median number in the list.",t.Msg.MATH_ONLIST_TOOLTIP_MIN="Return the smallest number in the list.",t.Msg.MATH_ONLIST_TOOLTIP_MODE="Return a list of the most common item(s) in the list.",t.Msg.MATH_ONLIST_TOOLTIP_RANDOM="Return a random element from the list.",t.Msg.MATH_ONLIST_TOOLTIP_STD_DEV="Return the standard deviation of the list.",t.Msg.MATH_ONLIST_TOOLTIP_SUM="Return the sum of all the numbers in the list.",t.Msg.MATH_POWER_SYMBOL="^",t.Msg.MATH_RANDOM_FLOAT_HELPURL="https://en.wikipedia.org/wiki/Random_number_generation",t.Msg.MATH_RANDOM_FLOAT_TITLE_RANDOM="random fraction",t.Msg.MATH_RANDOM_FLOAT_TOOLTIP="Return a random fraction between 0.0 (inclusive) and 1.0 (exclusive).",t.Msg.MATH_RANDOM_INT_HELPURL="https://en.wikipedia.org/wiki/Random_number_generation",t.Msg.MATH_RANDOM_INT_TITLE="random integer from %1 to %2",t.Msg.MATH_RANDOM_INT_TOOLTIP="Return a random integer between the two specified limits, inclusive.",t.Msg.MATH_ROUND_HELPURL="https://en.wikipedia.org/wiki/Rounding",t.Msg.MATH_ROUND_OPERATOR_ROUND="round",t.Msg.MATH_ROUND_OPERATOR_ROUNDDOWN="round down",t.Msg.MATH_ROUND_OPERATOR_ROUNDUP="round up",t.Msg.MATH_ROUND_TOOLTIP="Round a number up or down.",t.Msg.MATH_SINGLE_HELPURL="https://en.wikipedia.org/wiki/Square_root",t.Msg.MATH_SINGLE_OP_ABSOLUTE="absolute",t.Msg.MATH_SINGLE_OP_ROOT="square root",t.Msg.MATH_SINGLE_TOOLTIP_ABS="Return the absolute value of a number.",t.Msg.MATH_SINGLE_TOOLTIP_EXP="Return e to the power of a number.",t.Msg.MATH_SINGLE_TOOLTIP_LN="Return the natural logarithm of a number.",t.Msg.MATH_SINGLE_TOOLTIP_LOG10="Return the base 10 logarithm of a number.",t.Msg.MATH_SINGLE_TOOLTIP_NEG="Return the negation of a number.",t.Msg.MATH_SINGLE_TOOLTIP_POW10="Return 10 to the power of a number.",t.Msg.MATH_SINGLE_TOOLTIP_ROOT="Return the square root of a number.",t.Msg.MATH_SUBTRACTION_SYMBOL="-",t.Msg.MATH_TRIG_ACOS="acos",t.Msg.MATH_TRIG_ASIN="asin",t.Msg.MATH_TRIG_ATAN="atan",t.Msg.MATH_TRIG_COS="cos",t.Msg.MATH_TRIG_HELPURL="https://en.wikipedia.org/wiki/Trigonometric_functions",t.Msg.MATH_TRIG_SIN="sin",t.Msg.MATH_TRIG_TAN="tan",t.Msg.MATH_TRIG_TOOLTIP_ACOS="Return the arccosine of a number.",t.Msg.MATH_TRIG_TOOLTIP_ASIN="Return the arcsine of a number.",t.Msg.MATH_TRIG_TOOLTIP_ATAN="Return the arctangent of a number.",t.Msg.MATH_TRIG_TOOLTIP_COS="Return the cosine of a degree (not radian).",t.Msg.MATH_TRIG_TOOLTIP_SIN="Return the sine of a degree (not radian).",t.Msg.MATH_TRIG_TOOLTIP_TAN="Return the tangent of a degree (not radian).",t.Msg.NEW_COLOUR_VARIABLE="Create colour variable...",t.Msg.NEW_NUMBER_VARIABLE="Create number variable...",t.Msg.NEW_STRING_VARIABLE="Create string variable...",t.Msg.NEW_VARIABLE="Create variable...",t.Msg.NEW_VARIABLE_TITLE="New variable name:",t.Msg.NEW_VARIABLE_TYPE_TITLE="New variable type:",t.Msg.ORDINAL_NUMBER_SUFFIX="",t.Msg.PROCEDURES_ALLOW_STATEMENTS="allow statements",t.Msg.PROCEDURES_BEFORE_PARAMS="with:",t.Msg.PROCEDURES_CALLNORETURN_HELPURL="https://en.wikipedia.org/wiki/Subroutine",t.Msg.PROCEDURES_CALLNORETURN_TOOLTIP="Run the user-defined function '%1'.",t.Msg.PROCEDURES_CALLRETURN_HELPURL="https://en.wikipedia.org/wiki/Subroutine",t.Msg.PROCEDURES_CALLRETURN_TOOLTIP="Run the user-defined function '%1' and use its output.",t.Msg.PROCEDURES_CALL_BEFORE_PARAMS="with:",t.Msg.PROCEDURES_CREATE_DO="Create '%1'",t.Msg.PROCEDURES_DEFNORETURN_COMMENT="Describe this function...",t.Msg.PROCEDURES_DEFNORETURN_DO="",t.Msg.PROCEDURES_DEFNORETURN_HELPURL="https://en.wikipedia.org/wiki/Subroutine",t.Msg.PROCEDURES_DEFNORETURN_PROCEDURE="do something",t.Msg.PROCEDURES_DEFNORETURN_TITLE="to",t.Msg.PROCEDURES_DEFNORETURN_TOOLTIP="Creates a function with no output.",t.Msg.PROCEDURES_DEFRETURN_HELPURL="https://en.wikipedia.org/wiki/Subroutine",t.Msg.PROCEDURES_DEFRETURN_RETURN="return",t.Msg.PROCEDURES_DEFRETURN_TOOLTIP="Creates a function with an output.",t.Msg.PROCEDURES_DEF_DUPLICATE_WARNING="Warning: This function has duplicate parameters.",t.Msg.PROCEDURES_HIGHLIGHT_DEF="Highlight function definition",t.Msg.PROCEDURES_IFRETURN_HELPURL="http://c2.com/cgi/wiki?GuardClause",t.Msg.PROCEDURES_IFRETURN_TOOLTIP="If a value is true, then return a second value.",t.Msg.PROCEDURES_IFRETURN_WARNING="Warning: This block may be used only within a function definition.",t.Msg.PROCEDURES_MUTATORARG_TITLE="input name:",t.Msg.PROCEDURES_MUTATORARG_TOOLTIP="Add an input to the function.",t.Msg.PROCEDURES_MUTATORCONTAINER_TITLE="inputs",t.Msg.PROCEDURES_MUTATORCONTAINER_TOOLTIP="Add, remove, or reorder inputs to this function.",t.Msg.REDO="Redo",t.Msg.REMOVE_COMMENT="Remove Comment",t.Msg.RENAME_VARIABLE="Rename variable...",t.Msg.RENAME_VARIABLE_TITLE="Rename all '%1' variables to:",t.Msg.TEXT_APPEND_HELPURL="https://github.com/google/blockly/wiki/Text#text-modification",t.Msg.TEXT_APPEND_TITLE="to %1 append text %2",t.Msg.TEXT_APPEND_TOOLTIP="Append some text to variable '%1'.",t.Msg.TEXT_CHANGECASE_HELPURL="https://github.com/google/blockly/wiki/Text#adjusting-text-case",t.Msg.TEXT_CHANGECASE_OPERATOR_LOWERCASE="to lower case",t.Msg.TEXT_CHANGECASE_OPERATOR_TITLECASE="to Title Case",t.Msg.TEXT_CHANGECASE_OPERATOR_UPPERCASE="to UPPER CASE",t.Msg.TEXT_CHANGECASE_TOOLTIP="Return a copy of the text in a different case.",t.Msg.TEXT_CHARAT_FIRST="get first letter",t.Msg.TEXT_CHARAT_FROM_END="get letter # from end",t.Msg.TEXT_CHARAT_FROM_START="get letter #",t.Msg.TEXT_CHARAT_HELPURL="https://github.com/google/blockly/wiki/Text#extracting-text",t.Msg.TEXT_CHARAT_LAST="get last letter",t.Msg.TEXT_CHARAT_RANDOM="get random letter",t.Msg.TEXT_CHARAT_TAIL="",t.Msg.TEXT_CHARAT_TITLE="in text %1 %2",t.Msg.TEXT_CHARAT_TOOLTIP="Returns the letter at the specified position.",t.Msg.TEXT_COUNT_HELPURL="https://github.com/google/blockly/wiki/Text#counting-substrings",t.Msg.TEXT_COUNT_MESSAGE0="count %1 in %2",t.Msg.TEXT_COUNT_TOOLTIP="Count how many times some text occurs within some other text.",t.Msg.TEXT_CREATE_JOIN_ITEM_TOOLTIP="Add an item to the text.",t.Msg.TEXT_CREATE_JOIN_TITLE_JOIN="join",t.Msg.TEXT_CREATE_JOIN_TOOLTIP="Add, remove, or reorder sections to reconfigure this text block.",t.Msg.TEXT_GET_SUBSTRING_END_FROM_END="to letter # from end",t.Msg.TEXT_GET_SUBSTRING_END_FROM_START="to letter #",t.Msg.TEXT_GET_SUBSTRING_END_LAST="to last letter",t.Msg.TEXT_GET_SUBSTRING_HELPURL="https://github.com/google/blockly/wiki/Text#extracting-a-region-of-text",t.Msg.TEXT_GET_SUBSTRING_INPUT_IN_TEXT="in text",t.Msg.TEXT_GET_SUBSTRING_START_FIRST="get substring from first letter",t.Msg.TEXT_GET_SUBSTRING_START_FROM_END="get substring from letter # from end",t.Msg.TEXT_GET_SUBSTRING_START_FROM_START="get substring from letter #",t.Msg.TEXT_GET_SUBSTRING_TAIL="",t.Msg.TEXT_GET_SUBSTRING_TOOLTIP="Returns a specified portion of the text.",t.Msg.TEXT_INDEXOF_HELPURL="https://github.com/google/blockly/wiki/Text#finding-text",t.Msg.TEXT_INDEXOF_OPERATOR_FIRST="find first occurrence of text",t.Msg.TEXT_INDEXOF_OPERATOR_LAST="find last occurrence of text",t.Msg.TEXT_INDEXOF_TITLE="in text %1 %2 %3",t.Msg.TEXT_INDEXOF_TOOLTIP="Returns the index of the first/last occurrence of the first text in the second text. Returns %1 if text is not found.",t.Msg.TEXT_ISEMPTY_HELPURL="https://github.com/google/blockly/wiki/Text#checking-for-empty-text",t.Msg.TEXT_ISEMPTY_TITLE="%1 is empty",t.Msg.TEXT_ISEMPTY_TOOLTIP="Returns true if the provided text is empty.",t.Msg.TEXT_JOIN_HELPURL="https://github.com/google/blockly/wiki/Text#text-creation",t.Msg.TEXT_JOIN_TITLE_CREATEWITH="create text with",t.Msg.TEXT_JOIN_TOOLTIP="Create a piece of text by joining together any number of items.",t.Msg.TEXT_LENGTH_HELPURL="https://github.com/google/blockly/wiki/Text#text-modification",t.Msg.TEXT_LENGTH_TITLE="length of %1",t.Msg.TEXT_LENGTH_TOOLTIP="Returns the number of letters (including spaces) in the provided text.",t.Msg.TEXT_PRINT_HELPURL="https://github.com/google/blockly/wiki/Text#printing-text",t.Msg.TEXT_PRINT_TITLE="print %1",t.Msg.TEXT_PRINT_TOOLTIP="Print the specified text, number or other value.",t.Msg.TEXT_PROMPT_HELPURL="https://github.com/google/blockly/wiki/Text#getting-input-from-the-user",t.Msg.TEXT_PROMPT_TOOLTIP_NUMBER="Prompt for user for a number.",t.Msg.TEXT_PROMPT_TOOLTIP_TEXT="Prompt for user for some text.",t.Msg.TEXT_PROMPT_TYPE_NUMBER="prompt for number with message",t.Msg.TEXT_PROMPT_TYPE_TEXT="prompt for text with message",t.Msg.TEXT_REPLACE_HELPURL="https://github.com/google/blockly/wiki/Text#replacing-substrings",t.Msg.TEXT_REPLACE_MESSAGE0="replace %1 with %2 in %3",t.Msg.TEXT_REPLACE_TOOLTIP="Replace all occurances of some text within some other text.",t.Msg.TEXT_REVERSE_HELPURL="https://github.com/google/blockly/wiki/Text#reversing-text",t.Msg.TEXT_REVERSE_MESSAGE0="reverse %1",t.Msg.TEXT_REVERSE_TOOLTIP="Reverses the order of the characters in the text.",t.Msg.TEXT_TEXT_HELPURL="https://en.wikipedia.org/wiki/String_(computer_science)",t.Msg.TEXT_TEXT_TOOLTIP="A letter, word, or line of text.",t.Msg.TEXT_TRIM_HELPURL="https://github.com/google/blockly/wiki/Text#trimming-removing-spaces",t.Msg.TEXT_TRIM_OPERATOR_BOTH="trim spaces from both sides of",t.Msg.TEXT_TRIM_OPERATOR_LEFT="trim spaces from left side of",t.Msg.TEXT_TRIM_OPERATOR_RIGHT="trim spaces from right side of",t.Msg.TEXT_TRIM_TOOLTIP="Return a copy of the text with spaces removed from one or both ends.",t.Msg.TODAY="Today",t.Msg.UNDO="Undo",t.Msg.UNNAMED_KEY="unnamed",t.Msg.VARIABLES_DEFAULT_NAME="item",t.Msg.VARIABLES_GET_CREATE_SET="Create 'set %1'",t.Msg.VARIABLES_GET_HELPURL="https://github.com/google/blockly/wiki/Variables#get",t.Msg.VARIABLES_GET_TOOLTIP="Returns the value of this variable.",t.Msg.VARIABLES_SET="set %1 to %2",t.Msg.VARIABLES_SET_CREATE_GET="Create 'get %1'",t.Msg.VARIABLES_SET_HELPURL="https://github.com/google/blockly/wiki/Variables#set",t.Msg.VARIABLES_SET_TOOLTIP="Sets this variable to be equal to the input.",t.Msg.VARIABLE_ALREADY_EXISTS="A variable named '%1' already exists.",t.Msg.VARIABLE_ALREADY_EXISTS_FOR_ANOTHER_TYPE="A variable named '%1' already exists for another type: '%2'.",t.Msg.WORKSPACE_ARIA_LABEL="Blockly Workspace",t.Msg.WORKSPACE_COMMENT_DEFAULT_TEXT="Say something...",t.Msg.CONTROLS_FOREACH_INPUT_DO=t.Msg.CONTROLS_REPEAT_INPUT_DO,t.Msg.CONTROLS_FOR_INPUT_DO=t.Msg.CONTROLS_REPEAT_INPUT_DO,t.Msg.CONTROLS_IF_ELSEIF_TITLE_ELSEIF=t.Msg.CONTROLS_IF_MSG_ELSEIF,t.Msg.CONTROLS_IF_ELSE_TITLE_ELSE=t.Msg.CONTROLS_IF_MSG_ELSE,t.Msg.CONTROLS_IF_IF_TITLE_IF=t.Msg.CONTROLS_IF_MSG_IF,t.Msg.CONTROLS_IF_MSG_THEN=t.Msg.CONTROLS_REPEAT_INPUT_DO,t.Msg.CONTROLS_WHILEUNTIL_INPUT_DO=t.Msg.CONTROLS_REPEAT_INPUT_DO,t.Msg.LISTS_CREATE_WITH_ITEM_TITLE=t.Msg.VARIABLES_DEFAULT_NAME,t.Msg.LISTS_GET_INDEX_HELPURL=t.Msg.LISTS_INDEX_OF_HELPURL,t.Msg.LISTS_GET_INDEX_INPUT_IN_LIST=t.Msg.LISTS_INLIST,t.Msg.LISTS_GET_SUBLIST_INPUT_IN_LIST=t.Msg.LISTS_INLIST,t.Msg.LISTS_INDEX_OF_INPUT_IN_LIST=t.Msg.LISTS_INLIST,t.Msg.LISTS_SET_INDEX_INPUT_IN_LIST=t.Msg.LISTS_INLIST,t.Msg.MATH_CHANGE_TITLE_ITEM=t.Msg.VARIABLES_DEFAULT_NAME,t.Msg.PROCEDURES_DEFRETURN_COMMENT=t.Msg.PROCEDURES_DEFNORETURN_COMMENT,t.Msg.PROCEDURES_DEFRETURN_DO=t.Msg.PROCEDURES_DEFNORETURN_DO,t.Msg.PROCEDURES_DEFRETURN_PROCEDURE=t.Msg.PROCEDURES_DEFNORETURN_PROCEDURE,t.Msg.PROCEDURES_DEFRETURN_TITLE=t.Msg.PROCEDURES_DEFNORETURN_TITLE,t.Msg.TEXT_APPEND_VARIABLE=t.Msg.VARIABLES_DEFAULT_NAME,t.Msg.TEXT_CREATE_JOIN_ITEM_TITLE_ITEM=t.Msg.VARIABLES_DEFAULT_NAME,t.Msg.MATH_HUE="230",t.Msg.LOOPS_HUE="120",t.Msg.LISTS_HUE="260",t.Msg.LOGIC_HUE="210",t.Msg.VARIABLES_HUE="330",t.Msg.TEXTS_HUE="160",t.Msg.PROCEDURES_HUE="290",t.Msg.COLOUR_HUE="20",t.Msg.VARIABLES_DYNAMIC_HUE="310",t.Msg})?i.apply(e,n):i)||(t.exports=s)},function(t,e,o){var i,n,s;n=[o(3)],void 0===(s="function"==typeof(i=function(t){return t.Blocks={},t.Blocks.colour={},t.Constants={},t.Constants.Colour={},t.Constants.Colour.HUE=20,t.defineBlocksWithJsonArray([{type:"colour_picker",message0:"%1",args0:[{type:"field_colour",name:"COLOUR",colour:"#ff0000"}],output:"Colour",helpUrl:"%{BKY_COLOUR_PICKER_HELPURL}",style:"colour_blocks",tooltip:"%{BKY_COLOUR_PICKER_TOOLTIP}",extensions:["parent_tooltip_when_inline"]},{type:"colour_random",message0:"%{BKY_COLOUR_RANDOM_TITLE}",output:"Colour",helpUrl:"%{BKY_COLOUR_RANDOM_HELPURL}",style:"colour_blocks",tooltip:"%{BKY_COLOUR_RANDOM_TOOLTIP}"},{type:"colour_rgb",message0:"%{BKY_COLOUR_RGB_TITLE} %{BKY_COLOUR_RGB_RED} %1 %{BKY_COLOUR_RGB_GREEN} %2 %{BKY_COLOUR_RGB_BLUE} %3",args0:[{type:"input_value",name:"RED",check:"Number",align:"RIGHT"},{type:"input_value",name:"GREEN",check:"Number",align:"RIGHT"},{type:"input_value",name:"BLUE",check:"Number",align:"RIGHT"}],output:"Colour",helpUrl:"%{BKY_COLOUR_RGB_HELPURL}",style:"colour_blocks",tooltip:"%{BKY_COLOUR_RGB_TOOLTIP}"},{type:"colour_blend",message0:"%{BKY_COLOUR_BLEND_TITLE} %{BKY_COLOUR_BLEND_COLOUR1} %1 %{BKY_COLOUR_BLEND_COLOUR2} %2 %{BKY_COLOUR_BLEND_RATIO} %3",args0:[{type:"input_value",name:"COLOUR1",check:"Colour",align:"RIGHT"},{type:"input_value",name:"COLOUR2",check:"Colour",align:"RIGHT"},{type:"input_value",name:"RATIO",check:"Number",align:"RIGHT"}],output:"Colour",helpUrl:"%{BKY_COLOUR_BLEND_HELPURL}",style:"colour_blocks",tooltip:"%{BKY_COLOUR_BLEND_TOOLTIP}"}]),t.Blocks.lists={},t.Constants.Lists={},t.Constants.Lists.HUE=260,t.defineBlocksWithJsonArray([{type:"lists_create_empty",message0:"%{BKY_LISTS_CREATE_EMPTY_TITLE}",output:"Array",style:"list_blocks",tooltip:"%{BKY_LISTS_CREATE_EMPTY_TOOLTIP}",helpUrl:"%{BKY_LISTS_CREATE_EMPTY_HELPURL}"},{type:"lists_repeat",message0:"%{BKY_LISTS_REPEAT_TITLE}",args0:[{type:"input_value",name:"ITEM"},{type:"input_value",name:"NUM",check:"Number"}],output:"Array",style:"list_blocks",tooltip:"%{BKY_LISTS_REPEAT_TOOLTIP}",helpUrl:"%{BKY_LISTS_REPEAT_HELPURL}"},{type:"lists_reverse",message0:"%{BKY_LISTS_REVERSE_MESSAGE0}",args0:[{type:"input_value",name:"LIST",check:"Array"}],output:"Array",inputsInline:!0,style:"list_blocks",tooltip:"%{BKY_LISTS_REVERSE_TOOLTIP}",helpUrl:"%{BKY_LISTS_REVERSE_HELPURL}"},{type:"lists_isEmpty",message0:"%{BKY_LISTS_ISEMPTY_TITLE}",args0:[{type:"input_value",name:"VALUE",check:["String","Array"]}],output:"Boolean",style:"list_blocks",tooltip:"%{BKY_LISTS_ISEMPTY_TOOLTIP}",helpUrl:"%{BKY_LISTS_ISEMPTY_HELPURL}"},{type:"lists_length",message0:"%{BKY_LISTS_LENGTH_TITLE}",args0:[{type:"input_value",name:"VALUE",check:["String","Array"]}],output:"Number",style:"list_blocks",tooltip:"%{BKY_LISTS_LENGTH_TOOLTIP}",helpUrl:"%{BKY_LISTS_LENGTH_HELPURL}"}]),t.Blocks.lists_create_with={init:function(){this.setHelpUrl(t.Msg.LISTS_CREATE_WITH_HELPURL),this.setStyle("list_blocks"),this.itemCount_=3,this.updateShape_(),this.setOutput(!0,"Array"),this.setMutator(new t.Mutator(["lists_create_with_item"])),this.setTooltip(t.Msg.LISTS_CREATE_WITH_TOOLTIP)},mutationToDom:function(){var e=t.utils.xml.createElement("mutation");return e.setAttribute("items",this.itemCount_),e},domToMutation:function(t){this.itemCount_=parseInt(t.getAttribute("items"),10),this.updateShape_()},decompose:function(t){var e=t.newBlock("lists_create_with_container");e.initSvg();for(var o=e.getInput("STACK").connection,i=0;i<this.itemCount_;i++){var n=t.newBlock("lists_create_with_item");n.initSvg(),o.connect(n.previousConnection),o=n.nextConnection}return e},compose:function(e){var o=e.getInputTargetBlock("STACK");for(e=[];o;)e.push(o.valueConnection_),o=o.nextConnection&&o.nextConnection.targetBlock();for(o=0;o<this.itemCount_;o++){var i=this.getInput("ADD"+o).connection.targetConnection;i&&-1==e.indexOf(i)&&i.disconnect()}for(this.itemCount_=e.length,this.updateShape_(),o=0;o<this.itemCount_;o++)t.Mutator.reconnect(e[o],this,"ADD"+o)},saveConnections:function(t){t=t.getInputTargetBlock("STACK");for(var e=0;t;){var o=this.getInput("ADD"+e);t.valueConnection_=o&&o.connection.targetConnection,e++,t=t.nextConnection&&t.nextConnection.targetBlock()}},updateShape_:function(){this.itemCount_&&this.getInput("EMPTY")?this.removeInput("EMPTY"):this.itemCount_||this.getInput("EMPTY")||this.appendDummyInput("EMPTY").appendField(t.Msg.LISTS_CREATE_EMPTY_TITLE);for(var e=0;e<this.itemCount_;e++)if(!this.getInput("ADD"+e)){var o=this.appendValueInput("ADD"+e).setAlign(t.ALIGN_RIGHT);0==e&&o.appendField(t.Msg.LISTS_CREATE_WITH_INPUT_WITH)}for(;this.getInput("ADD"+e);)this.removeInput("ADD"+e),e++}},t.Blocks.lists_create_with_container={init:function(){this.setStyle("list_blocks"),this.appendDummyInput().appendField(t.Msg.LISTS_CREATE_WITH_CONTAINER_TITLE_ADD),this.appendStatementInput("STACK"),this.setTooltip(t.Msg.LISTS_CREATE_WITH_CONTAINER_TOOLTIP),this.contextMenu=!1}},t.Blocks.lists_create_with_item={init:function(){this.setStyle("list_blocks"),this.appendDummyInput().appendField(t.Msg.LISTS_CREATE_WITH_ITEM_TITLE),this.setPreviousStatement(!0),this.setNextStatement(!0),this.setTooltip(t.Msg.LISTS_CREATE_WITH_ITEM_TOOLTIP),this.contextMenu=!1}},t.Blocks.lists_indexOf={init:function(){var e=[[t.Msg.LISTS_INDEX_OF_FIRST,"FIRST"],[t.Msg.LISTS_INDEX_OF_LAST,"LAST"]];this.setHelpUrl(t.Msg.LISTS_INDEX_OF_HELPURL),this.setStyle("list_blocks"),this.setOutput(!0,"Number"),this.appendValueInput("VALUE").setCheck("Array").appendField(t.Msg.LISTS_INDEX_OF_INPUT_IN_LIST),this.appendValueInput("FIND").appendField(new t.FieldDropdown(e),"END"),this.setInputsInline(!0);var o=this;this.setTooltip((function(){return t.Msg.LISTS_INDEX_OF_TOOLTIP.replace("%1",o.workspace.options.oneBasedIndex?"0":"-1")}))}},t.Blocks.lists_getIndex={init:function(){var e=[[t.Msg.LISTS_GET_INDEX_GET,"GET"],[t.Msg.LISTS_GET_INDEX_GET_REMOVE,"GET_REMOVE"],[t.Msg.LISTS_GET_INDEX_REMOVE,"REMOVE"]];this.WHERE_OPTIONS=[[t.Msg.LISTS_GET_INDEX_FROM_START,"FROM_START"],[t.Msg.LISTS_GET_INDEX_FROM_END,"FROM_END"],[t.Msg.LISTS_GET_INDEX_FIRST,"FIRST"],[t.Msg.LISTS_GET_INDEX_LAST,"LAST"],[t.Msg.LISTS_GET_INDEX_RANDOM,"RANDOM"]],this.setHelpUrl(t.Msg.LISTS_GET_INDEX_HELPURL),this.setStyle("list_blocks"),e=new t.FieldDropdown(e,(function(t){t="REMOVE"==t,this.getSourceBlock().updateStatement_(t)})),this.appendValueInput("VALUE").setCheck("Array").appendField(t.Msg.LISTS_GET_INDEX_INPUT_IN_LIST),this.appendDummyInput().appendField(e,"MODE").appendField("","SPACE"),this.appendDummyInput("AT"),t.Msg.LISTS_GET_INDEX_TAIL&&this.appendDummyInput("TAIL").appendField(t.Msg.LISTS_GET_INDEX_TAIL),this.setInputsInline(!0),this.setOutput(!0),this.updateAt_(!0);var o=this;this.setTooltip((function(){var e=o.getFieldValue("MODE"),i=o.getFieldValue("WHERE"),n="";switch(e+" "+i){case"GET FROM_START":case"GET FROM_END":n=t.Msg.LISTS_GET_INDEX_TOOLTIP_GET_FROM;break;case"GET FIRST":n=t.Msg.LISTS_GET_INDEX_TOOLTIP_GET_FIRST;break;case"GET LAST":n=t.Msg.LISTS_GET_INDEX_TOOLTIP_GET_LAST;break;case"GET RANDOM":n=t.Msg.LISTS_GET_INDEX_TOOLTIP_GET_RANDOM;break;case"GET_REMOVE FROM_START":case"GET_REMOVE FROM_END":n=t.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_FROM;break;case"GET_REMOVE FIRST":n=t.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_FIRST;break;case"GET_REMOVE LAST":n=t.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_LAST;break;case"GET_REMOVE RANDOM":n=t.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_RANDOM;break;case"REMOVE FROM_START":case"REMOVE FROM_END":n=t.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_FROM;break;case"REMOVE FIRST":n=t.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_FIRST;break;case"REMOVE LAST":n=t.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_LAST;break;case"REMOVE RANDOM":n=t.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_RANDOM}return"FROM_START"!=i&&"FROM_END"!=i||(n+="  "+("FROM_START"==i?t.Msg.LISTS_INDEX_FROM_START_TOOLTIP:t.Msg.LISTS_INDEX_FROM_END_TOOLTIP).replace("%1",o.workspace.options.oneBasedIndex?"#1":"#0")),n}))},mutationToDom:function(){var e=t.utils.xml.createElement("mutation");e.setAttribute("statement",!this.outputConnection);var o=this.getInput("AT").type==t.INPUT_VALUE;return e.setAttribute("at",o),e},domToMutation:function(t){var e="true"==t.getAttribute("statement");this.updateStatement_(e),t="false"!=t.getAttribute("at"),this.updateAt_(t)},updateStatement_:function(t){t!=!this.outputConnection&&(this.unplug(!0,!0),t?(this.setOutput(!1),this.setPreviousStatement(!0),this.setNextStatement(!0)):(this.setPreviousStatement(!1),this.setNextStatement(!1),this.setOutput(!0)))},updateAt_:function(e){this.removeInput("AT"),this.removeInput("ORDINAL",!0),e?(this.appendValueInput("AT").setCheck("Number"),t.Msg.ORDINAL_NUMBER_SUFFIX&&this.appendDummyInput("ORDINAL").appendField(t.Msg.ORDINAL_NUMBER_SUFFIX)):this.appendDummyInput("AT");var o=new t.FieldDropdown(this.WHERE_OPTIONS,(function(t){var o="FROM_START"==t||"FROM_END"==t;if(o!=e){var i=this.getSourceBlock();return i.updateAt_(o),i.setFieldValue(t,"WHERE"),null}}));this.getInput("AT").appendField(o,"WHERE"),t.Msg.LISTS_GET_INDEX_TAIL&&this.moveInputBefore("TAIL",null)}},t.Blocks.lists_setIndex={init:function(){var e=[[t.Msg.LISTS_SET_INDEX_SET,"SET"],[t.Msg.LISTS_SET_INDEX_INSERT,"INSERT"]];this.WHERE_OPTIONS=[[t.Msg.LISTS_GET_INDEX_FROM_START,"FROM_START"],[t.Msg.LISTS_GET_INDEX_FROM_END,"FROM_END"],[t.Msg.LISTS_GET_INDEX_FIRST,"FIRST"],[t.Msg.LISTS_GET_INDEX_LAST,"LAST"],[t.Msg.LISTS_GET_INDEX_RANDOM,"RANDOM"]],this.setHelpUrl(t.Msg.LISTS_SET_INDEX_HELPURL),this.setStyle("list_blocks"),this.appendValueInput("LIST").setCheck("Array").appendField(t.Msg.LISTS_SET_INDEX_INPUT_IN_LIST),this.appendDummyInput().appendField(new t.FieldDropdown(e),"MODE").appendField("","SPACE"),this.appendDummyInput("AT"),this.appendValueInput("TO").appendField(t.Msg.LISTS_SET_INDEX_INPUT_TO),this.setInputsInline(!0),this.setPreviousStatement(!0),this.setNextStatement(!0),this.setTooltip(t.Msg.LISTS_SET_INDEX_TOOLTIP),this.updateAt_(!0);var o=this;this.setTooltip((function(){var e=o.getFieldValue("MODE"),i=o.getFieldValue("WHERE"),n="";switch(e+" "+i){case"SET FROM_START":case"SET FROM_END":n=t.Msg.LISTS_SET_INDEX_TOOLTIP_SET_FROM;break;case"SET FIRST":n=t.Msg.LISTS_SET_INDEX_TOOLTIP_SET_FIRST;break;case"SET LAST":n=t.Msg.LISTS_SET_INDEX_TOOLTIP_SET_LAST;break;case"SET RANDOM":n=t.Msg.LISTS_SET_INDEX_TOOLTIP_SET_RANDOM;break;case"INSERT FROM_START":case"INSERT FROM_END":n=t.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_FROM;break;case"INSERT FIRST":n=t.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_FIRST;break;case"INSERT LAST":n=t.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_LAST;break;case"INSERT RANDOM":n=t.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_RANDOM}return"FROM_START"!=i&&"FROM_END"!=i||(n+="  "+t.Msg.LISTS_INDEX_FROM_START_TOOLTIP.replace("%1",o.workspace.options.oneBasedIndex?"#1":"#0")),n}))},mutationToDom:function(){var e=t.utils.xml.createElement("mutation"),o=this.getInput("AT").type==t.INPUT_VALUE;return e.setAttribute("at",o),e},domToMutation:function(t){t="false"!=t.getAttribute("at"),this.updateAt_(t)},updateAt_:function(e){this.removeInput("AT"),this.removeInput("ORDINAL",!0),e?(this.appendValueInput("AT").setCheck("Number"),t.Msg.ORDINAL_NUMBER_SUFFIX&&this.appendDummyInput("ORDINAL").appendField(t.Msg.ORDINAL_NUMBER_SUFFIX)):this.appendDummyInput("AT");var o=new t.FieldDropdown(this.WHERE_OPTIONS,(function(t){var o="FROM_START"==t||"FROM_END"==t;if(o!=e){var i=this.getSourceBlock();return i.updateAt_(o),i.setFieldValue(t,"WHERE"),null}}));this.moveInputBefore("AT","TO"),this.getInput("ORDINAL")&&this.moveInputBefore("ORDINAL","TO"),this.getInput("AT").appendField(o,"WHERE")}},t.Blocks.lists_getSublist={init:function(){this.WHERE_OPTIONS_1=[[t.Msg.LISTS_GET_SUBLIST_START_FROM_START,"FROM_START"],[t.Msg.LISTS_GET_SUBLIST_START_FROM_END,"FROM_END"],[t.Msg.LISTS_GET_SUBLIST_START_FIRST,"FIRST"]],this.WHERE_OPTIONS_2=[[t.Msg.LISTS_GET_SUBLIST_END_FROM_START,"FROM_START"],[t.Msg.LISTS_GET_SUBLIST_END_FROM_END,"FROM_END"],[t.Msg.LISTS_GET_SUBLIST_END_LAST,"LAST"]],this.setHelpUrl(t.Msg.LISTS_GET_SUBLIST_HELPURL),this.setStyle("list_blocks"),this.appendValueInput("LIST").setCheck("Array").appendField(t.Msg.LISTS_GET_SUBLIST_INPUT_IN_LIST),this.appendDummyInput("AT1"),this.appendDummyInput("AT2"),t.Msg.LISTS_GET_SUBLIST_TAIL&&this.appendDummyInput("TAIL").appendField(t.Msg.LISTS_GET_SUBLIST_TAIL),this.setInputsInline(!0),this.setOutput(!0,"Array"),this.updateAt_(1,!0),this.updateAt_(2,!0),this.setTooltip(t.Msg.LISTS_GET_SUBLIST_TOOLTIP)},mutationToDom:function(){var e=t.utils.xml.createElement("mutation"),o=this.getInput("AT1").type==t.INPUT_VALUE;return e.setAttribute("at1",o),o=this.getInput("AT2").type==t.INPUT_VALUE,e.setAttribute("at2",o),e},domToMutation:function(t){var e="true"==t.getAttribute("at1");t="true"==t.getAttribute("at2"),this.updateAt_(1,e),this.updateAt_(2,t)},updateAt_:function(e,o){this.removeInput("AT"+e),this.removeInput("ORDINAL"+e,!0),o?(this.appendValueInput("AT"+e).setCheck("Number"),t.Msg.ORDINAL_NUMBER_SUFFIX&&this.appendDummyInput("ORDINAL"+e).appendField(t.Msg.ORDINAL_NUMBER_SUFFIX)):this.appendDummyInput("AT"+e);var i=new t.FieldDropdown(this["WHERE_OPTIONS_"+e],(function(t){var i="FROM_START"==t||"FROM_END"==t;if(i!=o){var n=this.getSourceBlock();return n.updateAt_(e,i),n.setFieldValue(t,"WHERE"+e),null}}));this.getInput("AT"+e).appendField(i,"WHERE"+e),1==e&&(this.moveInputBefore("AT1","AT2"),this.getInput("ORDINAL1")&&this.moveInputBefore("ORDINAL1","AT2")),t.Msg.LISTS_GET_SUBLIST_TAIL&&this.moveInputBefore("TAIL",null)}},t.Blocks.lists_sort={init:function(){this.jsonInit({message0:t.Msg.LISTS_SORT_TITLE,args0:[{type:"field_dropdown",name:"TYPE",options:[[t.Msg.LISTS_SORT_TYPE_NUMERIC,"NUMERIC"],[t.Msg.LISTS_SORT_TYPE_TEXT,"TEXT"],[t.Msg.LISTS_SORT_TYPE_IGNORECASE,"IGNORE_CASE"]]},{type:"field_dropdown",name:"DIRECTION",options:[[t.Msg.LISTS_SORT_ORDER_ASCENDING,"1"],[t.Msg.LISTS_SORT_ORDER_DESCENDING,"-1"]]},{type:"input_value",name:"LIST",check:"Array"}],output:"Array",style:"list_blocks",tooltip:t.Msg.LISTS_SORT_TOOLTIP,helpUrl:t.Msg.LISTS_SORT_HELPURL})}},t.Blocks.lists_split={init:function(){var e=this,o=new t.FieldDropdown([[t.Msg.LISTS_SPLIT_LIST_FROM_TEXT,"SPLIT"],[t.Msg.LISTS_SPLIT_TEXT_FROM_LIST,"JOIN"]],(function(t){e.updateType_(t)}));this.setHelpUrl(t.Msg.LISTS_SPLIT_HELPURL),this.setStyle("list_blocks"),this.appendValueInput("INPUT").setCheck("String").appendField(o,"MODE"),this.appendValueInput("DELIM").setCheck("String").appendField(t.Msg.LISTS_SPLIT_WITH_DELIMITER),this.setInputsInline(!0),this.setOutput(!0,"Array"),this.setTooltip((function(){var o=e.getFieldValue("MODE");if("SPLIT"==o)return t.Msg.LISTS_SPLIT_TOOLTIP_SPLIT;if("JOIN"==o)return t.Msg.LISTS_SPLIT_TOOLTIP_JOIN;throw Error("Unknown mode: "+o)}))},updateType_:function(t){if(this.getFieldValue("MODE")!=t){var e=this.getInput("INPUT").connection;e.setShadowDom(null);var o=e.targetBlock();o&&(e.disconnect(),o.isShadow()?o.dispose():this.bumpNeighbours())}"SPLIT"==t?(this.outputConnection.setCheck("Array"),this.getInput("INPUT").setCheck("String")):(this.outputConnection.setCheck("String"),this.getInput("INPUT").setCheck("Array"))},mutationToDom:function(){var e=t.utils.xml.createElement("mutation");return e.setAttribute("mode",this.getFieldValue("MODE")),e},domToMutation:function(t){this.updateType_(t.getAttribute("mode"))}},t.Blocks.logic={},t.Constants.Logic={},t.Constants.Logic.HUE=210,t.defineBlocksWithJsonArray([{type:"logic_boolean",message0:"%1",args0:[{type:"field_dropdown",name:"BOOL",options:[["%{BKY_LOGIC_BOOLEAN_TRUE}","TRUE"],["%{BKY_LOGIC_BOOLEAN_FALSE}","FALSE"]]}],output:"Boolean",style:"logic_blocks",tooltip:"%{BKY_LOGIC_BOOLEAN_TOOLTIP}",helpUrl:"%{BKY_LOGIC_BOOLEAN_HELPURL}"},{type:"controls_if",message0:"%{BKY_CONTROLS_IF_MSG_IF} %1",args0:[{type:"input_value",name:"IF0",check:"Boolean"}],message1:"%{BKY_CONTROLS_IF_MSG_THEN} %1",args1:[{type:"input_statement",name:"DO0"}],previousStatement:null,nextStatement:null,style:"logic_blocks",helpUrl:"%{BKY_CONTROLS_IF_HELPURL}",mutator:"controls_if_mutator",extensions:["controls_if_tooltip"]},{type:"controls_ifelse",message0:"%{BKY_CONTROLS_IF_MSG_IF} %1",args0:[{type:"input_value",name:"IF0",check:"Boolean"}],message1:"%{BKY_CONTROLS_IF_MSG_THEN} %1",args1:[{type:"input_statement",name:"DO0"}],message2:"%{BKY_CONTROLS_IF_MSG_ELSE} %1",args2:[{type:"input_statement",name:"ELSE"}],previousStatement:null,nextStatement:null,style:"logic_blocks",tooltip:"%{BKYCONTROLS_IF_TOOLTIP_2}",helpUrl:"%{BKY_CONTROLS_IF_HELPURL}",extensions:["controls_if_tooltip"]},{type:"logic_compare",message0:"%1 %2 %3",args0:[{type:"input_value",name:"A"},{type:"field_dropdown",name:"OP",options:[["=","EQ"],["≠","NEQ"],["‏<","LT"],["‏≤","LTE"],["‏>","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;i<this.argumentVarModels_.length;i++){var n=t.utils.xml.createElement("arg"),s=this.argumentVarModels_[i];n.setAttribute("name",s.name),n.setAttribute("varid",s.getId()),e&&this.paramIds_&&n.setAttribute("paramId",this.paramIds_[i]),o.appendChild(n)}return this.hasStatements_||o.setAttribute("statements","false"),o},domToMutation:function(e){this.arguments_=[],this.argumentVarModels_=[];for(var o,i=0;o=e.childNodes[i];i++)if("arg"==o.nodeName.toLowerCase()){var n=o.getAttribute("name");o=o.getAttribute("varid")||o.getAttribute("varId"),this.arguments_.push(n),null!=(o=t.Variables.getOrCreateVariablePackage(this.workspace,o,n,""))?this.argumentVarModels_.push(o):console.log("Failed to create a variable with name "+n+", ignoring.")}this.updateParams_(),t.Procedures.mutateCallers(this),this.setStatements_("false"!==e.getAttribute("statements"))},decompose:function(e){var o=t.utils.xml.createElement("block");o.setAttribute("type","procedures_mutatorcontainer");var i=t.utils.xml.createElement("statement");i.setAttribute("name","STACK"),o.appendChild(i);for(var n=0;n<this.arguments_.length;n++){var s=t.utils.xml.createElement("block");s.setAttribute("type","procedures_mutatorarg");var r=t.utils.xml.createElement("field");r.setAttribute("name","NAME");var a=t.utils.xml.createTextNode(this.arguments_[n]);r.appendChild(a),s.appendChild(r),r=t.utils.xml.createElement("next"),s.appendChild(r),i.appendChild(s),i=r}return e=t.Xml.domToBlock(o,e),"procedures_defreturn"==this.type?e.setFieldValue(this.hasStatements_,"STATEMENTS"):e.removeInput("STATEMENT_INPUT"),t.Procedures.mutateCallers(this),e},compose:function(e){this.arguments_=[],this.paramIds_=[],this.argumentVarModels_=[];for(var o=e.getInputTargetBlock("STACK");o;){var i=o.getFieldValue("NAME");this.arguments_.push(i),i=this.workspace.getVariable(i,""),this.argumentVarModels_.push(i),this.paramIds_.push(o.id),o=o.nextConnection&&o.nextConnection.targetBlock()}this.updateParams_(),t.Procedures.mutateCallers(this),null!==(e=e.getFieldValue("STATEMENTS"))&&(e="TRUE"==e,this.hasStatements_!=e)&&(e?(this.setStatements_(!0),t.Mutator.reconnect(this.statementConnection_,this,"STACK"),this.statementConnection_=null):(e=this.getInput("STACK").connection,(this.statementConnection_=e.targetConnection)&&((e=e.targetBlock()).unplug(),e.bumpNeighbours()),this.setStatements_(!1)))},getProcedureDef:function(){return[this.getFieldValue("NAME"),this.arguments_,!1]},getVars:function(){return this.arguments_},getVarModels:function(){return this.argumentVarModels_},renameVarById:function(e,o){var i=this.workspace.getVariableById(e);if(""==i.type){i=i.name,o=this.workspace.getVariableById(o);for(var n=!1,s=0;s<this.argumentVarModels_.length;s++)this.argumentVarModels_[s].getId()==e&&(this.arguments_[s]=o.name,this.argumentVarModels_[s]=o,n=!0);n&&(this.displayRenamedVar_(i,o.name),t.Procedures.mutateCallers(this))}},updateVarName:function(e){for(var o=e.name,i=!1,n=0;n<this.argumentVarModels_.length;n++)if(this.argumentVarModels_[n].getId()==e.getId()){var s=this.arguments_[n];this.arguments_[n]=o,i=!0}i&&(this.displayRenamedVar_(s,o),t.Procedures.mutateCallers(this))},displayRenamedVar_:function(e,o){if(this.updateParams_(),this.mutator&&this.mutator.isVisible())for(var i,n=this.mutator.workspace_.getAllBlocks(!1),s=0;i=n[s];s++)"procedures_mutatorarg"==i.type&&t.Names.equals(e,i.getFieldValue("NAME"))&&i.setFieldValue(o,"NAME")},customContextMenu:function(e){if(!this.isInFlyout){var o={enabled:!0},i=this.getFieldValue("NAME");o.text=t.Msg.PROCEDURES_CREATE_DO.replace("%1",i);var n=t.utils.xml.createElement("mutation");for(n.setAttribute("name",i),i=0;i<this.arguments_.length;i++){var s=t.utils.xml.createElement("arg");s.setAttribute("name",this.arguments_[i]),n.appendChild(s)}if((i=t.utils.xml.createElement("block")).setAttribute("type",this.callType_),i.appendChild(n),o.callback=t.ContextMenu.callbackFactory(this,i),e.push(o),!this.isCollapsed())for(i=0;i<this.argumentVarModels_.length;i++)o={enabled:!0},n=this.argumentVarModels_[i],o.text=t.Msg.VARIABLES_SET_CREATE_GET.replace("%1",n.name),n=t.Variables.generateVariableFieldDom(n),(s=t.utils.xml.createElement("block")).setAttribute("type","variables_get"),s.appendChild(n),o.callback=t.ContextMenu.callbackFactory(this,s),e.push(o)}},callType_:"procedures_callnoreturn"},t.Blocks.procedures_defreturn={init:function(){var e=new t.FieldTextInput("",t.Procedures.rename);e.setSpellcheck(!1),this.appendDummyInput().appendField(t.Msg.PROCEDURES_DEFRETURN_TITLE).appendField(e,"NAME").appendField("","PARAMS"),this.appendValueInput("RETURN").setAlign(t.ALIGN_RIGHT).appendField(t.Msg.PROCEDURES_DEFRETURN_RETURN),this.setMutator(new t.Mutator(["procedures_mutatorarg"])),(this.workspace.options.comments||this.workspace.options.parentWorkspace&&this.workspace.options.parentWorkspace.options.comments)&&t.Msg.PROCEDURES_DEFRETURN_COMMENT&&this.setCommentText(t.Msg.PROCEDURES_DEFRETURN_COMMENT),this.setStyle("procedure_blocks"),this.setTooltip(t.Msg.PROCEDURES_DEFRETURN_TOOLTIP),this.setHelpUrl(t.Msg.PROCEDURES_DEFRETURN_HELPURL),this.arguments_=[],this.argumentVarModels_=[],this.setStatements_(!0),this.statementConnection_=null},setStatements_:t.Blocks.procedures_defnoreturn.setStatements_,updateParams_:t.Blocks.procedures_defnoreturn.updateParams_,mutationToDom:t.Blocks.procedures_defnoreturn.mutationToDom,domToMutation:t.Blocks.procedures_defnoreturn.domToMutation,decompose:t.Blocks.procedures_defnoreturn.decompose,compose:t.Blocks.procedures_defnoreturn.compose,getProcedureDef:function(){return[this.getFieldValue("NAME"),this.arguments_,!0]},getVars:t.Blocks.procedures_defnoreturn.getVars,getVarModels:t.Blocks.procedures_defnoreturn.getVarModels,renameVarById:t.Blocks.procedures_defnoreturn.renameVarById,updateVarName:t.Blocks.procedures_defnoreturn.updateVarName,displayRenamedVar_:t.Blocks.procedures_defnoreturn.displayRenamedVar_,customContextMenu:t.Blocks.procedures_defnoreturn.customContextMenu,callType_:"procedures_callreturn"},t.Blocks.procedures_mutatorcontainer={init:function(){this.appendDummyInput().appendField(t.Msg.PROCEDURES_MUTATORCONTAINER_TITLE),this.appendStatementInput("STACK"),this.appendDummyInput("STATEMENT_INPUT").appendField(t.Msg.PROCEDURES_ALLOW_STATEMENTS).appendField(new t.FieldCheckbox("TRUE"),"STATEMENTS"),this.setStyle("procedure_blocks"),this.setTooltip(t.Msg.PROCEDURES_MUTATORCONTAINER_TOOLTIP),this.contextMenu=!1}},t.Blocks.procedures_mutatorarg={init:function(){var e=new t.FieldTextInput(t.Procedures.DEFAULT_ARG,this.validator_);e.oldShowEditorFn_=e.showEditor_,e.showEditor_=function(){this.createdVariables_=[],this.oldShowEditorFn_()},this.appendDummyInput().appendField(t.Msg.PROCEDURES_MUTATORARG_TITLE).appendField(e,"NAME"),this.setPreviousStatement(!0),this.setNextStatement(!0),this.setStyle("procedure_blocks"),this.setTooltip(t.Msg.PROCEDURES_MUTATORARG_TOOLTIP),this.contextMenu=!1,e.onFinishEditing_=this.deleteIntermediateVars_,e.createdVariables_=[],e.onFinishEditing_("x")},validator_:function(e){var o=this.getSourceBlock(),i=t.Mutator.findParentWs(o.workspace);if(!(e=e.replace(/[\s\xa0]+/g," ").replace(/^ | $/g,"")))return null;for(var n=(o.workspace.targetWorkspace||o.workspace).getAllBlocks(!1),s=e.toLowerCase(),r=0;r<n.length;r++)if(n[r].id!=this.getSourceBlock().id){var a=n[r].getFieldValue("NAME");if(a&&a.toLowerCase()==s)return null}return o.isInFlyout||((o=i.getVariable(e,""))&&o.name!=e&&i.renameVariableById(o.getId(),e),o||(o=i.createVariable(e,""))&&this.createdVariables_&&this.createdVariables_.push(o)),e},deleteIntermediateVars_:function(e){var o=t.Mutator.findParentWs(this.getSourceBlock().workspace);if(o)for(var i=0;i<this.createdVariables_.length;i++){var n=this.createdVariables_[i];n.name!=e&&o.deleteVariableById(n.getId())}}},t.Blocks.procedures_callnoreturn={init:function(){this.appendDummyInput("TOPROW").appendField(this.id,"NAME"),this.setPreviousStatement(!0),this.setNextStatement(!0),this.setStyle("procedure_blocks"),this.setHelpUrl(t.Msg.PROCEDURES_CALLNORETURN_HELPURL),this.arguments_=[],this.argumentVarModels_=[],this.quarkConnections_={},this.quarkIds_=null,this.previousEnabledState_=!0},getProcedureCall:function(){return this.getFieldValue("NAME")},renameProcedure:function(e,o){t.Names.equals(e,this.getProcedureCall())&&(this.setFieldValue(o,"NAME"),this.setTooltip((this.outputConnection?t.Msg.PROCEDURES_CALLRETURN_TOOLTIP:t.Msg.PROCEDURES_CALLNORETURN_TOOLTIP).replace("%1",o)))},setProcedureParameters_:function(e,o){var i=t.Procedures.getDefinition(this.getProcedureCall(),this.workspace),n=i&&i.mutator&&i.mutator.isVisible();if(n||(this.quarkConnections_={},this.quarkIds_=null),o)if(e.join("\n")==this.arguments_.join("\n"))this.quarkIds_=o;else{if(o.length!=e.length)throw RangeError("paramNames and paramIds must be the same length.");this.setCollapsed(!1),this.quarkIds_||(this.quarkConnections_={},this.quarkIds_=[]),i=this.rendered,this.rendered=!1;for(var s=0;s<this.arguments_.length;s++){var r=this.getInput("ARG"+s);r&&(r=r.connection.targetConnection,this.quarkConnections_[this.quarkIds_[s]]=r,n&&r&&-1==o.indexOf(this.quarkIds_[s])&&(r.disconnect(),r.getSourceBlock().bumpNeighbours()))}for(this.arguments_=[].concat(e),this.argumentVarModels_=[],s=0;s<this.arguments_.length;s++)e=t.Variables.getOrCreateVariablePackage(this.workspace,null,this.arguments_[s],""),this.argumentVarModels_.push(e);if(this.updateShape_(),this.quarkIds_=o)for(s=0;s<this.arguments_.length;s++)(o=this.quarkIds_[s])in this.quarkConnections_&&(r=this.quarkConnections_[o],t.Mutator.reconnect(r,this,"ARG"+s)||delete this.quarkConnections_[o]);(this.rendered=i)&&this.render()}},updateShape_:function(){for(var e=0;e<this.arguments_.length;e++){var o=this.getField("ARGNAME"+e);if(o){t.Events.disable();try{o.setValue(this.arguments_[e])}finally{t.Events.enable()}}else o=new t.FieldLabel(this.arguments_[e]),this.appendValueInput("ARG"+e).setAlign(t.ALIGN_RIGHT).appendField(o,"ARGNAME"+e).init()}for(;this.getInput("ARG"+e);)this.removeInput("ARG"+e),e++;(e=this.getInput("TOPROW"))&&(this.arguments_.length?this.getField("WITH")||(e.appendField(t.Msg.PROCEDURES_CALL_BEFORE_PARAMS,"WITH"),e.init()):this.getField("WITH")&&e.removeField("WITH"))},mutationToDom:function(){var e=t.utils.xml.createElement("mutation");e.setAttribute("name",this.getProcedureCall());for(var o=0;o<this.arguments_.length;o++){var i=t.utils.xml.createElement("arg");i.setAttribute("name",this.arguments_[o]),e.appendChild(i)}return e},domToMutation:function(t){var e=t.getAttribute("name");this.renameProcedure(this.getProcedureCall(),e),e=[];for(var o,i=[],n=0;o=t.childNodes[n];n++)"arg"==o.nodeName.toLowerCase()&&(e.push(o.getAttribute("name")),i.push(o.getAttribute("paramId")));this.setProcedureParameters_(e,i)},getVarModels:function(){return this.argumentVarModels_},onchange:function(e){if(this.workspace&&!this.workspace.isFlyout&&e.recordUndo)if(e.type==t.Events.BLOCK_CREATE&&-1!=e.ids.indexOf(this.id)){var o=this.getProcedureCall();if(!(o=t.Procedures.getDefinition(o,this.workspace))||o.type==this.defType_&&JSON.stringify(o.arguments_)==JSON.stringify(this.arguments_)||(o=null),!o){t.Events.setGroup(e.group),e=t.utils.xml.createElement("xml"),(o=t.utils.xml.createElement("block")).setAttribute("type",this.defType_);var i=this.getRelativeToSurfaceXY(),n=i.y+2*t.SNAP_RADIUS;o.setAttribute("x",i.x+t.SNAP_RADIUS*(this.RTL?-1:1)),o.setAttribute("y",n),i=this.mutationToDom(),o.appendChild(i),(i=t.utils.xml.createElement("field")).setAttribute("name","NAME"),i.appendChild(t.utils.xml.createTextNode(this.getProcedureCall())),o.appendChild(i),e.appendChild(o),t.Xml.domToWorkspace(e,this.workspace),t.Events.setGroup(!1)}}else e.type==t.Events.BLOCK_DELETE?(o=this.getProcedureCall(),(o=t.Procedures.getDefinition(o,this.workspace))||(t.Events.setGroup(e.group),this.dispose(!0),t.Events.setGroup(!1))):e.type==t.Events.CHANGE&&"disabled"==e.element&&(o=this.getProcedureCall(),(o=t.Procedures.getDefinition(o,this.workspace))&&o.id==e.blockId&&((o=t.Events.getGroup())&&console.log("Saw an existing group while responding to a definition change"),t.Events.setGroup(e.group),e.newValue?(this.previousEnabledState_=this.isEnabled(),this.setEnabled(!1)):this.setEnabled(this.previousEnabledState_),t.Events.setGroup(o)))},customContextMenu:function(e){if(this.workspace.isMovable()){var o={enabled:!0};o.text=t.Msg.PROCEDURES_HIGHLIGHT_DEF;var i=this.getProcedureCall(),n=this.workspace;o.callback=function(){var e=t.Procedures.getDefinition(i,n);e&&(n.centerOnBlock(e.id),e.select())},e.push(o)}},defType_:"procedures_defnoreturn"},t.Blocks.procedures_callreturn={init:function(){this.appendDummyInput("TOPROW").appendField("","NAME"),this.setOutput(!0),this.setStyle("procedure_blocks"),this.setHelpUrl(t.Msg.PROCEDURES_CALLRETURN_HELPURL),this.arguments_=[],this.quarkConnections_={},this.quarkIds_=null,this.previousEnabledState_=!0},getProcedureCall:t.Blocks.procedures_callnoreturn.getProcedureCall,renameProcedure:t.Blocks.procedures_callnoreturn.renameProcedure,setProcedureParameters_:t.Blocks.procedures_callnoreturn.setProcedureParameters_,updateShape_:t.Blocks.procedures_callnoreturn.updateShape_,mutationToDom:t.Blocks.procedures_callnoreturn.mutationToDom,domToMutation:t.Blocks.procedures_callnoreturn.domToMutation,getVarModels:t.Blocks.procedures_callnoreturn.getVarModels,onchange:t.Blocks.procedures_callnoreturn.onchange,customContextMenu:t.Blocks.procedures_callnoreturn.customContextMenu,defType_:"procedures_defreturn"},t.Blocks.procedures_ifreturn={init:function(){this.appendValueInput("CONDITION").setCheck("Boolean").appendField(t.Msg.CONTROLS_IF_MSG_IF),this.appendValueInput("VALUE").appendField(t.Msg.PROCEDURES_DEFRETURN_RETURN),this.setInputsInline(!0),this.setPreviousStatement(!0),this.setNextStatement(!0),this.setStyle("procedure_blocks"),this.setTooltip(t.Msg.PROCEDURES_IFRETURN_TOOLTIP),this.setHelpUrl(t.Msg.PROCEDURES_IFRETURN_HELPURL),this.hasReturnValue_=!0},mutationToDom:function(){var e=t.utils.xml.createElement("mutation");return e.setAttribute("value",Number(this.hasReturnValue_)),e},domToMutation:function(e){this.hasReturnValue_=1==e.getAttribute("value"),this.hasReturnValue_||(this.removeInput("VALUE"),this.appendDummyInput("VALUE").appendField(t.Msg.PROCEDURES_DEFRETURN_RETURN))},onchange:function(e){if(this.workspace.isDragging&&!this.workspace.isDragging()){e=!1;var o=this;do{if(-1!=this.FUNCTION_TYPES.indexOf(o.type)){e=!0;break}o=o.getSurroundParent()}while(o);e?("procedures_defnoreturn"==o.type&&this.hasReturnValue_?(this.removeInput("VALUE"),this.appendDummyInput("VALUE").appendField(t.Msg.PROCEDURES_DEFRETURN_RETURN),this.hasReturnValue_=!1):"procedures_defreturn"!=o.type||this.hasReturnValue_||(this.removeInput("VALUE"),this.appendValueInput("VALUE").appendField(t.Msg.PROCEDURES_DEFRETURN_RETURN),this.hasReturnValue_=!0),this.setWarningText(null),this.isInFlyout||this.setEnabled(!0)):(this.setWarningText(t.Msg.PROCEDURES_IFRETURN_WARNING),this.isInFlyout||this.getInheritedDisabled()||this.setEnabled(!1))}},FUNCTION_TYPES:["procedures_defnoreturn","procedures_defreturn"]},t.Blocks.texts={},t.Constants.Text={},t.Constants.Text.HUE=160,t.defineBlocksWithJsonArray([{type:"text",message0:"%1",args0:[{type:"field_input",name:"TEXT",text:""}],output:"String",style:"text_blocks",helpUrl:"%{BKY_TEXT_TEXT_HELPURL}",tooltip:"%{BKY_TEXT_TEXT_TOOLTIP}",extensions:["text_quotes","parent_tooltip_when_inline"]},{type:"text_multiline",message0:"%1 %2",args0:[{type:"field_image",src:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAARCAYAAADpPU2iAAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAAdhgAAHYYBXaITgQAAABh0RVh0U29mdHdhcmUAcGFpbnQubmV0IDQuMS42/U4J6AAAAP1JREFUOE+Vks0KQUEYhjmRIja4ABtZ2dm5A3t3Ia6AUm7CylYuQRaUhZSlLZJiQbFAyRnPN33y01HOW08z8873zpwzM4F3GWOCruvGIE4/rLaV+Nq1hVGMBqzhqlxgCys4wJA65xnogMHsQ5lujnYHTejBBCK2mE4abjCgMGhNxHgDFWjDSG07kdfVa2pZMf4ZyMAdWmpZMfYOsLiDMYMjlMB+K613QISRhTnITnsYg5yUd0DETmEoMlkFOeIT/A58iyK5E18BuTBfgYXfwNJv4P9/oEBerLylOnRhygmGdPpTTBZAPkde61lbQe4moWUvYUZYLfUNftIY4zwA5X2Z9AYnQrEAAAAASUVORK5CYII=",width:12,height:17,alt:"¶"},{type:"field_multilinetext",name:"TEXT",text:""}],output:"String",style:"text_blocks",helpUrl:"%{BKY_TEXT_TEXT_HELPURL}",tooltip:"%{BKY_TEXT_TEXT_TOOLTIP}",extensions:["parent_tooltip_when_inline"]},{type:"text_join",message0:"",output:"String",style:"text_blocks",helpUrl:"%{BKY_TEXT_JOIN_HELPURL}",tooltip:"%{BKY_TEXT_JOIN_TOOLTIP}",mutator:"text_join_mutator"},{type:"text_create_join_container",message0:"%{BKY_TEXT_CREATE_JOIN_TITLE_JOIN} %1 %2",args0:[{type:"input_dummy"},{type:"input_statement",name:"STACK"}],style:"text_blocks",tooltip:"%{BKY_TEXT_CREATE_JOIN_TOOLTIP}",enableContextMenu:!1},{type:"text_create_join_item",message0:"%{BKY_TEXT_CREATE_JOIN_ITEM_TITLE_ITEM}",previousStatement:null,nextStatement:null,style:"text_blocks",tooltip:"%{BKY_TEXT_CREATE_JOIN_ITEM_TOOLTIP}",enableContextMenu:!1},{type:"text_append",message0:"%{BKY_TEXT_APPEND_TITLE}",args0:[{type:"field_variable",name:"VAR",variable:"%{BKY_TEXT_APPEND_VARIABLE}"},{type:"input_value",name:"TEXT"}],previousStatement:null,nextStatement:null,style:"text_blocks",extensions:["text_append_tooltip"]},{type:"text_length",message0:"%{BKY_TEXT_LENGTH_TITLE}",args0:[{type:"input_value",name:"VALUE",check:["String","Array"]}],output:"Number",style:"text_blocks",tooltip:"%{BKY_TEXT_LENGTH_TOOLTIP}",helpUrl:"%{BKY_TEXT_LENGTH_HELPURL}"},{type:"text_isEmpty",message0:"%{BKY_TEXT_ISEMPTY_TITLE}",args0:[{type:"input_value",name:"VALUE",check:["String","Array"]}],output:"Boolean",style:"text_blocks",tooltip:"%{BKY_TEXT_ISEMPTY_TOOLTIP}",helpUrl:"%{BKY_TEXT_ISEMPTY_HELPURL}"},{type:"text_indexOf",message0:"%{BKY_TEXT_INDEXOF_TITLE}",args0:[{type:"input_value",name:"VALUE",check:"String"},{type:"field_dropdown",name:"END",options:[["%{BKY_TEXT_INDEXOF_OPERATOR_FIRST}","FIRST"],["%{BKY_TEXT_INDEXOF_OPERATOR_LAST}","LAST"]]},{type:"input_value",name:"FIND",check:"String"}],output:"Number",style:"text_blocks",helpUrl:"%{BKY_TEXT_INDEXOF_HELPURL}",inputsInline:!0,extensions:["text_indexOf_tooltip"]},{type:"text_charAt",message0:"%{BKY_TEXT_CHARAT_TITLE}",args0:[{type:"input_value",name:"VALUE",check:"String"},{type:"field_dropdown",name:"WHERE",options:[["%{BKY_TEXT_CHARAT_FROM_START}","FROM_START"],["%{BKY_TEXT_CHARAT_FROM_END}","FROM_END"],["%{BKY_TEXT_CHARAT_FIRST}","FIRST"],["%{BKY_TEXT_CHARAT_LAST}","LAST"],["%{BKY_TEXT_CHARAT_RANDOM}","RANDOM"]]}],output:"String",style:"text_blocks",helpUrl:"%{BKY_TEXT_CHARAT_HELPURL}",inputsInline:!0,mutator:"text_charAt_mutator"}]),t.Blocks.text_getSubstring={init:function(){this.WHERE_OPTIONS_1=[[t.Msg.TEXT_GET_SUBSTRING_START_FROM_START,"FROM_START"],[t.Msg.TEXT_GET_SUBSTRING_START_FROM_END,"FROM_END"],[t.Msg.TEXT_GET_SUBSTRING_START_FIRST,"FIRST"]],this.WHERE_OPTIONS_2=[[t.Msg.TEXT_GET_SUBSTRING_END_FROM_START,"FROM_START"],[t.Msg.TEXT_GET_SUBSTRING_END_FROM_END,"FROM_END"],[t.Msg.TEXT_GET_SUBSTRING_END_LAST,"LAST"]],this.setHelpUrl(t.Msg.TEXT_GET_SUBSTRING_HELPURL),this.setStyle("text_blocks"),this.appendValueInput("STRING").setCheck("String").appendField(t.Msg.TEXT_GET_SUBSTRING_INPUT_IN_TEXT),this.appendDummyInput("AT1"),this.appendDummyInput("AT2"),t.Msg.TEXT_GET_SUBSTRING_TAIL&&this.appendDummyInput("TAIL").appendField(t.Msg.TEXT_GET_SUBSTRING_TAIL),this.setInputsInline(!0),this.setOutput(!0,"String"),this.updateAt_(1,!0),this.updateAt_(2,!0),this.setTooltip(t.Msg.TEXT_GET_SUBSTRING_TOOLTIP)},mutationToDom:function(){var e=t.utils.xml.createElement("mutation"),o=this.getInput("AT1").type==t.INPUT_VALUE;return e.setAttribute("at1",o),o=this.getInput("AT2").type==t.INPUT_VALUE,e.setAttribute("at2",o),e},domToMutation:function(t){var e="true"==t.getAttribute("at1");t="true"==t.getAttribute("at2"),this.updateAt_(1,e),this.updateAt_(2,t)},updateAt_:function(e,o){this.removeInput("AT"+e),this.removeInput("ORDINAL"+e,!0),o?(this.appendValueInput("AT"+e).setCheck("Number"),t.Msg.ORDINAL_NUMBER_SUFFIX&&this.appendDummyInput("ORDINAL"+e).appendField(t.Msg.ORDINAL_NUMBER_SUFFIX)):this.appendDummyInput("AT"+e),2==e&&t.Msg.TEXT_GET_SUBSTRING_TAIL&&(this.removeInput("TAIL",!0),this.appendDummyInput("TAIL").appendField(t.Msg.TEXT_GET_SUBSTRING_TAIL));var i=new t.FieldDropdown(this["WHERE_OPTIONS_"+e],(function(t){var i="FROM_START"==t||"FROM_END"==t;if(i!=o){var n=this.getSourceBlock();return n.updateAt_(e,i),n.setFieldValue(t,"WHERE"+e),null}}));this.getInput("AT"+e).appendField(i,"WHERE"+e),1==e&&(this.moveInputBefore("AT1","AT2"),this.getInput("ORDINAL1")&&this.moveInputBefore("ORDINAL1","AT2"))}},t.Blocks.text_changeCase={init:function(){var e=[[t.Msg.TEXT_CHANGECASE_OPERATOR_UPPERCASE,"UPPERCASE"],[t.Msg.TEXT_CHANGECASE_OPERATOR_LOWERCASE,"LOWERCASE"],[t.Msg.TEXT_CHANGECASE_OPERATOR_TITLECASE,"TITLECASE"]];this.setHelpUrl(t.Msg.TEXT_CHANGECASE_HELPURL),this.setStyle("text_blocks"),this.appendValueInput("TEXT").setCheck("String").appendField(new t.FieldDropdown(e),"CASE"),this.setOutput(!0,"String"),this.setTooltip(t.Msg.TEXT_CHANGECASE_TOOLTIP)}},t.Blocks.text_trim={init:function(){var e=[[t.Msg.TEXT_TRIM_OPERATOR_BOTH,"BOTH"],[t.Msg.TEXT_TRIM_OPERATOR_LEFT,"LEFT"],[t.Msg.TEXT_TRIM_OPERATOR_RIGHT,"RIGHT"]];this.setHelpUrl(t.Msg.TEXT_TRIM_HELPURL),this.setStyle("text_blocks"),this.appendValueInput("TEXT").setCheck("String").appendField(new t.FieldDropdown(e),"MODE"),this.setOutput(!0,"String"),this.setTooltip(t.Msg.TEXT_TRIM_TOOLTIP)}},t.Blocks.text_print={init:function(){this.jsonInit({message0:t.Msg.TEXT_PRINT_TITLE,args0:[{type:"input_value",name:"TEXT"}],previousStatement:null,nextStatement:null,style:"text_blocks",tooltip:t.Msg.TEXT_PRINT_TOOLTIP,helpUrl:t.Msg.TEXT_PRINT_HELPURL})}},t.Blocks.text_prompt_ext={init:function(){var e=[[t.Msg.TEXT_PROMPT_TYPE_TEXT,"TEXT"],[t.Msg.TEXT_PROMPT_TYPE_NUMBER,"NUMBER"]];this.setHelpUrl(t.Msg.TEXT_PROMPT_HELPURL),this.setStyle("text_blocks");var o=this;e=new t.FieldDropdown(e,(function(t){o.updateType_(t)})),this.appendValueInput("TEXT").appendField(e,"TYPE"),this.setOutput(!0,"String"),this.setTooltip((function(){return"TEXT"==o.getFieldValue("TYPE")?t.Msg.TEXT_PROMPT_TOOLTIP_TEXT:t.Msg.TEXT_PROMPT_TOOLTIP_NUMBER}))},updateType_:function(t){this.outputConnection.setCheck("NUMBER"==t?"Number":"String")},mutationToDom:function(){var e=t.utils.xml.createElement("mutation");return e.setAttribute("type",this.getFieldValue("TYPE")),e},domToMutation:function(t){this.updateType_(t.getAttribute("type"))}},t.Blocks.text_prompt={init:function(){this.mixin(t.Constants.Text.QUOTE_IMAGE_MIXIN);var e=[[t.Msg.TEXT_PROMPT_TYPE_TEXT,"TEXT"],[t.Msg.TEXT_PROMPT_TYPE_NUMBER,"NUMBER"]],o=this;this.setHelpUrl(t.Msg.TEXT_PROMPT_HELPURL),this.setStyle("text_blocks"),e=new t.FieldDropdown(e,(function(t){o.updateType_(t)})),this.appendDummyInput().appendField(e,"TYPE").appendField(this.newQuote_(!0)).appendField(new t.FieldTextInput(""),"TEXT").appendField(this.newQuote_(!1)),this.setOutput(!0,"String"),this.setTooltip((function(){return"TEXT"==o.getFieldValue("TYPE")?t.Msg.TEXT_PROMPT_TOOLTIP_TEXT:t.Msg.TEXT_PROMPT_TOOLTIP_NUMBER}))},updateType_:t.Blocks.text_prompt_ext.updateType_,mutationToDom:t.Blocks.text_prompt_ext.mutationToDom,domToMutation:t.Blocks.text_prompt_ext.domToMutation},t.Blocks.text_count={init:function(){this.jsonInit({message0:t.Msg.TEXT_COUNT_MESSAGE0,args0:[{type:"input_value",name:"SUB",check:"String"},{type:"input_value",name:"TEXT",check:"String"}],output:"Number",inputsInline:!0,style:"text_blocks",tooltip:t.Msg.TEXT_COUNT_TOOLTIP,helpUrl:t.Msg.TEXT_COUNT_HELPURL})}},t.Blocks.text_replace={init:function(){this.jsonInit({message0:t.Msg.TEXT_REPLACE_MESSAGE0,args0:[{type:"input_value",name:"FROM",check:"String"},{type:"input_value",name:"TO",check:"String"},{type:"input_value",name:"TEXT",check:"String"}],output:"String",inputsInline:!0,style:"text_blocks",tooltip:t.Msg.TEXT_REPLACE_TOOLTIP,helpUrl:t.Msg.TEXT_REPLACE_HELPURL})}},t.Blocks.text_reverse={init:function(){this.jsonInit({message0:t.Msg.TEXT_REVERSE_MESSAGE0,args0:[{type:"input_value",name:"TEXT",check:"String"}],output:"String",inputsInline:!0,style:"text_blocks",tooltip:t.Msg.TEXT_REVERSE_TOOLTIP,helpUrl:t.Msg.TEXT_REVERSE_HELPURL})}},t.Constants.Text.QUOTE_IMAGE_MIXIN={QUOTE_IMAGE_LEFT_DATAURI:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAAKCAQAAAAqJXdxAAAAn0lEQVQI1z3OMa5BURSF4f/cQhAKjUQhuQmFNwGJEUi0RKN5rU7FHKhpjEH3TEMtkdBSCY1EIv8r7nFX9e29V7EBAOvu7RPjwmWGH/VuF8CyN9/OAdvqIXYLvtRaNjx9mMTDyo+NjAN1HNcl9ZQ5oQMM3dgDUqDo1l8DzvwmtZN7mnD+PkmLa+4mhrxVA9fRowBWmVBhFy5gYEjKMfz9AylsaRRgGzvZAAAAAElFTkSuQmCC",QUOTE_IMAGE_RIGHT_DATAURI:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAAKCAQAAAAqJXdxAAAAqUlEQVQI1z3KvUpCcRiA8ef9E4JNHhI0aFEacm1o0BsI0Slx8wa8gLauoDnoBhq7DcfWhggONDmJJgqCPA7neJ7p934EOOKOnM8Q7PDElo/4x4lFb2DmuUjcUzS3URnGib9qaPNbuXvBO3sGPHJDRG6fGVdMSeWDP2q99FQdFrz26Gu5Tq7dFMzUvbXy8KXeAj57cOklgA+u1B5AoslLtGIHQMaCVnwDnADZIFIrXsoXrgAAAABJRU5ErkJggg==",QUOTE_IMAGE_WIDTH:12,QUOTE_IMAGE_HEIGHT:12,quoteField_:function(t){for(var e,o=0;e=this.inputList[o];o++)for(var i,n=0;i=e.fieldRow[n];n++)if(t==i.name)return e.insertFieldAt(n,this.newQuote_(!0)),void e.insertFieldAt(n+2,this.newQuote_(!1));console.warn('field named "'+t+'" not found in '+this.toDevString())},newQuote_:function(e){return e=this.RTL?!e:e,new t.FieldImage(e?this.QUOTE_IMAGE_LEFT_DATAURI:this.QUOTE_IMAGE_RIGHT_DATAURI,this.QUOTE_IMAGE_WIDTH,this.QUOTE_IMAGE_HEIGHT,e?"“":"”")}},t.Constants.Text.TEXT_QUOTES_EXTENSION=function(){this.mixin(t.Constants.Text.QUOTE_IMAGE_MIXIN),this.quoteField_("TEXT")},t.Constants.Text.TEXT_JOIN_MUTATOR_MIXIN={mutationToDom:function(){var e=t.utils.xml.createElement("mutation");return e.setAttribute("items",this.itemCount_),e},domToMutation:function(t){this.itemCount_=parseInt(t.getAttribute("items"),10),this.updateShape_()},decompose:function(t){var e=t.newBlock("text_create_join_container");e.initSvg();for(var o=e.getInput("STACK").connection,i=0;i<this.itemCount_;i++){var n=t.newBlock("text_create_join_item");n.initSvg(),o.connect(n.previousConnection),o=n.nextConnection}return e},compose:function(e){var o=e.getInputTargetBlock("STACK");for(e=[];o;)e.push(o.valueConnection_),o=o.nextConnection&&o.nextConnection.targetBlock();for(o=0;o<this.itemCount_;o++){var i=this.getInput("ADD"+o).connection.targetConnection;i&&-1==e.indexOf(i)&&i.disconnect()}for(this.itemCount_=e.length,this.updateShape_(),o=0;o<this.itemCount_;o++)t.Mutator.reconnect(e[o],this,"ADD"+o)},saveConnections:function(t){t=t.getInputTargetBlock("STACK");for(var e=0;t;){var o=this.getInput("ADD"+e);t.valueConnection_=o&&o.connection.targetConnection,e++,t=t.nextConnection&&t.nextConnection.targetBlock()}},updateShape_:function(){this.itemCount_&&this.getInput("EMPTY")?this.removeInput("EMPTY"):this.itemCount_||this.getInput("EMPTY")||this.appendDummyInput("EMPTY").appendField(this.newQuote_(!0)).appendField(this.newQuote_(!1));for(var e=0;e<this.itemCount_;e++)if(!this.getInput("ADD"+e)){var o=this.appendValueInput("ADD"+e).setAlign(t.ALIGN_RIGHT);0==e&&o.appendField(t.Msg.TEXT_JOIN_TITLE_CREATEWITH)}for(;this.getInput("ADD"+e);)this.removeInput("ADD"+e),e++}},t.Constants.Text.TEXT_JOIN_EXTENSION=function(){this.mixin(t.Constants.Text.QUOTE_IMAGE_MIXIN),this.itemCount_=2,this.updateShape_(),this.setMutator(new t.Mutator(["text_create_join_item"]))},t.Extensions.register("text_append_tooltip",t.Extensions.buildTooltipWithFieldText("%{BKY_TEXT_APPEND_TOOLTIP}","VAR")),t.Constants.Text.TEXT_INDEXOF_TOOLTIP_EXTENSION=function(){var e=this;this.setTooltip((function(){return t.Msg.TEXT_INDEXOF_TOOLTIP.replace("%1",e.workspace.options.oneBasedIndex?"0":"-1")}))},t.Constants.Text.TEXT_CHARAT_MUTATOR_MIXIN={mutationToDom:function(){var e=t.utils.xml.createElement("mutation");return e.setAttribute("at",!!this.isAt_),e},domToMutation:function(t){t="false"!=t.getAttribute("at"),this.updateAt_(t)},updateAt_:function(e){this.removeInput("AT",!0),this.removeInput("ORDINAL",!0),e&&(this.appendValueInput("AT").setCheck("Number"),t.Msg.ORDINAL_NUMBER_SUFFIX&&this.appendDummyInput("ORDINAL").appendField(t.Msg.ORDINAL_NUMBER_SUFFIX)),t.Msg.TEXT_CHARAT_TAIL&&(this.removeInput("TAIL",!0),this.appendDummyInput("TAIL").appendField(t.Msg.TEXT_CHARAT_TAIL)),this.isAt_=e}},t.Constants.Text.TEXT_CHARAT_EXTENSION=function(){this.getField("WHERE").setValidator((function(t){(t="FROM_START"==t||"FROM_END"==t)!=this.isAt_&&this.getSourceBlock().updateAt_(t)})),this.updateAt_(!0);var e=this;this.setTooltip((function(){var o=e.getFieldValue("WHERE"),i=t.Msg.TEXT_CHARAT_TOOLTIP;return("FROM_START"==o||"FROM_END"==o)&&(o="FROM_START"==o?t.Msg.LISTS_INDEX_FROM_START_TOOLTIP:t.Msg.LISTS_INDEX_FROM_END_TOOLTIP)&&(i+="  "+o.replace("%1",e.workspace.options.oneBasedIndex?"#1":"#0")),i}))},t.Extensions.register("text_indexOf_tooltip",t.Constants.Text.TEXT_INDEXOF_TOOLTIP_EXTENSION),t.Extensions.register("text_quotes",t.Constants.Text.TEXT_QUOTES_EXTENSION),t.Extensions.registerMutator("text_join_mutator",t.Constants.Text.TEXT_JOIN_MUTATOR_MIXIN,t.Constants.Text.TEXT_JOIN_EXTENSION),t.Extensions.registerMutator("text_charAt_mutator",t.Constants.Text.TEXT_CHARAT_MUTATOR_MIXIN,t.Constants.Text.TEXT_CHARAT_EXTENSION),t.Blocks.variables={},t.Constants.Variables={},t.Constants.Variables.HUE=330,t.defineBlocksWithJsonArray([{type:"variables_get",message0:"%1",args0:[{type:"field_variable",name:"VAR",variable:"%{BKY_VARIABLES_DEFAULT_NAME}"}],output:null,style:"variable_blocks",helpUrl:"%{BKY_VARIABLES_GET_HELPURL}",tooltip:"%{BKY_VARIABLES_GET_TOOLTIP}",extensions:["contextMenu_variableSetterGetter"]},{type:"variables_set",message0:"%{BKY_VARIABLES_SET}",args0:[{type:"field_variable",name:"VAR",variable:"%{BKY_VARIABLES_DEFAULT_NAME}"},{type:"input_value",name:"VALUE"}],previousStatement:null,nextStatement:null,style:"variable_blocks",tooltip:"%{BKY_VARIABLES_SET_TOOLTIP}",helpUrl:"%{BKY_VARIABLES_SET_HELPURL}",extensions:["contextMenu_variableSetterGetter"]}]),t.Constants.Variables.CUSTOM_CONTEXT_MENU_VARIABLE_GETTER_SETTER_MIXIN={customContextMenu:function(e){if(this.isInFlyout)"variables_get"!=this.type&&"variables_get_reporter"!=this.type||(o={text:t.Msg.RENAME_VARIABLE,enabled:!0,callback:t.Constants.Variables.RENAME_OPTION_CALLBACK_FACTORY(this)},s=this.getField("VAR").getText(),n={text:t.Msg.DELETE_VARIABLE.replace("%1",s),enabled:!0,callback:t.Constants.Variables.DELETE_OPTION_CALLBACK_FACTORY(this)},e.unshift(o),e.unshift(n));else{if("variables_get"==this.type)var o="variables_set",i=t.Msg.VARIABLES_GET_CREATE_SET;else o="variables_get",i=t.Msg.VARIABLES_SET_CREATE_GET;var n={enabled:0<this.workspace.remainingCapacity()},s=this.getField("VAR").getText();n.text=i.replace("%1",s),(i=t.utils.xml.createElement("field")).setAttribute("name","VAR"),i.appendChild(t.utils.xml.createTextNode(s)),(s=t.utils.xml.createElement("block")).setAttribute("type",o),s.appendChild(i),n.callback=t.ContextMenu.callbackFactory(this,s),e.push(n)}}},t.Constants.Variables.RENAME_OPTION_CALLBACK_FACTORY=function(e){return function(){var o=e.workspace,i=e.getField("VAR").getVariable();t.Variables.renameVariable(o,i)}},t.Constants.Variables.DELETE_OPTION_CALLBACK_FACTORY=function(t){return function(){var e=t.workspace,o=t.getField("VAR").getVariable();e.deleteVariableById(o.getId()),e.refreshToolboxSelection()}},t.Extensions.registerMixin("contextMenu_variableSetterGetter",t.Constants.Variables.CUSTOM_CONTEXT_MENU_VARIABLE_GETTER_SETTER_MIXIN),t.Constants.VariablesDynamic={},t.Constants.VariablesDynamic.HUE=310,t.defineBlocksWithJsonArray([{type:"variables_get_dynamic",message0:"%1",args0:[{type:"field_variable",name:"VAR",variable:"%{BKY_VARIABLES_DEFAULT_NAME}"}],output:null,style:"variable_dynamic_blocks",helpUrl:"%{BKY_VARIABLES_GET_HELPURL}",tooltip:"%{BKY_VARIABLES_GET_TOOLTIP}",extensions:["contextMenu_variableDynamicSetterGetter"]},{type:"variables_set_dynamic",message0:"%{BKY_VARIABLES_SET}",args0:[{type:"field_variable",name:"VAR",variable:"%{BKY_VARIABLES_DEFAULT_NAME}"},{type:"input_value",name:"VALUE"}],previousStatement:null,nextStatement:null,style:"variable_dynamic_blocks",tooltip:"%{BKY_VARIABLES_SET_TOOLTIP}",helpUrl:"%{BKY_VARIABLES_SET_HELPURL}",extensions:["contextMenu_variableDynamicSetterGetter"]}]),t.Constants.VariablesDynamic.CUSTOM_CONTEXT_MENU_VARIABLE_GETTER_SETTER_MIXIN={customContextMenu:function(e){if(this.isInFlyout)"variables_get_dynamic"!=this.type&&"variables_get_reporter_dynamic"!=this.type||(o={text:t.Msg.RENAME_VARIABLE,enabled:!0,callback:t.Constants.Variables.RENAME_OPTION_CALLBACK_FACTORY(this)},r=this.getField("VAR").getText(),s={text:t.Msg.DELETE_VARIABLE.replace("%1",r),enabled:!0,callback:t.Constants.Variables.DELETE_OPTION_CALLBACK_FACTORY(this)},e.unshift(o),e.unshift(s));else{var o=this.getFieldValue("VAR"),i=this.workspace.getVariableById(o).type;if("variables_get_dynamic"==this.type){o="variables_set_dynamic";var n=t.Msg.VARIABLES_GET_CREATE_SET}else o="variables_get_dynamic",n=t.Msg.VARIABLES_SET_CREATE_GET;var s={enabled:0<this.workspace.remainingCapacity()},r=this.getField("VAR").getText();s.text=n.replace("%1",r),(n=t.utils.xml.createElement("field")).setAttribute("name","VAR"),n.setAttribute("variabletype",i),n.appendChild(t.utils.xml.createTextNode(r)),(r=t.utils.xml.createElement("block")).setAttribute("type",o),r.appendChild(n),s.callback=t.ContextMenu.callbackFactory(this,r),e.push(s)}},onchange:function(e){e=this.getFieldValue("VAR"),e=t.Variables.getVariable(this.workspace,e),"variables_get_dynamic"==this.type?this.outputConnection.setCheck(e.type):this.getInput("VALUE").connection.setCheck(e.type)}},t.Constants.VariablesDynamic.RENAME_OPTION_CALLBACK_FACTORY=function(e){return function(){var o=e.workspace,i=e.getField("VAR").getVariable();t.Variables.renameVariable(o,i)}},t.Constants.VariablesDynamic.DELETE_OPTION_CALLBACK_FACTORY=function(t){return function(){var e=t.workspace,o=t.getField("VAR").getVariable();e.deleteVariableById(o.getId()),e.refreshToolboxSelection()}},t.Extensions.registerMixin("contextMenu_variableDynamicSetterGetter",t.Constants.VariablesDynamic.CUSTOM_CONTEXT_MENU_VARIABLE_GETTER_SETTER_MIXIN),t.Blocks})?i.apply(e,n):i)||(t.exports=s)},function(t,e,o){var i,n,s;n=[o(3)],void 0===(s="function"==typeof(i=function(t){"use strict";return t.JavaScript=new t.Generator("JavaScript"),t.JavaScript.addReservedWords("break,case,catch,class,const,continue,debugger,default,delete,do,else,export,extends,finally,for,function,if,import,in,instanceof,new,return,super,switch,this,throw,try,typeof,var,void,while,with,yield,enum,implements,interface,let,package,private,protected,public,static,await,null,true,false,arguments,"+Object.getOwnPropertyNames(t.utils.global).join(",")),t.JavaScript.ORDER_ATOMIC=0,t.JavaScript.ORDER_NEW=1.1,t.JavaScript.ORDER_MEMBER=1.2,t.JavaScript.ORDER_FUNCTION_CALL=2,t.JavaScript.ORDER_INCREMENT=3,t.JavaScript.ORDER_DECREMENT=3,t.JavaScript.ORDER_BITWISE_NOT=4.1,t.JavaScript.ORDER_UNARY_PLUS=4.2,t.JavaScript.ORDER_UNARY_NEGATION=4.3,t.JavaScript.ORDER_LOGICAL_NOT=4.4,t.JavaScript.ORDER_TYPEOF=4.5,t.JavaScript.ORDER_VOID=4.6,t.JavaScript.ORDER_DELETE=4.7,t.JavaScript.ORDER_AWAIT=4.8,t.JavaScript.ORDER_EXPONENTIATION=5,t.JavaScript.ORDER_MULTIPLICATION=5.1,t.JavaScript.ORDER_DIVISION=5.2,t.JavaScript.ORDER_MODULUS=5.3,t.JavaScript.ORDER_SUBTRACTION=6.1,t.JavaScript.ORDER_ADDITION=6.2,t.JavaScript.ORDER_BITWISE_SHIFT=7,t.JavaScript.ORDER_RELATIONAL=8,t.JavaScript.ORDER_IN=8,t.JavaScript.ORDER_INSTANCEOF=8,t.JavaScript.ORDER_EQUALITY=9,t.JavaScript.ORDER_BITWISE_AND=10,t.JavaScript.ORDER_BITWISE_XOR=11,t.JavaScript.ORDER_BITWISE_OR=12,t.JavaScript.ORDER_LOGICAL_AND=13,t.JavaScript.ORDER_LOGICAL_OR=14,t.JavaScript.ORDER_CONDITIONAL=15,t.JavaScript.ORDER_ASSIGNMENT=16,t.JavaScript.ORDER_YIELD=17,t.JavaScript.ORDER_COMMA=18,t.JavaScript.ORDER_NONE=99,t.JavaScript.ORDER_OVERRIDES=[[t.JavaScript.ORDER_FUNCTION_CALL,t.JavaScript.ORDER_MEMBER],[t.JavaScript.ORDER_FUNCTION_CALL,t.JavaScript.ORDER_FUNCTION_CALL],[t.JavaScript.ORDER_MEMBER,t.JavaScript.ORDER_MEMBER],[t.JavaScript.ORDER_MEMBER,t.JavaScript.ORDER_FUNCTION_CALL],[t.JavaScript.ORDER_LOGICAL_NOT,t.JavaScript.ORDER_LOGICAL_NOT],[t.JavaScript.ORDER_MULTIPLICATION,t.JavaScript.ORDER_MULTIPLICATION],[t.JavaScript.ORDER_ADDITION,t.JavaScript.ORDER_ADDITION],[t.JavaScript.ORDER_LOGICAL_AND,t.JavaScript.ORDER_LOGICAL_AND],[t.JavaScript.ORDER_LOGICAL_OR,t.JavaScript.ORDER_LOGICAL_OR]],t.JavaScript.init=function(e){t.JavaScript.definitions_=Object.create(null),t.JavaScript.functionNames_=Object.create(null),t.JavaScript.variableDB_?t.JavaScript.variableDB_.reset():t.JavaScript.variableDB_=new t.Names(t.JavaScript.RESERVED_WORDS_),t.JavaScript.variableDB_.setVariableMap(e.getVariableMap());for(var o=[],i=t.Variables.allDeveloperVariables(e),n=0;n<i.length;n++)o.push(t.JavaScript.variableDB_.getName(i[n],t.Names.DEVELOPER_VARIABLE_TYPE));for(e=t.Variables.allUsedVarModels(e),n=0;n<e.length;n++)o.push(t.JavaScript.variableDB_.getName(e[n].getId(),t.VARIABLE_CATEGORY_NAME));o.length&&(t.JavaScript.definitions_.variables="var "+o.join(", ")+";")},t.JavaScript.finish=function(e){var o,i=[];for(o in t.JavaScript.definitions_)i.push(t.JavaScript.definitions_[o]);return delete t.JavaScript.definitions_,delete t.JavaScript.functionNames_,t.JavaScript.variableDB_.reset(),i.join("\n\n")+"\n\n\n"+e},t.JavaScript.scrubNakedValue=function(t){return t+";\n"},t.JavaScript.quote_=function(t){return"'"+(t=t.replace(/\\/g,"\\\\").replace(/\n/g,"\\\n").replace(/'/g,"\\'"))+"'"},t.JavaScript.multiline_quote_=function(e){return e.split(/\n/g).map(t.JavaScript.quote_).join(" + '\\n' +\n")},t.JavaScript.scrub_=function(e,o,i){var n="";if(!e.outputConnection||!e.outputConnection.targetConnection){var s=e.getCommentText();s&&(s=t.utils.string.wrap(s,t.JavaScript.COMMENT_WRAP-3),n+=t.JavaScript.prefixLines(s+"\n","// "));for(var r=0;r<e.inputList.length;r++)e.inputList[r].type==t.INPUT_VALUE&&(s=e.inputList[r].connection.targetBlock())&&(s=t.JavaScript.allNestedComments(s))&&(n+=t.JavaScript.prefixLines(s,"// "))}return e=e.nextConnection&&e.nextConnection.targetBlock(),n+o+(i=i?"":t.JavaScript.blockToCode(e))},t.JavaScript.getAdjusted=function(e,o,i,n,s){i=i||0,s=s||t.JavaScript.ORDER_NONE,e.workspace.options.oneBasedIndex&&i--;var r=e.workspace.options.oneBasedIndex?"1":"0";if(e=0<i?t.JavaScript.valueToCode(e,o,t.JavaScript.ORDER_ADDITION)||r:0>i?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(0<i){e=e+" + "+i;var a=t.JavaScript.ORDER_ADDITION}else 0>i&&(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<e.itemCount_;i++)o[i]=t.JavaScript.valueToCode(e,"ADD"+i,t.JavaScript.ORDER_COMMA)||"null";return["["+o.join(", ")+"]",t.JavaScript.ORDER_ATOMIC]},t.JavaScript.lists_repeat=function(e){return[t.JavaScript.provideFunction_("listsRepeat",["function "+t.JavaScript.FUNCTION_NAME_PLACEHOLDER_+"(value, n) {","  var array = [];","  for (var i = 0; i < n; i++) {","    array[i] = value;","  }","  return array;","}"])+"("+(t.JavaScript.valueToCode(e,"ITEM",t.JavaScript.ORDER_COMMA)||"null")+", "+(e=t.JavaScript.valueToCode(e,"NUM",t.JavaScript.ORDER_COMMA)||"0")+")",t.JavaScript.ORDER_FUNCTION_CALL]},t.JavaScript.lists_length=function(e){return[(t.JavaScript.valueToCode(e,"VALUE",t.JavaScript.ORDER_MEMBER)||"[]")+".length",t.JavaScript.ORDER_MEMBER]},t.JavaScript.lists_isEmpty=function(e){return["!"+(t.JavaScript.valueToCode(e,"VALUE",t.JavaScript.ORDER_MEMBER)||"[]")+".length",t.JavaScript.ORDER_LOGICAL_NOT]},t.JavaScript.lists_indexOf=function(e){var o="FIRST"==e.getFieldValue("END")?"indexOf":"lastIndexOf",i=t.JavaScript.valueToCode(e,"FIND",t.JavaScript.ORDER_NONE)||"''";return o=(t.JavaScript.valueToCode(e,"VALUE",t.JavaScript.ORDER_MEMBER)||"[]")+"."+o+"("+i+")",e.workspace.options.oneBasedIndex?[o+" + 1",t.JavaScript.ORDER_ADDITION]:[o,t.JavaScript.ORDER_FUNCTION_CALL]},t.JavaScript.lists_getIndex=function(e){var o=e.getFieldValue("MODE")||"GET",i=e.getFieldValue("WHERE")||"FROM_START",n=t.JavaScript.valueToCode(e,"VALUE","RANDOM"==i?t.JavaScript.ORDER_COMMA:t.JavaScript.ORDER_MEMBER)||"[]";switch(i){case"FIRST":if("GET"==o)return[n+"[0]",t.JavaScript.ORDER_MEMBER];if("GET_REMOVE"==o)return[n+".shift()",t.JavaScript.ORDER_MEMBER];if("REMOVE"==o)return n+".shift();\n";break;case"LAST":if("GET"==o)return[n+".slice(-1)[0]",t.JavaScript.ORDER_MEMBER];if("GET_REMOVE"==o)return[n+".pop()",t.JavaScript.ORDER_MEMBER];if("REMOVE"==o)return n+".pop();\n";break;case"FROM_START":if(e=t.JavaScript.getAdjusted(e,"AT"),"GET"==o)return[n+"["+e+"]",t.JavaScript.ORDER_MEMBER];if("GET_REMOVE"==o)return[n+".splice("+e+", 1)[0]",t.JavaScript.ORDER_FUNCTION_CALL];if("REMOVE"==o)return n+".splice("+e+", 1);\n";break;case"FROM_END":if(e=t.JavaScript.getAdjusted(e,"AT",1,!0),"GET"==o)return[n+".slice("+e+")[0]",t.JavaScript.ORDER_FUNCTION_CALL];if("GET_REMOVE"==o)return[n+".splice("+e+", 1)[0]",t.JavaScript.ORDER_FUNCTION_CALL];if("REMOVE"==o)return n+".splice("+e+", 1);";break;case"RANDOM":if(n=t.JavaScript.provideFunction_("listsGetRandomItem",["function "+t.JavaScript.FUNCTION_NAME_PLACEHOLDER_+"(list, remove) {","  var x = Math.floor(Math.random() * list.length);","  if (remove) {","    return list.splice(x, 1)[0];","  } else {","    return list[x];","  }","}"])+"("+n+", "+("GET"!=o)+")","GET"==o||"GET_REMOVE"==o)return[n,t.JavaScript.ORDER_FUNCTION_CALL];if("REMOVE"==o)return n+";\n"}throw Error("Unhandled combination (lists_getIndex).")},t.JavaScript.lists_setIndex=function(e){function o(){if(i.match(/^\w+$/))return"";var e=t.JavaScript.variableDB_.getDistinctName("tmpList",t.VARIABLE_CATEGORY_NAME),o="var "+e+" = "+i+";\n";return i=e,o}var i=t.JavaScript.valueToCode(e,"LIST",t.JavaScript.ORDER_MEMBER)||"[]",n=e.getFieldValue("MODE")||"GET",s=e.getFieldValue("WHERE")||"FROM_START",r=t.JavaScript.valueToCode(e,"TO",t.JavaScript.ORDER_ASSIGNMENT)||"null";switch(s){case"FIRST":if("SET"==n)return i+"[0] = "+r+";\n";if("INSERT"==n)return i+".unshift("+r+");\n";break;case"LAST":if("SET"==n)return(e=o())+(i+"[")+i+".length - 1] = "+r+";\n";if("INSERT"==n)return i+".push("+r+");\n";break;case"FROM_START":if(s=t.JavaScript.getAdjusted(e,"AT"),"SET"==n)return i+"["+s+"] = "+r+";\n";if("INSERT"==n)return i+".splice("+s+", 0, "+r+");\n";break;case"FROM_END":if(s=t.JavaScript.getAdjusted(e,"AT",1,!1,t.JavaScript.ORDER_SUBTRACTION),e=o(),"SET"==n)return e+(i+"[")+i+".length - "+s+"] = "+r+";\n";if("INSERT"==n)return e+(i+".splice(")+i+".length - "+s+", 0, "+r+");\n";break;case"RANDOM":if(e=o(),e+="var "+(s=t.JavaScript.variableDB_.getDistinctName("tmpX",t.VARIABLE_CATEGORY_NAME))+" = Math.floor(Math.random() * "+i+".length);\n","SET"==n)return e+(i+"[")+s+"] = "+r+";\n";if("INSERT"==n)return e+(i+".splice(")+s+", 0, "+r+");\n"}throw Error("Unhandled combination (lists_setIndex).")},t.JavaScript.lists.getIndex_=function(t,e,o){return"FIRST"==e?"0":"FROM_END"==e?t+".length - 1 - "+o:"LAST"==e?t+".length - 1":o},t.JavaScript.lists_getSublist=function(e){var o=t.JavaScript.valueToCode(e,"LIST",t.JavaScript.ORDER_MEMBER)||"[]",i=e.getFieldValue("WHERE1"),n=e.getFieldValue("WHERE2");if("FIRST"==i&&"LAST"==n)o+=".slice(0)";else if(o.match(/^\w+$/)||"FROM_END"!=i&&"FROM_START"==n){switch(i){case"FROM_START":var s=t.JavaScript.getAdjusted(e,"AT1");break;case"FROM_END":s=o+".length - "+(s=t.JavaScript.getAdjusted(e,"AT1",1,!1,t.JavaScript.ORDER_SUBTRACTION));break;case"FIRST":s="0";break;default:throw Error("Unhandled option (lists_getSublist).")}switch(n){case"FROM_START":e=t.JavaScript.getAdjusted(e,"AT2",1);break;case"FROM_END":e=o+".length - "+(e=t.JavaScript.getAdjusted(e,"AT2",0,!1,t.JavaScript.ORDER_SUBTRACTION));break;case"LAST":e=o+".length";break;default:throw Error("Unhandled option (lists_getSublist).")}o=o+".slice("+s+", "+e+")"}else{s=t.JavaScript.getAdjusted(e,"AT1"),e=t.JavaScript.getAdjusted(e,"AT2");var r=t.JavaScript.lists.getIndex_,a={FIRST:"First",LAST:"Last",FROM_START:"FromStart",FROM_END:"FromEnd"};o=t.JavaScript.provideFunction_("subsequence"+a[i]+a[n],["function "+t.JavaScript.FUNCTION_NAME_PLACEHOLDER_+"(sequence"+("FROM_END"==i||"FROM_START"==i?", at1":"")+("FROM_END"==n||"FROM_START"==n?", at2":"")+") {","  var start = "+r("sequence",i,"at1")+";","  var end = "+r("sequence",n,"at2")+" + 1;","  return sequence.slice(start, end);","}"])+"("+o+("FROM_END"==i||"FROM_START"==i?", "+s:"")+("FROM_END"==n||"FROM_START"==n?", "+e:"")+")"}return[o,t.JavaScript.ORDER_FUNCTION_CALL]},t.JavaScript.lists_sort=function(e){var o=t.JavaScript.valueToCode(e,"LIST",t.JavaScript.ORDER_FUNCTION_CALL)||"[]",i="1"===e.getFieldValue("DIRECTION")?1:-1;return e=e.getFieldValue("TYPE"),[o+".slice().sort("+t.JavaScript.provideFunction_("listsGetSortCompare",["function "+t.JavaScript.FUNCTION_NAME_PLACEHOLDER_+"(type, direction) {","  var compareFuncs = {",'    "NUMERIC": function(a, b) {',"        return Number(a) - Number(b); },",'    "TEXT": function(a, b) {',"        return a.toString() > 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<o?" else ":"")+"if ("+n+") {\n"+s+"}",++o}while(e.getInput("IF"+o));return(e.getInput("ELSE")||t.JavaScript.STATEMENT_SUFFIX)&&(s=t.JavaScript.statementToCode(e,"ELSE"),t.JavaScript.STATEMENT_SUFFIX&&(s=t.JavaScript.prefixLines(t.JavaScript.injectId(t.JavaScript.STATEMENT_SUFFIX,e),t.JavaScript.INDENT)+s),i+=" else {\n"+s+"}"),i+"\n"},t.JavaScript.controls_ifelse=t.JavaScript.controls_if,t.JavaScript.logic_compare=function(e){var o={EQ:"==",NEQ:"!=",LT:"<",LTE:"<=",GT:">",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<e.arguments_.length;c++)l[c]=t.JavaScript.variableDB_.getName(e.arguments_[c],t.VARIABLE_CATEGORY_NAME);return i="function "+o+"("+l.join(", ")+") {\n"+i+n+s+a+r+"}",i=t.JavaScript.scrub_(e,i),t.JavaScript.definitions_["%"+o]=i,null},t.JavaScript.procedures_defnoreturn=t.JavaScript.procedures_defreturn,t.JavaScript.procedures_callreturn=function(e){for(var o=t.JavaScript.variableDB_.getName(e.getFieldValue("NAME"),t.PROCEDURE_CATEGORY_NAME),i=[],n=0;n<e.arguments_.length;n++)i[n]=t.JavaScript.valueToCode(e,"ARG"+n,t.JavaScript.ORDER_COMMA)||"null";return[o+"("+i.join(", ")+")",t.JavaScript.ORDER_FUNCTION_CALL]},t.JavaScript.procedures_callnoreturn=function(e){return t.JavaScript.procedures_callreturn(e)[0]+";\n"},t.JavaScript.procedures_ifreturn=function(e){var o="if ("+(t.JavaScript.valueToCode(e,"CONDITION",t.JavaScript.ORDER_NONE)||"false")+") {\n";return t.JavaScript.STATEMENT_SUFFIX&&(o+=t.JavaScript.prefixLines(t.JavaScript.injectId(t.JavaScript.STATEMENT_SUFFIX,e),t.JavaScript.INDENT)),e.hasReturnValue_?(e=t.JavaScript.valueToCode(e,"VALUE",t.JavaScript.ORDER_NONE)||"null",o+=t.JavaScript.INDENT+"return "+e+";\n"):o+=t.JavaScript.INDENT+"return;\n",o+"}\n"},t.JavaScript.texts={},t.JavaScript.text=function(e){return[t.JavaScript.quote_(e.getFieldValue("TEXT")),t.JavaScript.ORDER_ATOMIC]},t.JavaScript.text_multiline=function(e){return(e=t.JavaScript.multiline_quote_(e.getFieldValue("TEXT"))).includes("\n")&&(e="("+e+")"),[e,t.JavaScript.ORDER_ATOMIC]},t.JavaScript.text.forceString_=function(e){return t.JavaScript.text.forceString_.strRegExp.test(e)?e:"String("+e+")"},t.JavaScript.text.forceString_.strRegExp=/^\s*'([^']|\\')*'\s*$/,t.JavaScript.text_join=function(e){switch(e.itemCount_){case 0:return["''",t.JavaScript.ORDER_ATOMIC];case 1:return e=t.JavaScript.valueToCode(e,"ADD0",t.JavaScript.ORDER_NONE)||"''",[e=t.JavaScript.text.forceString_(e),t.JavaScript.ORDER_FUNCTION_CALL];case 2:var o=t.JavaScript.valueToCode(e,"ADD0",t.JavaScript.ORDER_NONE)||"''";return e=t.JavaScript.valueToCode(e,"ADD1",t.JavaScript.ORDER_NONE)||"''",[e=t.JavaScript.text.forceString_(o)+" + "+t.JavaScript.text.forceString_(e),t.JavaScript.ORDER_ADDITION];default:o=Array(e.itemCount_);for(var i=0;i<e.itemCount_;i++)o[i]=t.JavaScript.valueToCode(e,"ADD"+i,t.JavaScript.ORDER_COMMA)||"''";return[e="["+o.join(",")+"].join('')",t.JavaScript.ORDER_FUNCTION_CALL]}},t.JavaScript.text_append=function(e){var o=t.JavaScript.variableDB_.getName(e.getFieldValue("VAR"),t.VARIABLE_CATEGORY_NAME);return e=t.JavaScript.valueToCode(e,"TEXT",t.JavaScript.ORDER_NONE)||"''",o+" += "+t.JavaScript.text.forceString_(e)+";\n"},t.JavaScript.text_length=function(e){return[(t.JavaScript.valueToCode(e,"VALUE",t.JavaScript.ORDER_FUNCTION_CALL)||"''")+".length",t.JavaScript.ORDER_MEMBER]},t.JavaScript.text_isEmpty=function(e){return["!"+(t.JavaScript.valueToCode(e,"VALUE",t.JavaScript.ORDER_MEMBER)||"''")+".length",t.JavaScript.ORDER_LOGICAL_NOT]},t.JavaScript.text_indexOf=function(e){var o="FIRST"==e.getFieldValue("END")?"indexOf":"lastIndexOf",i=t.JavaScript.valueToCode(e,"FIND",t.JavaScript.ORDER_NONE)||"''";return o=(t.JavaScript.valueToCode(e,"VALUE",t.JavaScript.ORDER_MEMBER)||"''")+"."+o+"("+i+")",e.workspace.options.oneBasedIndex?[o+" + 1",t.JavaScript.ORDER_ADDITION]:[o,t.JavaScript.ORDER_FUNCTION_CALL]},t.JavaScript.text_charAt=function(e){var o=e.getFieldValue("WHERE")||"FROM_START",i=t.JavaScript.valueToCode(e,"VALUE","RANDOM"==o?t.JavaScript.ORDER_NONE:t.JavaScript.ORDER_MEMBER)||"''";switch(o){case"FIRST":return[i+".charAt(0)",t.JavaScript.ORDER_FUNCTION_CALL];case"LAST":return[i+".slice(-1)",t.JavaScript.ORDER_FUNCTION_CALL];case"FROM_START":return[i+".charAt("+(e=t.JavaScript.getAdjusted(e,"AT"))+")",t.JavaScript.ORDER_FUNCTION_CALL];case"FROM_END":return[i+".slice("+(e=t.JavaScript.getAdjusted(e,"AT",1,!0))+").charAt(0)",t.JavaScript.ORDER_FUNCTION_CALL];case"RANDOM":return[t.JavaScript.provideFunction_("textRandomLetter",["function "+t.JavaScript.FUNCTION_NAME_PLACEHOLDER_+"(text) {","  var x = Math.floor(Math.random() * text.length);","  return text[x];","}"])+"("+i+")",t.JavaScript.ORDER_FUNCTION_CALL]}throw Error("Unhandled option (text_charAt).")},t.JavaScript.text.getIndex_=function(t,e,o){return"FIRST"==e?"0":"FROM_END"==e?t+".length - 1 - "+o:"LAST"==e?t+".length - 1":o},t.JavaScript.text_getSubstring=function(e){var o=t.JavaScript.valueToCode(e,"STRING",t.JavaScript.ORDER_FUNCTION_CALL)||"''",i=e.getFieldValue("WHERE1"),n=e.getFieldValue("WHERE2");if("FIRST"!=i||"LAST"!=n)if(o.match(/^'?\w+'?$/)||"FROM_END"!=i&&"LAST"!=i&&"FROM_END"!=n&&"LAST"!=n){switch(i){case"FROM_START":var s=t.JavaScript.getAdjusted(e,"AT1");break;case"FROM_END":s=o+".length - "+(s=t.JavaScript.getAdjusted(e,"AT1",1,!1,t.JavaScript.ORDER_SUBTRACTION));break;case"FIRST":s="0";break;default:throw Error("Unhandled option (text_getSubstring).")}switch(n){case"FROM_START":e=t.JavaScript.getAdjusted(e,"AT2",1);break;case"FROM_END":e=o+".length - "+(e=t.JavaScript.getAdjusted(e,"AT2",0,!1,t.JavaScript.ORDER_SUBTRACTION));break;case"LAST":e=o+".length";break;default:throw Error("Unhandled option (text_getSubstring).")}o=o+".slice("+s+", "+e+")"}else{s=t.JavaScript.getAdjusted(e,"AT1"),e=t.JavaScript.getAdjusted(e,"AT2");var r=t.JavaScript.text.getIndex_,a={FIRST:"First",LAST:"Last",FROM_START:"FromStart",FROM_END:"FromEnd"};o=t.JavaScript.provideFunction_("subsequence"+a[i]+a[n],["function "+t.JavaScript.FUNCTION_NAME_PLACEHOLDER_+"(sequence"+("FROM_END"==i||"FROM_START"==i?", at1":"")+("FROM_END"==n||"FROM_START"==n?", at2":"")+") {","  var start = "+r("sequence",i,"at1")+";","  var end = "+r("sequence",n,"at2")+" + 1;","  return sequence.slice(start, end);","}"])+"("+o+("FROM_END"==i||"FROM_START"==i?", "+s:"")+("FROM_END"==n||"FROM_START"==n?", "+e:"")+")"}return[o,t.JavaScript.ORDER_FUNCTION_CALL]},t.JavaScript.text_changeCase=function(e){var o={UPPERCASE:".toUpperCase()",LOWERCASE:".toLowerCase()",TITLECASE:null}[e.getFieldValue("CASE")];return e=t.JavaScript.valueToCode(e,"TEXT",o?t.JavaScript.ORDER_MEMBER:t.JavaScript.ORDER_NONE)||"''",[o?e+o:t.JavaScript.provideFunction_("textToTitleCase",["function "+t.JavaScript.FUNCTION_NAME_PLACEHOLDER_+"(str) {","  return str.replace(/\\S+/g,","      function(txt) {return txt[0].toUpperCase() + txt.substring(1).toLowerCase();});","}"])+"("+e+")",t.JavaScript.ORDER_FUNCTION_CALL]},t.JavaScript.text_trim=function(e){var o={LEFT:".replace(/^[\\s\\xa0]+/, '')",RIGHT:".replace(/[\\s\\xa0]+$/, '')",BOTH:".trim()"}[e.getFieldValue("MODE")];return[(t.JavaScript.valueToCode(e,"TEXT",t.JavaScript.ORDER_MEMBER)||"''")+o,t.JavaScript.ORDER_FUNCTION_CALL]},t.JavaScript.text_print=function(e){return"window.alert("+(t.JavaScript.valueToCode(e,"TEXT",t.JavaScript.ORDER_NONE)||"''")+");\n"},t.JavaScript.text_prompt_ext=function(e){var o="window.prompt("+(e.getField("TEXT")?t.JavaScript.quote_(e.getFieldValue("TEXT")):t.JavaScript.valueToCode(e,"TEXT",t.JavaScript.ORDER_NONE)||"''")+")";return"NUMBER"==e.getFieldValue("TYPE")&&(o="Number("+o+")"),[o,t.JavaScript.ORDER_FUNCTION_CALL]},t.JavaScript.text_prompt=t.JavaScript.text_prompt_ext,t.JavaScript.text_count=function(e){var o=t.JavaScript.valueToCode(e,"TEXT",t.JavaScript.ORDER_MEMBER)||"''";return e=t.JavaScript.valueToCode(e,"SUB",t.JavaScript.ORDER_NONE)||"''",[t.JavaScript.provideFunction_("textCount",["function "+t.JavaScript.FUNCTION_NAME_PLACEHOLDER_+"(haystack, needle) {","  if (needle.length === 0) {","    return haystack.length + 1;","  } else {","    return haystack.split(needle).length - 1;","  }","}"])+"("+o+", "+e+")",t.JavaScript.ORDER_SUBTRACTION]},t.JavaScript.text_replace=function(e){var o=t.JavaScript.valueToCode(e,"TEXT",t.JavaScript.ORDER_MEMBER)||"''",i=t.JavaScript.valueToCode(e,"FROM",t.JavaScript.ORDER_NONE)||"''";return e=t.JavaScript.valueToCode(e,"TO",t.JavaScript.ORDER_NONE)||"''",[t.JavaScript.provideFunction_("textReplace",["function "+t.JavaScript.FUNCTION_NAME_PLACEHOLDER_+"(haystack, needle, replacement) {",'  needle = needle.replace(/([-()\\[\\]{}+?*.$\\^|,:#<!\\\\])/g,"\\\\$1")','                 .replace(/\\x08/g,"\\\\x08");',"  return haystack.replace(new RegExp(needle, 'g'), replacement);","}"])+"("+o+", "+i+", "+e+")",t.JavaScript.ORDER_MEMBER]},t.JavaScript.text_reverse=function(e){return[(t.JavaScript.valueToCode(e,"TEXT",t.JavaScript.ORDER_MEMBER)||"''")+".split('').reverse().join('')",t.JavaScript.ORDER_MEMBER]},t.JavaScript.variables={},t.JavaScript.variables_get=function(e){return[t.JavaScript.variableDB_.getName(e.getFieldValue("VAR"),t.VARIABLE_CATEGORY_NAME),t.JavaScript.ORDER_ATOMIC]},t.JavaScript.variables_set=function(e){var o=t.JavaScript.valueToCode(e,"VALUE",t.JavaScript.ORDER_ASSIGNMENT)||"0";return t.JavaScript.variableDB_.getName(e.getFieldValue("VAR"),t.VARIABLE_CATEGORY_NAME)+" = "+o+";\n"},t.JavaScript.variablesDynamic={},t.JavaScript.variables_get_dynamic=t.JavaScript.variables_get,t.JavaScript.variables_set_dynamic=t.JavaScript.variables_set,t.JavaScript})?i.apply(e,n):i)||(t.exports=s)},function(t,e){t.exports=function(t){if(!t.webpackPolyfill){var e=Object.create(t);e.children||(e.children=[]),Object.defineProperty(e,"loaded",{enumerable:!0,get:function(){return e.l}}),Object.defineProperty(e,"id",{enumerable:!0,get:function(){return e.i}}),Object.defineProperty(e,"exports",{enumerable:!0}),e.webpackPolyfill=1}return e}}]]);
\ No newline at end of file
diff --git a/static/repl/playground/2.playground.js b/static/repl/playground/2.playground.js
deleted file mode 100644 (file)
index ac986de..0000000
+++ /dev/null
@@ -1 +0,0 @@
-(window.webpackJsonp=window.webpackJsonp||[]).push([[2],{1:function(e,n,t){"use strict";t.r(n);var i=t(2),o=t(4),r=t.n(o),a={backupBlocks_:function(e){if("localStorage"in window){var n=r.a.Xml.workspaceToDom(e),t=window.location.href.split("#")[0];window.localStorage.setItem(t,r.a.Xml.domToText(n))}},backupOnUnload:function(e){var n=e||r.a.getMainWorkspace();window.addEventListener("unload",(function(){a.backupBlocks_(n)}),!1)},restoreBlocks:function(e){var n=window.location.href.split("#")[0];if("localStorage"in window&&window.localStorage[n]){var t=e||r.a.getMainWorkspace(),i=r.a.Xml.textToDom(window.localStorage[n]);r.a.Xml.domToWorkspace(i,t)}},link:function(e){var n=e||r.a.getMainWorkspace(),t=r.a.Xml.workspaceToDom(n,!0);if(1==n.getTopBlocks(!1).length&&t.querySelector){var i=t.querySelector("block");i&&(i.removeAttribute("x"),i.removeAttribute("y"))}var o=r.a.Xml.domToText(t);a.makeRequest_("/storage","xml",o,n)},retrieveXml:function(e,n){var t=n||r.a.getMainWorkspace();a.makeRequest_("/storage","key",e,t)},httpRequest_:null,makeRequest_:function(e,n,t,i){a.httpRequest_&&a.httpRequest_.abort(),a.httpRequest_=new XMLHttpRequest,a.httpRequest_.name=n,a.httpRequest_.onreadystatechange=a.handleRequest_,a.httpRequest_.open("POST",e),a.httpRequest_.setRequestHeader("Content-Type","application/x-www-form-urlencoded"),a.httpRequest_.send(n+"="+encodeURIComponent(t)),a.httpRequest_.workspace=i},handleRequest_:function(){if(4==a.httpRequest_.readyState){if(200!=a.httpRequest_.status)a.alert(a.HTTPREQUEST_ERROR+"\nhttpRequest_.status: "+a.httpRequest_.status);else{var e=a.httpRequest_.responseText.trim();"xml"==a.httpRequest_.name?(window.location.hash=e,a.alert(a.LINK_ALERT.replace("%1",window.location.href))):"key"==a.httpRequest_.name&&(e.length?a.loadXml_(e,a.httpRequest_.workspace):a.alert(a.HASH_ERROR.replace("%1",window.location.hash))),a.monitorChanges_(a.httpRequest_.workspace)}a.httpRequest_=null}},monitorChanges_:function(e){var n=r.a.Xml.workspaceToDom(e),t=r.a.Xml.domToText(n);e.addChangeListener((function n(){var i=r.a.Xml.workspaceToDom(e),o=r.a.Xml.domToText(i);t!=o&&(window.location.hash="",e.removeChangeListener(n))}))},loadXml_:function(e,n){try{e=r.a.Xml.textToDom(e)}catch(n){return void a.alert(a.XML_ERROR+"\nXML: "+e)}n.clear(),r.a.Xml.domToWorkspace(e,n)},alert:function(e){window.alert(e)}},l=a;!async function(){Object(i.ob)(),function(e,n){console.log("Blockly starting");const t=document.getElementById(n);r.a.JavaScript.INDENT="";var i={toolbox:'<xml xmlns="https://developers.google.com/blockly/xml">\n  <category name="Miniscript" colour="#5ba55b">\n    <block type="and"></block>\n    <block type="or">\n      <field name="A_weight">1</field>\n      <field name="B_weight">1</field>\n    </block>\n    <block type="thresh">\n      <field name="Threshold">1</field>\n    </block>\n    <block type="after">\n      <field name="NAME">1</field>\n    </block>\n    <block type="pk"></block>\n    <block type="adapter"></block>\n    <block type="older">\n      <field name="NAME">1</field>\n    </block>\n    <block type="alias_key">\n      <field name="label">Alias</field>\n      <field name="name">name</field>\n    </block>\n    <block type="existing_key">\n      <field name="NAME">Existing Key</field>\n      <field name="key">tpub, WIF, hex...</field>\n    </block>\n  </category>\n  <category name="Examples" colour="#5b67a5">\n    <block type="pk">\n      <value name="pk">\n        <block type="alias_key">\n          <field name="label">Alias</field>\n          <field name="name">Alice</field>\n        </block>\n      </value>\n    </block>\n    <block type="or">\n      <field name="A_weight">1</field>\n      <field name="B_weight">1</field>\n      <statement name="A">\n        <block type="pk">\n          <value name="pk">\n            <block type="alias_key">\n              <field name="label">Alias</field>\n              <field name="name">Alice</field>\n            </block>\n          </value>\n        </block>\n      </statement>\n      <statement name="B">\n        <block type="pk">\n          <value name="pk">\n            <block type="alias_key">\n              <field name="label">Alias</field>\n              <field name="name">Bob</field>\n            </block>\n          </value>\n        </block>\n      </statement>\n    </block>\n    <block type="or">\n      <field name="A_weight">99</field>\n      <field name="B_weight">1</field>\n      <statement name="A">\n        <block type="pk">\n          <value name="pk">\n            <block type="alias_key">\n              <field name="label">Alias</field>\n              <field name="name">KeyLikely</field>\n            </block>\n          </value>\n        </block>\n      </statement>\n      <statement name="B">\n        <block type="pk">\n          <value name="pk">\n            <block type="alias_key">\n              <field name="label">Alias</field>\n              <field name="name">Likely</field>\n            </block>\n          </value>\n        </block>\n      </statement>\n    </block>\n    <block type="and">\n      <statement name="A">\n        <block type="pk">\n          <value name="pk">\n            <block type="alias_key">\n              <field name="label">Alias</field>\n              <field name="name">User</field>\n            </block>\n          </value>\n        </block>\n      </statement>\n      <statement name="B">\n        <block type="or">\n          <field name="A_weight">99</field>\n          <field name="B_weight">1</field>\n          <statement name="A">\n            <block type="pk">\n              <value name="pk">\n                <block type="alias_key">\n                  <field name="label">Alias</field>\n                  <field name="name">Service</field>\n                </block>\n              </value>\n            </block>\n          </statement>\n          <statement name="B">\n            <block type="older">\n              <field name="NAME">12960</field>\n            </block>\n          </statement>\n        </block>\n      </statement>\n    </block>\n    <block type="thresh">\n      <field name="Threshold">3</field>\n      <statement name="A">\n        <block type="adapter">\n          <statement name="NAME">\n            <block type="pk">\n              <value name="pk">\n                <block type="alias_key">\n                  <field name="label">Alias</field>\n                  <field name="name">Alice</field>\n                </block>\n              </value>\n            </block>\n          </statement>\n          <next>\n            <block type="adapter">\n              <statement name="NAME">\n                <block type="pk">\n                  <value name="pk">\n                    <block type="alias_key">\n                      <field name="label">Alias</field>\n                      <field name="name">Bob</field>\n                    </block>\n                  </value>\n                </block>\n              </statement>\n              <next>\n                <block type="adapter">\n                  <statement name="NAME">\n                    <block type="pk">\n                      <value name="pk">\n                        <block type="alias_key">\n                          <field name="label">Alias</field>\n                          <field name="name">Carol</field>\n                        </block>\n                      </value>\n                    </block>\n                  </statement>\n                  <next>\n                    <block type="adapter">\n                      <statement name="NAME">\n                        <block type="older">\n                          <field name="NAME">12960</field>\n                        </block>\n                      </statement>\n                    </block>\n                  </next>\n                </block>\n              </next>\n            </block>\n          </next>\n        </block>\n      </statement>\n    </block>\n  </category>\n</xml>',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='<i class="fas fa-expand"></i>',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+=`<span class="command">> ${e}</span>\n`,a=r.push(e),l.run(e).then(e=>{e&&(t.innerHTML+=`<span class="success">${e}</span>\n`)}).catch(e=>t.innerHTML+=`<span class="error">${e}</span>\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&&a<r.length&&(o.value=r[++a]||"")},{run:u}}(a.value,u.value.length>0?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=`<span class="error">${e}</span>`))},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=`<span class="error">${e}</span>`)}}()},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(;a<i;a++){const n=e.charCodeAt(a);if(n>127)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;o<t;o++)i+=", "+e(n[o]);return i+="]",i}const i=/\[object ([^\]]+)\]/.exec(toString.call(n));let o;if(!(i.length>1))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 (file)
index cdcd136..0000000
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 (file)
index 5c4764d..0000000
+++ /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;i<c.length;i++)n(c[i]);var b=f;u(u.s=0)}([function(e,n,t){Promise.all([t.e(1),t.e(2)]).then(t.bind(null,1)).catch(e=>console.error("Error importing `index.js`:",e))}]);
\ No newline at end of file