From 6ed2b6a31fb4ae8cf479e1cb0cfeefa02187c4c1 Mon Sep 17 00:00:00 2001 From: Aaron Dodson Date: Thu, 9 Dec 2021 13:18:21 -0800 Subject: [PATCH 001/128] chore: Update metadata for December 2021 (#5811) --- tests/scripts/check_metadata.sh | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/tests/scripts/check_metadata.sh b/tests/scripts/check_metadata.sh index 02195205c..7bf9e38e2 100755 --- a/tests/scripts/check_metadata.sh +++ b/tests/scripts/check_metadata.sh @@ -28,7 +28,8 @@ readonly BUILD_DIR='build' # Q3 2021 6.20210701.0 731695 (mid-quarter goog.module conversion) # Q3 2021 6.20210701.0 808807 (late-quarter goog.module conversion) # Q4 2021 7.20211209.0-beta.0 920002 -readonly BLOCKLY_SIZE_EXPECTED=920002 +# Q4 2021 7.20211209.0 929665 +readonly BLOCKLY_SIZE_EXPECTED=929665 # Size of blocks_compressed.js # Q2 2019 2.20190722.0 75618 @@ -42,7 +43,8 @@ readonly BLOCKLY_SIZE_EXPECTED=920002 # Q2 2021 6.20210701.0 76669 # Q3 2021 6.20210701.0 76669 # Q4 2021 7.20211209.0-beta.0 82054 -readonly BLOCKS_SIZE_EXPECTED=82054 +# Q4 2021 7.20211209.0 86966 +readonly BLOCKS_SIZE_EXPECTED=86966 # Size of blockly_compressed.js.gz # Q2 2019 2.20190722.0 180925 @@ -57,7 +59,8 @@ readonly BLOCKS_SIZE_EXPECTED=82054 # Q3 2021 6.20210701.0 147476 (mid-quarter goog.module conversion) # Q3 2021 6.20210701.0 152025 (late-quarter goog.module conversion) # Q4 2021 7.20211209.0-beta.0 169863 -readonly BLOCKLY_GZ_SIZE_EXPECTED=169863 +# Q4 2021 7.20211209.0 171759 +readonly BLOCKLY_GZ_SIZE_EXPECTED=171759 # Size of blocks_compressed.js.gz # Q2 2019 2.20190722.0 14552 @@ -71,7 +74,8 @@ readonly BLOCKLY_GZ_SIZE_EXPECTED=169863 # Q2 2021 6.20210701.0 15275 # Q3 2021 6.20210701.0 15284 # Q4 2021 7.20211209.0-beta.0 16616 -readonly BLOCKS_GZ_SIZE_EXPECTED=16616 +# Q4 2021 7.20211209.0 15760 +readonly BLOCKS_GZ_SIZE_EXPECTED=15760 # ANSI colors readonly BOLD_GREEN='\033[1;32m' From ec6bf32ade0f668bf1fd7cb85799da2b8dd41530 Mon Sep 17 00:00:00 2001 From: Christopher Allen Date: Fri, 10 Dec 2021 10:08:39 +0000 Subject: [PATCH 002/128] chore(deps): Remove dependency on `babel-eslint`; simplify eslintrc for mocha tests (#5794) * chore(deps): Remove deprecated babel-lint package When dependabot submitted PR #5791, it became apparent that eslint version >= 8 is incompatible with babel-eslint v10.1.0 despite the latter not having a version restriction against it. This is probably because v10.1.0 is the last version of the package before it was deprecated and renamed @babel/eslint-parser. A little more investigation determined that there is no longer any need to have eslint use a non-default parser for tests/mocha/**/*.js, so the most straight forward solution is just to remove the dependency entirely. * refactor(tests): Simplify tests/mocha/.eslintrc.json Remove all rules that seem to be redundant with our top-level .eslintrc.json. This finishes reverting most of the changes made in PR #4062. --- package-lock.json | 300 ------------------------------------- package.json | 1 - tests/mocha/.eslintrc.json | 23 --- 3 files changed, 324 deletions(-) diff --git a/package-lock.json b/package-lock.json index 04055f457..52ffe448d 100644 --- a/package-lock.json +++ b/package-lock.json @@ -16,7 +16,6 @@ "@blockly/dev-tools": "^2.6.1", "@blockly/theme-modern": "^2.1.1", "@wdio/selenium-standalone-service": "^7.10.1", - "babel-eslint": "^10.1.0", "chai": "^4.2.0", "clang-format": "^1.6.0", "closure-calculate-chunks": "^3.0.2", @@ -59,70 +58,6 @@ "node": ">=6.9.0" } }, - "node_modules/@babel/generator": { - "version": "7.16.0", - "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.16.0.tgz", - "integrity": "sha512-RR8hUCfRQn9j9RPKEVXo9LiwoxLPYn6hNZlvUOR8tSnaxlD0p0+la00ZP9/SnRt6HchKr+X0fO2r8vrETiJGew==", - "dev": true, - "dependencies": { - "@babel/types": "^7.16.0", - "jsesc": "^2.5.1", - "source-map": "^0.5.0" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-function-name": { - "version": "7.16.0", - "resolved": "https://registry.npmjs.org/@babel/helper-function-name/-/helper-function-name-7.16.0.tgz", - "integrity": "sha512-BZh4mEk1xi2h4HFjWUXRQX5AEx4rvaZxHgax9gcjdLWdkjsY7MKt5p0otjsg5noXw+pB+clMCjw+aEVYADMjog==", - "dev": true, - "dependencies": { - "@babel/helper-get-function-arity": "^7.16.0", - "@babel/template": "^7.16.0", - "@babel/types": "^7.16.0" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-get-function-arity": { - "version": "7.16.0", - "resolved": "https://registry.npmjs.org/@babel/helper-get-function-arity/-/helper-get-function-arity-7.16.0.tgz", - "integrity": "sha512-ASCquNcywC1NkYh/z7Cgp3w31YW8aojjYIlNg4VeJiHkqyP4AzIvr4qx7pYDb4/s8YcsZWqqOSxgkvjUz1kpDQ==", - "dev": true, - "dependencies": { - "@babel/types": "^7.16.0" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-hoist-variables": { - "version": "7.16.0", - "resolved": "https://registry.npmjs.org/@babel/helper-hoist-variables/-/helper-hoist-variables-7.16.0.tgz", - "integrity": "sha512-1AZlpazjUR0EQZQv3sgRNfM9mEVWPK3M6vlalczA+EECcPz3XPh6VplbErL5UoMpChhSck5wAJHthlj1bYpcmg==", - "dev": true, - "dependencies": { - "@babel/types": "^7.16.0" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-split-export-declaration": { - "version": "7.16.0", - "resolved": "https://registry.npmjs.org/@babel/helper-split-export-declaration/-/helper-split-export-declaration-7.16.0.tgz", - "integrity": "sha512-0YMMRpuDFNGTHNRiiqJX19GjNXA4H0E8jZ2ibccfSxaCogbm3am5WN/2nQNj0YnQwGWM1J06GOcQ2qnh3+0paw==", - "dev": true, - "dependencies": { - "@babel/types": "^7.16.0" - }, - "engines": { - "node": ">=6.9.0" - } - }, "node_modules/@babel/helper-validator-identifier": { "version": "7.15.7", "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.15.7.tgz", @@ -217,65 +152,6 @@ "node": ">=4" } }, - "node_modules/@babel/parser": { - "version": "7.16.4", - "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.16.4.tgz", - "integrity": "sha512-6V0qdPUaiVHH3RtZeLIsc+6pDhbYzHR8ogA8w+f+Wc77DuXto19g2QUwveINoS34Uw+W8/hQDGJCx+i4n7xcng==", - "dev": true, - "bin": { - "parser": "bin/babel-parser.js" - }, - "engines": { - "node": ">=6.0.0" - } - }, - "node_modules/@babel/template": { - "version": "7.16.0", - "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.16.0.tgz", - "integrity": "sha512-MnZdpFD/ZdYhXwiunMqqgyZyucaYsbL0IrjoGjaVhGilz+x8YB++kRfygSOIj1yOtWKPlx7NBp+9I1RQSgsd5A==", - "dev": true, - "dependencies": { - "@babel/code-frame": "^7.16.0", - "@babel/parser": "^7.16.0", - "@babel/types": "^7.16.0" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/traverse": { - "version": "7.16.3", - "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.16.3.tgz", - "integrity": "sha512-eolumr1vVMjqevCpwVO99yN/LoGL0EyHiLO5I043aYQvwOJ9eR5UsZSClHVCzfhBduMAsSzgA/6AyqPjNayJag==", - "dev": true, - "dependencies": { - "@babel/code-frame": "^7.16.0", - "@babel/generator": "^7.16.0", - "@babel/helper-function-name": "^7.16.0", - "@babel/helper-hoist-variables": "^7.16.0", - "@babel/helper-split-export-declaration": "^7.16.0", - "@babel/parser": "^7.16.3", - "@babel/types": "^7.16.0", - "debug": "^4.1.0", - "globals": "^11.1.0" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/types": { - "version": "7.16.0", - "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.16.0.tgz", - "integrity": "sha512-PJgg/k3SdLsGb3hhisFvtLOw5ts113klrpLuIPtCJIU+BB24fqq6lf8RWqKJEjzqXR9AEH1rIb5XTqwBHB+kQg==", - "dev": true, - "dependencies": { - "@babel/helper-validator-identifier": "^7.15.7", - "to-fast-properties": "^2.0.0" - }, - "engines": { - "node": ">=6.9.0" - } - }, "node_modules/@blockly/block-test": { "version": "1.1.5", "resolved": "https://registry.npmjs.org/@blockly/block-test/-/block-test-1.1.5.tgz", @@ -1498,27 +1374,6 @@ "resolved": "https://registry.npmjs.org/aws4/-/aws4-1.11.0.tgz", "integrity": "sha512-xh1Rl34h6Fi1DC2WWKfxUTVqRsNnr6LsKz2+hfwDxQJWmrx8+c7ylaqBMcHfl1U1r2dsifOvKX3LQuLNZ+XSvA==" }, - "node_modules/babel-eslint": { - "version": "10.1.0", - "resolved": "https://registry.npmjs.org/babel-eslint/-/babel-eslint-10.1.0.tgz", - "integrity": "sha512-ifWaTHQ0ce+448CYop8AdrQiBsGrnC+bMgfyKFdi6EsPLTAWG+QfyDeM6OH+FmWnKvEq5NnBMLvlBUPKQZoDSg==", - "deprecated": "babel-eslint is now @babel/eslint-parser. This package will no longer receive updates.", - "dev": true, - "dependencies": { - "@babel/code-frame": "^7.0.0", - "@babel/parser": "^7.7.0", - "@babel/traverse": "^7.7.0", - "@babel/types": "^7.7.0", - "eslint-visitor-keys": "^1.0.0", - "resolve": "^1.12.0" - }, - "engines": { - "node": ">=6" - }, - "peerDependencies": { - "eslint": ">= 4.12.1" - } - }, "node_modules/bach": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/bach/-/bach-1.2.0.tgz", @@ -4851,15 +4706,6 @@ "which": "bin/which" } }, - "node_modules/globals": { - "version": "11.12.0", - "resolved": "https://registry.npmjs.org/globals/-/globals-11.12.0.tgz", - "integrity": "sha512-WOBp/EEGUiIsJSp7wcv/y6MO+lV9UoncWqxuFfm8eBwzWNgyfBd6Gz+IeKQ9jCmyhoH99g15M3T+QaVHFjizVA==", - "dev": true, - "engines": { - "node": ">=4" - } - }, "node_modules/glogg": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/glogg/-/glogg-1.0.2.tgz", @@ -6811,18 +6657,6 @@ "iconv-lite": "0.4.24" } }, - "node_modules/jsesc": { - "version": "2.5.2", - "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-2.5.2.tgz", - "integrity": "sha512-OYu7XEzjkCQ3C5Ps3QIZsQfNpqoJyZZA99wd9aWd05NCtC5pWOkShK2mkL6HXQR6/Cy2lbNdPlZBpuQHXE63gA==", - "dev": true, - "bin": { - "jsesc": "bin/jsesc" - }, - "engines": { - "node": ">=4" - } - }, "node_modules/json-buffer": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/json-buffer/-/json-buffer-3.0.1.tgz", @@ -11189,15 +11023,6 @@ "node": ">=0.10.0" } }, - "node_modules/to-fast-properties": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/to-fast-properties/-/to-fast-properties-2.0.0.tgz", - "integrity": "sha1-3F5pjL0HkmW8c+A3doGk5Og/YW4=", - "dev": true, - "engines": { - "node": ">=4" - } - }, "node_modules/to-object-path": { "version": "0.3.0", "resolved": "https://registry.npmjs.org/to-object-path/-/to-object-path-0.3.0.tgz", @@ -12320,55 +12145,6 @@ "@babel/highlight": "^7.16.0" } }, - "@babel/generator": { - "version": "7.16.0", - "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.16.0.tgz", - "integrity": "sha512-RR8hUCfRQn9j9RPKEVXo9LiwoxLPYn6hNZlvUOR8tSnaxlD0p0+la00ZP9/SnRt6HchKr+X0fO2r8vrETiJGew==", - "dev": true, - "requires": { - "@babel/types": "^7.16.0", - "jsesc": "^2.5.1", - "source-map": "^0.5.0" - } - }, - "@babel/helper-function-name": { - "version": "7.16.0", - "resolved": "https://registry.npmjs.org/@babel/helper-function-name/-/helper-function-name-7.16.0.tgz", - "integrity": "sha512-BZh4mEk1xi2h4HFjWUXRQX5AEx4rvaZxHgax9gcjdLWdkjsY7MKt5p0otjsg5noXw+pB+clMCjw+aEVYADMjog==", - "dev": true, - "requires": { - "@babel/helper-get-function-arity": "^7.16.0", - "@babel/template": "^7.16.0", - "@babel/types": "^7.16.0" - } - }, - "@babel/helper-get-function-arity": { - "version": "7.16.0", - "resolved": "https://registry.npmjs.org/@babel/helper-get-function-arity/-/helper-get-function-arity-7.16.0.tgz", - "integrity": "sha512-ASCquNcywC1NkYh/z7Cgp3w31YW8aojjYIlNg4VeJiHkqyP4AzIvr4qx7pYDb4/s8YcsZWqqOSxgkvjUz1kpDQ==", - "dev": true, - "requires": { - "@babel/types": "^7.16.0" - } - }, - "@babel/helper-hoist-variables": { - "version": "7.16.0", - "resolved": "https://registry.npmjs.org/@babel/helper-hoist-variables/-/helper-hoist-variables-7.16.0.tgz", - "integrity": "sha512-1AZlpazjUR0EQZQv3sgRNfM9mEVWPK3M6vlalczA+EECcPz3XPh6VplbErL5UoMpChhSck5wAJHthlj1bYpcmg==", - "dev": true, - "requires": { - "@babel/types": "^7.16.0" - } - }, - "@babel/helper-split-export-declaration": { - "version": "7.16.0", - "resolved": "https://registry.npmjs.org/@babel/helper-split-export-declaration/-/helper-split-export-declaration-7.16.0.tgz", - "integrity": "sha512-0YMMRpuDFNGTHNRiiqJX19GjNXA4H0E8jZ2ibccfSxaCogbm3am5WN/2nQNj0YnQwGWM1J06GOcQ2qnh3+0paw==", - "dev": true, - "requires": { - "@babel/types": "^7.16.0" - } - }, "@babel/helper-validator-identifier": { "version": "7.15.7", "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.15.7.tgz", @@ -12444,50 +12220,6 @@ } } }, - "@babel/parser": { - "version": "7.16.4", - "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.16.4.tgz", - "integrity": "sha512-6V0qdPUaiVHH3RtZeLIsc+6pDhbYzHR8ogA8w+f+Wc77DuXto19g2QUwveINoS34Uw+W8/hQDGJCx+i4n7xcng==", - "dev": true - }, - "@babel/template": { - "version": "7.16.0", - "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.16.0.tgz", - "integrity": "sha512-MnZdpFD/ZdYhXwiunMqqgyZyucaYsbL0IrjoGjaVhGilz+x8YB++kRfygSOIj1yOtWKPlx7NBp+9I1RQSgsd5A==", - "dev": true, - "requires": { - "@babel/code-frame": "^7.16.0", - "@babel/parser": "^7.16.0", - "@babel/types": "^7.16.0" - } - }, - "@babel/traverse": { - "version": "7.16.3", - "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.16.3.tgz", - "integrity": "sha512-eolumr1vVMjqevCpwVO99yN/LoGL0EyHiLO5I043aYQvwOJ9eR5UsZSClHVCzfhBduMAsSzgA/6AyqPjNayJag==", - "dev": true, - "requires": { - "@babel/code-frame": "^7.16.0", - "@babel/generator": "^7.16.0", - "@babel/helper-function-name": "^7.16.0", - "@babel/helper-hoist-variables": "^7.16.0", - "@babel/helper-split-export-declaration": "^7.16.0", - "@babel/parser": "^7.16.3", - "@babel/types": "^7.16.0", - "debug": "^4.1.0", - "globals": "^11.1.0" - } - }, - "@babel/types": { - "version": "7.16.0", - "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.16.0.tgz", - "integrity": "sha512-PJgg/k3SdLsGb3hhisFvtLOw5ts113klrpLuIPtCJIU+BB24fqq6lf8RWqKJEjzqXR9AEH1rIb5XTqwBHB+kQg==", - "dev": true, - "requires": { - "@babel/helper-validator-identifier": "^7.15.7", - "to-fast-properties": "^2.0.0" - } - }, "@blockly/block-test": { "version": "1.1.5", "resolved": "https://registry.npmjs.org/@blockly/block-test/-/block-test-1.1.5.tgz", @@ -13460,20 +13192,6 @@ "resolved": "https://registry.npmjs.org/aws4/-/aws4-1.11.0.tgz", "integrity": "sha512-xh1Rl34h6Fi1DC2WWKfxUTVqRsNnr6LsKz2+hfwDxQJWmrx8+c7ylaqBMcHfl1U1r2dsifOvKX3LQuLNZ+XSvA==" }, - "babel-eslint": { - "version": "10.1.0", - "resolved": "https://registry.npmjs.org/babel-eslint/-/babel-eslint-10.1.0.tgz", - "integrity": "sha512-ifWaTHQ0ce+448CYop8AdrQiBsGrnC+bMgfyKFdi6EsPLTAWG+QfyDeM6OH+FmWnKvEq5NnBMLvlBUPKQZoDSg==", - "dev": true, - "requires": { - "@babel/code-frame": "^7.0.0", - "@babel/parser": "^7.7.0", - "@babel/traverse": "^7.7.0", - "@babel/types": "^7.7.0", - "eslint-visitor-keys": "^1.0.0", - "resolve": "^1.12.0" - } - }, "bach": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/bach/-/bach-1.2.0.tgz", @@ -16128,12 +15846,6 @@ } } }, - "globals": { - "version": "11.12.0", - "resolved": "https://registry.npmjs.org/globals/-/globals-11.12.0.tgz", - "integrity": "sha512-WOBp/EEGUiIsJSp7wcv/y6MO+lV9UoncWqxuFfm8eBwzWNgyfBd6Gz+IeKQ9jCmyhoH99g15M3T+QaVHFjizVA==", - "dev": true - }, "glogg": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/glogg/-/glogg-1.0.2.tgz", @@ -17689,12 +17401,6 @@ } } }, - "jsesc": { - "version": "2.5.2", - "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-2.5.2.tgz", - "integrity": "sha512-OYu7XEzjkCQ3C5Ps3QIZsQfNpqoJyZZA99wd9aWd05NCtC5pWOkShK2mkL6HXQR6/Cy2lbNdPlZBpuQHXE63gA==", - "dev": true - }, "json-buffer": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/json-buffer/-/json-buffer-3.0.1.tgz", @@ -21254,12 +20960,6 @@ "is-negated-glob": "^1.0.0" } }, - "to-fast-properties": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/to-fast-properties/-/to-fast-properties-2.0.0.tgz", - "integrity": "sha1-3F5pjL0HkmW8c+A3doGk5Og/YW4=", - "dev": true - }, "to-object-path": { "version": "0.3.0", "resolved": "https://registry.npmjs.org/to-object-path/-/to-object-path-0.3.0.tgz", diff --git a/package.json b/package.json index b9bc028eb..f9f89ec7a 100644 --- a/package.json +++ b/package.json @@ -69,7 +69,6 @@ "@blockly/dev-tools": "^2.6.1", "@blockly/theme-modern": "^2.1.1", "@wdio/selenium-standalone-service": "^7.10.1", - "babel-eslint": "^10.1.0", "chai": "^4.2.0", "clang-format": "^1.6.0", "closure-calculate-chunks": "^3.0.2", diff --git a/tests/mocha/.eslintrc.json b/tests/mocha/.eslintrc.json index dad7c25ca..c42c50c20 100644 --- a/tests/mocha/.eslintrc.json +++ b/tests/mocha/.eslintrc.json @@ -1,5 +1,4 @@ { - "parser": "babel-eslint", "env": { "browser": true, "mocha": true @@ -11,30 +10,8 @@ }, "rules": { "no-unused-vars": ["off"], - "es5/no-arrow-functions": ["off"], - "es5/no-binary-and-octal-literals": ["off"], - "es5/no-block-scoping": ["off"], - "es5/no-classes": ["off"], - "es5/no-computed-properties": ["off"], - "es5/no-default-parameters": ["off"], - "es5/no-destructuring": ["off"], - "es5/no-es6-methods": ["off"], - "es5/no-es6-static-methods": ["off"], - "es5/no-for-of": ["off"], - "es5/no-generators": ["off"], - "es5/no-modules": ["off"], - "es5/no-object-super": ["off"], - "es5/no-rest-parameters": ["off"], - "es5/no-shorthand-properties": ["off"], - "es5/no-spread": ["off"], - "es5/no-template-literals": ["off"], - "es5/no-typeof-symbol": ["off"], - "es5/no-unicode-code-point-escape": ["off"], - "es5/no-unicode-regex": ["off"], // Allow uncommented helper functions in tests. "require-jsdoc": ["off"], - // In mocha tests in suites, `this` is meaningful and useful. - "no-invalid-this": ["off"], "prefer-rest-params": ["off"] }, "extends": "../../.eslintrc.json" From c14a88945eea0dac8cfb88e4ffc0b892cad282fa Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 10 Dec 2021 10:24:05 +0000 Subject: [PATCH 003/128] chore(deps): bump eslint from 7.32.0 to 8.4.1 (#5807) Bumps [eslint](https://github.com/eslint/eslint) from 7.32.0 to 8.4.1. - [Release notes](https://github.com/eslint/eslint/releases) - [Changelog](https://github.com/eslint/eslint/blob/main/CHANGELOG.md) - [Commits](https://github.com/eslint/eslint/compare/v7.32.0...v8.4.1) --- updated-dependencies: - dependency-name: eslint dependency-type: direct:development update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- package-lock.json | 615 ++++++++++++++-------------------------------- package.json | 2 +- 2 files changed, 191 insertions(+), 426 deletions(-) diff --git a/package-lock.json b/package-lock.json index 52ffe448d..21c8b2e41 100644 --- a/package-lock.json +++ b/package-lock.json @@ -20,7 +20,7 @@ "clang-format": "^1.6.0", "closure-calculate-chunks": "^3.0.2", "concurrently": "^6.0.0", - "eslint": "^7.28.0", + "eslint": "^8.4.1", "eslint-config-google": "^0.14.0", "google-closure-compiler": "^20211107.0.0", "google-closure-deps": "^20211107.0.0", @@ -250,50 +250,23 @@ } }, "node_modules/@eslint/eslintrc": { - "version": "0.4.3", - "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-0.4.3.tgz", - "integrity": "sha512-J6KFFz5QCYUJq3pf0mjEcCJVERbzv71PUIDczuh9JkwGEzced6CO5ADLHB1rbf/+oPBtoPfMYNOpGDzCANlbXw==", + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-1.0.5.tgz", + "integrity": "sha512-BLxsnmK3KyPunz5wmCCpqy0YelEoxxGmH73Is+Z74oOTMtExcjkr3dDR6quwrjh1YspA8DH9gnX1o069KiS9AQ==", "dev": true, "dependencies": { "ajv": "^6.12.4", - "debug": "^4.1.1", - "espree": "^7.3.0", + "debug": "^4.3.2", + "espree": "^9.2.0", "globals": "^13.9.0", "ignore": "^4.0.6", "import-fresh": "^3.2.1", - "js-yaml": "^3.13.1", + "js-yaml": "^4.1.0", "minimatch": "^3.0.4", "strip-json-comments": "^3.1.1" }, "engines": { - "node": "^10.12.0 || >=12.0.0" - } - }, - "node_modules/@eslint/eslintrc/node_modules/globals": { - "version": "13.12.0", - "resolved": "https://registry.npmjs.org/globals/-/globals-13.12.0.tgz", - "integrity": "sha512-uS8X6lSKN2JumVoXrbUz+uG4BYG+eiawqm3qFcT7ammfbUHeCBoJMlHcec/S3krSk73/AE/f0szYFmgAA3kYZg==", - "dev": true, - "dependencies": { - "type-fest": "^0.20.2" - }, - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/@eslint/eslintrc/node_modules/type-fest": { - "version": "0.20.2", - "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.20.2.tgz", - "integrity": "sha512-Ne+eE4r0/iWnpAxD852z3A+N0Bt5RN//NjJwRd2VFHEmrywxf5vsZlh4R6lixl6B+wz/8d+maTSAkN1FIkI3LQ==", - "dev": true, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" } }, "node_modules/@gulp-sourcemaps/identity-map": { @@ -379,12 +352,12 @@ } }, "node_modules/@humanwhocodes/config-array": { - "version": "0.5.0", - "resolved": "https://registry.npmjs.org/@humanwhocodes/config-array/-/config-array-0.5.0.tgz", - "integrity": "sha512-FagtKFz74XrTl7y6HCzQpwDfXP0yhxe9lHLD1UZxjvZIcbyRz8zTFF/yYNfSfzU414eDwZ1SrO0Qvtyf+wFMQg==", + "version": "0.9.2", + "resolved": "https://registry.npmjs.org/@humanwhocodes/config-array/-/config-array-0.9.2.tgz", + "integrity": "sha512-UXOuFCGcwciWckOpmfKDq/GyhlTf9pN/BzG//x8p8zTOFEcGuA68ANXheFS0AGvy3qgZqLBUkMs7hqzqCKOVwA==", "dev": true, "dependencies": { - "@humanwhocodes/object-schema": "^1.2.0", + "@humanwhocodes/object-schema": "^1.2.1", "debug": "^4.1.1", "minimatch": "^3.0.4" }, @@ -1059,13 +1032,10 @@ "dev": true }, "node_modules/argparse": { - "version": "1.0.10", - "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz", - "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==", - "dev": true, - "dependencies": { - "sprintf-js": "~1.0.2" - } + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", + "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", + "dev": true }, "node_modules/aria-query": { "version": "5.0.0", @@ -1286,15 +1256,6 @@ "node": ">=0.10.0" } }, - "node_modules/astral-regex": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/astral-regex/-/astral-regex-2.0.0.tgz", - "integrity": "sha512-Z7tMw1ytTXt5jqMcOP+OQteU1VuNK9Y02uuJtKQ1Sv69jXQKKg5cibLwGJow8yzZP+eAc18EmLGPal0bp36rvQ==", - "dev": true, - "engines": { - "node": ">=8" - } - }, "node_modules/async": { "version": "1.5.2", "resolved": "https://registry.npmjs.org/async/-/async-1.5.2.tgz", @@ -3358,37 +3319,36 @@ } }, "node_modules/eslint": { - "version": "7.32.0", - "resolved": "https://registry.npmjs.org/eslint/-/eslint-7.32.0.tgz", - "integrity": "sha512-VHZ8gX+EDfz+97jGcgyGCyRia/dPOd6Xh9yPv8Bl1+SoaIwD+a/vlrOmGRUyOYu7MwUhc7CxqeaDZU13S4+EpA==", + "version": "8.4.1", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-8.4.1.tgz", + "integrity": "sha512-TxU/p7LB1KxQ6+7aztTnO7K0i+h0tDi81YRY9VzB6Id71kNz+fFYnf5HD5UOQmxkzcoa0TlVZf9dpMtUv0GpWg==", "dev": true, "dependencies": { - "@babel/code-frame": "7.12.11", - "@eslint/eslintrc": "^0.4.3", - "@humanwhocodes/config-array": "^0.5.0", + "@eslint/eslintrc": "^1.0.5", + "@humanwhocodes/config-array": "^0.9.2", "ajv": "^6.10.0", "chalk": "^4.0.0", "cross-spawn": "^7.0.2", - "debug": "^4.0.1", + "debug": "^4.3.2", "doctrine": "^3.0.0", "enquirer": "^2.3.5", "escape-string-regexp": "^4.0.0", - "eslint-scope": "^5.1.1", - "eslint-utils": "^2.1.0", - "eslint-visitor-keys": "^2.0.0", - "espree": "^7.3.1", + "eslint-scope": "^7.1.0", + "eslint-utils": "^3.0.0", + "eslint-visitor-keys": "^3.1.0", + "espree": "^9.2.0", "esquery": "^1.4.0", "esutils": "^2.0.2", "fast-deep-equal": "^3.1.3", "file-entry-cache": "^6.0.1", "functional-red-black-tree": "^1.0.1", - "glob-parent": "^5.1.2", + "glob-parent": "^6.0.1", "globals": "^13.6.0", "ignore": "^4.0.6", "import-fresh": "^3.0.0", "imurmurhash": "^0.1.4", "is-glob": "^4.0.0", - "js-yaml": "^3.13.1", + "js-yaml": "^4.1.0", "json-stable-stringify-without-jsonify": "^1.0.1", "levn": "^0.4.1", "lodash.merge": "^4.6.2", @@ -3396,11 +3356,10 @@ "natural-compare": "^1.4.0", "optionator": "^0.9.1", "progress": "^2.0.0", - "regexpp": "^3.1.0", + "regexpp": "^3.2.0", "semver": "^7.2.1", - "strip-ansi": "^6.0.0", + "strip-ansi": "^6.0.1", "strip-json-comments": "^3.1.0", - "table": "^6.0.9", "text-table": "^0.2.0", "v8-compile-cache": "^2.0.3" }, @@ -3408,7 +3367,7 @@ "eslint": "bin/eslint.js" }, "engines": { - "node": "^10.12.0 || >=12.0.0" + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" }, "funding": { "url": "https://opencollective.com/eslint" @@ -3427,52 +3386,46 @@ } }, "node_modules/eslint-scope": { - "version": "5.1.1", - "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-5.1.1.tgz", - "integrity": "sha512-2NxwbF/hZ0KpepYN0cNbo+FN6XoK7GaHlQhgx/hIZl6Va0bF45RQOOwhLIy8lQDbuCiadSLCBnH2CFYquit5bw==", + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-7.1.0.tgz", + "integrity": "sha512-aWwkhnS0qAXqNOgKOK0dJ2nvzEbhEvpy8OlJ9kZ0FeZnA6zpjv1/Vei+puGFFX7zkPCkHHXb7IDX3A+7yPrRWg==", "dev": true, "dependencies": { "esrecurse": "^4.3.0", - "estraverse": "^4.1.1" + "estraverse": "^5.2.0" }, "engines": { - "node": ">=8.0.0" + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + } + }, + "node_modules/eslint-scope/node_modules/estraverse": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", + "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", + "dev": true, + "engines": { + "node": ">=4.0" } }, "node_modules/eslint-utils": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/eslint-utils/-/eslint-utils-2.1.0.tgz", - "integrity": "sha512-w94dQYoauyvlDc43XnGB8lU3Zt713vNChgt4EWwhXAP2XkBvndfxF0AgIqKOOasjPIPzj9JqgwkwbCYD0/V3Zg==", + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/eslint-utils/-/eslint-utils-3.0.0.tgz", + "integrity": "sha512-uuQC43IGctw68pJA1RgbQS8/NP7rch6Cwd4j3ZBtgo4/8Flj4eGE7ZYSZRN3iq5pVUv6GPdW5Z1RFleo84uLDA==", "dev": true, "dependencies": { - "eslint-visitor-keys": "^1.1.0" + "eslint-visitor-keys": "^2.0.0" }, "engines": { - "node": ">=6" + "node": "^10.0.0 || ^12.0.0 || >= 14.0.0" }, "funding": { "url": "https://github.com/sponsors/mysticatea" + }, + "peerDependencies": { + "eslint": ">=5" } }, - "node_modules/eslint-visitor-keys": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-1.3.0.tgz", - "integrity": "sha512-6J72N8UNa462wa/KFODt/PJ3IU60SDpC3QXC1Hjc1BXXpfL2C9R5+AU7jhe0F6GREqVMh4Juu+NY7xn+6dipUQ==", - "dev": true, - "engines": { - "node": ">=4" - } - }, - "node_modules/eslint/node_modules/@babel/code-frame": { - "version": "7.12.11", - "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.12.11.tgz", - "integrity": "sha512-Zt1yodBx1UcyiePMSkWnU4hPqhwq7hGi2nFL1LeA3EUl+q2LQx16MISgJ0+z7dnmgvP9QtIleuETGOiOH1RcIw==", - "dev": true, - "dependencies": { - "@babel/highlight": "^7.10.4" - } - }, - "node_modules/eslint/node_modules/eslint-visitor-keys": { + "node_modules/eslint-utils/node_modules/eslint-visitor-keys": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-2.1.0.tgz", "integrity": "sha512-0rSmRBzXgDzIsD6mGdJgevzgezI534Cer5L/vyMX0kHzT/jiB43jRhd9YUlMGYLQy2zprNmoT8qasCGtY+QaKw==", @@ -3481,57 +3434,39 @@ "node": ">=10" } }, - "node_modules/eslint/node_modules/globals": { - "version": "13.12.0", - "resolved": "https://registry.npmjs.org/globals/-/globals-13.12.0.tgz", - "integrity": "sha512-uS8X6lSKN2JumVoXrbUz+uG4BYG+eiawqm3qFcT7ammfbUHeCBoJMlHcec/S3krSk73/AE/f0szYFmgAA3kYZg==", + "node_modules/eslint-visitor-keys": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.1.0.tgz", + "integrity": "sha512-yWJFpu4DtjsWKkt5GeNBBuZMlNcYVs6vRCLoCVEJrTjaSB6LC98gFipNK/erM2Heg/E8mIK+hXG/pJMLK+eRZA==", "dev": true, - "dependencies": { - "type-fest": "^0.20.2" - }, "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" } }, - "node_modules/eslint/node_modules/type-fest": { - "version": "0.20.2", - "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.20.2.tgz", - "integrity": "sha512-Ne+eE4r0/iWnpAxD852z3A+N0Bt5RN//NjJwRd2VFHEmrywxf5vsZlh4R6lixl6B+wz/8d+maTSAkN1FIkI3LQ==", + "node_modules/eslint/node_modules/glob-parent": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz", + "integrity": "sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==", "dev": true, - "engines": { - "node": ">=10" + "dependencies": { + "is-glob": "^4.0.3" }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" + "engines": { + "node": ">=10.13.0" } }, "node_modules/espree": { - "version": "7.3.1", - "resolved": "https://registry.npmjs.org/espree/-/espree-7.3.1.tgz", - "integrity": "sha512-v3JCNCE64umkFpmkFGqzVKsOT0tN1Zr+ueqLZfpV1Ob8e+CEgPWa+OxCoGH3tnhimMKIaBm4m/vaRpJ/krRz2g==", + "version": "9.2.0", + "resolved": "https://registry.npmjs.org/espree/-/espree-9.2.0.tgz", + "integrity": "sha512-oP3utRkynpZWF/F2x/HZJ+AGtnIclaR7z1pYPxy7NYM2fSO6LgK/Rkny8anRSPK/VwEA1eqm2squui0T7ZMOBg==", "dev": true, "dependencies": { - "acorn": "^7.4.0", + "acorn": "^8.6.0", "acorn-jsx": "^5.3.1", - "eslint-visitor-keys": "^1.3.0" + "eslint-visitor-keys": "^3.1.0" }, "engines": { - "node": "^10.12.0 || >=12.0.0" - } - }, - "node_modules/espree/node_modules/acorn": { - "version": "7.4.1", - "resolved": "https://registry.npmjs.org/acorn/-/acorn-7.4.1.tgz", - "integrity": "sha512-nQyp0o1/mNdbTO1PO6kHkwSrmgZ0MT/jCCpNiwbUjGoRN4dlBhqJtoQuCnEOKzgTVwg0ZWiCoQy6SxMebQVh8A==", - "dev": true, - "bin": { - "acorn": "bin/acorn" - }, - "engines": { - "node": ">=0.4.0" + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" } }, "node_modules/esprima": { @@ -4706,6 +4641,33 @@ "which": "bin/which" } }, + "node_modules/globals": { + "version": "13.12.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-13.12.0.tgz", + "integrity": "sha512-uS8X6lSKN2JumVoXrbUz+uG4BYG+eiawqm3qFcT7ammfbUHeCBoJMlHcec/S3krSk73/AE/f0szYFmgAA3kYZg==", + "dev": true, + "dependencies": { + "type-fest": "^0.20.2" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/globals/node_modules/type-fest": { + "version": "0.20.2", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.20.2.tgz", + "integrity": "sha512-Ne+eE4r0/iWnpAxD852z3A+N0Bt5RN//NjJwRd2VFHEmrywxf5vsZlh4R6lixl6B+wz/8d+maTSAkN1FIkI3LQ==", + "dev": true, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/glogg": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/glogg/-/glogg-1.0.2.tgz", @@ -6569,13 +6531,12 @@ "dev": true }, "node_modules/js-yaml": { - "version": "3.14.1", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.14.1.tgz", - "integrity": "sha512-okMH7OXXJ7YrN9Ok3/SXrnu4iX9yOk+25nqX4imS2npuvTYDmo/QEZoqwZkYaIDk3jVvBOTOIEgEhaLOynBS9g==", + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.0.tgz", + "integrity": "sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA==", "dev": true, "dependencies": { - "argparse": "^1.0.7", - "esprima": "^4.0.0" + "argparse": "^2.0.1" }, "bin": { "js-yaml": "bin/js-yaml.js" @@ -7120,12 +7081,6 @@ "lodash._reinterpolate": "^3.0.0" } }, - "node_modules/lodash.truncate": { - "version": "4.4.2", - "resolved": "https://registry.npmjs.org/lodash.truncate/-/lodash.truncate-4.4.2.tgz", - "integrity": "sha1-WjUNoLERO4N+z//VgSy+WNbq4ZM=", - "dev": true - }, "node_modules/lodash.union": { "version": "4.6.0", "resolved": "https://registry.npmjs.org/lodash.union/-/lodash.union-4.6.0.tgz", @@ -7669,12 +7624,6 @@ "url": "https://opencollective.com/mochajs" } }, - "node_modules/mocha/node_modules/argparse": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", - "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", - "dev": true - }, "node_modules/mocha/node_modules/debug": { "version": "4.3.2", "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.2.tgz", @@ -7727,18 +7676,6 @@ "url": "https://github.com/sponsors/isaacs" } }, - "node_modules/mocha/node_modules/js-yaml": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.0.tgz", - "integrity": "sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA==", - "dev": true, - "dependencies": { - "argparse": "^2.0.1" - }, - "bin": { - "js-yaml": "bin/js-yaml.js" - } - }, "node_modules/mocha/node_modules/ms": { "version": "2.1.3", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", @@ -9705,15 +9642,6 @@ "node": ">=0.10.0" } }, - "node_modules/require-from-string": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", - "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", - "dev": true, - "engines": { - "node": ">=0.10.0" - } - }, "node_modules/require-main-filename": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/require-main-filename/-/require-main-filename-1.0.1.tgz", @@ -10124,23 +10052,6 @@ "node": ">=0.3.1" } }, - "node_modules/slice-ansi": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-4.0.0.tgz", - "integrity": "sha512-qMCMfhY040cVHT43K9BFygqYbUPFZKHOg7K73mtTWJRb8pyP3fzf4Ixd5SzdEJQ6MRUg/WBnOLxghZtKKurENQ==", - "dev": true, - "dependencies": { - "ansi-styles": "^4.0.0", - "astral-regex": "^2.0.0", - "is-fullwidth-code-point": "^3.0.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/chalk/slice-ansi?sponsor=1" - } - }, "node_modules/snapdragon": { "version": "0.8.2", "resolved": "https://registry.npmjs.org/snapdragon/-/snapdragon-0.8.2.tgz", @@ -10457,12 +10368,6 @@ "node": ">=0.10.0" } }, - "node_modules/sprintf-js": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz", - "integrity": "sha1-BOaSb2YolTVPPdAVIDYzuFcpfiw=", - "dev": true - }, "node_modules/sshpk": { "version": "1.16.1", "resolved": "https://registry.npmjs.org/sshpk/-/sshpk-1.16.1.tgz", @@ -10794,44 +10699,6 @@ "resolved": "https://registry.npmjs.org/symbol-tree/-/symbol-tree-3.2.4.tgz", "integrity": "sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==" }, - "node_modules/table": { - "version": "6.7.5", - "resolved": "https://registry.npmjs.org/table/-/table-6.7.5.tgz", - "integrity": "sha512-LFNeryOqiQHqCVKzhkymKwt6ozeRhlm8IL1mE8rNUurkir4heF6PzMyRgaTa4tlyPTGGgXuvVOF/OLWiH09Lqw==", - "dev": true, - "dependencies": { - "ajv": "^8.0.1", - "lodash.truncate": "^4.4.2", - "slice-ansi": "^4.0.0", - "string-width": "^4.2.3", - "strip-ansi": "^6.0.1" - }, - "engines": { - "node": ">=10.0.0" - } - }, - "node_modules/table/node_modules/ajv": { - "version": "8.8.2", - "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.8.2.tgz", - "integrity": "sha512-x9VuX+R/jcFj1DHo/fCp99esgGDWiHENrKxaCENuCxpoMCmAt/COCGVDwA7kleEpEzJjDnvh3yGoOuLu0Dtllw==", - "dev": true, - "dependencies": { - "fast-deep-equal": "^3.1.1", - "json-schema-traverse": "^1.0.0", - "require-from-string": "^2.0.2", - "uri-js": "^4.2.2" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/epoberezkin" - } - }, - "node_modules/table/node_modules/json-schema-traverse": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", - "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", - "dev": true - }, "node_modules/tar-fs": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.1.tgz", @@ -12282,37 +12149,20 @@ "requires": {} }, "@eslint/eslintrc": { - "version": "0.4.3", - "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-0.4.3.tgz", - "integrity": "sha512-J6KFFz5QCYUJq3pf0mjEcCJVERbzv71PUIDczuh9JkwGEzced6CO5ADLHB1rbf/+oPBtoPfMYNOpGDzCANlbXw==", + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-1.0.5.tgz", + "integrity": "sha512-BLxsnmK3KyPunz5wmCCpqy0YelEoxxGmH73Is+Z74oOTMtExcjkr3dDR6quwrjh1YspA8DH9gnX1o069KiS9AQ==", "dev": true, "requires": { "ajv": "^6.12.4", - "debug": "^4.1.1", - "espree": "^7.3.0", + "debug": "^4.3.2", + "espree": "^9.2.0", "globals": "^13.9.0", "ignore": "^4.0.6", "import-fresh": "^3.2.1", - "js-yaml": "^3.13.1", + "js-yaml": "^4.1.0", "minimatch": "^3.0.4", "strip-json-comments": "^3.1.1" - }, - "dependencies": { - "globals": { - "version": "13.12.0", - "resolved": "https://registry.npmjs.org/globals/-/globals-13.12.0.tgz", - "integrity": "sha512-uS8X6lSKN2JumVoXrbUz+uG4BYG+eiawqm3qFcT7ammfbUHeCBoJMlHcec/S3krSk73/AE/f0szYFmgAA3kYZg==", - "dev": true, - "requires": { - "type-fest": "^0.20.2" - } - }, - "type-fest": { - "version": "0.20.2", - "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.20.2.tgz", - "integrity": "sha512-Ne+eE4r0/iWnpAxD852z3A+N0Bt5RN//NjJwRd2VFHEmrywxf5vsZlh4R6lixl6B+wz/8d+maTSAkN1FIkI3LQ==", - "dev": true - } } }, "@gulp-sourcemaps/identity-map": { @@ -12384,12 +12234,12 @@ } }, "@humanwhocodes/config-array": { - "version": "0.5.0", - "resolved": "https://registry.npmjs.org/@humanwhocodes/config-array/-/config-array-0.5.0.tgz", - "integrity": "sha512-FagtKFz74XrTl7y6HCzQpwDfXP0yhxe9lHLD1UZxjvZIcbyRz8zTFF/yYNfSfzU414eDwZ1SrO0Qvtyf+wFMQg==", + "version": "0.9.2", + "resolved": "https://registry.npmjs.org/@humanwhocodes/config-array/-/config-array-0.9.2.tgz", + "integrity": "sha512-UXOuFCGcwciWckOpmfKDq/GyhlTf9pN/BzG//x8p8zTOFEcGuA68ANXheFS0AGvy3qgZqLBUkMs7hqzqCKOVwA==", "dev": true, "requires": { - "@humanwhocodes/object-schema": "^1.2.0", + "@humanwhocodes/object-schema": "^1.2.1", "debug": "^4.1.1", "minimatch": "^3.0.4" } @@ -12957,13 +12807,10 @@ "dev": true }, "argparse": { - "version": "1.0.10", - "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz", - "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==", - "dev": true, - "requires": { - "sprintf-js": "~1.0.2" - } + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", + "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", + "dev": true }, "aria-query": { "version": "5.0.0", @@ -13125,12 +12972,6 @@ "integrity": "sha1-WWZ/QfrdTyDMvCu5a41Pf3jsA2c=", "dev": true }, - "astral-regex": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/astral-regex/-/astral-regex-2.0.0.tgz", - "integrity": "sha512-Z7tMw1ytTXt5jqMcOP+OQteU1VuNK9Y02uuJtKQ1Sv69jXQKKg5cibLwGJow8yzZP+eAc18EmLGPal0bp36rvQ==", - "dev": true - }, "async": { "version": "1.5.2", "resolved": "https://registry.npmjs.org/async/-/async-1.5.2.tgz", @@ -14783,37 +14624,36 @@ } }, "eslint": { - "version": "7.32.0", - "resolved": "https://registry.npmjs.org/eslint/-/eslint-7.32.0.tgz", - "integrity": "sha512-VHZ8gX+EDfz+97jGcgyGCyRia/dPOd6Xh9yPv8Bl1+SoaIwD+a/vlrOmGRUyOYu7MwUhc7CxqeaDZU13S4+EpA==", + "version": "8.4.1", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-8.4.1.tgz", + "integrity": "sha512-TxU/p7LB1KxQ6+7aztTnO7K0i+h0tDi81YRY9VzB6Id71kNz+fFYnf5HD5UOQmxkzcoa0TlVZf9dpMtUv0GpWg==", "dev": true, "requires": { - "@babel/code-frame": "7.12.11", - "@eslint/eslintrc": "^0.4.3", - "@humanwhocodes/config-array": "^0.5.0", + "@eslint/eslintrc": "^1.0.5", + "@humanwhocodes/config-array": "^0.9.2", "ajv": "^6.10.0", "chalk": "^4.0.0", "cross-spawn": "^7.0.2", - "debug": "^4.0.1", + "debug": "^4.3.2", "doctrine": "^3.0.0", "enquirer": "^2.3.5", "escape-string-regexp": "^4.0.0", - "eslint-scope": "^5.1.1", - "eslint-utils": "^2.1.0", - "eslint-visitor-keys": "^2.0.0", - "espree": "^7.3.1", + "eslint-scope": "^7.1.0", + "eslint-utils": "^3.0.0", + "eslint-visitor-keys": "^3.1.0", + "espree": "^9.2.0", "esquery": "^1.4.0", "esutils": "^2.0.2", "fast-deep-equal": "^3.1.3", "file-entry-cache": "^6.0.1", "functional-red-black-tree": "^1.0.1", - "glob-parent": "^5.1.2", + "glob-parent": "^6.0.1", "globals": "^13.6.0", "ignore": "^4.0.6", "import-fresh": "^3.0.0", "imurmurhash": "^0.1.4", "is-glob": "^4.0.0", - "js-yaml": "^3.13.1", + "js-yaml": "^4.1.0", "json-stable-stringify-without-jsonify": "^1.0.1", "levn": "^0.4.1", "lodash.merge": "^4.6.2", @@ -14821,44 +14661,22 @@ "natural-compare": "^1.4.0", "optionator": "^0.9.1", "progress": "^2.0.0", - "regexpp": "^3.1.0", + "regexpp": "^3.2.0", "semver": "^7.2.1", - "strip-ansi": "^6.0.0", + "strip-ansi": "^6.0.1", "strip-json-comments": "^3.1.0", - "table": "^6.0.9", "text-table": "^0.2.0", "v8-compile-cache": "^2.0.3" }, "dependencies": { - "@babel/code-frame": { - "version": "7.12.11", - "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.12.11.tgz", - "integrity": "sha512-Zt1yodBx1UcyiePMSkWnU4hPqhwq7hGi2nFL1LeA3EUl+q2LQx16MISgJ0+z7dnmgvP9QtIleuETGOiOH1RcIw==", + "glob-parent": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz", + "integrity": "sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==", "dev": true, "requires": { - "@babel/highlight": "^7.10.4" + "is-glob": "^4.0.3" } - }, - "eslint-visitor-keys": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-2.1.0.tgz", - "integrity": "sha512-0rSmRBzXgDzIsD6mGdJgevzgezI534Cer5L/vyMX0kHzT/jiB43jRhd9YUlMGYLQy2zprNmoT8qasCGtY+QaKw==", - "dev": true - }, - "globals": { - "version": "13.12.0", - "resolved": "https://registry.npmjs.org/globals/-/globals-13.12.0.tgz", - "integrity": "sha512-uS8X6lSKN2JumVoXrbUz+uG4BYG+eiawqm3qFcT7ammfbUHeCBoJMlHcec/S3krSk73/AE/f0szYFmgAA3kYZg==", - "dev": true, - "requires": { - "type-fest": "^0.20.2" - } - }, - "type-fest": { - "version": "0.20.2", - "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.20.2.tgz", - "integrity": "sha512-Ne+eE4r0/iWnpAxD852z3A+N0Bt5RN//NjJwRd2VFHEmrywxf5vsZlh4R6lixl6B+wz/8d+maTSAkN1FIkI3LQ==", - "dev": true } } }, @@ -14870,47 +14688,55 @@ "requires": {} }, "eslint-scope": { - "version": "5.1.1", - "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-5.1.1.tgz", - "integrity": "sha512-2NxwbF/hZ0KpepYN0cNbo+FN6XoK7GaHlQhgx/hIZl6Va0bF45RQOOwhLIy8lQDbuCiadSLCBnH2CFYquit5bw==", + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-7.1.0.tgz", + "integrity": "sha512-aWwkhnS0qAXqNOgKOK0dJ2nvzEbhEvpy8OlJ9kZ0FeZnA6zpjv1/Vei+puGFFX7zkPCkHHXb7IDX3A+7yPrRWg==", "dev": true, "requires": { "esrecurse": "^4.3.0", - "estraverse": "^4.1.1" + "estraverse": "^5.2.0" + }, + "dependencies": { + "estraverse": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", + "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", + "dev": true + } } }, "eslint-utils": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/eslint-utils/-/eslint-utils-2.1.0.tgz", - "integrity": "sha512-w94dQYoauyvlDc43XnGB8lU3Zt713vNChgt4EWwhXAP2XkBvndfxF0AgIqKOOasjPIPzj9JqgwkwbCYD0/V3Zg==", + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/eslint-utils/-/eslint-utils-3.0.0.tgz", + "integrity": "sha512-uuQC43IGctw68pJA1RgbQS8/NP7rch6Cwd4j3ZBtgo4/8Flj4eGE7ZYSZRN3iq5pVUv6GPdW5Z1RFleo84uLDA==", "dev": true, "requires": { - "eslint-visitor-keys": "^1.1.0" + "eslint-visitor-keys": "^2.0.0" + }, + "dependencies": { + "eslint-visitor-keys": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-2.1.0.tgz", + "integrity": "sha512-0rSmRBzXgDzIsD6mGdJgevzgezI534Cer5L/vyMX0kHzT/jiB43jRhd9YUlMGYLQy2zprNmoT8qasCGtY+QaKw==", + "dev": true + } } }, "eslint-visitor-keys": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-1.3.0.tgz", - "integrity": "sha512-6J72N8UNa462wa/KFODt/PJ3IU60SDpC3QXC1Hjc1BXXpfL2C9R5+AU7jhe0F6GREqVMh4Juu+NY7xn+6dipUQ==", + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.1.0.tgz", + "integrity": "sha512-yWJFpu4DtjsWKkt5GeNBBuZMlNcYVs6vRCLoCVEJrTjaSB6LC98gFipNK/erM2Heg/E8mIK+hXG/pJMLK+eRZA==", "dev": true }, "espree": { - "version": "7.3.1", - "resolved": "https://registry.npmjs.org/espree/-/espree-7.3.1.tgz", - "integrity": "sha512-v3JCNCE64umkFpmkFGqzVKsOT0tN1Zr+ueqLZfpV1Ob8e+CEgPWa+OxCoGH3tnhimMKIaBm4m/vaRpJ/krRz2g==", + "version": "9.2.0", + "resolved": "https://registry.npmjs.org/espree/-/espree-9.2.0.tgz", + "integrity": "sha512-oP3utRkynpZWF/F2x/HZJ+AGtnIclaR7z1pYPxy7NYM2fSO6LgK/Rkny8anRSPK/VwEA1eqm2squui0T7ZMOBg==", "dev": true, "requires": { - "acorn": "^7.4.0", + "acorn": "^8.6.0", "acorn-jsx": "^5.3.1", - "eslint-visitor-keys": "^1.3.0" - }, - "dependencies": { - "acorn": { - "version": "7.4.1", - "resolved": "https://registry.npmjs.org/acorn/-/acorn-7.4.1.tgz", - "integrity": "sha512-nQyp0o1/mNdbTO1PO6kHkwSrmgZ0MT/jCCpNiwbUjGoRN4dlBhqJtoQuCnEOKzgTVwg0ZWiCoQy6SxMebQVh8A==", - "dev": true - } + "eslint-visitor-keys": "^3.1.0" } }, "esprima": { @@ -15846,6 +15672,23 @@ } } }, + "globals": { + "version": "13.12.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-13.12.0.tgz", + "integrity": "sha512-uS8X6lSKN2JumVoXrbUz+uG4BYG+eiawqm3qFcT7ammfbUHeCBoJMlHcec/S3krSk73/AE/f0szYFmgAA3kYZg==", + "dev": true, + "requires": { + "type-fest": "^0.20.2" + }, + "dependencies": { + "type-fest": { + "version": "0.20.2", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.20.2.tgz", + "integrity": "sha512-Ne+eE4r0/iWnpAxD852z3A+N0Bt5RN//NjJwRd2VFHEmrywxf5vsZlh4R6lixl6B+wz/8d+maTSAkN1FIkI3LQ==", + "dev": true + } + } + }, "glogg": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/glogg/-/glogg-1.0.2.tgz", @@ -17331,13 +17174,12 @@ "dev": true }, "js-yaml": { - "version": "3.14.1", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.14.1.tgz", - "integrity": "sha512-okMH7OXXJ7YrN9Ok3/SXrnu4iX9yOk+25nqX4imS2npuvTYDmo/QEZoqwZkYaIDk3jVvBOTOIEgEhaLOynBS9g==", + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.0.tgz", + "integrity": "sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA==", "dev": true, "requires": { - "argparse": "^1.0.7", - "esprima": "^4.0.0" + "argparse": "^2.0.1" } }, "jsbn": { @@ -17823,12 +17665,6 @@ "lodash._reinterpolate": "^3.0.0" } }, - "lodash.truncate": { - "version": "4.4.2", - "resolved": "https://registry.npmjs.org/lodash.truncate/-/lodash.truncate-4.4.2.tgz", - "integrity": "sha1-WjUNoLERO4N+z//VgSy+WNbq4ZM=", - "dev": true - }, "lodash.union": { "version": "4.6.0", "resolved": "https://registry.npmjs.org/lodash.union/-/lodash.union-4.6.0.tgz", @@ -18253,12 +18089,6 @@ "yargs-unparser": "2.0.0" }, "dependencies": { - "argparse": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", - "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", - "dev": true - }, "debug": { "version": "4.3.2", "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.2.tgz", @@ -18296,15 +18126,6 @@ "path-is-absolute": "^1.0.0" } }, - "js-yaml": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.0.tgz", - "integrity": "sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA==", - "dev": true, - "requires": { - "argparse": "^2.0.1" - } - }, "ms": { "version": "2.1.3", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", @@ -19852,12 +19673,6 @@ "integrity": "sha1-jGStX9MNqxyXbiNE/+f3kqam30I=", "dev": true }, - "require-from-string": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", - "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", - "dev": true - }, "require-main-filename": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/require-main-filename/-/require-main-filename-1.0.1.tgz", @@ -20194,17 +20009,6 @@ } } }, - "slice-ansi": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-4.0.0.tgz", - "integrity": "sha512-qMCMfhY040cVHT43K9BFygqYbUPFZKHOg7K73mtTWJRb8pyP3fzf4Ixd5SzdEJQ6MRUg/WBnOLxghZtKKurENQ==", - "dev": true, - "requires": { - "ansi-styles": "^4.0.0", - "astral-regex": "^2.0.0", - "is-fullwidth-code-point": "^3.0.0" - } - }, "snapdragon": { "version": "0.8.2", "resolved": "https://registry.npmjs.org/snapdragon/-/snapdragon-0.8.2.tgz", @@ -20480,12 +20284,6 @@ "extend-shallow": "^3.0.0" } }, - "sprintf-js": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz", - "integrity": "sha1-BOaSb2YolTVPPdAVIDYzuFcpfiw=", - "dev": true - }, "sshpk": { "version": "1.16.1", "resolved": "https://registry.npmjs.org/sshpk/-/sshpk-1.16.1.tgz", @@ -20761,39 +20559,6 @@ "resolved": "https://registry.npmjs.org/symbol-tree/-/symbol-tree-3.2.4.tgz", "integrity": "sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==" }, - "table": { - "version": "6.7.5", - "resolved": "https://registry.npmjs.org/table/-/table-6.7.5.tgz", - "integrity": "sha512-LFNeryOqiQHqCVKzhkymKwt6ozeRhlm8IL1mE8rNUurkir4heF6PzMyRgaTa4tlyPTGGgXuvVOF/OLWiH09Lqw==", - "dev": true, - "requires": { - "ajv": "^8.0.1", - "lodash.truncate": "^4.4.2", - "slice-ansi": "^4.0.0", - "string-width": "^4.2.3", - "strip-ansi": "^6.0.1" - }, - "dependencies": { - "ajv": { - "version": "8.8.2", - "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.8.2.tgz", - "integrity": "sha512-x9VuX+R/jcFj1DHo/fCp99esgGDWiHENrKxaCENuCxpoMCmAt/COCGVDwA7kleEpEzJjDnvh3yGoOuLu0Dtllw==", - "dev": true, - "requires": { - "fast-deep-equal": "^3.1.1", - "json-schema-traverse": "^1.0.0", - "require-from-string": "^2.0.2", - "uri-js": "^4.2.2" - } - }, - "json-schema-traverse": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", - "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", - "dev": true - } - } - }, "tar-fs": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.1.tgz", diff --git a/package.json b/package.json index f9f89ec7a..61a4139d5 100644 --- a/package.json +++ b/package.json @@ -73,7 +73,7 @@ "clang-format": "^1.6.0", "closure-calculate-chunks": "^3.0.2", "concurrently": "^6.0.0", - "eslint": "^7.28.0", + "eslint": "^8.4.1", "eslint-config-google": "^0.14.0", "google-closure-compiler": "^20211107.0.0", "google-closure-deps": "^20211107.0.0", From 0a96543a1179636e4efeb3c654c075952aca0c9f Mon Sep 17 00:00:00 2001 From: Maribeth Bottorff Date: Mon, 13 Dec 2021 14:56:05 -0800 Subject: [PATCH 005/128] fix: fix keycodes type (#5805) --- core/shortcut_registry.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/shortcut_registry.js b/core/shortcut_registry.js index 58de799d0..4fcec3f7c 100644 --- a/core/shortcut_registry.js +++ b/core/shortcut_registry.js @@ -51,7 +51,7 @@ const ShortcutRegistry = function() { /** * Enum of valid modifiers. - * @enum {!KeyCodes} + * @enum {!KeyCodes} */ ShortcutRegistry.modifierKeys = { 'Shift': KeyCodes.SHIFT, From 025bab656669f99ebdb8b95bea39ebae296f1495 Mon Sep 17 00:00:00 2001 From: Maribeth Bottorff Date: Mon, 13 Dec 2021 14:56:22 -0800 Subject: [PATCH 006/128] fix: Use correct namespace for svgMath functions (#5813) --- core/utils.js | 12 ++++++------ core/utils/svg_math.js | 12 ++++++------ 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/core/utils.js b/core/utils.js index aa2f61d32..7b014733c 100644 --- a/core/utils.js +++ b/core/utils.js @@ -110,7 +110,7 @@ exports.isTargetInput = isTargetInput; const getRelativeXY = function(element) { deprecation.warn( 'Blockly.utils.getRelativeXY', 'December 2021', 'December 2022', - 'Blockly.svgMath.getRelativeXY'); + 'Blockly.utils.svgMath.getRelativeXY'); return svgMath.getRelativeXY(element); }; exports.getRelativeXY = getRelativeXY; @@ -128,7 +128,7 @@ exports.getRelativeXY = getRelativeXY; const getInjectionDivXY = function(element) { deprecation.warn( 'Blockly.utils.getInjectionDivXY_', 'December 2021', 'December 2022', - 'Blockly.svgMath.getInjectionDivXY'); + 'Blockly.utils.svgMath.getInjectionDivXY'); return svgMath.getInjectionDivXY(element); }; exports.getInjectionDivXY_ = getInjectionDivXY; @@ -261,7 +261,7 @@ exports.genUid = genUid; const is3dSupported = function() { deprecation.warn( 'Blockly.utils.is3dSupported', 'December 2021', 'December 2022', - 'Blockly.svgMath.is3dSupported'); + 'Blockly.utils.svgMath.is3dSupported'); return svgMath.is3dSupported(); }; exports.is3dSupported = is3dSupported; @@ -278,7 +278,7 @@ exports.is3dSupported = is3dSupported; const getViewportBBox = function() { deprecation.warn( 'Blockly.utils.getViewportBBox', 'December 2021', 'December 2022', - 'Blockly.svgMath.getViewportBBox'); + 'Blockly.utils.svgMath.getViewportBBox'); return svgMath.getViewportBBox(); }; exports.getViewportBBox = getViewportBBox; @@ -309,7 +309,7 @@ exports.arrayRemove = arrayRemove; const getDocumentScroll = function() { deprecation.warn( 'Blockly.utils.getDocumentScroll', 'December 2021', 'December 2022', - 'Blockly.svgMath.getDocumentScroll'); + 'Blockly.utils.svgMath.getDocumentScroll'); return svgMath.getDocumentScroll(); }; exports.getDocumentScroll = getDocumentScroll; @@ -344,7 +344,7 @@ exports.getBlockTypeCounts = getBlockTypeCounts; const screenToWsCoordinates = function(ws, screenCoordinates) { deprecation.warn( 'Blockly.utils.screenToWsCoordinates', 'December 2021', 'December 2022', - 'Blockly.svgMath.screenToWsCoordinates'); + 'Blockly.utils.svgMath.screenToWsCoordinates'); return svgMath.screenToWsCoordinates(ws, screenCoordinates); }; exports.screenToWsCoordinates = screenToWsCoordinates; diff --git a/core/utils/svg_math.js b/core/utils/svg_math.js index be90641da..60751a490 100644 --- a/core/utils/svg_math.js +++ b/core/utils/svg_math.js @@ -51,7 +51,7 @@ const XY_STYLE_REGEX = * its parent. Only for SVG elements and children (e.g. rect, g, path). * @param {!Element} element SVG element to find the coordinates of. * @return {!Coordinate} Object with .x and .y properties. - * @alias Blockly.svgMath.getRelativeXY + * @alias Blockly.utils.svgMath.getRelativeXY */ const getRelativeXY = function(element) { const xy = new Coordinate(0, 0); @@ -96,7 +96,7 @@ exports.getRelativeXY = getRelativeXY; * not a child of the div Blockly was injected into, the behaviour is * undefined. * @return {!Coordinate} Object with .x and .y properties. - * @alias Blockly.svgMath.getInjectionDivXY + * @alias Blockly.utils.svgMath.getInjectionDivXY */ const getInjectionDivXY = function(element) { let x = 0; @@ -119,7 +119,7 @@ exports.getInjectionDivXY = getInjectionDivXY; * Check if 3D transforms are supported by adding an element * and attempting to set the property. * @return {boolean} True if 3D transforms are supported. - * @alias Blockly.svgMath.is3dSupported + * @alias Blockly.utils.svgMath.is3dSupported */ const is3dSupported = function() { if (is3dSupported.cached_ !== undefined) { @@ -172,7 +172,7 @@ exports.is3dSupported = is3dSupported; * scroll into account. * @return {!Rect} An object containing window width, height, and * scroll position in window coordinates. - * @alias Blockly.svgMath.getViewportBBox + * @alias Blockly.utils.svgMath.getViewportBBox * @package */ const getViewportBBox = function() { @@ -188,7 +188,7 @@ exports.getViewportBBox = getViewportBBox; * Gets the document scroll distance as a coordinate object. * Copied from Closure's goog.dom.getDocumentScroll. * @return {!Coordinate} Object with values 'x' and 'y'. - * @alias Blockly.svgMath.getDocumentScroll + * @alias Blockly.utils.svgMath.getDocumentScroll */ const getDocumentScroll = function() { const el = document.documentElement; @@ -210,7 +210,7 @@ exports.getDocumentScroll = getDocumentScroll; * @param {!Coordinate} screenCoordinates The screen coordinates to * be converted to workspace coordinates * @return {!Coordinate} The workspace coordinates. - * @alias Blockly.svgMath.screenToWsCoordinates + * @alias Blockly.utils.svgMath.screenToWsCoordinates */ const screenToWsCoordinates = function(ws, screenCoordinates) { const screenX = screenCoordinates.x; From 6fc3316309534270106050f0e1fecb7a09b8e62c Mon Sep 17 00:00:00 2001 From: Rachel Fenichel Date: Tue, 14 Dec 2021 11:51:03 -0800 Subject: [PATCH 007/128] fix: re-expose HSV_VALUE and HSV_SATURATION as settable properties on Blockly (#5821) --- core/blockly.js | 32 ++++++++++++++++-- core/internal_constants.js | 16 --------- core/utils/colour.js | 68 ++++++++++++++++++++++++++++++++++---- core/utils/parsing.js | 4 +-- 4 files changed, 92 insertions(+), 28 deletions(-) diff --git a/core/blockly.js b/core/blockly.js index dd12f0f1b..b916abd6e 100644 --- a/core/blockly.js +++ b/core/blockly.js @@ -444,6 +444,36 @@ Object.defineProperties(exports, { common.setSelected(newSelection); }, }, + /** + * The richness of block colours, regardless of the hue. + * Must be in the range of 0 (inclusive) to 1 (exclusive). + * @name Blockly.HSV_SATURATION + * @type {number} + * @suppress {checkTypes} + */ + HSV_SATURATION: { + get: function() { + return utils.colour.getHsvSaturation(); + }, + set: function(newValue) { + utils.colour.setHsvSaturation(newValue); + }, + }, + /** + * The intensity of block colours, regardless of the hue. + * Must be in the range of 0 (inclusive) to 1 (exclusive). + * @name Blockly.HSV_VALUE + * @type {number} + * @suppress {checkTypes} + */ + HSV_VALUE: { + get: function() { + return utils.colour.getHsvValue(); + }, + set: function(newValue) { + utils.colour.setHsvValue(newValue); + }, + }, }); /** @@ -639,8 +669,6 @@ exports.COLLAPSE_CHARS = internalConstants.COLLAPSE_CHARS; exports.LONGPRESS = internalConstants.LONGPRESS; exports.SOUND_LIMIT = internalConstants.SOUND_LIMIT; exports.DRAG_STACK = internalConstants.DRAG_STACK; -exports.HSV_SATURATION = internalConstants.HSV_SATURATION; -exports.HSV_VALUE = internalConstants.HSV_VALUE; exports.SPRITE = internalConstants.SPRITE; exports.DRAG_NONE = internalConstants.DRAG_NONE; exports.DRAG_STICKY = internalConstants.DRAG_STICKY; diff --git a/core/internal_constants.js b/core/internal_constants.js index f043fa8b4..d5952eb05 100644 --- a/core/internal_constants.js +++ b/core/internal_constants.js @@ -121,22 +121,6 @@ exports.SOUND_LIMIT = SOUND_LIMIT; const DRAG_STACK = true; exports.DRAG_STACK = DRAG_STACK; -/** - * The richness of block colours, regardless of the hue. - * Must be in the range of 0 (inclusive) to 1 (exclusive). - * @alias Blockly.internalConstants.HSV_SATURATION - */ -const HSV_SATURATION = 0.45; -exports.HSV_SATURATION = HSV_SATURATION; - -/** - * The intensity of block colours, regardless of the hue. - * Must be in the range of 0 (inclusive) to 1 (exclusive). - * @alias Blockly.internalConstants.HSV_VALUE - */ -const HSV_VALUE = 0.65; -exports.HSV_VALUE = HSV_VALUE; - /** * Sprited icons and images. * @alias Blockly.internalConstants.SPRITE diff --git a/core/utils/colour.js b/core/utils/colour.js index 662473233..18cbf3b61 100644 --- a/core/utils/colour.js +++ b/core/utils/colour.js @@ -6,21 +6,76 @@ /** * @fileoverview Utility methods for colour manipulation. - * These methods are not specific to Blockly, and could be factored out into - * a JavaScript framework such as Closure. */ 'use strict'; /** * Utility methods for colour manipulation. - * These methods are not specific to Blockly, and could be factored out into - * a JavaScript framework such as Closure. * @namespace Blockly.utils.colour */ goog.module('Blockly.utils.colour'); -const internalConstants = goog.require('Blockly.internalConstants'); +/** + * The richness of block colours, regardless of the hue. + * Must be in the range of 0 (inclusive) to 1 (exclusive). + * @alias Blockly.utils.colour.hsvSaturation + * @package + */ +let hsvSaturation = 0.45; +/** + * Get the richness of block colours, regardless of the hue. + * @alias Blockly.utils.colour.getHsvSaturation + * @return {number} The current richness. + * @package + */ +const getHsvSaturation = function() { + return hsvSaturation; +}; +exports.getHsvSaturation = getHsvSaturation; + +/** + * Set the richness of block colours, regardless of the hue. + * @param {number} newSaturation The new richness, in the range of 0 + * (inclusive) to 1 (exclusive) + * @alias Blockly.utils.colour.setHsvSaturation + * @package + */ +const setHsvSaturation = function(newSaturation) { + hsvSaturation = newSaturation; +}; +exports.setHsvSaturation = setHsvSaturation; + +/** + * The intensity of block colours, regardless of the hue. + * Must be in the range of 0 (inclusive) to 1 (exclusive). + * @alias Blockly.utils.colour.hsvValue + * @package + */ +let hsvValue = 0.65; + +/** + * Get the intensity of block colours, regardless of the hue. + * @alias Blockly.utils.colour.getHsvValue + * @return {number} The current intensity. + * @package + */ +const getHsvValue = function() { + return hsvValue; +}; +exports.getHsvValue = getHsvValue; + +/** + * Set the intensity of block colours, regardless of the hue. + * @param {number} newValue The new intensity, in the range of 0 + * (inclusive) to 1 (exclusive) + * @alias Blockly.utils.colour.setHsvValue + * @package + */ +const setHsvValue = function(newValue) { + hsvValue = newValue; +}; +exports.setHsvValue = setHsvValue; /** * Parses a colour from a string. @@ -228,7 +283,6 @@ exports.names = names; * @alias Blockly.utils.colour.hueToHex */ const hueToHex = function(hue) { - return hsvToHex( - hue, internalConstants.HSV_SATURATION, internalConstants.HSV_VALUE * 255); + return hsvToHex(hue, hsvSaturation, hsvValue * 255); }; exports.hueToHex = hueToHex; diff --git a/core/utils/parsing.js b/core/utils/parsing.js index 9df2bc777..b8eb9bedf 100644 --- a/core/utils/parsing.js +++ b/core/utils/parsing.js @@ -15,7 +15,6 @@ goog.module('Blockly.utils.parsing'); const colourUtils = goog.require('Blockly.utils.colour'); -const internalConstants = goog.require('Blockly.internalConstants'); const stringUtils = goog.require('Blockly.utils.string'); const {Msg} = goog.require('Blockly.Msg'); @@ -243,8 +242,7 @@ const parseBlockColour = function(colour) { return { hue: hue, hex: colourUtils.hsvToHex( - hue, internalConstants.HSV_SATURATION, - internalConstants.HSV_VALUE * 255), + hue, colourUtils.getHsvSaturation(), colourUtils.getHsvValue() * 255), }; } else { const hex = colourUtils.parse(dereferenced); From da07cbdcbf46ef38afdd605eb23372fad92d5c7f Mon Sep 17 00:00:00 2001 From: alschmiedt Date: Wed, 15 Dec 2021 11:41:13 -0800 Subject: [PATCH 008/128] chore: update the dev-tools version (#5823) --- package-lock.json | 114 +++++++++++++++++++++++++++------------------- package.json | 2 +- 2 files changed, 68 insertions(+), 48 deletions(-) diff --git a/package-lock.json b/package-lock.json index 21c8b2e41..f3faa8f05 100644 --- a/package-lock.json +++ b/package-lock.json @@ -5,7 +5,6 @@ "requires": true, "packages": { "": { - "name": "blockly", "version": "7.20211209.0", "license": "Apache-2.0", "dependencies": { @@ -13,7 +12,7 @@ }, "devDependencies": { "@blockly/block-test": "^1.0.0", - "@blockly/dev-tools": "^2.6.1", + "@blockly/dev-tools": "^3.0.1", "@blockly/theme-modern": "^2.1.1", "@wdio/selenium-standalone-service": "^7.10.1", "chai": "^4.2.0", @@ -165,16 +164,16 @@ } }, "node_modules/@blockly/dev-tools": { - "version": "2.6.1", - "resolved": "https://registry.npmjs.org/@blockly/dev-tools/-/dev-tools-2.6.1.tgz", - "integrity": "sha512-mv7u3x/Z2qA2PCSPomz0S4ofQn+m/UHC/AoNu1FZuwNAwuE5SCy7HCTDracpKWqoK8iuXwi4PWUdu669CDbp5A==", + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/@blockly/dev-tools/-/dev-tools-3.0.1.tgz", + "integrity": "sha512-afFCokPWHKeFrZRSoHa0oBBUWIwqI02/svYPRTjviEsxGcU89nG/bYBpfG9Fosm8hEKROvZf7/bIMn0x1KlCBA==", "dev": true, "dependencies": { - "@blockly/block-test": "^1.1.5", - "@blockly/theme-dark": "^2.0.6", - "@blockly/theme-deuteranopia": "^1.0.7", - "@blockly/theme-highcontrast": "^1.0.7", - "@blockly/theme-tritanopia": "^1.0.7", + "@blockly/block-test": "^2.0.1", + "@blockly/theme-dark": "^2.0.7", + "@blockly/theme-deuteranopia": "^1.0.8", + "@blockly/theme-highcontrast": "^1.0.8", + "@blockly/theme-tritanopia": "^1.0.8", "chai": "^4.2.0", "dat.gui": "^0.7.7", "lodash.assign": "^4.2.0", @@ -186,43 +185,55 @@ "node": ">=8.0.0" }, "peerDependencies": { - "blockly": "4.20201217.0 - 6" + "blockly": "^7.20211209.0" + } + }, + "node_modules/@blockly/dev-tools/node_modules/@blockly/block-test": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@blockly/block-test/-/block-test-2.0.1.tgz", + "integrity": "sha512-d8E109UEWTtFv1bfy5paQNk9HYdZDWH5S7qkCrlKTtSatPDt8f3SGCr/lu8JC086/LhjRafgX1RTa0uwJIDDdg==", + "dev": true, + "engines": { + "node": ">=8.17.0" + }, + "peerDependencies": { + "blockly": "^7.20211209.0" } }, "node_modules/@blockly/theme-dark": { - "version": "2.0.6", - "resolved": "https://registry.npmjs.org/@blockly/theme-dark/-/theme-dark-2.0.6.tgz", - "integrity": "sha512-2gPz3Iw+VjBFaNhoYXm/zRA2Xhe/nDnpOyPxbav7sGs4XcO4F0yPruuXxBm7oGGbGudmxmJXhTdmV+4d8MpvSg==", + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/@blockly/theme-dark/-/theme-dark-2.0.7.tgz", + "integrity": "sha512-sErL00Uaa0yBviBWpNT0tobaty5BYb+xbE3LwSsot7P/4u/j+pD+oKS8fqt8xsWxbtn67zL8PARmaP3KVe4+Aw==", "dev": true, "engines": { "node": ">=8.17.0" }, "peerDependencies": { - "blockly": "3.20200123.0 - 6" + "blockly": "3.20200123.0 - 7" } }, "node_modules/@blockly/theme-deuteranopia": { - "version": "1.0.7", - "resolved": "https://registry.npmjs.org/@blockly/theme-deuteranopia/-/theme-deuteranopia-1.0.7.tgz", - "integrity": "sha512-m2Jo6lCYnVn3eLzmBoSBN31t2qQ8fAjEJmcUBcpJ56TGB1gks1vGVJHg/yhcK+vUB85IFuUUUJ6+MOjhEZFOvQ==", + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/@blockly/theme-deuteranopia/-/theme-deuteranopia-1.0.8.tgz", + "integrity": "sha512-/9aDJCUuyDJ4OSHr2lCJRpqBLSvgV8YP7uCeCKuoY3uMnMKTxEcJ/AUma+oF98os+i3/GeNzCMYQ/6bdlCXRIQ==", "dev": true, "engines": { "node": ">=8.17.0" }, "peerDependencies": { - "blockly": "3.20200123.0 - 6" + "blockly": "3.20200123.0 - 7" } }, "node_modules/@blockly/theme-highcontrast": { - "version": "1.0.7", - "resolved": "https://registry.npmjs.org/@blockly/theme-highcontrast/-/theme-highcontrast-1.0.7.tgz", - "integrity": "sha512-FI/LyP/gGCatpeKvKTLSyColgyHETKSFo5RrgbZ+GTgVAQxXAj7MQ4DZDtlWECOKaT6WGQLNk5OserBXMCtDbQ==", + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/@blockly/theme-highcontrast/-/theme-highcontrast-1.0.8.tgz", + "integrity": "sha512-A9bvQpmNtsn3W3pWa0NRttBm1IeIhV6zGAp4ziY+GU0kNGZDgbrP10JJKfz3dv+RCaXmslE9kS25RU/LYJjB/Q==", "dev": true, "engines": { "node": ">=8.17.0" }, "peerDependencies": { - "blockly": "3.20200123.0 - 6" + "blockly": "3.20200123.0 - 7" } }, "node_modules/@blockly/theme-modern": { @@ -238,15 +249,15 @@ } }, "node_modules/@blockly/theme-tritanopia": { - "version": "1.0.7", - "resolved": "https://registry.npmjs.org/@blockly/theme-tritanopia/-/theme-tritanopia-1.0.7.tgz", - "integrity": "sha512-Y6d8ZR3y9iz1GdihHbSYGTIwWEanWtp0tYPtsVx3QlcKMuc+NyAtGQVE324ZTA+N1ayH4L31CGRAAo7AAm3gPA==", + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/@blockly/theme-tritanopia/-/theme-tritanopia-1.0.8.tgz", + "integrity": "sha512-61G8VB5a8F9eRMYAXpeRia/DrRRfAnUqpA62pksvtcRwMoztwhToUHHkSYuOHxpDpKG/rTlaFtf/GUHFFaFHEQ==", "dev": true, "engines": { "node": ">=8.17.0" }, "peerDependencies": { - "blockly": "3.20200123.0 - 6" + "blockly": "3.20200123.0 - 7" } }, "node_modules/@eslint/eslintrc": { @@ -12095,42 +12106,51 @@ "requires": {} }, "@blockly/dev-tools": { - "version": "2.6.1", - "resolved": "https://registry.npmjs.org/@blockly/dev-tools/-/dev-tools-2.6.1.tgz", - "integrity": "sha512-mv7u3x/Z2qA2PCSPomz0S4ofQn+m/UHC/AoNu1FZuwNAwuE5SCy7HCTDracpKWqoK8iuXwi4PWUdu669CDbp5A==", + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/@blockly/dev-tools/-/dev-tools-3.0.1.tgz", + "integrity": "sha512-afFCokPWHKeFrZRSoHa0oBBUWIwqI02/svYPRTjviEsxGcU89nG/bYBpfG9Fosm8hEKROvZf7/bIMn0x1KlCBA==", "dev": true, "requires": { - "@blockly/block-test": "^1.1.5", - "@blockly/theme-dark": "^2.0.6", - "@blockly/theme-deuteranopia": "^1.0.7", - "@blockly/theme-highcontrast": "^1.0.7", - "@blockly/theme-tritanopia": "^1.0.7", + "@blockly/block-test": "^2.0.1", + "@blockly/theme-dark": "^2.0.7", + "@blockly/theme-deuteranopia": "^1.0.8", + "@blockly/theme-highcontrast": "^1.0.8", + "@blockly/theme-tritanopia": "^1.0.8", "chai": "^4.2.0", "dat.gui": "^0.7.7", "lodash.assign": "^4.2.0", "lodash.merge": "^4.6.2", "monaco-editor": "^0.20.0", "sinon": "^9.0.2" + }, + "dependencies": { + "@blockly/block-test": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@blockly/block-test/-/block-test-2.0.1.tgz", + "integrity": "sha512-d8E109UEWTtFv1bfy5paQNk9HYdZDWH5S7qkCrlKTtSatPDt8f3SGCr/lu8JC086/LhjRafgX1RTa0uwJIDDdg==", + "dev": true, + "requires": {} + } } }, "@blockly/theme-dark": { - "version": "2.0.6", - "resolved": "https://registry.npmjs.org/@blockly/theme-dark/-/theme-dark-2.0.6.tgz", - "integrity": "sha512-2gPz3Iw+VjBFaNhoYXm/zRA2Xhe/nDnpOyPxbav7sGs4XcO4F0yPruuXxBm7oGGbGudmxmJXhTdmV+4d8MpvSg==", + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/@blockly/theme-dark/-/theme-dark-2.0.7.tgz", + "integrity": "sha512-sErL00Uaa0yBviBWpNT0tobaty5BYb+xbE3LwSsot7P/4u/j+pD+oKS8fqt8xsWxbtn67zL8PARmaP3KVe4+Aw==", "dev": true, "requires": {} }, "@blockly/theme-deuteranopia": { - "version": "1.0.7", - "resolved": "https://registry.npmjs.org/@blockly/theme-deuteranopia/-/theme-deuteranopia-1.0.7.tgz", - "integrity": "sha512-m2Jo6lCYnVn3eLzmBoSBN31t2qQ8fAjEJmcUBcpJ56TGB1gks1vGVJHg/yhcK+vUB85IFuUUUJ6+MOjhEZFOvQ==", + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/@blockly/theme-deuteranopia/-/theme-deuteranopia-1.0.8.tgz", + "integrity": "sha512-/9aDJCUuyDJ4OSHr2lCJRpqBLSvgV8YP7uCeCKuoY3uMnMKTxEcJ/AUma+oF98os+i3/GeNzCMYQ/6bdlCXRIQ==", "dev": true, "requires": {} }, "@blockly/theme-highcontrast": { - "version": "1.0.7", - "resolved": "https://registry.npmjs.org/@blockly/theme-highcontrast/-/theme-highcontrast-1.0.7.tgz", - "integrity": "sha512-FI/LyP/gGCatpeKvKTLSyColgyHETKSFo5RrgbZ+GTgVAQxXAj7MQ4DZDtlWECOKaT6WGQLNk5OserBXMCtDbQ==", + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/@blockly/theme-highcontrast/-/theme-highcontrast-1.0.8.tgz", + "integrity": "sha512-A9bvQpmNtsn3W3pWa0NRttBm1IeIhV6zGAp4ziY+GU0kNGZDgbrP10JJKfz3dv+RCaXmslE9kS25RU/LYJjB/Q==", "dev": true, "requires": {} }, @@ -12142,9 +12162,9 @@ "requires": {} }, "@blockly/theme-tritanopia": { - "version": "1.0.7", - "resolved": "https://registry.npmjs.org/@blockly/theme-tritanopia/-/theme-tritanopia-1.0.7.tgz", - "integrity": "sha512-Y6d8ZR3y9iz1GdihHbSYGTIwWEanWtp0tYPtsVx3QlcKMuc+NyAtGQVE324ZTA+N1ayH4L31CGRAAo7AAm3gPA==", + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/@blockly/theme-tritanopia/-/theme-tritanopia-1.0.8.tgz", + "integrity": "sha512-61G8VB5a8F9eRMYAXpeRia/DrRRfAnUqpA62pksvtcRwMoztwhToUHHkSYuOHxpDpKG/rTlaFtf/GUHFFaFHEQ==", "dev": true, "requires": {} }, diff --git a/package.json b/package.json index 61a4139d5..35eb6573a 100644 --- a/package.json +++ b/package.json @@ -66,7 +66,7 @@ "license": "Apache-2.0", "devDependencies": { "@blockly/block-test": "^1.0.0", - "@blockly/dev-tools": "^2.6.1", + "@blockly/dev-tools": "^3.0.1", "@blockly/theme-modern": "^2.1.1", "@wdio/selenium-standalone-service": "^7.10.1", "chai": "^4.2.0", From 68d81132b851d20884ee9da41719fa62cdfce0ee Mon Sep 17 00:00:00 2001 From: Mark Friedman Date: Wed, 15 Dec 2021 15:46:17 -0800 Subject: [PATCH 009/128] fix: change getCandidate_ and showInsertionMarker_ to be more dynamic (#5722) * Change getCandidate_ and showInsertionMarker_ to be more dynamic * Ran clang formatter * Fix typos * Fix issue with dragging stacks * From PR comment --- core/insertion_marker_manager.js | 27 +++++++++++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-) diff --git a/core/insertion_marker_manager.js b/core/insertion_marker_manager.js index df86ecc8c..b2592d491 100644 --- a/core/insertion_marker_manager.js +++ b/core/insertion_marker_manager.js @@ -431,6 +431,16 @@ InsertionMarkerManager.prototype.getCandidate_ = function(dxy) { let candidateClosest = null; let candidateLocal = null; + // It's possible that a block has added or removed connections during a drag, + // (e.g. in a drag/move event handler), so let's update the available + // connections. Note that this will be called on every move while dragging, so + // it might cause slowness, especially if the block stack is large. If so, + // maybe it could be made more efficient. Also note that we won't update the + // connections if we've already connected the insertion marker to a block. + if (!this.markerConnection_ || !this.markerConnection_.isConnected()) { + this.updateAvailableConnections(); + } + for (let i = 0; i < this.availableConnections_.length; i++) { const myConnection = this.availableConnections_[i]; const neighbour = myConnection.closest(radius, dxy); @@ -617,8 +627,21 @@ InsertionMarkerManager.prototype.showInsertionMarker_ = function() { const closest = this.closestConnection_; const isLastInStack = this.lastOnStack_ && local === this.lastOnStack_; - const imBlock = isLastInStack ? this.lastMarker_ : this.firstMarker_; - const imConn = imBlock.getMatchingConnection(local.getSourceBlock(), local); + let imBlock = isLastInStack ? this.lastMarker_ : this.firstMarker_; + let imConn; + try { + imConn = imBlock.getMatchingConnection(local.getSourceBlock(), local); + } catch (e) { + // It's possible that the number of connections on the local block has + // changed since the insertion marker was originally created. Let's + // recreate the insertion marker and try again. In theory we could probably + // recreate the marker block (e.g. in getCandidate_), which is called more + // often during the drag, but creating a block that often might be too slow, + // so we only do it if necessary. + this.firstMarker_ = this.createMarkerBlock_(this.topBlock_); + imBlock = isLastInStack ? this.lastMarker_ : this.firstMarker_; + imConn = imBlock.getMatchingConnection(local.getSourceBlock(), local); + } if (imConn === this.markerConnection_) { throw Error( From e8ea2e9902fb9f642459e7341c3d59e19f359fca Mon Sep 17 00:00:00 2001 From: ChrisJaunes Date: Wed, 22 Dec 2021 00:49:35 +0800 Subject: [PATCH 010/128] fix: Fixed the label closure on demo/blockfactory (#5833) * fix: Fixed the label closure on demo/blockfactory * fix: remove on demo/blockfactory --- demos/blockfactory/index.html | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/demos/blockfactory/index.html b/demos/blockfactory/index.html index ef154942c..adecaeebc 100644 --- a/demos/blockfactory/index.html +++ b/demos/blockfactory/index.html @@ -143,9 +143,9 @@ @@ -153,9 +153,9 @@ From 7af05012ff04cdb4a290eacb813ba215efb9f845 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 21 Dec 2021 13:20:50 -0800 Subject: [PATCH 011/128] chore(deps): bump typescript from 4.5.2 to 4.5.4 (#5825) Bumps [typescript](https://github.com/Microsoft/TypeScript) from 4.5.2 to 4.5.4. - [Release notes](https://github.com/Microsoft/TypeScript/releases) - [Commits](https://github.com/Microsoft/TypeScript/compare/v4.5.2...v4.5.4) --- updated-dependencies: - dependency-name: typescript dependency-type: direct:development update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- package-lock.json | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/package-lock.json b/package-lock.json index f3faa8f05..0dee55dd2 100644 --- a/package-lock.json +++ b/package-lock.json @@ -11100,9 +11100,9 @@ "dev": true }, "node_modules/typescript": { - "version": "4.5.2", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-4.5.2.tgz", - "integrity": "sha512-5BlMof9H1yGt0P8/WF+wPNw6GfctgGjXp5hkblpyT+8rkASSmkUKMXrxR0Xg8ThVCi/JnHQiKXeBaEwCeQwMFw==", + "version": "4.5.4", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-4.5.4.tgz", + "integrity": "sha512-VgYs2A2QIRuGphtzFV7aQJduJ2gyfTljngLzjpfW9FoYZF6xuw1W0vW9ghCKLfcWrCFxK81CSGRAvS1pn4fIUg==", "dev": true, "bin": { "tsc": "bin/tsc", @@ -20905,9 +20905,9 @@ "dev": true }, "typescript": { - "version": "4.5.2", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-4.5.2.tgz", - "integrity": "sha512-5BlMof9H1yGt0P8/WF+wPNw6GfctgGjXp5hkblpyT+8rkASSmkUKMXrxR0Xg8ThVCi/JnHQiKXeBaEwCeQwMFw==", + "version": "4.5.4", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-4.5.4.tgz", + "integrity": "sha512-VgYs2A2QIRuGphtzFV7aQJduJ2gyfTljngLzjpfW9FoYZF6xuw1W0vW9ghCKLfcWrCFxK81CSGRAvS1pn4fIUg==", "dev": true }, "ua-parser-js": { From bf4e640b28ad99f2ea907a82d0fcbec461e50fca Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 21 Dec 2021 13:39:24 -0800 Subject: [PATCH 012/128] chore(deps): bump google-closure-compiler (#5810) Bumps [google-closure-compiler](https://github.com/google/closure-compiler-npm) from 20211107.0.0 to 20211201.0.0. - [Release notes](https://github.com/google/closure-compiler-npm/releases) - [Commits](https://github.com/google/closure-compiler-npm/compare/v20211107.0.0...v20211201.0.0) --- updated-dependencies: - dependency-name: google-closure-compiler dependency-type: direct:development update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- package-lock.json | 78 +++++++++++++++++++++++------------------------ package.json | 2 +- 2 files changed, 40 insertions(+), 40 deletions(-) diff --git a/package-lock.json b/package-lock.json index 0dee55dd2..9db4f38ce 100644 --- a/package-lock.json +++ b/package-lock.json @@ -21,7 +21,7 @@ "concurrently": "^6.0.0", "eslint": "^8.4.1", "eslint-config-google": "^0.14.0", - "google-closure-compiler": "^20211107.0.0", + "google-closure-compiler": "^20211201.0.0", "google-closure-deps": "^20211107.0.0", "gulp": "^4.0.2", "gulp-clang-format": "^1.0.27", @@ -4692,13 +4692,13 @@ } }, "node_modules/google-closure-compiler": { - "version": "20211107.0.0", - "resolved": "https://registry.npmjs.org/google-closure-compiler/-/google-closure-compiler-20211107.0.0.tgz", - "integrity": "sha512-CVP18mjlTz+T8D0J2/vNGAkCRd9cZb06kRb0Fp/VXntFvcYdNWNs780vkiplNGtuxyI6Kn3NQPlZZutFuME4ww==", + "version": "20211201.0.0", + "resolved": "https://registry.npmjs.org/google-closure-compiler/-/google-closure-compiler-20211201.0.0.tgz", + "integrity": "sha512-QPNp6uHR94EKbi17XCsdISHAqIgk1Ep7LpB+rmPDY7VoNAX4784WT/0bz6HyVK4QYRVLlNAy2X+1+VlFhS0FzQ==", "dev": true, "dependencies": { "chalk": "2.x", - "google-closure-compiler-java": "^20211107.0.0", + "google-closure-compiler-java": "^20211201.0.0", "minimist": "1.x", "vinyl": "2.x", "vinyl-sourcemaps-apply": "^0.2.0" @@ -4710,21 +4710,21 @@ "node": ">=10" }, "optionalDependencies": { - "google-closure-compiler-linux": "^20211107.0.0", - "google-closure-compiler-osx": "^20211107.0.0", - "google-closure-compiler-windows": "^20211107.0.0" + "google-closure-compiler-linux": "^20211201.0.0", + "google-closure-compiler-osx": "^20211201.0.0", + "google-closure-compiler-windows": "^20211201.0.0" } }, "node_modules/google-closure-compiler-java": { - "version": "20211107.0.0", - "resolved": "https://registry.npmjs.org/google-closure-compiler-java/-/google-closure-compiler-java-20211107.0.0.tgz", - "integrity": "sha512-WavJ1Rx+Fv98rNKClQD6b+GMCVqws7GkbI7sdxiIbrzeNiXwa5K8TKBaqyUx/G1myQ6+gml6GULgJi7nsBOXVQ==", + "version": "20211201.0.0", + "resolved": "https://registry.npmjs.org/google-closure-compiler-java/-/google-closure-compiler-java-20211201.0.0.tgz", + "integrity": "sha512-TQop4dF0k/mb9sPu0aZsvW8OVfuZG4+t4ITZeA/u43deiAA4AFScZQQUMUmoVmXzR8Jz0eeucKoZPTwKAwcSmQ==", "dev": true }, "node_modules/google-closure-compiler-linux": { - "version": "20211107.0.0", - "resolved": "https://registry.npmjs.org/google-closure-compiler-linux/-/google-closure-compiler-linux-20211107.0.0.tgz", - "integrity": "sha512-ULk90c4IiuTcHZ892eFusN/WYfY+gvopy38msrmUnYrmLjq5Ssef7NtDRUhYe9SIX7Dd5NM2jo7u7XjEu/4NCQ==", + "version": "20211201.0.0", + "resolved": "https://registry.npmjs.org/google-closure-compiler-linux/-/google-closure-compiler-linux-20211201.0.0.tgz", + "integrity": "sha512-7nMgBFZYYQTvDLcO+LqqwtibgZJu8qaFJbK84T12xneY1Yy1fUSn56NXaZ9cgdS7p30Hqy6tYcw9ZSuxK7fuEA==", "cpu": [ "x64", "x86" @@ -4736,9 +4736,9 @@ ] }, "node_modules/google-closure-compiler-osx": { - "version": "20211107.0.0", - "resolved": "https://registry.npmjs.org/google-closure-compiler-osx/-/google-closure-compiler-osx-20211107.0.0.tgz", - "integrity": "sha512-nTDR6oAQ6GHT1UakZc4OdyZh2AqwKce7aZQS+XLWojh98SEq7JS5dyEkFBK6a1lqWyOMLH2Mrr3XhNobY/umbA==", + "version": "20211201.0.0", + "resolved": "https://registry.npmjs.org/google-closure-compiler-osx/-/google-closure-compiler-osx-20211201.0.0.tgz", + "integrity": "sha512-eJKmvYm5C82BAcfK64/7nR3RbR4bwIXO2Dmhmb5AR6FXxD/J1svaG3BMINlS+U/GT7NeV4Z7bKb2TcPIAfGO9A==", "cpu": [ "x64", "x86", @@ -4751,9 +4751,9 @@ ] }, "node_modules/google-closure-compiler-windows": { - "version": "20211107.0.0", - "resolved": "https://registry.npmjs.org/google-closure-compiler-windows/-/google-closure-compiler-windows-20211107.0.0.tgz", - "integrity": "sha512-0G7Dd/ZoSPS6pSsOdA6N4LJU0zJddHcS+PiNixQVN50kuHH3DjfI+gCyLx7CkJUZEuGiGHDVkc0ZmKBR5iq4QA==", + "version": "20211201.0.0", + "resolved": "https://registry.npmjs.org/google-closure-compiler-windows/-/google-closure-compiler-windows-20211201.0.0.tgz", + "integrity": "sha512-OPZYA0+tJSjutt1EYrECmXChNsY5USoMbQkBEmwI29riVvNnK5Ot+/SE66/NPHwm3qI/p3O7TnOTKhVpXKed5Q==", "cpu": [ "x64" ], @@ -15719,16 +15719,16 @@ } }, "google-closure-compiler": { - "version": "20211107.0.0", - "resolved": "https://registry.npmjs.org/google-closure-compiler/-/google-closure-compiler-20211107.0.0.tgz", - "integrity": "sha512-CVP18mjlTz+T8D0J2/vNGAkCRd9cZb06kRb0Fp/VXntFvcYdNWNs780vkiplNGtuxyI6Kn3NQPlZZutFuME4ww==", + "version": "20211201.0.0", + "resolved": "https://registry.npmjs.org/google-closure-compiler/-/google-closure-compiler-20211201.0.0.tgz", + "integrity": "sha512-QPNp6uHR94EKbi17XCsdISHAqIgk1Ep7LpB+rmPDY7VoNAX4784WT/0bz6HyVK4QYRVLlNAy2X+1+VlFhS0FzQ==", "dev": true, "requires": { "chalk": "2.x", - "google-closure-compiler-java": "^20211107.0.0", - "google-closure-compiler-linux": "^20211107.0.0", - "google-closure-compiler-osx": "^20211107.0.0", - "google-closure-compiler-windows": "^20211107.0.0", + "google-closure-compiler-java": "^20211201.0.0", + "google-closure-compiler-linux": "^20211201.0.0", + "google-closure-compiler-osx": "^20211201.0.0", + "google-closure-compiler-windows": "^20211201.0.0", "minimist": "1.x", "vinyl": "2.x", "vinyl-sourcemaps-apply": "^0.2.0" @@ -15793,29 +15793,29 @@ } }, "google-closure-compiler-java": { - "version": "20211107.0.0", - "resolved": "https://registry.npmjs.org/google-closure-compiler-java/-/google-closure-compiler-java-20211107.0.0.tgz", - "integrity": "sha512-WavJ1Rx+Fv98rNKClQD6b+GMCVqws7GkbI7sdxiIbrzeNiXwa5K8TKBaqyUx/G1myQ6+gml6GULgJi7nsBOXVQ==", + "version": "20211201.0.0", + "resolved": "https://registry.npmjs.org/google-closure-compiler-java/-/google-closure-compiler-java-20211201.0.0.tgz", + "integrity": "sha512-TQop4dF0k/mb9sPu0aZsvW8OVfuZG4+t4ITZeA/u43deiAA4AFScZQQUMUmoVmXzR8Jz0eeucKoZPTwKAwcSmQ==", "dev": true }, "google-closure-compiler-linux": { - "version": "20211107.0.0", - "resolved": "https://registry.npmjs.org/google-closure-compiler-linux/-/google-closure-compiler-linux-20211107.0.0.tgz", - "integrity": "sha512-ULk90c4IiuTcHZ892eFusN/WYfY+gvopy38msrmUnYrmLjq5Ssef7NtDRUhYe9SIX7Dd5NM2jo7u7XjEu/4NCQ==", + "version": "20211201.0.0", + "resolved": "https://registry.npmjs.org/google-closure-compiler-linux/-/google-closure-compiler-linux-20211201.0.0.tgz", + "integrity": "sha512-7nMgBFZYYQTvDLcO+LqqwtibgZJu8qaFJbK84T12xneY1Yy1fUSn56NXaZ9cgdS7p30Hqy6tYcw9ZSuxK7fuEA==", "dev": true, "optional": true }, "google-closure-compiler-osx": { - "version": "20211107.0.0", - "resolved": "https://registry.npmjs.org/google-closure-compiler-osx/-/google-closure-compiler-osx-20211107.0.0.tgz", - "integrity": "sha512-nTDR6oAQ6GHT1UakZc4OdyZh2AqwKce7aZQS+XLWojh98SEq7JS5dyEkFBK6a1lqWyOMLH2Mrr3XhNobY/umbA==", + "version": "20211201.0.0", + "resolved": "https://registry.npmjs.org/google-closure-compiler-osx/-/google-closure-compiler-osx-20211201.0.0.tgz", + "integrity": "sha512-eJKmvYm5C82BAcfK64/7nR3RbR4bwIXO2Dmhmb5AR6FXxD/J1svaG3BMINlS+U/GT7NeV4Z7bKb2TcPIAfGO9A==", "dev": true, "optional": true }, "google-closure-compiler-windows": { - "version": "20211107.0.0", - "resolved": "https://registry.npmjs.org/google-closure-compiler-windows/-/google-closure-compiler-windows-20211107.0.0.tgz", - "integrity": "sha512-0G7Dd/ZoSPS6pSsOdA6N4LJU0zJddHcS+PiNixQVN50kuHH3DjfI+gCyLx7CkJUZEuGiGHDVkc0ZmKBR5iq4QA==", + "version": "20211201.0.0", + "resolved": "https://registry.npmjs.org/google-closure-compiler-windows/-/google-closure-compiler-windows-20211201.0.0.tgz", + "integrity": "sha512-OPZYA0+tJSjutt1EYrECmXChNsY5USoMbQkBEmwI29riVvNnK5Ot+/SE66/NPHwm3qI/p3O7TnOTKhVpXKed5Q==", "dev": true, "optional": true }, diff --git a/package.json b/package.json index 35eb6573a..2ce0d3cb8 100644 --- a/package.json +++ b/package.json @@ -75,7 +75,7 @@ "concurrently": "^6.0.0", "eslint": "^8.4.1", "eslint-config-google": "^0.14.0", - "google-closure-compiler": "^20211107.0.0", + "google-closure-compiler": "^20211201.0.0", "google-closure-deps": "^20211107.0.0", "gulp": "^4.0.2", "gulp-clang-format": "^1.0.27", From b58dc05d1c74be10d0b6fd6991a597187d03fdc5 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 21 Dec 2021 13:40:22 -0800 Subject: [PATCH 013/128] chore(deps): bump @blockly/block-test from 1.1.5 to 2.0.1 (#5836) Bumps [@blockly/block-test](https://github.com/google/blockly-samples/tree/HEAD/plugins/block-test) from 1.1.5 to 2.0.1. - [Release notes](https://github.com/google/blockly-samples/releases) - [Commits](https://github.com/google/blockly-samples/commits/@blockly/block-test@2.0.1/plugins/block-test) --- updated-dependencies: - dependency-name: "@blockly/block-test" dependency-type: direct:development update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- package-lock.json | 37 ++++++++----------------------------- package.json | 2 +- 2 files changed, 9 insertions(+), 30 deletions(-) diff --git a/package-lock.json b/package-lock.json index 9db4f38ce..61f4b77f7 100644 --- a/package-lock.json +++ b/package-lock.json @@ -11,7 +11,7 @@ "jsdom": "15.2.1" }, "devDependencies": { - "@blockly/block-test": "^1.0.0", + "@blockly/block-test": "^2.0.1", "@blockly/dev-tools": "^3.0.1", "@blockly/theme-modern": "^2.1.1", "@wdio/selenium-standalone-service": "^7.10.1", @@ -152,15 +152,15 @@ } }, "node_modules/@blockly/block-test": { - "version": "1.1.5", - "resolved": "https://registry.npmjs.org/@blockly/block-test/-/block-test-1.1.5.tgz", - "integrity": "sha512-lSDPuwOIEn8DLOzOLu/xNX6U4E4ps+9o5epxJ1JXxBjHqIBw7ghihHfsvuZ1c+rSsBnKGgwBzh5odq6ynIV2GQ==", + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@blockly/block-test/-/block-test-2.0.1.tgz", + "integrity": "sha512-d8E109UEWTtFv1bfy5paQNk9HYdZDWH5S7qkCrlKTtSatPDt8f3SGCr/lu8JC086/LhjRafgX1RTa0uwJIDDdg==", "dev": true, "engines": { "node": ">=8.17.0" }, "peerDependencies": { - "blockly": "2 - 6" + "blockly": "^7.20211209.0" } }, "node_modules/@blockly/dev-tools": { @@ -188,18 +188,6 @@ "blockly": "^7.20211209.0" } }, - "node_modules/@blockly/dev-tools/node_modules/@blockly/block-test": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/@blockly/block-test/-/block-test-2.0.1.tgz", - "integrity": "sha512-d8E109UEWTtFv1bfy5paQNk9HYdZDWH5S7qkCrlKTtSatPDt8f3SGCr/lu8JC086/LhjRafgX1RTa0uwJIDDdg==", - "dev": true, - "engines": { - "node": ">=8.17.0" - }, - "peerDependencies": { - "blockly": "^7.20211209.0" - } - }, "node_modules/@blockly/theme-dark": { "version": "2.0.7", "resolved": "https://registry.npmjs.org/@blockly/theme-dark/-/theme-dark-2.0.7.tgz", @@ -12099,9 +12087,9 @@ } }, "@blockly/block-test": { - "version": "1.1.5", - "resolved": "https://registry.npmjs.org/@blockly/block-test/-/block-test-1.1.5.tgz", - "integrity": "sha512-lSDPuwOIEn8DLOzOLu/xNX6U4E4ps+9o5epxJ1JXxBjHqIBw7ghihHfsvuZ1c+rSsBnKGgwBzh5odq6ynIV2GQ==", + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@blockly/block-test/-/block-test-2.0.1.tgz", + "integrity": "sha512-d8E109UEWTtFv1bfy5paQNk9HYdZDWH5S7qkCrlKTtSatPDt8f3SGCr/lu8JC086/LhjRafgX1RTa0uwJIDDdg==", "dev": true, "requires": {} }, @@ -12122,15 +12110,6 @@ "lodash.merge": "^4.6.2", "monaco-editor": "^0.20.0", "sinon": "^9.0.2" - }, - "dependencies": { - "@blockly/block-test": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/@blockly/block-test/-/block-test-2.0.1.tgz", - "integrity": "sha512-d8E109UEWTtFv1bfy5paQNk9HYdZDWH5S7qkCrlKTtSatPDt8f3SGCr/lu8JC086/LhjRafgX1RTa0uwJIDDdg==", - "dev": true, - "requires": {} - } } }, "@blockly/theme-dark": { diff --git a/package.json b/package.json index 2ce0d3cb8..86d463d13 100644 --- a/package.json +++ b/package.json @@ -65,7 +65,7 @@ }, "license": "Apache-2.0", "devDependencies": { - "@blockly/block-test": "^1.0.0", + "@blockly/block-test": "^2.0.1", "@blockly/dev-tools": "^3.0.1", "@blockly/theme-modern": "^2.1.1", "@wdio/selenium-standalone-service": "^7.10.1", From b5abb3e6443fedd0c78472b49f8941475fb9da57 Mon Sep 17 00:00:00 2001 From: Rachel Fenichel Date: Tue, 4 Jan 2022 15:00:14 -0800 Subject: [PATCH 014/128] chore(release): add release-please config (#5848) --- .github/workflows/release-please.yml | 15 +++++++++++++++ .release-please-manifest.json | 3 +++ CHANGELOG.md | 0 release-please-config.json | 7 +++++++ 4 files changed, 25 insertions(+) create mode 100644 .github/workflows/release-please.yml create mode 100644 .release-please-manifest.json create mode 100644 CHANGELOG.md create mode 100644 release-please-config.json diff --git a/.github/workflows/release-please.yml b/.github/workflows/release-please.yml new file mode 100644 index 000000000..6fc36aff0 --- /dev/null +++ b/.github/workflows/release-please.yml @@ -0,0 +1,15 @@ +on: + push: + branches: + - develop +name: release-please +jobs: + release-please: + runs-on: ubuntu-latest + steps: + - uses: GoogleCloudPlatform/release-please-action@v3.0.0 + with: + token: ${{ secrets.GITHUB_TOKEN }} + release-type: node + package-name: blockly + command: manifest diff --git a/.release-please-manifest.json b/.release-please-manifest.json new file mode 100644 index 000000000..f3df3ba67 --- /dev/null +++ b/.release-please-manifest.json @@ -0,0 +1,3 @@ +{ + "package.json": "7.20211209.0" +} diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 000000000..e69de29bb diff --git a/release-please-config.json b/release-please-config.json new file mode 100644 index 000000000..518b7a8ea --- /dev/null +++ b/release-please-config.json @@ -0,0 +1,7 @@ +{ + "bootstrap-sha": "428574d499b99c7d89189abe9d2f9a4dd3d4c79a", + "packages": { + ".": {} + }, + "draft": true +} From 835fb02343df0a4b9dab7704a4b3d8be8e9a497c Mon Sep 17 00:00:00 2001 From: alschmiedt Date: Tue, 4 Jan 2022 15:06:41 -0800 Subject: [PATCH 015/128] fix: setting null for a font style on a theme (#5831) --- core/renderers/common/constants.js | 23 +++++++++++------------ 1 file changed, 11 insertions(+), 12 deletions(-) diff --git a/core/renderers/common/constants.js b/core/renderers/common/constants.js index 81401c6c6..295ccf368 100644 --- a/core/renderers/common/constants.js +++ b/core/renderers/common/constants.js @@ -622,18 +622,17 @@ ConstantProvider.prototype.setDynamicProperties_ = function(theme) { * @protected */ ConstantProvider.prototype.setFontConstants_ = function(theme) { - this.FIELD_TEXT_FONTFAMILY = - theme.fontStyle && theme.fontStyle['family'] !== undefined ? - theme.fontStyle['family'] : - this.FIELD_TEXT_FONTFAMILY; - this.FIELD_TEXT_FONTWEIGHT = - theme.fontStyle && theme.fontStyle['weight'] !== undefined ? - theme.fontStyle['weight'] : - this.FIELD_TEXT_FONTWEIGHT; - this.FIELD_TEXT_FONTSIZE = - theme.fontStyle && theme.fontStyle['size'] !== undefined ? - theme.fontStyle['size'] : - this.FIELD_TEXT_FONTSIZE; + if (theme.fontStyle && theme.fontStyle['family']) { + this.FIELD_TEXT_FONTFAMILY = theme.fontStyle['family']; + } + + if (theme.fontStyle && theme.fontStyle['weight']) { + this.FIELD_TEXT_FONTWEIGHT = theme.fontStyle['weight']; + } + + if (theme.fontStyle && theme.fontStyle['size']) { + this.FIELD_TEXT_FONTSIZE = theme.fontStyle['size']; + } const fontMetrics = dom.measureFontMetrics( 'Hg', this.FIELD_TEXT_FONTSIZE + 'pt', this.FIELD_TEXT_FONTWEIGHT, From 8a71f879504503f4aec1140fe653d93602c664df Mon Sep 17 00:00:00 2001 From: Beka Westberg Date: Tue, 4 Jan 2022 18:07:41 -0500 Subject: [PATCH 016/128] fix: procedure param edits breaking undo (#5845) --- core/mutator.js | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/core/mutator.js b/core/mutator.js index 5e4e9ace6..f8c95326c 100644 --- a/core/mutator.js +++ b/core/mutator.js @@ -419,7 +419,10 @@ Mutator.prototype.updateWorkspace_ = function() { // When the mutator's workspace changes, update the source block. if (this.rootBlock_.workspace === this.workspace_) { - eventUtils.setGroup(true); + const existingGroup = eventUtils.getGroup(); + if (!existingGroup) { + eventUtils.setGroup(true); + } const block = /** @type {!BlockSvg} */ (this.block_); const oldExtraState = BlockChange.getExtraBlockState_(block); @@ -444,11 +447,12 @@ Mutator.prototype.updateWorkspace_ = function() { eventUtils.fire(new (eventUtils.get(eventUtils.BLOCK_CHANGE))( block, 'mutation', null, oldExtraState, newExtraState)); // Ensure that any bump is part of this mutation's event group. - const group = eventUtils.getGroup(); + const mutationGroup = eventUtils.getGroup(); setTimeout(function() { - eventUtils.setGroup(group); + const oldGroup = eventUtils.getGroup(); + eventUtils.setGroup(mutationGroup); block.bumpNeighbours(); - eventUtils.setGroup(false); + eventUtils.setGroup(oldGroup); }, internalConstants.BUMP_DELAY); } @@ -457,7 +461,7 @@ Mutator.prototype.updateWorkspace_ = function() { if (!this.workspace_.isDragging()) { this.resizeBubble_(); } - eventUtils.setGroup(false); + eventUtils.setGroup(existingGroup); } }; From 5204569cff58c1ead7c15165a1351fa6a2ba2ad3 Mon Sep 17 00:00:00 2001 From: Beka Westberg Date: Thu, 6 Jan 2022 13:08:43 -0500 Subject: [PATCH 017/128] fix: bumping a block after duplicate breaking undo (#5844) * fix: bumping a block after duplicate breaking undo * fix: fixup dependencies --- core/clipboard.js | 3 --- core/workspace_svg.js | 7 +++++++ tests/deps.js | 6 +++--- 3 files changed, 10 insertions(+), 6 deletions(-) diff --git a/core/clipboard.js b/core/clipboard.js index ee7ef2a54..fc0377b7b 100644 --- a/core/clipboard.js +++ b/core/clipboard.js @@ -15,7 +15,6 @@ */ goog.module('Blockly.clipboard'); -const eventUtils = goog.require('Blockly.Events.utils'); /* eslint-disable-next-line no-unused-vars */ const {ICopyable} = goog.requireType('Blockly.ICopyable'); @@ -55,9 +54,7 @@ const paste = function() { } if (copyData.typeCounts && workspace.isCapacityAvailable(copyData.typeCounts)) { - eventUtils.setGroup(true); workspace.paste(copyData.saveInfo); - eventUtils.setGroup(false); return true; } return false; diff --git a/core/workspace_svg.js b/core/workspace_svg.js index 80e84f51c..28b3c8eca 100644 --- a/core/workspace_svg.js +++ b/core/workspace_svg.js @@ -1524,6 +1524,11 @@ WorkspaceSvg.prototype.paste = function(state) { this.currentGesture_.cancel(); // Dragging while pasting? No. } + const existingGroup = eventUtils.getGroup(); + if (!existingGroup) { + eventUtils.setGroup(true); + } + // Checks if this is JSON. JSON has a type property, while elements don't. if (state['type']) { this.pasteBlock_(null, /** @type {!blocks.State} */ (state)); @@ -1535,6 +1540,8 @@ WorkspaceSvg.prototype.paste = function(state) { this.pasteBlock_(xmlBlock, null); } } + + eventUtils.setGroup(existingGroup); }; /** diff --git a/tests/deps.js b/tests/deps.js index 2e9528e75..55bfc76b6 100644 --- a/tests/deps.js +++ b/tests/deps.js @@ -20,7 +20,7 @@ goog.addDependency('../../core/browser_events.js', ['Blockly.browserEvents'], [' goog.addDependency('../../core/bubble.js', ['Blockly.Bubble'], ['Blockly.IBubble', 'Blockly.Scrollbar', 'Blockly.Touch', 'Blockly.Workspace', 'Blockly.browserEvents', 'Blockly.utils.Coordinate', 'Blockly.utils.Size', 'Blockly.utils.Svg', 'Blockly.utils.dom', 'Blockly.utils.math', 'Blockly.utils.userAgent'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/bubble_dragger.js', ['Blockly.BubbleDragger'], ['Blockly.Bubble', 'Blockly.ComponentManager', 'Blockly.Events.CommentMove', 'Blockly.Events.utils', 'Blockly.constants', 'Blockly.utils.Coordinate', 'Blockly.utils.svgMath'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/bump_objects.js', ['Blockly.bumpObjects'], ['Blockly.Events.utils', 'Blockly.utils.math'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/clipboard.js', ['Blockly.clipboard'], ['Blockly.Events.utils'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/clipboard.js', ['Blockly.clipboard'], [], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/comment.js', ['Blockly.Comment'], ['Blockly.Bubble', 'Blockly.Css', 'Blockly.Events.BlockChange', 'Blockly.Events.BubbleOpen', 'Blockly.Events.utils', 'Blockly.Icon', 'Blockly.Warning', 'Blockly.browserEvents', 'Blockly.utils.Svg', 'Blockly.utils.dom', 'Blockly.utils.object', 'Blockly.utils.userAgent'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/common.js', ['Blockly.common'], ['Blockly.blocks'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/component_manager.js', ['Blockly.ComponentManager'], ['Blockly.utils.array'], {'lang': 'es6', 'module': 'goog'}); @@ -228,7 +228,7 @@ goog.addDependency('../../core/trashcan.js', ['Blockly.Trashcan'], ['Blockly.Com goog.addDependency('../../core/utils.js', ['Blockly.utils'], ['Blockly.Extensions', 'Blockly.browserEvents', 'Blockly.common', 'Blockly.utils.Coordinate', 'Blockly.utils.KeyCodes', 'Blockly.utils.Metrics', 'Blockly.utils.Rect', 'Blockly.utils.Size', 'Blockly.utils.Svg', 'Blockly.utils.aria', 'Blockly.utils.array', 'Blockly.utils.colour', 'Blockly.utils.deprecation', 'Blockly.utils.dom', 'Blockly.utils.global', 'Blockly.utils.idGenerator', 'Blockly.utils.math', 'Blockly.utils.object', 'Blockly.utils.parsing', 'Blockly.utils.string', 'Blockly.utils.style', 'Blockly.utils.svgMath', 'Blockly.utils.svgPaths', 'Blockly.utils.toolbox', 'Blockly.utils.userAgent', 'Blockly.utils.xml'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/utils/aria.js', ['Blockly.utils.aria'], [], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/utils/array.js', ['Blockly.utils.array'], [], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/utils/colour.js', ['Blockly.utils.colour'], ['Blockly.internalConstants'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/utils/colour.js', ['Blockly.utils.colour'], [], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/utils/coordinate.js', ['Blockly.utils.Coordinate'], [], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/utils/deprecation.js', ['Blockly.utils.deprecation'], [], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/utils/dom.js', ['Blockly.utils.dom'], ['Blockly.utils.userAgent'], {'lang': 'es6', 'module': 'goog'}); @@ -238,7 +238,7 @@ goog.addDependency('../../core/utils/keycodes.js', ['Blockly.utils.KeyCodes'], [ goog.addDependency('../../core/utils/math.js', ['Blockly.utils.math'], [], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/utils/metrics.js', ['Blockly.utils.Metrics'], [], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/utils/object.js', ['Blockly.utils.object'], [], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/utils/parsing.js', ['Blockly.utils.parsing'], ['Blockly.Msg', 'Blockly.internalConstants', 'Blockly.utils.colour', 'Blockly.utils.string'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/utils/parsing.js', ['Blockly.utils.parsing'], ['Blockly.Msg', 'Blockly.utils.colour', 'Blockly.utils.string'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/utils/rect.js', ['Blockly.utils.Rect'], [], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/utils/size.js', ['Blockly.utils.Size'], [], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/utils/string.js', ['Blockly.utils.string'], [], {'lang': 'es6', 'module': 'goog'}); From 9b63fd93973b198047e438e10fd69cae6144c4ed Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 6 Jan 2022 10:35:48 -0800 Subject: [PATCH 018/128] chore(deps): bump @blockly/theme-modern from 2.1.24 to 2.1.25 (#5837) Bumps [@blockly/theme-modern](https://github.com/google/blockly-samples/tree/HEAD/plugins/theme-modern) from 2.1.24 to 2.1.25. - [Release notes](https://github.com/google/blockly-samples/releases) - [Commits](https://github.com/google/blockly-samples/commits/@blockly/theme-modern@2.1.25/plugins/theme-modern) --- updated-dependencies: - dependency-name: "@blockly/theme-modern" dependency-type: direct:development update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- package-lock.json | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/package-lock.json b/package-lock.json index 61f4b77f7..8392f4df9 100644 --- a/package-lock.json +++ b/package-lock.json @@ -225,15 +225,15 @@ } }, "node_modules/@blockly/theme-modern": { - "version": "2.1.24", - "resolved": "https://registry.npmjs.org/@blockly/theme-modern/-/theme-modern-2.1.24.tgz", - "integrity": "sha512-glTi5qhHr+S87S1skWG8Sre+DYeSIBG3j+YBbwwRX9k3zYtGO+W7sOdJ9DsBJj8NVukPpV1RhQhu5rt93Pp2rw==", + "version": "2.1.25", + "resolved": "https://registry.npmjs.org/@blockly/theme-modern/-/theme-modern-2.1.25.tgz", + "integrity": "sha512-CeImJoVh0Kv9O7GAlCzhrL5UDZRxe94H9ib1mGVi/eWweGA2ruU3pR/TLjg9d5oCuBbqaaGEsXEoZMiraE8pZQ==", "dev": true, "engines": { "node": ">=8.17.0" }, "peerDependencies": { - "blockly": "3.20200123.0 - 6" + "blockly": "3.20200123.0 - 7" } }, "node_modules/@blockly/theme-tritanopia": { @@ -12134,9 +12134,9 @@ "requires": {} }, "@blockly/theme-modern": { - "version": "2.1.24", - "resolved": "https://registry.npmjs.org/@blockly/theme-modern/-/theme-modern-2.1.24.tgz", - "integrity": "sha512-glTi5qhHr+S87S1skWG8Sre+DYeSIBG3j+YBbwwRX9k3zYtGO+W7sOdJ9DsBJj8NVukPpV1RhQhu5rt93Pp2rw==", + "version": "2.1.25", + "resolved": "https://registry.npmjs.org/@blockly/theme-modern/-/theme-modern-2.1.25.tgz", + "integrity": "sha512-CeImJoVh0Kv9O7GAlCzhrL5UDZRxe94H9ib1mGVi/eWweGA2ruU3pR/TLjg9d5oCuBbqaaGEsXEoZMiraE8pZQ==", "dev": true, "requires": {} }, From 4b2b658f3ea3494c4995cc15df5f38f469a755da Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 6 Jan 2022 10:41:12 -0800 Subject: [PATCH 019/128] chore(deps): bump closure-calculate-chunks from 3.0.2 to 3.0.3 (#5815) Bumps [closure-calculate-chunks](https://github.com/chadkillingsworth/closure-calculate-chunks) from 3.0.2 to 3.0.3. - [Release notes](https://github.com/chadkillingsworth/closure-calculate-chunks/releases) - [Commits](https://github.com/chadkillingsworth/closure-calculate-chunks/compare/v3.0.2...v3.0.3) --- updated-dependencies: - dependency-name: closure-calculate-chunks dependency-type: direct:development update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- package-lock.json | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/package-lock.json b/package-lock.json index 8392f4df9..2284629c3 100644 --- a/package-lock.json +++ b/package-lock.json @@ -2215,9 +2215,9 @@ } }, "node_modules/closure-calculate-chunks": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/closure-calculate-chunks/-/closure-calculate-chunks-3.0.2.tgz", - "integrity": "sha512-nCpUyKcCF+Izk1CzobGu2HdHrlXAVguiM2gpmwW2UX+JAAJyPKyyYJPnIIifZ2wVuxZBG4FlVWjV69y8TOa5Bg==", + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/closure-calculate-chunks/-/closure-calculate-chunks-3.0.3.tgz", + "integrity": "sha512-xtDmQORvSXfgT+6Xkde1RYTHsowCwqyHL92WdG4ZJKJ4bpu+A9yWK32kr4gInZEKRSAS0QrCrkXQJq4bOD5cJA==", "dev": true, "dependencies": { "acorn": "8.x", @@ -13724,9 +13724,9 @@ } }, "closure-calculate-chunks": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/closure-calculate-chunks/-/closure-calculate-chunks-3.0.2.tgz", - "integrity": "sha512-nCpUyKcCF+Izk1CzobGu2HdHrlXAVguiM2gpmwW2UX+JAAJyPKyyYJPnIIifZ2wVuxZBG4FlVWjV69y8TOa5Bg==", + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/closure-calculate-chunks/-/closure-calculate-chunks-3.0.3.tgz", + "integrity": "sha512-xtDmQORvSXfgT+6Xkde1RYTHsowCwqyHL92WdG4ZJKJ4bpu+A9yWK32kr4gInZEKRSAS0QrCrkXQJq4bOD5cJA==", "dev": true, "requires": { "acorn": "8.x", From 769a25f4badffd2409ce19535344c98f5d8b01c9 Mon Sep 17 00:00:00 2001 From: Neil Fraser Date: Thu, 6 Jan 2022 10:42:32 -0800 Subject: [PATCH 020/128] fix: Don't throw if drag surface is empty. (#5695) Observed this error in Blockly Games Bird 6 (Chrome OS): Uncaught TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'. It has only shown up once, and I can't reproduce, but it looks like the drag surface was being cleared while empty. Maybe some weird multi-touch operation? Open question: Leave the code as is so that the error is thown and visible, or supress it? --- core/block_drag_surface.js | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/core/block_drag_surface.js b/core/block_drag_surface.js index 2ff685cde..ff619d390 100644 --- a/core/block_drag_surface.js +++ b/core/block_drag_surface.js @@ -252,11 +252,14 @@ BlockDragSurfaceSvg.prototype.getWsTranslation = function() { * being moved to a different surface. */ BlockDragSurfaceSvg.prototype.clearAndHide = function(opt_newSurface) { - if (opt_newSurface) { - // appendChild removes the node from this.dragGroup_ - opt_newSurface.appendChild(this.getCurrentBlock()); - } else { - this.dragGroup_.removeChild(this.getCurrentBlock()); + const currentBlockElement = this.getCurrentBlock(); + if (currentBlockElement) { + if (opt_newSurface) { + // appendChild removes the node from this.dragGroup_ + opt_newSurface.appendChild(currentBlockElement); + } else { + this.dragGroup_.removeChild(currentBlockElement); + } } this.SVG_.style.display = 'none'; if (this.dragGroup_.childNodes.length) { From 5cef21b55c8e2434f469ff6b02c0a31a28f4fc4f Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 6 Jan 2022 10:43:23 -0800 Subject: [PATCH 021/128] chore(deps): bump webdriverio from 7.16.10 to 7.16.12 (#5824) Bumps [webdriverio](https://github.com/webdriverio/webdriverio) from 7.16.10 to 7.16.12. - [Release notes](https://github.com/webdriverio/webdriverio/releases) - [Changelog](https://github.com/webdriverio/webdriverio/blob/main/CHANGELOG.md) - [Commits](https://github.com/webdriverio/webdriverio/compare/v7.16.10...v7.16.12) --- updated-dependencies: - dependency-name: webdriverio dependency-type: direct:development update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- package-lock.json | 844 +++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 768 insertions(+), 76 deletions(-) diff --git a/package-lock.json b/package-lock.json index 2284629c3..c4ce97fcb 100644 --- a/package-lock.json +++ b/package-lock.json @@ -668,6 +668,231 @@ "node": ">=12.0.0" } }, + "node_modules/@wdio/cli/node_modules/@wdio/repl": { + "version": "7.16.3", + "resolved": "https://registry.npmjs.org/@wdio/repl/-/repl-7.16.3.tgz", + "integrity": "sha512-aFpWyAIuPo6VVmkotZDWXMzd4qw3gD+xAhB6blNrMCZKWnz9+HqZnuGGc6pmiyuc5yFzb9wF22tnIxuyTyH7yA==", + "dev": true, + "peer": true, + "dependencies": { + "@wdio/utils": "7.16.3" + }, + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/@wdio/cli/node_modules/debug": { + "version": "4.3.2", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.2.tgz", + "integrity": "sha512-mOp8wKcvj7XxC78zLgw/ZA+6TSgkoE2C/ienthhRD298T7UNwAg9diBpLRxC0mOezLl4B0xV7M0cCO6P/O0Xhw==", + "dev": true, + "peer": true, + "dependencies": { + "ms": "2.1.2" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/@wdio/cli/node_modules/devtools": { + "version": "7.16.10", + "resolved": "https://registry.npmjs.org/devtools/-/devtools-7.16.10.tgz", + "integrity": "sha512-43uB3t6uNjWsqiQKRLY7axFLuMdKqlQxq6N3FWCfBKl9We1oygkGkE7Scnushdbc4lk7QwGXBC1DQ83dCgA5Gw==", + "dev": true, + "peer": true, + "dependencies": { + "@types/node": "^16.11.1", + "@types/ua-parser-js": "^0.7.33", + "@wdio/config": "7.16.3", + "@wdio/logger": "7.16.0", + "@wdio/protocols": "7.16.7", + "@wdio/types": "7.16.3", + "@wdio/utils": "7.16.3", + "chrome-launcher": "^0.15.0", + "edge-paths": "^2.1.0", + "puppeteer-core": "^11.0.0", + "query-selector-shadow-dom": "^1.0.0", + "ua-parser-js": "^1.0.1", + "uuid": "^8.0.0" + }, + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/@wdio/cli/node_modules/devtools-protocol": { + "version": "0.0.944179", + "resolved": "https://registry.npmjs.org/devtools-protocol/-/devtools-protocol-0.0.944179.tgz", + "integrity": "sha512-oqBbLKuCAkEqqsWn0rsfkjy79F0/QTQR/rlijZzeHInJfDRPYwP0D04NiQX9MQmucrAyRWGseY0b/ff0yhQdXg==", + "dev": true, + "peer": true + }, + "node_modules/@wdio/cli/node_modules/node-fetch": { + "version": "2.6.5", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.5.tgz", + "integrity": "sha512-mmlIVHJEu5rnIxgEgez6b9GgWXbkZj5YZ7fx+2r94a2E+Uirsp6HsPTPlomfdHtpt/B0cdKviwkoaM6pyvUOpQ==", + "dev": true, + "peer": true, + "dependencies": { + "whatwg-url": "^5.0.0" + }, + "engines": { + "node": "4.x || >=6.0.0" + } + }, + "node_modules/@wdio/cli/node_modules/puppeteer-core": { + "version": "11.0.0", + "resolved": "https://registry.npmjs.org/puppeteer-core/-/puppeteer-core-11.0.0.tgz", + "integrity": "sha512-hfQ39KNP0qKplQ86iaCNXHH9zpWlV01UFdggt2qffgWeCBF9KMavwP/k/iK/JidPPWfOnKZhDLSHZVSUr73DtA==", + "dev": true, + "peer": true, + "dependencies": { + "debug": "4.3.2", + "devtools-protocol": "0.0.901419", + "extract-zip": "2.0.1", + "https-proxy-agent": "5.0.0", + "node-fetch": "2.6.5", + "pkg-dir": "4.2.0", + "progress": "2.0.3", + "proxy-from-env": "1.1.0", + "rimraf": "3.0.2", + "tar-fs": "2.1.1", + "unbzip2-stream": "1.4.3", + "ws": "8.2.3" + }, + "engines": { + "node": ">=10.18.1" + } + }, + "node_modules/@wdio/cli/node_modules/puppeteer-core/node_modules/devtools-protocol": { + "version": "0.0.901419", + "resolved": "https://registry.npmjs.org/devtools-protocol/-/devtools-protocol-0.0.901419.tgz", + "integrity": "sha512-4INMPwNm9XRpBukhNbF7OB6fNTTCaI8pzy/fXg0xQzAy5h3zL1P8xT3QazgKqBrb/hAYwIBizqDBZ7GtJE74QQ==", + "dev": true, + "peer": true + }, + "node_modules/@wdio/cli/node_modules/tr46": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz", + "integrity": "sha1-gYT9NH2snNwYWZLzpmIuFLnZq2o=", + "dev": true, + "peer": true + }, + "node_modules/@wdio/cli/node_modules/uuid": { + "version": "8.3.2", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz", + "integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==", + "dev": true, + "peer": true, + "bin": { + "uuid": "dist/bin/uuid" + } + }, + "node_modules/@wdio/cli/node_modules/webdriver": { + "version": "7.16.9", + "resolved": "https://registry.npmjs.org/webdriver/-/webdriver-7.16.9.tgz", + "integrity": "sha512-6bpiyE3/1ncgyNM/RwzEWjpxu2NLYyeYNu/97OMEwFMDV8EqvlZh3wFnODi6tY0K5t4dEryIPiyjF3MDVySRAg==", + "dev": true, + "peer": true, + "dependencies": { + "@types/node": "^16.11.1", + "@wdio/config": "7.16.3", + "@wdio/logger": "7.16.0", + "@wdio/protocols": "7.16.7", + "@wdio/types": "7.16.3", + "@wdio/utils": "7.16.3", + "got": "^11.0.2", + "ky": "^0.28.5", + "lodash.merge": "^4.6.1" + }, + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/@wdio/cli/node_modules/webdriverio": { + "version": "7.16.10", + "resolved": "https://registry.npmjs.org/webdriverio/-/webdriverio-7.16.10.tgz", + "integrity": "sha512-Idsn0084HqcqHa5/BW/75dwFEitSDi/hhXk+GRA0wZkVU7woE8ZKACsMS270kOADgXYU9XJBT8jo6YM3R3Sa+Q==", + "dev": true, + "peer": true, + "dependencies": { + "@types/aria-query": "^5.0.0", + "@types/node": "^16.11.1", + "@wdio/config": "7.16.3", + "@wdio/logger": "7.16.0", + "@wdio/protocols": "7.16.7", + "@wdio/repl": "7.16.3", + "@wdio/types": "7.16.3", + "@wdio/utils": "7.16.3", + "archiver": "^5.0.0", + "aria-query": "^5.0.0", + "css-shorthand-properties": "^1.1.1", + "css-value": "^0.0.1", + "devtools": "7.16.10", + "devtools-protocol": "^0.0.944179", + "fs-extra": "^10.0.0", + "get-port": "^5.1.1", + "grapheme-splitter": "^1.0.2", + "lodash.clonedeep": "^4.5.0", + "lodash.isobject": "^3.0.2", + "lodash.isplainobject": "^4.0.6", + "lodash.zip": "^4.2.0", + "minimatch": "^3.0.4", + "puppeteer-core": "^11.0.0", + "query-selector-shadow-dom": "^1.0.0", + "resq": "^1.9.1", + "rgb2hex": "0.2.5", + "serialize-error": "^8.0.0", + "webdriver": "7.16.9" + }, + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/@wdio/cli/node_modules/webidl-conversions": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", + "integrity": "sha1-JFNCdeKnvGvnvIZhHMFq4KVlSHE=", + "dev": true, + "peer": true + }, + "node_modules/@wdio/cli/node_modules/whatwg-url": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz", + "integrity": "sha1-lmRU6HZUYuN2RNNib2dCzotwll0=", + "dev": true, + "peer": true, + "dependencies": { + "tr46": "~0.0.3", + "webidl-conversions": "^3.0.0" + } + }, + "node_modules/@wdio/cli/node_modules/ws": { + "version": "8.2.3", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.2.3.tgz", + "integrity": "sha512-wBuoj1BDpC6ZQ1B7DWQBYVLphPWkm8i9Y0/3YdHjHKHiohOJ1ws+3OccDWtH+PoC9DZD5WOTrJvNbWvjS6JWaA==", + "dev": true, + "peer": true, + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": "^5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, "node_modules/@wdio/config": { "version": "7.16.3", "resolved": "https://registry.npmjs.org/@wdio/config/-/config-7.16.3.tgz", @@ -708,12 +933,39 @@ } }, "node_modules/@wdio/repl": { - "version": "7.16.3", - "resolved": "https://registry.npmjs.org/@wdio/repl/-/repl-7.16.3.tgz", - "integrity": "sha512-aFpWyAIuPo6VVmkotZDWXMzd4qw3gD+xAhB6blNrMCZKWnz9+HqZnuGGc6pmiyuc5yFzb9wF22tnIxuyTyH7yA==", + "version": "7.16.11", + "resolved": "https://registry.npmjs.org/@wdio/repl/-/repl-7.16.11.tgz", + "integrity": "sha512-wcKkb8L4VmotiE00wxn+RybG5FIUu4Ll7VvLM+DRd9TqEs1IEYwqKLaZKEP1lo/O2nKdcYFHtiAYZ9hon9947Q==", "dev": true, "dependencies": { - "@wdio/utils": "7.16.3" + "@wdio/utils": "7.16.11" + }, + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/@wdio/repl/node_modules/@wdio/types": { + "version": "7.16.11", + "resolved": "https://registry.npmjs.org/@wdio/types/-/types-7.16.11.tgz", + "integrity": "sha512-OFVTFEB6qdG84Y+cOWIacV0loGMgq2SF/rGGlGxai89V3UQxzCFTYVoAx6odAuSNZ37wmfWCykyAR/lAlMItoQ==", + "dev": true, + "dependencies": { + "@types/node": "^16.11.1", + "got": "^11.8.1" + }, + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/@wdio/repl/node_modules/@wdio/utils": { + "version": "7.16.11", + "resolved": "https://registry.npmjs.org/@wdio/utils/-/utils-7.16.11.tgz", + "integrity": "sha512-qeXHREZJ7mz3C2cWGOmFG6MS6njp1js4f8zca3iqxaorWshwkrlNsps3B1iTHfkvK6oWnmc2Q0o5CrtLZl0LkA==", + "dev": true, + "dependencies": { + "@wdio/logger": "7.16.0", + "@wdio/types": "7.16.11", + "p-iteration": "^1.1.8" }, "engines": { "node": ">=12.0.0" @@ -759,6 +1011,7 @@ "resolved": "https://registry.npmjs.org/@wdio/utils/-/utils-7.16.3.tgz", "integrity": "sha512-/662h5Z7B5TejHN6GiW96PAKuTPi/xcAGmtjA9ozRBI2/0eHSccDfNEaBgTTjLqqEgGAXylHcOuxHOrKx2ddJw==", "dev": true, + "peer": true, "dependencies": { "@wdio/logger": "7.16.0", "@wdio/types": "7.16.3", @@ -2958,21 +3211,21 @@ } }, "node_modules/devtools": { - "version": "7.16.10", - "resolved": "https://registry.npmjs.org/devtools/-/devtools-7.16.10.tgz", - "integrity": "sha512-43uB3t6uNjWsqiQKRLY7axFLuMdKqlQxq6N3FWCfBKl9We1oygkGkE7Scnushdbc4lk7QwGXBC1DQ83dCgA5Gw==", + "version": "7.16.12", + "resolved": "https://registry.npmjs.org/devtools/-/devtools-7.16.12.tgz", + "integrity": "sha512-gKe2DV1VkcZ4omTEss3cTeVg/ZmAUkJArAQp22ceDEbeE6AYYDeCpFDlZmbVgsjMxh+gY2mU5IWQlRIY/7Vyrg==", "dev": true, "dependencies": { "@types/node": "^16.11.1", "@types/ua-parser-js": "^0.7.33", - "@wdio/config": "7.16.3", + "@wdio/config": "7.16.11", "@wdio/logger": "7.16.0", "@wdio/protocols": "7.16.7", - "@wdio/types": "7.16.3", - "@wdio/utils": "7.16.3", + "@wdio/types": "7.16.11", + "@wdio/utils": "7.16.11", "chrome-launcher": "^0.15.0", "edge-paths": "^2.1.0", - "puppeteer-core": "^11.0.0", + "puppeteer-core": "^13.0.0", "query-selector-shadow-dom": "^1.0.0", "ua-parser-js": "^1.0.1", "uuid": "^8.0.0" @@ -2982,11 +3235,53 @@ } }, "node_modules/devtools-protocol": { - "version": "0.0.944179", - "resolved": "https://registry.npmjs.org/devtools-protocol/-/devtools-protocol-0.0.944179.tgz", - "integrity": "sha512-oqBbLKuCAkEqqsWn0rsfkjy79F0/QTQR/rlijZzeHInJfDRPYwP0D04NiQX9MQmucrAyRWGseY0b/ff0yhQdXg==", + "version": "0.0.948846", + "resolved": "https://registry.npmjs.org/devtools-protocol/-/devtools-protocol-0.0.948846.tgz", + "integrity": "sha512-5fGyt9xmMqUl2VI7+rnUkKCiAQIpLns8sfQtTENy5L70ktbNw0Z3TFJ1JoFNYdx/jffz4YXU45VF75wKZD7sZQ==", "dev": true }, + "node_modules/devtools/node_modules/@wdio/config": { + "version": "7.16.11", + "resolved": "https://registry.npmjs.org/@wdio/config/-/config-7.16.11.tgz", + "integrity": "sha512-sIk9FINQfXohuDONb8RA1uv+29XvUw6OBHfaaU7/c9gfKiOWiRczdfiLqfySZRwYgEgNhzCw5vHIogTry1h+xQ==", + "dev": true, + "dependencies": { + "@wdio/logger": "7.16.0", + "@wdio/types": "7.16.11", + "deepmerge": "^4.0.0", + "glob": "^7.1.2" + }, + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/devtools/node_modules/@wdio/types": { + "version": "7.16.11", + "resolved": "https://registry.npmjs.org/@wdio/types/-/types-7.16.11.tgz", + "integrity": "sha512-OFVTFEB6qdG84Y+cOWIacV0loGMgq2SF/rGGlGxai89V3UQxzCFTYVoAx6odAuSNZ37wmfWCykyAR/lAlMItoQ==", + "dev": true, + "dependencies": { + "@types/node": "^16.11.1", + "got": "^11.8.1" + }, + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/devtools/node_modules/@wdio/utils": { + "version": "7.16.11", + "resolved": "https://registry.npmjs.org/@wdio/utils/-/utils-7.16.11.tgz", + "integrity": "sha512-qeXHREZJ7mz3C2cWGOmFG6MS6njp1js4f8zca3iqxaorWshwkrlNsps3B1iTHfkvK6oWnmc2Q0o5CrtLZl0LkA==", + "dev": true, + "dependencies": { + "@wdio/logger": "7.16.0", + "@wdio/types": "7.16.11", + "p-iteration": "^1.1.8" + }, + "engines": { + "node": ">=12.0.0" + } + }, "node_modules/devtools/node_modules/uuid": { "version": "8.3.2", "resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz", @@ -9022,13 +9317,13 @@ } }, "node_modules/puppeteer-core": { - "version": "11.0.0", - "resolved": "https://registry.npmjs.org/puppeteer-core/-/puppeteer-core-11.0.0.tgz", - "integrity": "sha512-hfQ39KNP0qKplQ86iaCNXHH9zpWlV01UFdggt2qffgWeCBF9KMavwP/k/iK/JidPPWfOnKZhDLSHZVSUr73DtA==", + "version": "13.0.0", + "resolved": "https://registry.npmjs.org/puppeteer-core/-/puppeteer-core-13.0.0.tgz", + "integrity": "sha512-JJvGCuUNpONaFK/1tizyVthfqkEaiTCteL9HkdxN3//P9cVa+YnehlKIoJCStiKRaa3CjRu/dIJftA5XJ2EGrQ==", "dev": true, "dependencies": { "debug": "4.3.2", - "devtools-protocol": "0.0.901419", + "devtools-protocol": "0.0.937139", "extract-zip": "2.0.1", "https-proxy-agent": "5.0.0", "node-fetch": "2.6.5", @@ -9062,9 +9357,9 @@ } }, "node_modules/puppeteer-core/node_modules/devtools-protocol": { - "version": "0.0.901419", - "resolved": "https://registry.npmjs.org/devtools-protocol/-/devtools-protocol-0.0.901419.tgz", - "integrity": "sha512-4INMPwNm9XRpBukhNbF7OB6fNTTCaI8pzy/fXg0xQzAy5h3zL1P8xT3QazgKqBrb/hAYwIBizqDBZ7GtJE74QQ==", + "version": "0.0.937139", + "resolved": "https://registry.npmjs.org/devtools-protocol/-/devtools-protocol-0.0.937139.tgz", + "integrity": "sha512-daj+rzR3QSxsPRy5vjjthn58axO8c11j58uY0lG5vvlJk/EiOdCWOptGdkXDjtuRHr78emKq0udHCXM4trhoDQ==", "dev": true }, "node_modules/puppeteer-core/node_modules/node-fetch": { @@ -11540,17 +11835,17 @@ } }, "node_modules/webdriver": { - "version": "7.16.9", - "resolved": "https://registry.npmjs.org/webdriver/-/webdriver-7.16.9.tgz", - "integrity": "sha512-6bpiyE3/1ncgyNM/RwzEWjpxu2NLYyeYNu/97OMEwFMDV8EqvlZh3wFnODi6tY0K5t4dEryIPiyjF3MDVySRAg==", + "version": "7.16.11", + "resolved": "https://registry.npmjs.org/webdriver/-/webdriver-7.16.11.tgz", + "integrity": "sha512-6nBOXae4xuBH4Nqvi/zvtwjnxSLTONBpxOiRJtQ68CYTYv5+w3m8CsaWy3HbK/0XXa++NYl62bDNn70OGEKb+Q==", "dev": true, "dependencies": { "@types/node": "^16.11.1", - "@wdio/config": "7.16.3", + "@wdio/config": "7.16.11", "@wdio/logger": "7.16.0", "@wdio/protocols": "7.16.7", - "@wdio/types": "7.16.3", - "@wdio/utils": "7.16.3", + "@wdio/types": "7.16.11", + "@wdio/utils": "7.16.11", "got": "^11.0.2", "ky": "^0.28.5", "lodash.merge": "^4.6.1" @@ -11559,26 +11854,68 @@ "node": ">=12.0.0" } }, + "node_modules/webdriver/node_modules/@wdio/config": { + "version": "7.16.11", + "resolved": "https://registry.npmjs.org/@wdio/config/-/config-7.16.11.tgz", + "integrity": "sha512-sIk9FINQfXohuDONb8RA1uv+29XvUw6OBHfaaU7/c9gfKiOWiRczdfiLqfySZRwYgEgNhzCw5vHIogTry1h+xQ==", + "dev": true, + "dependencies": { + "@wdio/logger": "7.16.0", + "@wdio/types": "7.16.11", + "deepmerge": "^4.0.0", + "glob": "^7.1.2" + }, + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/webdriver/node_modules/@wdio/types": { + "version": "7.16.11", + "resolved": "https://registry.npmjs.org/@wdio/types/-/types-7.16.11.tgz", + "integrity": "sha512-OFVTFEB6qdG84Y+cOWIacV0loGMgq2SF/rGGlGxai89V3UQxzCFTYVoAx6odAuSNZ37wmfWCykyAR/lAlMItoQ==", + "dev": true, + "dependencies": { + "@types/node": "^16.11.1", + "got": "^11.8.1" + }, + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/webdriver/node_modules/@wdio/utils": { + "version": "7.16.11", + "resolved": "https://registry.npmjs.org/@wdio/utils/-/utils-7.16.11.tgz", + "integrity": "sha512-qeXHREZJ7mz3C2cWGOmFG6MS6njp1js4f8zca3iqxaorWshwkrlNsps3B1iTHfkvK6oWnmc2Q0o5CrtLZl0LkA==", + "dev": true, + "dependencies": { + "@wdio/logger": "7.16.0", + "@wdio/types": "7.16.11", + "p-iteration": "^1.1.8" + }, + "engines": { + "node": ">=12.0.0" + } + }, "node_modules/webdriverio": { - "version": "7.16.10", - "resolved": "https://registry.npmjs.org/webdriverio/-/webdriverio-7.16.10.tgz", - "integrity": "sha512-Idsn0084HqcqHa5/BW/75dwFEitSDi/hhXk+GRA0wZkVU7woE8ZKACsMS270kOADgXYU9XJBT8jo6YM3R3Sa+Q==", + "version": "7.16.12", + "resolved": "https://registry.npmjs.org/webdriverio/-/webdriverio-7.16.12.tgz", + "integrity": "sha512-pRKDRnfaE3xrNPI4TFT3kEf29l9aS6BylQOoX6DHM6gla8Xf/4seykWn1uJOCP71M9cvL8uuTZRTkfNTLGJcdQ==", "dev": true, "dependencies": { "@types/aria-query": "^5.0.0", "@types/node": "^16.11.1", - "@wdio/config": "7.16.3", + "@wdio/config": "7.16.11", "@wdio/logger": "7.16.0", "@wdio/protocols": "7.16.7", - "@wdio/repl": "7.16.3", - "@wdio/types": "7.16.3", - "@wdio/utils": "7.16.3", + "@wdio/repl": "7.16.11", + "@wdio/types": "7.16.11", + "@wdio/utils": "7.16.11", "archiver": "^5.0.0", "aria-query": "^5.0.0", "css-shorthand-properties": "^1.1.1", "css-value": "^0.0.1", - "devtools": "7.16.10", - "devtools-protocol": "^0.0.944179", + "devtools": "7.16.12", + "devtools-protocol": "^0.0.948846", "fs-extra": "^10.0.0", "get-port": "^5.1.1", "grapheme-splitter": "^1.0.2", @@ -11587,12 +11924,54 @@ "lodash.isplainobject": "^4.0.6", "lodash.zip": "^4.2.0", "minimatch": "^3.0.4", - "puppeteer-core": "^11.0.0", + "puppeteer-core": "^13.0.0", "query-selector-shadow-dom": "^1.0.0", "resq": "^1.9.1", "rgb2hex": "0.2.5", "serialize-error": "^8.0.0", - "webdriver": "7.16.9" + "webdriver": "7.16.11" + }, + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/webdriverio/node_modules/@wdio/config": { + "version": "7.16.11", + "resolved": "https://registry.npmjs.org/@wdio/config/-/config-7.16.11.tgz", + "integrity": "sha512-sIk9FINQfXohuDONb8RA1uv+29XvUw6OBHfaaU7/c9gfKiOWiRczdfiLqfySZRwYgEgNhzCw5vHIogTry1h+xQ==", + "dev": true, + "dependencies": { + "@wdio/logger": "7.16.0", + "@wdio/types": "7.16.11", + "deepmerge": "^4.0.0", + "glob": "^7.1.2" + }, + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/webdriverio/node_modules/@wdio/types": { + "version": "7.16.11", + "resolved": "https://registry.npmjs.org/@wdio/types/-/types-7.16.11.tgz", + "integrity": "sha512-OFVTFEB6qdG84Y+cOWIacV0loGMgq2SF/rGGlGxai89V3UQxzCFTYVoAx6odAuSNZ37wmfWCykyAR/lAlMItoQ==", + "dev": true, + "dependencies": { + "@types/node": "^16.11.1", + "got": "^11.8.1" + }, + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/webdriverio/node_modules/@wdio/utils": { + "version": "7.16.11", + "resolved": "https://registry.npmjs.org/@wdio/utils/-/utils-7.16.11.tgz", + "integrity": "sha512-qeXHREZJ7mz3C2cWGOmFG6MS6njp1js4f8zca3iqxaorWshwkrlNsps3B1iTHfkvK6oWnmc2Q0o5CrtLZl0LkA==", + "dev": true, + "dependencies": { + "@wdio/logger": "7.16.0", + "@wdio/types": "7.16.11", + "p-iteration": "^1.1.8" }, "engines": { "node": ">=12.0.0" @@ -12530,6 +12909,192 @@ "webdriverio": "7.16.10", "yargs": "^17.0.0", "yarn-install": "^1.0.0" + }, + "dependencies": { + "@wdio/repl": { + "version": "7.16.3", + "resolved": "https://registry.npmjs.org/@wdio/repl/-/repl-7.16.3.tgz", + "integrity": "sha512-aFpWyAIuPo6VVmkotZDWXMzd4qw3gD+xAhB6blNrMCZKWnz9+HqZnuGGc6pmiyuc5yFzb9wF22tnIxuyTyH7yA==", + "dev": true, + "peer": true, + "requires": { + "@wdio/utils": "7.16.3" + } + }, + "debug": { + "version": "4.3.2", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.2.tgz", + "integrity": "sha512-mOp8wKcvj7XxC78zLgw/ZA+6TSgkoE2C/ienthhRD298T7UNwAg9diBpLRxC0mOezLl4B0xV7M0cCO6P/O0Xhw==", + "dev": true, + "peer": true, + "requires": { + "ms": "2.1.2" + } + }, + "devtools": { + "version": "7.16.10", + "resolved": "https://registry.npmjs.org/devtools/-/devtools-7.16.10.tgz", + "integrity": "sha512-43uB3t6uNjWsqiQKRLY7axFLuMdKqlQxq6N3FWCfBKl9We1oygkGkE7Scnushdbc4lk7QwGXBC1DQ83dCgA5Gw==", + "dev": true, + "peer": true, + "requires": { + "@types/node": "^16.11.1", + "@types/ua-parser-js": "^0.7.33", + "@wdio/config": "7.16.3", + "@wdio/logger": "7.16.0", + "@wdio/protocols": "7.16.7", + "@wdio/types": "7.16.3", + "@wdio/utils": "7.16.3", + "chrome-launcher": "^0.15.0", + "edge-paths": "^2.1.0", + "puppeteer-core": "^11.0.0", + "query-selector-shadow-dom": "^1.0.0", + "ua-parser-js": "^1.0.1", + "uuid": "^8.0.0" + } + }, + "devtools-protocol": { + "version": "0.0.944179", + "resolved": "https://registry.npmjs.org/devtools-protocol/-/devtools-protocol-0.0.944179.tgz", + "integrity": "sha512-oqBbLKuCAkEqqsWn0rsfkjy79F0/QTQR/rlijZzeHInJfDRPYwP0D04NiQX9MQmucrAyRWGseY0b/ff0yhQdXg==", + "dev": true, + "peer": true + }, + "node-fetch": { + "version": "2.6.5", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.5.tgz", + "integrity": "sha512-mmlIVHJEu5rnIxgEgez6b9GgWXbkZj5YZ7fx+2r94a2E+Uirsp6HsPTPlomfdHtpt/B0cdKviwkoaM6pyvUOpQ==", + "dev": true, + "peer": true, + "requires": { + "whatwg-url": "^5.0.0" + } + }, + "puppeteer-core": { + "version": "11.0.0", + "resolved": "https://registry.npmjs.org/puppeteer-core/-/puppeteer-core-11.0.0.tgz", + "integrity": "sha512-hfQ39KNP0qKplQ86iaCNXHH9zpWlV01UFdggt2qffgWeCBF9KMavwP/k/iK/JidPPWfOnKZhDLSHZVSUr73DtA==", + "dev": true, + "peer": true, + "requires": { + "debug": "4.3.2", + "devtools-protocol": "0.0.901419", + "extract-zip": "2.0.1", + "https-proxy-agent": "5.0.0", + "node-fetch": "2.6.5", + "pkg-dir": "4.2.0", + "progress": "2.0.3", + "proxy-from-env": "1.1.0", + "rimraf": "3.0.2", + "tar-fs": "2.1.1", + "unbzip2-stream": "1.4.3", + "ws": "8.2.3" + }, + "dependencies": { + "devtools-protocol": { + "version": "0.0.901419", + "resolved": "https://registry.npmjs.org/devtools-protocol/-/devtools-protocol-0.0.901419.tgz", + "integrity": "sha512-4INMPwNm9XRpBukhNbF7OB6fNTTCaI8pzy/fXg0xQzAy5h3zL1P8xT3QazgKqBrb/hAYwIBizqDBZ7GtJE74QQ==", + "dev": true, + "peer": true + } + } + }, + "tr46": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz", + "integrity": "sha1-gYT9NH2snNwYWZLzpmIuFLnZq2o=", + "dev": true, + "peer": true + }, + "uuid": { + "version": "8.3.2", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz", + "integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==", + "dev": true, + "peer": true + }, + "webdriver": { + "version": "7.16.9", + "resolved": "https://registry.npmjs.org/webdriver/-/webdriver-7.16.9.tgz", + "integrity": "sha512-6bpiyE3/1ncgyNM/RwzEWjpxu2NLYyeYNu/97OMEwFMDV8EqvlZh3wFnODi6tY0K5t4dEryIPiyjF3MDVySRAg==", + "dev": true, + "peer": true, + "requires": { + "@types/node": "^16.11.1", + "@wdio/config": "7.16.3", + "@wdio/logger": "7.16.0", + "@wdio/protocols": "7.16.7", + "@wdio/types": "7.16.3", + "@wdio/utils": "7.16.3", + "got": "^11.0.2", + "ky": "^0.28.5", + "lodash.merge": "^4.6.1" + } + }, + "webdriverio": { + "version": "7.16.10", + "resolved": "https://registry.npmjs.org/webdriverio/-/webdriverio-7.16.10.tgz", + "integrity": "sha512-Idsn0084HqcqHa5/BW/75dwFEitSDi/hhXk+GRA0wZkVU7woE8ZKACsMS270kOADgXYU9XJBT8jo6YM3R3Sa+Q==", + "dev": true, + "peer": true, + "requires": { + "@types/aria-query": "^5.0.0", + "@types/node": "^16.11.1", + "@wdio/config": "7.16.3", + "@wdio/logger": "7.16.0", + "@wdio/protocols": "7.16.7", + "@wdio/repl": "7.16.3", + "@wdio/types": "7.16.3", + "@wdio/utils": "7.16.3", + "archiver": "^5.0.0", + "aria-query": "^5.0.0", + "css-shorthand-properties": "^1.1.1", + "css-value": "^0.0.1", + "devtools": "7.16.10", + "devtools-protocol": "^0.0.944179", + "fs-extra": "^10.0.0", + "get-port": "^5.1.1", + "grapheme-splitter": "^1.0.2", + "lodash.clonedeep": "^4.5.0", + "lodash.isobject": "^3.0.2", + "lodash.isplainobject": "^4.0.6", + "lodash.zip": "^4.2.0", + "minimatch": "^3.0.4", + "puppeteer-core": "^11.0.0", + "query-selector-shadow-dom": "^1.0.0", + "resq": "^1.9.1", + "rgb2hex": "0.2.5", + "serialize-error": "^8.0.0", + "webdriver": "7.16.9" + } + }, + "webidl-conversions": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", + "integrity": "sha1-JFNCdeKnvGvnvIZhHMFq4KVlSHE=", + "dev": true, + "peer": true + }, + "whatwg-url": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz", + "integrity": "sha1-lmRU6HZUYuN2RNNib2dCzotwll0=", + "dev": true, + "peer": true, + "requires": { + "tr46": "~0.0.3", + "webidl-conversions": "^3.0.0" + } + }, + "ws": { + "version": "8.2.3", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.2.3.tgz", + "integrity": "sha512-wBuoj1BDpC6ZQ1B7DWQBYVLphPWkm8i9Y0/3YdHjHKHiohOJ1ws+3OccDWtH+PoC9DZD5WOTrJvNbWvjS6JWaA==", + "dev": true, + "peer": true, + "requires": {} + } } }, "@wdio/config": { @@ -12563,12 +13128,35 @@ "dev": true }, "@wdio/repl": { - "version": "7.16.3", - "resolved": "https://registry.npmjs.org/@wdio/repl/-/repl-7.16.3.tgz", - "integrity": "sha512-aFpWyAIuPo6VVmkotZDWXMzd4qw3gD+xAhB6blNrMCZKWnz9+HqZnuGGc6pmiyuc5yFzb9wF22tnIxuyTyH7yA==", + "version": "7.16.11", + "resolved": "https://registry.npmjs.org/@wdio/repl/-/repl-7.16.11.tgz", + "integrity": "sha512-wcKkb8L4VmotiE00wxn+RybG5FIUu4Ll7VvLM+DRd9TqEs1IEYwqKLaZKEP1lo/O2nKdcYFHtiAYZ9hon9947Q==", "dev": true, "requires": { - "@wdio/utils": "7.16.3" + "@wdio/utils": "7.16.11" + }, + "dependencies": { + "@wdio/types": { + "version": "7.16.11", + "resolved": "https://registry.npmjs.org/@wdio/types/-/types-7.16.11.tgz", + "integrity": "sha512-OFVTFEB6qdG84Y+cOWIacV0loGMgq2SF/rGGlGxai89V3UQxzCFTYVoAx6odAuSNZ37wmfWCykyAR/lAlMItoQ==", + "dev": true, + "requires": { + "@types/node": "^16.11.1", + "got": "^11.8.1" + } + }, + "@wdio/utils": { + "version": "7.16.11", + "resolved": "https://registry.npmjs.org/@wdio/utils/-/utils-7.16.11.tgz", + "integrity": "sha512-qeXHREZJ7mz3C2cWGOmFG6MS6njp1js4f8zca3iqxaorWshwkrlNsps3B1iTHfkvK6oWnmc2Q0o5CrtLZl0LkA==", + "dev": true, + "requires": { + "@wdio/logger": "7.16.0", + "@wdio/types": "7.16.11", + "p-iteration": "^1.1.8" + } + } } }, "@wdio/selenium-standalone-service": { @@ -12602,6 +13190,7 @@ "resolved": "https://registry.npmjs.org/@wdio/utils/-/utils-7.16.3.tgz", "integrity": "sha512-/662h5Z7B5TejHN6GiW96PAKuTPi/xcAGmtjA9ozRBI2/0eHSccDfNEaBgTTjLqqEgGAXylHcOuxHOrKx2ddJw==", "dev": true, + "peer": true, "requires": { "@wdio/logger": "7.16.0", "@wdio/types": "7.16.3", @@ -14312,26 +14901,59 @@ "dev": true }, "devtools": { - "version": "7.16.10", - "resolved": "https://registry.npmjs.org/devtools/-/devtools-7.16.10.tgz", - "integrity": "sha512-43uB3t6uNjWsqiQKRLY7axFLuMdKqlQxq6N3FWCfBKl9We1oygkGkE7Scnushdbc4lk7QwGXBC1DQ83dCgA5Gw==", + "version": "7.16.12", + "resolved": "https://registry.npmjs.org/devtools/-/devtools-7.16.12.tgz", + "integrity": "sha512-gKe2DV1VkcZ4omTEss3cTeVg/ZmAUkJArAQp22ceDEbeE6AYYDeCpFDlZmbVgsjMxh+gY2mU5IWQlRIY/7Vyrg==", "dev": true, "requires": { "@types/node": "^16.11.1", "@types/ua-parser-js": "^0.7.33", - "@wdio/config": "7.16.3", + "@wdio/config": "7.16.11", "@wdio/logger": "7.16.0", "@wdio/protocols": "7.16.7", - "@wdio/types": "7.16.3", - "@wdio/utils": "7.16.3", + "@wdio/types": "7.16.11", + "@wdio/utils": "7.16.11", "chrome-launcher": "^0.15.0", "edge-paths": "^2.1.0", - "puppeteer-core": "^11.0.0", + "puppeteer-core": "^13.0.0", "query-selector-shadow-dom": "^1.0.0", "ua-parser-js": "^1.0.1", "uuid": "^8.0.0" }, "dependencies": { + "@wdio/config": { + "version": "7.16.11", + "resolved": "https://registry.npmjs.org/@wdio/config/-/config-7.16.11.tgz", + "integrity": "sha512-sIk9FINQfXohuDONb8RA1uv+29XvUw6OBHfaaU7/c9gfKiOWiRczdfiLqfySZRwYgEgNhzCw5vHIogTry1h+xQ==", + "dev": true, + "requires": { + "@wdio/logger": "7.16.0", + "@wdio/types": "7.16.11", + "deepmerge": "^4.0.0", + "glob": "^7.1.2" + } + }, + "@wdio/types": { + "version": "7.16.11", + "resolved": "https://registry.npmjs.org/@wdio/types/-/types-7.16.11.tgz", + "integrity": "sha512-OFVTFEB6qdG84Y+cOWIacV0loGMgq2SF/rGGlGxai89V3UQxzCFTYVoAx6odAuSNZ37wmfWCykyAR/lAlMItoQ==", + "dev": true, + "requires": { + "@types/node": "^16.11.1", + "got": "^11.8.1" + } + }, + "@wdio/utils": { + "version": "7.16.11", + "resolved": "https://registry.npmjs.org/@wdio/utils/-/utils-7.16.11.tgz", + "integrity": "sha512-qeXHREZJ7mz3C2cWGOmFG6MS6njp1js4f8zca3iqxaorWshwkrlNsps3B1iTHfkvK6oWnmc2Q0o5CrtLZl0LkA==", + "dev": true, + "requires": { + "@wdio/logger": "7.16.0", + "@wdio/types": "7.16.11", + "p-iteration": "^1.1.8" + } + }, "uuid": { "version": "8.3.2", "resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz", @@ -14341,9 +14963,9 @@ } }, "devtools-protocol": { - "version": "0.0.944179", - "resolved": "https://registry.npmjs.org/devtools-protocol/-/devtools-protocol-0.0.944179.tgz", - "integrity": "sha512-oqBbLKuCAkEqqsWn0rsfkjy79F0/QTQR/rlijZzeHInJfDRPYwP0D04NiQX9MQmucrAyRWGseY0b/ff0yhQdXg==", + "version": "0.0.948846", + "resolved": "https://registry.npmjs.org/devtools-protocol/-/devtools-protocol-0.0.948846.tgz", + "integrity": "sha512-5fGyt9xmMqUl2VI7+rnUkKCiAQIpLns8sfQtTENy5L70ktbNw0Z3TFJ1JoFNYdx/jffz4YXU45VF75wKZD7sZQ==", "dev": true }, "diff": { @@ -19190,13 +19812,13 @@ "integrity": "sha512-XRsRjdf+j5ml+y/6GKHPZbrF/8p2Yga0JPtdqTIY2Xe5ohJPD9saDJJLPvp9+NSBprVvevdXZybnj2cv8OEd0A==" }, "puppeteer-core": { - "version": "11.0.0", - "resolved": "https://registry.npmjs.org/puppeteer-core/-/puppeteer-core-11.0.0.tgz", - "integrity": "sha512-hfQ39KNP0qKplQ86iaCNXHH9zpWlV01UFdggt2qffgWeCBF9KMavwP/k/iK/JidPPWfOnKZhDLSHZVSUr73DtA==", + "version": "13.0.0", + "resolved": "https://registry.npmjs.org/puppeteer-core/-/puppeteer-core-13.0.0.tgz", + "integrity": "sha512-JJvGCuUNpONaFK/1tizyVthfqkEaiTCteL9HkdxN3//P9cVa+YnehlKIoJCStiKRaa3CjRu/dIJftA5XJ2EGrQ==", "dev": true, "requires": { "debug": "4.3.2", - "devtools-protocol": "0.0.901419", + "devtools-protocol": "0.0.937139", "extract-zip": "2.0.1", "https-proxy-agent": "5.0.0", "node-fetch": "2.6.5", @@ -19219,9 +19841,9 @@ } }, "devtools-protocol": { - "version": "0.0.901419", - "resolved": "https://registry.npmjs.org/devtools-protocol/-/devtools-protocol-0.0.901419.tgz", - "integrity": "sha512-4INMPwNm9XRpBukhNbF7OB6fNTTCaI8pzy/fXg0xQzAy5h3zL1P8xT3QazgKqBrb/hAYwIBizqDBZ7GtJE74QQ==", + "version": "0.0.937139", + "resolved": "https://registry.npmjs.org/devtools-protocol/-/devtools-protocol-0.0.937139.tgz", + "integrity": "sha512-daj+rzR3QSxsPRy5vjjthn58axO8c11j58uY0lG5vvlJk/EiOdCWOptGdkXDjtuRHr78emKq0udHCXM4trhoDQ==", "dev": true }, "node-fetch": { @@ -21260,42 +21882,77 @@ } }, "webdriver": { - "version": "7.16.9", - "resolved": "https://registry.npmjs.org/webdriver/-/webdriver-7.16.9.tgz", - "integrity": "sha512-6bpiyE3/1ncgyNM/RwzEWjpxu2NLYyeYNu/97OMEwFMDV8EqvlZh3wFnODi6tY0K5t4dEryIPiyjF3MDVySRAg==", + "version": "7.16.11", + "resolved": "https://registry.npmjs.org/webdriver/-/webdriver-7.16.11.tgz", + "integrity": "sha512-6nBOXae4xuBH4Nqvi/zvtwjnxSLTONBpxOiRJtQ68CYTYv5+w3m8CsaWy3HbK/0XXa++NYl62bDNn70OGEKb+Q==", "dev": true, "requires": { "@types/node": "^16.11.1", - "@wdio/config": "7.16.3", + "@wdio/config": "7.16.11", "@wdio/logger": "7.16.0", "@wdio/protocols": "7.16.7", - "@wdio/types": "7.16.3", - "@wdio/utils": "7.16.3", + "@wdio/types": "7.16.11", + "@wdio/utils": "7.16.11", "got": "^11.0.2", "ky": "^0.28.5", "lodash.merge": "^4.6.1" + }, + "dependencies": { + "@wdio/config": { + "version": "7.16.11", + "resolved": "https://registry.npmjs.org/@wdio/config/-/config-7.16.11.tgz", + "integrity": "sha512-sIk9FINQfXohuDONb8RA1uv+29XvUw6OBHfaaU7/c9gfKiOWiRczdfiLqfySZRwYgEgNhzCw5vHIogTry1h+xQ==", + "dev": true, + "requires": { + "@wdio/logger": "7.16.0", + "@wdio/types": "7.16.11", + "deepmerge": "^4.0.0", + "glob": "^7.1.2" + } + }, + "@wdio/types": { + "version": "7.16.11", + "resolved": "https://registry.npmjs.org/@wdio/types/-/types-7.16.11.tgz", + "integrity": "sha512-OFVTFEB6qdG84Y+cOWIacV0loGMgq2SF/rGGlGxai89V3UQxzCFTYVoAx6odAuSNZ37wmfWCykyAR/lAlMItoQ==", + "dev": true, + "requires": { + "@types/node": "^16.11.1", + "got": "^11.8.1" + } + }, + "@wdio/utils": { + "version": "7.16.11", + "resolved": "https://registry.npmjs.org/@wdio/utils/-/utils-7.16.11.tgz", + "integrity": "sha512-qeXHREZJ7mz3C2cWGOmFG6MS6njp1js4f8zca3iqxaorWshwkrlNsps3B1iTHfkvK6oWnmc2Q0o5CrtLZl0LkA==", + "dev": true, + "requires": { + "@wdio/logger": "7.16.0", + "@wdio/types": "7.16.11", + "p-iteration": "^1.1.8" + } + } } }, "webdriverio": { - "version": "7.16.10", - "resolved": "https://registry.npmjs.org/webdriverio/-/webdriverio-7.16.10.tgz", - "integrity": "sha512-Idsn0084HqcqHa5/BW/75dwFEitSDi/hhXk+GRA0wZkVU7woE8ZKACsMS270kOADgXYU9XJBT8jo6YM3R3Sa+Q==", + "version": "7.16.12", + "resolved": "https://registry.npmjs.org/webdriverio/-/webdriverio-7.16.12.tgz", + "integrity": "sha512-pRKDRnfaE3xrNPI4TFT3kEf29l9aS6BylQOoX6DHM6gla8Xf/4seykWn1uJOCP71M9cvL8uuTZRTkfNTLGJcdQ==", "dev": true, "requires": { "@types/aria-query": "^5.0.0", "@types/node": "^16.11.1", - "@wdio/config": "7.16.3", + "@wdio/config": "7.16.11", "@wdio/logger": "7.16.0", "@wdio/protocols": "7.16.7", - "@wdio/repl": "7.16.3", - "@wdio/types": "7.16.3", - "@wdio/utils": "7.16.3", + "@wdio/repl": "7.16.11", + "@wdio/types": "7.16.11", + "@wdio/utils": "7.16.11", "archiver": "^5.0.0", "aria-query": "^5.0.0", "css-shorthand-properties": "^1.1.1", "css-value": "^0.0.1", - "devtools": "7.16.10", - "devtools-protocol": "^0.0.944179", + "devtools": "7.16.12", + "devtools-protocol": "^0.0.948846", "fs-extra": "^10.0.0", "get-port": "^5.1.1", "grapheme-splitter": "^1.0.2", @@ -21304,12 +21961,47 @@ "lodash.isplainobject": "^4.0.6", "lodash.zip": "^4.2.0", "minimatch": "^3.0.4", - "puppeteer-core": "^11.0.0", + "puppeteer-core": "^13.0.0", "query-selector-shadow-dom": "^1.0.0", "resq": "^1.9.1", "rgb2hex": "0.2.5", "serialize-error": "^8.0.0", - "webdriver": "7.16.9" + "webdriver": "7.16.11" + }, + "dependencies": { + "@wdio/config": { + "version": "7.16.11", + "resolved": "https://registry.npmjs.org/@wdio/config/-/config-7.16.11.tgz", + "integrity": "sha512-sIk9FINQfXohuDONb8RA1uv+29XvUw6OBHfaaU7/c9gfKiOWiRczdfiLqfySZRwYgEgNhzCw5vHIogTry1h+xQ==", + "dev": true, + "requires": { + "@wdio/logger": "7.16.0", + "@wdio/types": "7.16.11", + "deepmerge": "^4.0.0", + "glob": "^7.1.2" + } + }, + "@wdio/types": { + "version": "7.16.11", + "resolved": "https://registry.npmjs.org/@wdio/types/-/types-7.16.11.tgz", + "integrity": "sha512-OFVTFEB6qdG84Y+cOWIacV0loGMgq2SF/rGGlGxai89V3UQxzCFTYVoAx6odAuSNZ37wmfWCykyAR/lAlMItoQ==", + "dev": true, + "requires": { + "@types/node": "^16.11.1", + "got": "^11.8.1" + } + }, + "@wdio/utils": { + "version": "7.16.11", + "resolved": "https://registry.npmjs.org/@wdio/utils/-/utils-7.16.11.tgz", + "integrity": "sha512-qeXHREZJ7mz3C2cWGOmFG6MS6njp1js4f8zca3iqxaorWshwkrlNsps3B1iTHfkvK6oWnmc2Q0o5CrtLZl0LkA==", + "dev": true, + "requires": { + "@wdio/logger": "7.16.0", + "@wdio/types": "7.16.11", + "p-iteration": "^1.1.8" + } + } } }, "webidl-conversions": { From b124610bd764b6dac37818443748b157d442c1e2 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 6 Jan 2022 10:47:24 -0800 Subject: [PATCH 022/128] chore(deps): bump concurrently from 6.4.0 to 7.0.0 (#5847) Bumps [concurrently](https://github.com/open-cli-tools/concurrently) from 6.4.0 to 7.0.0. - [Release notes](https://github.com/open-cli-tools/concurrently/releases) - [Commits](https://github.com/open-cli-tools/concurrently/compare/v6.4.0...v7.0.0) --- updated-dependencies: - dependency-name: concurrently dependency-type: direct:development update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- package-lock.json | 18 +++++++++--------- package.json | 2 +- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/package-lock.json b/package-lock.json index c4ce97fcb..0b22ecbdb 100644 --- a/package-lock.json +++ b/package-lock.json @@ -18,7 +18,7 @@ "chai": "^4.2.0", "clang-format": "^1.6.0", "closure-calculate-chunks": "^3.0.2", - "concurrently": "^6.0.0", + "concurrently": "^7.0.0", "eslint": "^8.4.1", "eslint-config-google": "^0.14.0", "google-closure-compiler": "^20211201.0.0", @@ -2683,9 +2683,9 @@ } }, "node_modules/concurrently": { - "version": "6.4.0", - "resolved": "https://registry.npmjs.org/concurrently/-/concurrently-6.4.0.tgz", - "integrity": "sha512-HZ3D0RTQMH3oS4gvtYj1P+NBc6PzE2McEra6yEFcQKrUQ9HvtTGU4Dbne083F034p+LRb7kWU0tPRNvSGs1UCQ==", + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/concurrently/-/concurrently-7.0.0.tgz", + "integrity": "sha512-WKM7PUsI8wyXpF80H+zjHP32fsgsHNQfPLw/e70Z5dYkV7hF+rf8q3D+ScWJIEr57CpkO3OWBko6hwhQLPR8Pw==", "dev": true, "dependencies": { "chalk": "^4.1.0", @@ -2698,10 +2698,10 @@ "yargs": "^16.2.0" }, "bin": { - "concurrently": "bin/concurrently.js" + "concurrently": "dist/bin/concurrently.js" }, "engines": { - "node": ">=10.0.0" + "node": "^12.20.0 || ^14.13.0 || >=16.0.0" } }, "node_modules/concurrently/node_modules/rxjs": { @@ -14486,9 +14486,9 @@ } }, "concurrently": { - "version": "6.4.0", - "resolved": "https://registry.npmjs.org/concurrently/-/concurrently-6.4.0.tgz", - "integrity": "sha512-HZ3D0RTQMH3oS4gvtYj1P+NBc6PzE2McEra6yEFcQKrUQ9HvtTGU4Dbne083F034p+LRb7kWU0tPRNvSGs1UCQ==", + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/concurrently/-/concurrently-7.0.0.tgz", + "integrity": "sha512-WKM7PUsI8wyXpF80H+zjHP32fsgsHNQfPLw/e70Z5dYkV7hF+rf8q3D+ScWJIEr57CpkO3OWBko6hwhQLPR8Pw==", "dev": true, "requires": { "chalk": "^4.1.0", diff --git a/package.json b/package.json index 86d463d13..19200ee78 100644 --- a/package.json +++ b/package.json @@ -72,7 +72,7 @@ "chai": "^4.2.0", "clang-format": "^1.6.0", "closure-calculate-chunks": "^3.0.2", - "concurrently": "^6.0.0", + "concurrently": "^7.0.0", "eslint": "^8.4.1", "eslint-config-google": "^0.14.0", "google-closure-compiler": "^20211201.0.0", From 18b56d5da8ba7b4d8fe65057ca7cbbd976f0a42f Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 6 Jan 2022 10:53:45 -0800 Subject: [PATCH 023/128] chore(deps): bump eslint from 8.4.1 to 8.6.0 (#5850) Bumps [eslint](https://github.com/eslint/eslint) from 8.4.1 to 8.6.0. - [Release notes](https://github.com/eslint/eslint/releases) - [Changelog](https://github.com/eslint/eslint/blob/main/CHANGELOG.md) - [Commits](https://github.com/eslint/eslint/compare/v8.4.1...v8.6.0) --- updated-dependencies: - dependency-name: eslint dependency-type: direct:development update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- package-lock.json | 44 ++++++++++++++++++++++---------------------- 1 file changed, 22 insertions(+), 22 deletions(-) diff --git a/package-lock.json b/package-lock.json index 0b22ecbdb..6287fd81e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1039,9 +1039,9 @@ } }, "node_modules/acorn": { - "version": "8.6.0", - "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.6.0.tgz", - "integrity": "sha512-U1riIR+lBSNi3IbxtaHOIKdH8sLFv3NYfNv8sg7ZsNhcfl4HF2++BfqqrNAxoCLQW1iiylOj76ecnaUxz+z9yw==", + "version": "8.7.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.7.0.tgz", + "integrity": "sha512-V/LGr1APy+PXIwKebEWrkZPwoeoF+w1jiOBUmuxuiUIaOHtob8Qc9BTrYo7VuI5fR8tqsy+buA2WFooR5olqvQ==", "dev": true, "bin": { "acorn": "bin/acorn" @@ -3613,9 +3613,9 @@ } }, "node_modules/eslint": { - "version": "8.4.1", - "resolved": "https://registry.npmjs.org/eslint/-/eslint-8.4.1.tgz", - "integrity": "sha512-TxU/p7LB1KxQ6+7aztTnO7K0i+h0tDi81YRY9VzB6Id71kNz+fFYnf5HD5UOQmxkzcoa0TlVZf9dpMtUv0GpWg==", + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-8.6.0.tgz", + "integrity": "sha512-UvxdOJ7mXFlw7iuHZA4jmzPaUqIw54mZrv+XPYKNbKdLR0et4rf60lIZUU9kiNtnzzMzGWxMV+tQ7uG7JG8DPw==", "dev": true, "dependencies": { "@eslint/eslintrc": "^1.0.5", @@ -3630,7 +3630,7 @@ "eslint-scope": "^7.1.0", "eslint-utils": "^3.0.0", "eslint-visitor-keys": "^3.1.0", - "espree": "^9.2.0", + "espree": "^9.3.0", "esquery": "^1.4.0", "esutils": "^2.0.2", "fast-deep-equal": "^3.1.3", @@ -3750,12 +3750,12 @@ } }, "node_modules/espree": { - "version": "9.2.0", - "resolved": "https://registry.npmjs.org/espree/-/espree-9.2.0.tgz", - "integrity": "sha512-oP3utRkynpZWF/F2x/HZJ+AGtnIclaR7z1pYPxy7NYM2fSO6LgK/Rkny8anRSPK/VwEA1eqm2squui0T7ZMOBg==", + "version": "9.3.0", + "resolved": "https://registry.npmjs.org/espree/-/espree-9.3.0.tgz", + "integrity": "sha512-d/5nCsb0JcqsSEeQzFZ8DH1RmxPcglRWh24EFTlUEmCKoehXGdpsx0RkHDubqUI8LSAIKMQp4r9SzQ3n+sm4HQ==", "dev": true, "dependencies": { - "acorn": "^8.6.0", + "acorn": "^8.7.0", "acorn-jsx": "^5.3.1", "eslint-visitor-keys": "^3.1.0" }, @@ -13212,9 +13212,9 @@ } }, "acorn": { - "version": "8.6.0", - "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.6.0.tgz", - "integrity": "sha512-U1riIR+lBSNi3IbxtaHOIKdH8sLFv3NYfNv8sg7ZsNhcfl4HF2++BfqqrNAxoCLQW1iiylOj76ecnaUxz+z9yw==", + "version": "8.7.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.7.0.tgz", + "integrity": "sha512-V/LGr1APy+PXIwKebEWrkZPwoeoF+w1jiOBUmuxuiUIaOHtob8Qc9BTrYo7VuI5fR8tqsy+buA2WFooR5olqvQ==", "dev": true }, "acorn-globals": { @@ -15245,9 +15245,9 @@ } }, "eslint": { - "version": "8.4.1", - "resolved": "https://registry.npmjs.org/eslint/-/eslint-8.4.1.tgz", - "integrity": "sha512-TxU/p7LB1KxQ6+7aztTnO7K0i+h0tDi81YRY9VzB6Id71kNz+fFYnf5HD5UOQmxkzcoa0TlVZf9dpMtUv0GpWg==", + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-8.6.0.tgz", + "integrity": "sha512-UvxdOJ7mXFlw7iuHZA4jmzPaUqIw54mZrv+XPYKNbKdLR0et4rf60lIZUU9kiNtnzzMzGWxMV+tQ7uG7JG8DPw==", "dev": true, "requires": { "@eslint/eslintrc": "^1.0.5", @@ -15262,7 +15262,7 @@ "eslint-scope": "^7.1.0", "eslint-utils": "^3.0.0", "eslint-visitor-keys": "^3.1.0", - "espree": "^9.2.0", + "espree": "^9.3.0", "esquery": "^1.4.0", "esutils": "^2.0.2", "fast-deep-equal": "^3.1.3", @@ -15350,12 +15350,12 @@ "dev": true }, "espree": { - "version": "9.2.0", - "resolved": "https://registry.npmjs.org/espree/-/espree-9.2.0.tgz", - "integrity": "sha512-oP3utRkynpZWF/F2x/HZJ+AGtnIclaR7z1pYPxy7NYM2fSO6LgK/Rkny8anRSPK/VwEA1eqm2squui0T7ZMOBg==", + "version": "9.3.0", + "resolved": "https://registry.npmjs.org/espree/-/espree-9.3.0.tgz", + "integrity": "sha512-d/5nCsb0JcqsSEeQzFZ8DH1RmxPcglRWh24EFTlUEmCKoehXGdpsx0RkHDubqUI8LSAIKMQp4r9SzQ3n+sm4HQ==", "dev": true, "requires": { - "acorn": "^8.6.0", + "acorn": "^8.7.0", "acorn-jsx": "^5.3.1", "eslint-visitor-keys": "^3.1.0" } From 2adf326c230589800880faa9599eca2ecc94d283 Mon Sep 17 00:00:00 2001 From: alschmiedt Date: Thu, 6 Jan 2022 11:28:27 -0800 Subject: [PATCH 024/128] fix: update the playground to load compressed when hosted (#5835) --- tests/multi_playground.html | 23 +- tests/playground.html | 33 +- tests/playgrounds/compressed.html | 1211 ----------------------- tests/playgrounds/load_all.js | 53 + tests/playgrounds/multi_compressed.html | 470 --------- 5 files changed, 80 insertions(+), 1710 deletions(-) delete mode 100644 tests/playgrounds/compressed.html create mode 100644 tests/playgrounds/load_all.js delete mode 100644 tests/playgrounds/multi_compressed.html diff --git a/tests/multi_playground.html b/tests/multi_playground.html index 0cabadb6d..da48e2c85 100644 --- a/tests/multi_playground.html +++ b/tests/multi_playground.html @@ -3,15 +3,16 @@ Multi-toolbox Playground - - - + + + - - - -
- -

Blockly Playground

- -

Show - - Hide - - Advanced

- -
- - -
-

- - - -
- - - - - -
- -

- -

- Stress test:   - - - -

-
    -
  • - - -
  • -
  • - - -
  • -
- - - - - - - - - - - - - - diff --git a/tests/playgrounds/load_all.js b/tests/playgrounds/load_all.js new file mode 100644 index 000000000..a444e8cd3 --- /dev/null +++ b/tests/playgrounds/load_all.js @@ -0,0 +1,53 @@ +/** + * @license + * Copyright 2021 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ + +/** + * @fileoverview Loads uncompressed Blockly when running locally. Loads + * compressed otherwise. + */ +'use strict'; + + +/** + * Loads all the compressed or uncompressed dependencies necessary to run the + * playground. This is necessary since the goog.module conversion. Please see + * issue #5557 for more information. + */ +(function() { +const isIe = navigator.userAgent.indexOf('MSIE') !== -1 || + navigator.appVersion.indexOf('Trident/') > -1; + +if ((location.hostname === 'localhost' || location.hostname === '127.0.0.1' || + location.hostname === '[::1]') && + !isIe) { + document.write( + ``); + document.write(``); + document.write(``); + document.write( + ``); + document.write(``); +} else { + document.write( + ``); + document.write(``); + document.write(``); + document.write(``); + document.write(``); + document.write(``); + document.write(``); + document.write(``); +} +})(); diff --git a/tests/playgrounds/multi_compressed.html b/tests/playgrounds/multi_compressed.html deleted file mode 100644 index 29f0ae383..000000000 --- a/tests/playgrounds/multi_compressed.html +++ /dev/null @@ -1,470 +0,0 @@ - - - - -Multi-toolbox Compressed Playground - - - - - - - - -

Blockly Multi Playground

- -
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
LTR, Vertical, StartRTL, Vertical, Start
LTR, Vertical, EndRTL, Vertical, End
LTR, Horizontal, StartRTL, Horizontal, Start
LTR, Horizontal, EndRTL, Horizontal, End
- - - - - - From 69642f74eaa04956c74aac00dc1fb329e7372f2e Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 6 Jan 2022 11:32:03 -0800 Subject: [PATCH 025/128] chore(deps): bump google-closure-deps from 20211107.0.0 to 20211201.0.0 (#5852) Bumps [google-closure-deps](https://github.com/google/closure-library) from 20211107.0.0 to 20211201.0.0. - [Release notes](https://github.com/google/closure-library/releases) - [Commits](https://github.com/google/closure-library/compare/v20211107...v20211201) --- updated-dependencies: - dependency-name: google-closure-deps dependency-type: direct:development update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- package-lock.json | 14 +++++++------- package.json | 2 +- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/package-lock.json b/package-lock.json index 6287fd81e..c4616b0c0 100644 --- a/package-lock.json +++ b/package-lock.json @@ -22,7 +22,7 @@ "eslint": "^8.4.1", "eslint-config-google": "^0.14.0", "google-closure-compiler": "^20211201.0.0", - "google-closure-deps": "^20211107.0.0", + "google-closure-deps": "^20211201.0.0", "gulp": "^4.0.2", "gulp-clang-format": "^1.0.27", "gulp-concat": "^2.6.1", @@ -5118,9 +5118,9 @@ } }, "node_modules/google-closure-deps": { - "version": "20211107.0.0", - "resolved": "https://registry.npmjs.org/google-closure-deps/-/google-closure-deps-20211107.0.0.tgz", - "integrity": "sha512-RkxMNY9U+AcVRc70oY95pz1TeAmS8yHwwfyN+LZ5Jrx+mBg9k+UYoE2rS8SiwcF/VjyOHlfw2sw6GIUO56hXCg==", + "version": "20211201.0.0", + "resolved": "https://registry.npmjs.org/google-closure-deps/-/google-closure-deps-20211201.0.0.tgz", + "integrity": "sha512-mVjOs2kue01UDuaNqULzSAuuXd/zXTxSO/838ePmfi7mg9vQRr/H2d9xUk9441ryg6+pI1pgEDB5HRWhrsV3aQ==", "dev": true, "dependencies": { "minimatch": "^3.0.4", @@ -16421,9 +16421,9 @@ "optional": true }, "google-closure-deps": { - "version": "20211107.0.0", - "resolved": "https://registry.npmjs.org/google-closure-deps/-/google-closure-deps-20211107.0.0.tgz", - "integrity": "sha512-RkxMNY9U+AcVRc70oY95pz1TeAmS8yHwwfyN+LZ5Jrx+mBg9k+UYoE2rS8SiwcF/VjyOHlfw2sw6GIUO56hXCg==", + "version": "20211201.0.0", + "resolved": "https://registry.npmjs.org/google-closure-deps/-/google-closure-deps-20211201.0.0.tgz", + "integrity": "sha512-mVjOs2kue01UDuaNqULzSAuuXd/zXTxSO/838ePmfi7mg9vQRr/H2d9xUk9441ryg6+pI1pgEDB5HRWhrsV3aQ==", "dev": true, "requires": { "minimatch": "^3.0.4", diff --git a/package.json b/package.json index 19200ee78..59ba7e6f5 100644 --- a/package.json +++ b/package.json @@ -76,7 +76,7 @@ "eslint": "^8.4.1", "eslint-config-google": "^0.14.0", "google-closure-compiler": "^20211201.0.0", - "google-closure-deps": "^20211107.0.0", + "google-closure-deps": "^20211201.0.0", "gulp": "^4.0.2", "gulp-clang-format": "^1.0.27", "gulp-concat": "^2.6.1", From df2eafb8ddb5bf4e1f6091b4199f9de600ea5582 Mon Sep 17 00:00:00 2001 From: Rachel Fenichel Date: Thu, 6 Jan 2022 13:13:40 -0800 Subject: [PATCH 026/128] refactor: move properties into constructors and convert to classes (#5822) * refactor: move properties to constructor in block_drag_surface.js * refactor: move properties to constructor in block_svg.js * refactor: move properties to constructor in block.js * refactor: move properties to constructor in bubble.js * refactor: move properties to constructor in connection.js * refactor: move properties to constructor in flyout_base.js * refactor: move properties to constructor in flyout_button.js * refactor: move properties to constructor in generator.js * refactor: move properties to constructor in grid.js * refactor: move properties to constructor in input.js * refactor: move properties to constructor in mutator.js * refactor: move properties to constructor in scrollbar.js * refactor: move properties to constructor in trashcan.js * refactor: move properties to constructor in warning.js * refactor: move properties to constructor in workspace_audio.js * refactor: move properties to constructor in workspace_drag_surface_svg.js * refactor: move properties to constructor in workspace_svg.js * refactor: move properties to constructor in workspace.js * refactor: move properties to constructor in zoom_controls.js * chore: rebuild * refactor: convert zoom_controls.js to es6 class and format * refactor: convert workspace_audio.js to es6 class and format * refactor: convert workspace_dragger.js to es6 class and format * refactor: convert workspace_drag_surface_svg.js to es6 class and format * refactor: convert variable_model.js to es6 class and format * refactor: convert variable_map.js to es6 class and format * refactor: convert theme.js to es6 class and format * chore: remove bad comment --- core/block.js | 191 +++---- core/block_drag_surface.js | 90 ++- core/block_svg.js | 161 +++--- core/bubble.js | 98 ++-- core/connection.js | 83 ++- core/flyout_base.js | 178 +++--- core/flyout_button.js | 24 +- core/generator.js | 106 ++-- core/grid.js | 16 +- core/input.js | 25 +- core/mutator.js | 40 +- core/scrollbar.js | 118 ++-- core/theme.js | 274 +++++---- core/trashcan.js | 127 ++--- core/variable_map.js | 704 ++++++++++++----------- core/variable_model.js | 111 ++-- core/warning.js | 11 +- core/workspace.js | 53 +- core/workspace_audio.js | 242 ++++---- core/workspace_drag_surface_svg.js | 279 +++++----- core/workspace_dragger.js | 151 +++-- core/workspace_svg.js | 544 +++++++++--------- core/zoom_controls.js | 864 ++++++++++++++--------------- scripts/gulpfiles/chunks.json | 4 +- 24 files changed, 2242 insertions(+), 2252 deletions(-) diff --git a/core/block.js b/core/block.js index cda2e39a7..0b0226035 100644 --- a/core/block.js +++ b/core/block.js @@ -82,6 +82,94 @@ const Block = function(workspace, prototypeName, opt_id) { '" conflicts with Blockly.Generator members.'); } + /** + * Optional text data that round-trips between blocks and XML. + * Has no effect. May be used by 3rd parties for meta information. + * @type {?string} + */ + this.data = null; + + /** + * Has this block been disposed of? + * @type {boolean} + * @package + */ + this.disposed = false; + + /** + * Colour of the block as HSV hue value (0-360) + * This may be null if the block colour was not set via a hue number. + * @type {?number} + * @private + */ + this.hue_ = null; + + /** + * Colour of the block in '#RRGGBB' format. + * @type {string} + * @protected + */ + this.colour_ = '#000000'; + + /** + * Name of the block style. + * @type {string} + * @protected + */ + this.styleName_ = ''; + + /** + * An optional method called during initialization. + * @type {undefined|?function()} + */ + this.init = undefined; + + /** + * An optional serialization method for defining how to serialize the + * mutation state to XML. This must be coupled with defining `domToMutation`. + * @type {undefined|?function(...):!Element} + */ + this.mutationToDom = undefined; + + /** + * An optional deserialization method for defining how to deserialize the + * mutation state from XML. This must be coupled with defining + * `mutationToDom`. + * @type {undefined|?function(!Element)} + */ + this.domToMutation = undefined; + + /** + * An optional serialization method for defining how to serialize the block's + * extra state (eg mutation state) to something JSON compatible. This must be + * coupled with defining `loadExtraState`. + * @type {undefined|?function(): *} + */ + this.saveExtraState = undefined; + + /** + * An optional serialization method for defining how to deserialize the + * block's extra state (eg mutation state) from something JSON compatible. + * This must be coupled with defining `saveExtraState`. + * @type {undefined|?function(*)} + */ + this.loadExtraState = undefined; + + /** + * An optional property for suppressing adding STATEMENT_PREFIX and + * STATEMENT_SUFFIX to generated code. + * @type {?boolean} + */ + this.suppressPrefixSuffix = false; + + /** + * An optional property for declaring developer variables. Return a list of + * variable names for use by generators. Developer variables are never shown + * to the user, but are declared as global variables in the generated code. + * @type {undefined|?function():!Array} + */ + this.getDeveloperVariables = undefined; + /** @type {string} */ this.id = (opt_id && !workspace.getBlockById(opt_id)) ? opt_id : idGenerator.genUid(); @@ -271,6 +359,14 @@ const Block = function(workspace, prototypeName, opt_id) { */ Block.CommentModel; +/** + * An optional callback method to use whenever the block's parent workspace + * changes. This is usually only called from the constructor, the block type + * initializer function, or an extension initializer function. + * @type {undefined|?function(Abstract)} + */ +Block.prototype.onchange; + /** * The language-neutral ID given to the collapsed input. * @const {string} @@ -283,101 +379,6 @@ Block.COLLAPSED_INPUT_NAME = constants.COLLAPSED_INPUT_NAME; */ Block.COLLAPSED_FIELD_NAME = constants.COLLAPSED_FIELD_NAME; -/** - * Optional text data that round-trips between blocks and XML. - * Has no effect. May be used by 3rd parties for meta information. - * @type {?string} - */ -Block.prototype.data = null; - -/** - * Has this block been disposed of? - * @type {boolean} - * @package - */ -Block.prototype.disposed = false; - -/** - * Colour of the block as HSV hue value (0-360) - * This may be null if the block colour was not set via a hue number. - * @type {?number} - * @private - */ -Block.prototype.hue_ = null; - -/** - * Colour of the block in '#RRGGBB' format. - * @type {string} - * @protected - */ -Block.prototype.colour_ = '#000000'; - -/** - * Name of the block style. - * @type {string} - * @protected - */ -Block.prototype.styleName_ = ''; - -/** - * An optional method called during initialization. - * @type {?function()} - */ -Block.prototype.init; - -/** - * An optional callback method to use whenever the block's parent workspace - * changes. This is usually only called from the constructor, the block type - * initializer function, or an extension initializer function. - * @type {?function(Abstract)} - */ -Block.prototype.onchange; - -/** - * An optional serialization method for defining how to serialize the - * mutation state to XML. This must be coupled with defining `domToMutation`. - * @type {?function(...):!Element} - */ -Block.prototype.mutationToDom; - -/** - * An optional deserialization method for defining how to deserialize the - * mutation state from XML. This must be coupled with defining `mutationToDom`. - * @type {?function(!Element)} - */ -Block.prototype.domToMutation; - -/** - * An optional serialization method for defining how to serialize the block's - * extra state (eg mutation state) to something JSON compatible. This must be - * coupled with defining `loadExtraState`. - * @type {?function(): *} - */ -Block.prototype.saveExtraState; - -/** - * An optional serialization method for defining how to deserialize the block's - * extra state (eg mutation state) from something JSON compatible. This must be - * coupled with defining `saveExtraState`. - * @type {?function(*)} - */ -Block.prototype.loadExtraState; - -/** - * An optional property for suppressing adding STATEMENT_PREFIX and - * STATEMENT_SUFFIX to generated code. - * @type {?boolean} - */ -Block.prototype.suppressPrefixSuffix; - -/** - * An optional property for declaring developer variables. Return a list of - * variable names for use by generators. Developer variables are never shown to - * the user, but are declared as global variables in the generated code. - * @type {?function():!Array} - */ -Block.prototype.getDeveloperVariables; - /** * Dispose of this block. * @param {boolean} healStack If true, then try to heal any gap by connecting diff --git a/core/block_drag_surface.js b/core/block_drag_surface.js index ff619d390..7c7a64f17 100644 --- a/core/block_drag_surface.js +++ b/core/block_drag_surface.js @@ -41,60 +41,56 @@ const {Svg} = goog.require('Blockly.utils.Svg'); */ const BlockDragSurfaceSvg = function(container) { /** + * The SVG drag surface. Set once by BlockDragSurfaceSvg.createDom. + * @type {?SVGElement} + * @private + */ + this.SVG_ = null; + + /** + * This is where blocks live while they are being dragged if the drag surface + * is enabled. + * @type {?SVGElement} + * @private + */ + this.dragGroup_ = null; + + /** + * Containing HTML element; parent of the workspace and the drag surface. * @type {!Element} * @private */ this.container_ = container; + + /** + * Cached value for the scale of the drag surface. + * Used to set/get the correct translation during and after a drag. + * @type {number} + * @private + */ + this.scale_ = 1; + + /** + * Cached value for the translation of the drag surface. + * This translation is in pixel units, because the scale is applied to the + * drag group rather than the top-level SVG. + * @type {?Coordinate} + * @private + */ + this.surfaceXY_ = null; + + /** + * Cached value for the translation of the child drag surface in pixel units. + * Since the child drag surface tracks the translation of the workspace this + * is ultimately the translation of the workspace. + * @type {!Coordinate} + * @private + */ + this.childSurfaceXY_ = new Coordinate(0, 0); + this.createDom(); }; -/** - * The SVG drag surface. Set once by BlockDragSurfaceSvg.createDom. - * @type {?SVGElement} - * @private - */ -BlockDragSurfaceSvg.prototype.SVG_ = null; - -/** - * This is where blocks live while they are being dragged if the drag surface - * is enabled. - * @type {?SVGElement} - * @private - */ -BlockDragSurfaceSvg.prototype.dragGroup_ = null; - -/** - * Containing HTML element; parent of the workspace and the drag surface. - * @type {?Element} - * @private - */ -BlockDragSurfaceSvg.prototype.container_ = null; - -/** - * Cached value for the scale of the drag surface. - * Used to set/get the correct translation during and after a drag. - * @type {number} - * @private - */ -BlockDragSurfaceSvg.prototype.scale_ = 1; - -/** - * Cached value for the translation of the drag surface. - * This translation is in pixel units, because the scale is applied to the - * drag group rather than the top-level SVG. - * @type {?Coordinate} - * @private - */ -BlockDragSurfaceSvg.prototype.surfaceXY_ = null; - -/** - * Cached value for the translation of the child drag surface in pixel units. - * Since the child drag surface tracks the translation of the workspace this is - * ultimately the translation of the workspace. - * @type {!Coordinate} - * @private - */ -BlockDragSurfaceSvg.prototype.childSurfaceXY_ = new Coordinate(0, 0); /** * Create the drag surface and inject it into the container. diff --git a/core/block_svg.js b/core/block_svg.js index b3fcf2fc4..54dbdbefd 100644 --- a/core/block_svg.js +++ b/core/block_svg.js @@ -95,6 +95,88 @@ goog.require('Blockly.Touch'); * @alias Blockly.BlockSvg */ const BlockSvg = function(workspace, prototypeName, opt_id) { + /** + * An optional method called when a mutator dialog is first opened. + * This function must create and initialize a top-level block for the mutator + * dialog, and return it. This function should also populate this top-level + * block with any sub-blocks which are appropriate. This method must also be + * coupled with defining a `compose` method for the default mutation dialog + * button and UI to appear. + * @type {undefined|?function(WorkspaceSvg):!BlockSvg} + */ + this.decompose = undefined; + + /** + * An optional method called when a mutator dialog saves its content. + * This function is called to modify the original block according to new + * settings. This method must also be coupled with defining a `decompose` + * method for the default mutation dialog button and UI to appear. + * @type {undefined|?function(!BlockSvg)} + */ + this.compose = undefined; + + /** + * An optional method for defining custom block context menu items. + * @type {undefined|?function(!Array)} + */ + this.customContextMenu = undefined; + + /** + * An property used internally to reference the block's rendering debugger. + * @type {?BlockRenderingDebug} + * @package + */ + this.renderingDebugger = null; + + /** + * Height of this block, not including any statement blocks above or below. + * Height is in workspace units. + * @type {number} + */ + this.height = 0; + + /** + * Width of this block, including any connected value blocks. + * Width is in workspace units. + * @type {number} + */ + this.width = 0; + + /** + * Map from IDs for warnings text to PIDs of functions to apply them. + * Used to be able to maintain multiple warnings. + * @type {Object} + * @private + */ + this.warningTextDb_ = null; + + /** + * Block's mutator icon (if any). + * @type {?Mutator} + */ + this.mutator = null; + + /** + * Block's comment icon (if any). + * @type {?Comment} + * @deprecated August 2019. Use getCommentIcon instead. + */ + this.comment = null; + + /** + * Block's comment icon (if any). + * @type {?Comment} + * @private + */ + this.commentIcon_ = null; + + /** + * Block's warning icon (if any). + * @type {?Warning} + */ + this.warning = null; + + // Create core elements for the block. /** * @type {!SVGGElement} @@ -163,26 +245,6 @@ const BlockSvg = function(workspace, prototypeName, opt_id) { }; object.inherits(BlockSvg, Block); -/** - * Height of this block, not including any statement blocks above or below. - * Height is in workspace units. - */ -BlockSvg.prototype.height = 0; - -/** - * Width of this block, including any connected value blocks. - * Width is in workspace units. - */ -BlockSvg.prototype.width = 0; - -/** - * Map from IDs for warnings text to PIDs of functions to apply them. - * Used to be able to maintain multiple warnings. - * @type {Object} - * @private - */ -BlockSvg.prototype.warningTextDb_ = null; - /** * Constant for identifying rows that are to be rendered inline. * Don't collide with Blockly.inputTypes. @@ -199,39 +261,6 @@ BlockSvg.INLINE = -1; */ BlockSvg.COLLAPSED_WARNING_ID = 'TEMP_COLLAPSED_WARNING_'; -/** - * An optional method called when a mutator dialog is first opened. - * This function must create and initialize a top-level block for the mutator - * dialog, and return it. This function should also populate this top-level - * block with any sub-blocks which are appropriate. This method must also be - * coupled with defining a `compose` method for the default mutation dialog - * button and UI to appear. - * @type {?function(WorkspaceSvg):!BlockSvg} - */ -BlockSvg.prototype.decompose; - -/** - * An optional method called when a mutator dialog saves its content. - * This function is called to modify the original block according to new - * settings. This method must also be coupled with defining a `decompose` - * method for the default mutation dialog button and UI to appear. - * @type {?function(!BlockSvg)} - */ -BlockSvg.prototype.compose; - -/** - * An optional method for defining custom block context menu items. - * @type {?function(!Array)} - */ -BlockSvg.prototype.customContextMenu; - -/** - * An property used internally to reference the block's rendering debugger. - * @type {?BlockRenderingDebug} - * @package - */ -BlockSvg.prototype.renderingDebugger; - /** * Create and initialize the SVG representation of the block. * May be called more than once. @@ -323,32 +352,6 @@ BlockSvg.prototype.unselect = function() { this.removeSelect(); }; -/** - * Block's mutator icon (if any). - * @type {?Mutator} - */ -BlockSvg.prototype.mutator = null; - -/** - * Block's comment icon (if any). - * @type {?Comment} - * @deprecated August 2019. Use getCommentIcon instead. - */ -BlockSvg.prototype.comment = null; - -/** - * Block's comment icon (if any). - * @type {?Comment} - * @private - */ -BlockSvg.prototype.commentIcon_ = null; - -/** - * Block's warning icon (if any). - * @type {?Warning} - */ -BlockSvg.prototype.warning = null; - /** * Returns a list of mutator, comment, and warning icons. * @return {!Array} List of icons. diff --git a/core/bubble.js b/core/bubble.js index d9e6df9f0..78799c0ec 100644 --- a/core/bubble.js +++ b/core/bubble.js @@ -58,6 +58,58 @@ const Bubble = function( this.content_ = content; this.shape_ = shape; + /** + * Flag to stop incremental rendering during construction. + * @type {boolean} + * @private + */ + this.rendered_ = false; + + /** + * Absolute coordinate of anchor point, in workspace coordinates. + * @type {Coordinate} + * @private + */ + this.anchorXY_ = null; + + /** + * Relative X coordinate of bubble with respect to the anchor's centre, + * in workspace units. + * In RTL mode the initial value is negated. + * @type {number} + * @private + */ + this.relativeLeft_ = 0; + + /** + * Relative Y coordinate of bubble with respect to the anchor's centre, in + * workspace units. + * @type {number} + * @private + */ + this.relativeTop_ = 0; + + /** + * Width of bubble, in workspace units. + * @type {number} + * @private + */ + this.width_ = 0; + + /** + * Height of bubble, in workspace units. + * @type {number} + * @private + */ + this.height_ = 0; + + /** + * Automatically position and reposition the bubble. + * @type {boolean} + * @private + */ + this.autoLayout_ = true; + /** * Method to call on resize of bubble. * @type {?function()} @@ -182,52 +234,6 @@ Bubble.bubbleMouseUp_ = function(_e) { Bubble.unbindDragEvents_(); }; -/** - * Flag to stop incremental rendering during construction. - * @private - */ -Bubble.prototype.rendered_ = false; - -/** - * Absolute coordinate of anchor point, in workspace coordinates. - * @type {Coordinate} - * @private - */ -Bubble.prototype.anchorXY_ = null; - -/** - * Relative X coordinate of bubble with respect to the anchor's centre, - * in workspace units. - * In RTL mode the initial value is negated. - * @private - */ -Bubble.prototype.relativeLeft_ = 0; - -/** - * Relative Y coordinate of bubble with respect to the anchor's centre, in - * workspace units. - * @private - */ -Bubble.prototype.relativeTop_ = 0; - -/** - * Width of bubble, in workspace units. - * @private - */ -Bubble.prototype.width_ = 0; - -/** - * Height of bubble, in workspace units. - * @private - */ -Bubble.prototype.height_ = 0; - -/** - * Automatically position and reposition the bubble. - * @private - */ -Bubble.prototype.autoLayout_ = true; - /** * Create the bubble's DOM. * @param {!Element} content SVG content for the bubble. diff --git a/core/connection.js b/core/connection.js index 25f31bbe5..3273ab100 100644 --- a/core/connection.js +++ b/core/connection.js @@ -49,6 +49,47 @@ const Connection = function(source, type) { this.sourceBlock_ = source; /** @type {number} */ this.type = type; + + /** + * Connection this connection connects to. Null if not connected. + * @type {Connection} + */ + this.targetConnection = null; + + /** + * Has this connection been disposed of? + * @type {boolean} + * @package + */ + this.disposed = false; + + /** + * List of compatible value types. Null if all types are compatible. + * @type {Array} + * @private + */ + this.check_ = null; + + /** + * DOM representation of a shadow block, or null if none. + * @type {Element} + * @private + */ + this.shadowDom_ = null; + + /** + * Horizontal location of this connection. + * @type {number} + * @package + */ + this.x = 0; + + /** + * Vertical location of this connection. + * @type {number} + * @package + */ + this.y = 0; }; /** @@ -64,47 +105,6 @@ Connection.REASON_SHADOW_PARENT = 6; Connection.REASON_DRAG_CHECKS_FAILED = 7; Connection.REASON_PREVIOUS_AND_OUTPUT = 8; -/** - * Connection this connection connects to. Null if not connected. - * @type {Connection} - */ -Connection.prototype.targetConnection = null; - -/** - * Has this connection been disposed of? - * @type {boolean} - * @package - */ -Connection.prototype.disposed = false; - -/** - * List of compatible value types. Null if all types are compatible. - * @type {Array} - * @private - */ -Connection.prototype.check_ = null; - -/** - * DOM representation of a shadow block, or null if none. - * @type {Element} - * @private - */ -Connection.prototype.shadowDom_ = null; - -/** - * Horizontal location of this connection. - * @type {number} - * @package - */ -Connection.prototype.x = 0; - -/** - * Vertical location of this connection. - * @type {number} - * @package - */ -Connection.prototype.y = 0; - /** * Connect two connections together. This is the connection on the superior * block. @@ -163,7 +163,6 @@ Connection.prototype.connect_ = function(childConnection) { } }; - /** * Dispose of this connection and deal with connected blocks. * @package diff --git a/core/flyout_base.js b/core/flyout_base.js index d1484ffa8..5e8f1c6cc 100644 --- a/core/flyout_base.js +++ b/core/flyout_base.js @@ -167,98 +167,98 @@ const Flyout = function(workspaceOptions) { * @private */ this.recycledBlocks_ = []; + + /** + * Does the flyout automatically close when a block is created? + * @type {boolean} + */ + this.autoClose = true; + + /** + * Whether the flyout is visible. + * @type {boolean} + * @private + */ + this.isVisible_ = false; + + /** + * Whether the workspace containing this flyout is visible. + * @type {boolean} + * @private + */ + this.containerVisible_ = true; + + /** + * Corner radius of the flyout background. + * @type {number} + * @const + */ + this.CORNER_RADIUS = 8; + + /** + * Margin around the edges of the blocks in the flyout. + * @type {number} + * @const + */ + this.MARGIN = this.CORNER_RADIUS; + + // TODO: Move GAP_X and GAP_Y to their appropriate files. + + /** + * Gap between items in horizontal flyouts. Can be overridden with the "sep" + * element. + * @const {number} + */ + this.GAP_X = this.MARGIN * 3; + + /** + * Gap between items in vertical flyouts. Can be overridden with the "sep" + * element. + * @const {number} + */ + this.GAP_Y = this.MARGIN * 3; + + /** + * Top/bottom padding between scrollbar and edge of flyout background. + * @type {number} + * @const + */ + this.SCROLLBAR_MARGIN = 2.5; + + /** + * Width of flyout. + * @type {number} + * @protected + */ + this.width_ = 0; + + /** + * Height of flyout. + * @type {number} + * @protected + */ + this.height_ = 0; + + /** + * Range of a drag angle from a flyout considered "dragging toward workspace". + * Drags that are within the bounds of this many degrees from the orthogonal + * line to the flyout edge are considered to be "drags toward the workspace". + * Example: + * Flyout Edge Workspace + * [block] / <-within this angle, drags "toward workspace" | + * [block] ---- orthogonal to flyout boundary ---- | + * [block] \ | + * The angle is given in degrees from the orthogonal. + * + * This is used to know when to create a new block and when to scroll the + * flyout. Setting it to 360 means that all drags create a new block. + * @type {number} + * @protected + */ + this.dragAngleRange_ = 70; }; object.inherits(Flyout, DeleteArea); -/** - * Does the flyout automatically close when a block is created? - * @type {boolean} - */ -Flyout.prototype.autoClose = true; - -/** - * Whether the flyout is visible. - * @type {boolean} - * @private - */ -Flyout.prototype.isVisible_ = false; - -/** - * Whether the workspace containing this flyout is visible. - * @type {boolean} - * @private - */ -Flyout.prototype.containerVisible_ = true; - -/** - * Corner radius of the flyout background. - * @type {number} - * @const - */ -Flyout.prototype.CORNER_RADIUS = 8; - -/** - * Margin around the edges of the blocks in the flyout. - * @type {number} - * @const - */ -Flyout.prototype.MARGIN = Flyout.prototype.CORNER_RADIUS; - -// TODO: Move GAP_X and GAP_Y to their appropriate files. - -/** - * Gap between items in horizontal flyouts. Can be overridden with the "sep" - * element. - * @const {number} - */ -Flyout.prototype.GAP_X = Flyout.prototype.MARGIN * 3; - -/** - * Gap between items in vertical flyouts. Can be overridden with the "sep" - * element. - * @const {number} - */ -Flyout.prototype.GAP_Y = Flyout.prototype.MARGIN * 3; - -/** - * Top/bottom padding between scrollbar and edge of flyout background. - * @type {number} - * @const - */ -Flyout.prototype.SCROLLBAR_MARGIN = 2.5; - -/** - * Width of flyout. - * @type {number} - * @protected - */ -Flyout.prototype.width_ = 0; - -/** - * Height of flyout. - * @type {number} - * @protected - */ -Flyout.prototype.height_ = 0; - -/** - * Range of a drag angle from a flyout considered "dragging toward workspace". - * Drags that are within the bounds of this many degrees from the orthogonal - * line to the flyout edge are considered to be "drags toward the workspace". - * Example: - * Flyout Edge Workspace - * [block] / <-within this angle, drags "toward workspace" | - * [block] ---- orthogonal to flyout boundary ---- | - * [block] \ | - * The angle is given in degrees from the orthogonal. - * - * This is used to know when to create a new block and when to scroll the - * flyout. Setting it to 360 means that all drags create a new block. - * @type {number} - * @protected - */ -Flyout.prototype.dragAngleRange_ = 70; - /** * Creates the flyout's DOM. Only needs to be called once. The flyout can * either exist as its own SVG element or be a g element nested inside a diff --git a/core/flyout_button.js b/core/flyout_button.js index 6ade89e2d..a76b0fa85 100644 --- a/core/flyout_button.js +++ b/core/flyout_button.js @@ -102,6 +102,18 @@ const FlyoutButton = function(workspace, targetWorkspace, json, isLabel) { * @type {!toolbox.ButtonOrLabelInfo} */ this.info = json; + + /** + * The width of the button's rect. + * @type {number} + */ + this.width = 0; + + /** + * The height of the button's rect. + * @type {number} + */ + this.height = 0; }; /** @@ -114,18 +126,6 @@ FlyoutButton.MARGIN_X = 5; */ FlyoutButton.MARGIN_Y = 2; -/** - * The width of the button's rect. - * @type {number} - */ -FlyoutButton.prototype.width = 0; - -/** - * The height of the button's rect. - * @type {number} - */ -FlyoutButton.prototype.height = 0; - /** * Create the button elements. * @return {!SVGElement} The button's SVG group. diff --git a/core/generator.js b/core/generator.js index 6e8a7bfa7..55b7f9095 100644 --- a/core/generator.js +++ b/core/generator.js @@ -37,61 +37,61 @@ const Generator = function(name) { this.name_ = name; this.FUNCTION_NAME_PLACEHOLDER_REGEXP_ = new RegExp(this.FUNCTION_NAME_PLACEHOLDER_, 'g'); + + /** + * Arbitrary code to inject into locations that risk causing infinite loops. + * Any instances of '%1' will be replaced by the block ID that failed. + * E.g. ' checkTimeout(%1);\n' + * @type {?string} + */ + this.INFINITE_LOOP_TRAP = null; + + /** + * Arbitrary code to inject before every statement. + * Any instances of '%1' will be replaced by the block ID of the statement. + * E.g. 'highlight(%1);\n' + * @type {?string} + */ + this.STATEMENT_PREFIX = null; + + /** + * Arbitrary code to inject after every statement. + * Any instances of '%1' will be replaced by the block ID of the statement. + * E.g. 'highlight(%1);\n' + * @type {?string} + */ + this.STATEMENT_SUFFIX = null; + + /** + * The method of indenting. Defaults to two spaces, but language generators + * may override this to increase indent or change to tabs. + * @type {string} + */ + this.INDENT = ' '; + + /** + * Maximum length for a comment before wrapping. Does not account for + * indenting level. + * @type {number} + */ + this.COMMENT_WRAP = 60; + + /** + * List of outer-inner pairings that do NOT require parentheses. + * @type {!Array>} + */ + this.ORDER_OVERRIDES = []; + + /** + * Whether the init method has been called. + * Generators that set this flag to false after creation and true in init + * will cause blockToCode to emit a warning if the generator has not been + * initialized. If this flag is untouched, it will have no effect. + * @type {?boolean} + */ + this.isInitialized = null; }; -/** - * Arbitrary code to inject into locations that risk causing infinite loops. - * Any instances of '%1' will be replaced by the block ID that failed. - * E.g. ' checkTimeout(%1);\n' - * @type {?string} - */ -Generator.prototype.INFINITE_LOOP_TRAP = null; - -/** - * Arbitrary code to inject before every statement. - * Any instances of '%1' will be replaced by the block ID of the statement. - * E.g. 'highlight(%1);\n' - * @type {?string} - */ -Generator.prototype.STATEMENT_PREFIX = null; - -/** - * Arbitrary code to inject after every statement. - * Any instances of '%1' will be replaced by the block ID of the statement. - * E.g. 'highlight(%1);\n' - * @type {?string} - */ -Generator.prototype.STATEMENT_SUFFIX = null; - -/** - * The method of indenting. Defaults to two spaces, but language generators - * may override this to increase indent or change to tabs. - * @type {string} - */ -Generator.prototype.INDENT = ' '; - -/** - * Maximum length for a comment before wrapping. Does not account for - * indenting level. - * @type {number} - */ -Generator.prototype.COMMENT_WRAP = 60; - -/** - * List of outer-inner pairings that do NOT require parentheses. - * @type {!Array>} - */ -Generator.prototype.ORDER_OVERRIDES = []; - -/** - * Whether the init method has been called. - * Generators that set this flag to false after creation and true in init - * will cause blockToCode to emit a warning if the generator has not been - * initialized. If this flag is untouched, it will have no effect. - * @type {?boolean} - */ -Generator.prototype.isInitialized = null; - /** * Generate code for all blocks in the workspace to the specified language. * @param {!Workspace=} workspace Workspace to generate code from. diff --git a/core/grid.js b/core/grid.js index a16d3f083..950175607 100644 --- a/core/grid.js +++ b/core/grid.js @@ -33,6 +33,14 @@ const {Svg} = goog.require('Blockly.utils.Svg'); * @alias Blockly.Grid */ const Grid = function(pattern, options) { + /** + * The scale of the grid, used to set stroke width on grid lines. + * This should always be the same as the workspace scale. + * @type {number} + * @private + */ + this.scale_ = 1; + /** * The grid's SVG pattern, created during injection. * @type {!SVGElement} @@ -77,14 +85,6 @@ const Grid = function(pattern, options) { this.snapToGrid_ = options['snap']; }; -/** - * The scale of the grid, used to set stroke width on grid lines. - * This should always be the same as the workspace scale. - * @type {number} - * @private - */ -Grid.prototype.scale_ = 1; - /** * Dispose of this grid and unlink from the DOM. * @package diff --git a/core/input.js b/core/input.js index edc0c5c62..318063022 100644 --- a/core/input.js +++ b/core/input.js @@ -69,20 +69,21 @@ const Input = function(type, name, block, connection) { this.connection = connection; /** @type {!Array} */ this.fieldRow = []; + + /** + * Alignment of input's fields (left, right or centre). + * @type {number} + */ + this.align = Align.LEFT; + + /** + * Is the input visible? + * @type {boolean} + * @private + */ + this.visible_ = true; }; -/** - * Alignment of input's fields (left, right or centre). - * @type {number} - */ -Input.prototype.align = Align.LEFT; - -/** - * Is the input visible? - * @type {boolean} - * @private - */ -Input.prototype.visible_ = true; /** * Get the source block for this input. diff --git a/core/mutator.js b/core/mutator.js index f8c95326c..bbadd41ea 100644 --- a/core/mutator.js +++ b/core/mutator.js @@ -57,28 +57,30 @@ goog.require('Blockly.Events.BubbleOpen'); const Mutator = function(quarkNames) { Mutator.superClass_.constructor.call(this, null); this.quarkNames_ = quarkNames; + + /** + * Workspace in the mutator's bubble. + * @type {?WorkspaceSvg} + * @private + */ + this.workspace_ = null; + + /** + * Width of workspace. + * @type {number} + * @private + */ + this.workspaceWidth_ = 0; + + /** + * Height of workspace. + * @type {number} + * @private + */ + this.workspaceHeight_ = 0; }; object.inherits(Mutator, Icon); -/** - * Workspace in the mutator's bubble. - * @type {?WorkspaceSvg} - * @private - */ -Mutator.prototype.workspace_ = null; - -/** - * Width of workspace. - * @private - */ -Mutator.prototype.workspaceWidth_ = 0; - -/** - * Height of workspace. - * @private - */ -Mutator.prototype.workspaceHeight_ = 0; - /** * Set the block this mutator is associated with. * @param {!BlockSvg} block The block associated with this mutator. diff --git a/core/scrollbar.js b/core/scrollbar.js index 42b7d9953..45f4fa5fe 100644 --- a/core/scrollbar.js +++ b/core/scrollbar.js @@ -87,6 +87,66 @@ const Scrollbar = function( */ this.ratio = null; + /** + * The location of the origin of the workspace that the scrollbar is in, + * measured in CSS pixels relative to the injection div origin. This is + * usually (0, 0). When the scrollbar is in a flyout it may have a different + * origin. + * @type {Coordinate} + * @private + */ + this.origin_ = new Coordinate(0, 0); + + /** + * The position of the mouse along this scrollbar's major axis at the start of + * the most recent drag. + * Units are CSS pixels, with (0, 0) at the top left of the browser window. + * For a horizontal scrollbar this is the x coordinate of the mouse down + * event; for a vertical scrollbar it's the y coordinate of the mouse down + * event. + * @type {number} + * @private + */ + this.startDragMouse_ = 0; + + /** + * The length of the scrollbars (including the handle and the background), in + * CSS pixels. This is equivalent to scrollbar background length and the area + * within which the scrollbar handle can move. + * @type {number} + * @private + */ + this.scrollbarLength_ = 0; + + /** + * The length of the scrollbar handle in CSS pixels. + * @type {number} + * @private + */ + this.handleLength_ = 0; + + /** + * The offset of the start of the handle from the scrollbar position, in CSS + * pixels. + * @type {number} + * @private + */ + this.handlePosition_ = 0; + + /** + * Whether the scrollbar handle is visible. + * @type {boolean} + * @private + */ + this.isVisible_ = true; + + /** + * Whether the workspace containing this scrollbar is visible. + * @type {boolean} + * @private + */ + this.containerVisible_ = true; + this.createDom_(opt_class); /** @@ -124,64 +184,6 @@ const Scrollbar = function( this.svgHandle_, 'mousedown', scrollbar, scrollbar.onMouseDownHandle_); }; -/** - * The location of the origin of the workspace that the scrollbar is in, - * measured in CSS pixels relative to the injection div origin. This is usually - * (0, 0). When the scrollbar is in a flyout it may have a different origin. - * @type {Coordinate} - * @private - */ -Scrollbar.prototype.origin_ = new Coordinate(0, 0); - -/** - * The position of the mouse along this scrollbar's major axis at the start of - * the most recent drag. - * Units are CSS pixels, with (0, 0) at the top left of the browser window. - * For a horizontal scrollbar this is the x coordinate of the mouse down event; - * for a vertical scrollbar it's the y coordinate of the mouse down event. - * @type {number} - * @private - */ -Scrollbar.prototype.startDragMouse_ = 0; - -/** - * The length of the scrollbars (including the handle and the background), in - * CSS pixels. This is equivalent to scrollbar background length and the area - * within which the scrollbar handle can move. - * @type {number} - * @private - */ -Scrollbar.prototype.scrollbarLength_ = 0; - -/** - * The length of the scrollbar handle in CSS pixels. - * @type {number} - * @private - */ -Scrollbar.prototype.handleLength_ = 0; - -/** - * The offset of the start of the handle from the scrollbar position, in CSS - * pixels. - * @type {number} - * @private - */ -Scrollbar.prototype.handlePosition_ = 0; - -/** - * Whether the scrollbar handle is visible. - * @type {boolean} - * @private - */ -Scrollbar.prototype.isVisible_ = true; - -/** - * Whether the workspace containing this scrollbar is visible. - * @type {boolean} - * @private - */ -Scrollbar.prototype.containerVisible_ = true; - /** * Width of vertical scrollbar or height of horizontal scrollbar in CSS pixels. * Scrollbars should be larger on touch devices. diff --git a/core/theme.js b/core/theme.js index fb78bde30..d156b1227 100644 --- a/core/theme.js +++ b/core/theme.js @@ -21,65 +21,157 @@ const registry = goog.require('Blockly.registry'); /** * Class for a theme. - * @param {string} name Theme name. - * @param {!Object=} opt_blockStyles A map - * from style names (strings) to objects with style attributes for blocks. - * @param {!Object=} opt_categoryStyles A - * map from style names (strings) to objects with style attributes for - * categories. - * @param {!Theme.ComponentStyle=} opt_componentStyles A map of Blockly - * component names to style value. - * @constructor * @alias Blockly.Theme */ -const Theme = function( - name, opt_blockStyles, opt_categoryStyles, opt_componentStyles) { +class Theme { /** - * The theme name. This can be used to reference a specific theme in CSS. - * @type {string} + * @param {string} name Theme name. + * @param {!Object=} opt_blockStyles A map + * from style names (strings) to objects with style attributes for blocks. + * @param {!Object=} opt_categoryStyles A + * map from style names (strings) to objects with style attributes for + * categories. + * @param {!Theme.ComponentStyle=} opt_componentStyles A map of Blockly + * component names to style value. */ - this.name = name; + constructor(name, opt_blockStyles, opt_categoryStyles, opt_componentStyles) { + /** + * The theme name. This can be used to reference a specific theme in CSS. + * @type {string} + */ + this.name = name; + /** + * The block styles map. + * @type {!Object} + * @package + */ + this.blockStyles = opt_blockStyles || Object.create(null); + + /** + * The category styles map. + * @type {!Object} + * @package + */ + this.categoryStyles = opt_categoryStyles || Object.create(null); + + /** + * The UI components styles map. + * @type {!Theme.ComponentStyle} + * @package + */ + this.componentStyles = opt_componentStyles || + (/** @type {Theme.ComponentStyle} */ (Object.create(null))); + + /** + * The font style. + * @type {!Theme.FontStyle} + * @package + */ + this.fontStyle = /** @type {Theme.FontStyle} */ (Object.create(null)); + + /** + * Whether or not to add a 'hat' on top of all blocks with no previous or + * output connections. + * @type {?boolean} + * @package + */ + this.startHats = null; + + // Register the theme by name. + registry.register(registry.Type.THEME, name, this); + } /** - * The block styles map. - * @type {!Object} + * Gets the class name that identifies this theme. + * @return {string} The CSS class name. * @package */ - this.blockStyles = opt_blockStyles || Object.create(null); - + getClassName() { + return this.name + '-theme'; + } /** - * The category styles map. - * @type {!Object} - * @package + * Overrides or adds a style to the blockStyles map. + * @param {string} blockStyleName The name of the block style. + * @param {Theme.BlockStyle} blockStyle The block style. */ - this.categoryStyles = opt_categoryStyles || Object.create(null); - + setBlockStyle(blockStyleName, blockStyle) { + this.blockStyles[blockStyleName] = blockStyle; + } /** - * The UI components styles map. - * @type {!Theme.ComponentStyle} - * @package + * Overrides or adds a style to the categoryStyles map. + * @param {string} categoryStyleName The name of the category style. + * @param {Theme.CategoryStyle} categoryStyle The category style. */ - this.componentStyles = opt_componentStyles || - (/** @type {Theme.ComponentStyle} */ (Object.create(null))); - + setCategoryStyle(categoryStyleName, categoryStyle) { + this.categoryStyles[categoryStyleName] = categoryStyle; + } /** - * The font style. - * @type {!Theme.FontStyle} - * @package + * Gets the style for a given Blockly UI component. If the style value is a + * string, we attempt to find the value of any named references. + * @param {string} componentName The name of the component. + * @return {?string} The style value. */ - this.fontStyle = /** @type {Theme.FontStyle} */ (Object.create(null)); - + getComponentStyle(componentName) { + const style = this.componentStyles[componentName]; + if (style && typeof style === 'string' && + this.getComponentStyle(/** @type {string} */ (style))) { + return this.getComponentStyle(/** @type {string} */ (style)); + } + return style ? String(style) : null; + } /** - * Whether or not to add a 'hat' on top of all blocks with no previous or - * output connections. - * @type {?boolean} - * @package + * Configure a specific Blockly UI component with a style value. + * @param {string} componentName The name of the component. + * @param {*} styleValue The style value. */ - this.startHats = null; + setComponentStyle(componentName, styleValue) { + this.componentStyles[componentName] = styleValue; + } + /** + * Configure a theme's font style. + * @param {Theme.FontStyle} fontStyle The font style. + */ + setFontStyle(fontStyle) { + this.fontStyle = fontStyle; + } + /** + * Configure a theme's start hats. + * @param {boolean} startHats True if the theme enables start hats, false + * otherwise. + */ + setStartHats(startHats) { + this.startHats = startHats; + } + /** + * Define a new Blockly theme. + * @param {string} name The name of the theme. + * @param {!Object} themeObj An object containing theme properties. + * @return {!Theme} A new Blockly theme. + */ + static defineTheme(name, themeObj) { + const theme = new Theme(name); + let base = themeObj['base']; + if (base) { + if (typeof base === 'string') { + base = registry.getObject(registry.Type.THEME, base); + } + if (base instanceof Theme) { + object.deepMerge(theme, base); + theme.name = name; + } + } - // Register the theme by name. - registry.register(registry.Type.THEME, name, this); -}; + object.deepMerge(theme.blockStyles, themeObj['blockStyles']); + object.deepMerge(theme.categoryStyles, themeObj['categoryStyles']); + object.deepMerge(theme.componentStyles, themeObj['componentStyles']); + object.deepMerge(theme.fontStyle, themeObj['fontStyle']); + if (themeObj['startHats'] !== null) { + theme.startHats = themeObj['startHats']; + } + + return theme; + } +} /** * A block style. @@ -133,102 +225,4 @@ Theme.ComponentStyle; */ Theme.FontStyle; -/** - * Gets the class name that identifies this theme. - * @return {string} The CSS class name. - * @package - */ -Theme.prototype.getClassName = function() { - return this.name + '-theme'; -}; - -/** - * Overrides or adds a style to the blockStyles map. - * @param {string} blockStyleName The name of the block style. - * @param {Theme.BlockStyle} blockStyle The block style. - */ -Theme.prototype.setBlockStyle = function(blockStyleName, blockStyle) { - this.blockStyles[blockStyleName] = blockStyle; -}; - -/** - * Overrides or adds a style to the categoryStyles map. - * @param {string} categoryStyleName The name of the category style. - * @param {Theme.CategoryStyle} categoryStyle The category style. - */ -Theme.prototype.setCategoryStyle = function(categoryStyleName, categoryStyle) { - this.categoryStyles[categoryStyleName] = categoryStyle; -}; - -/** - * Gets the style for a given Blockly UI component. If the style value is a - * string, we attempt to find the value of any named references. - * @param {string} componentName The name of the component. - * @return {?string} The style value. - */ -Theme.prototype.getComponentStyle = function(componentName) { - const style = this.componentStyles[componentName]; - if (style && typeof style === 'string' && - this.getComponentStyle(/** @type {string} */ (style))) { - return this.getComponentStyle(/** @type {string} */ (style)); - } - return style ? String(style) : null; -}; - -/** - * Configure a specific Blockly UI component with a style value. - * @param {string} componentName The name of the component. - * @param {*} styleValue The style value. - */ -Theme.prototype.setComponentStyle = function(componentName, styleValue) { - this.componentStyles[componentName] = styleValue; -}; - -/** - * Configure a theme's font style. - * @param {Theme.FontStyle} fontStyle The font style. - */ -Theme.prototype.setFontStyle = function(fontStyle) { - this.fontStyle = fontStyle; -}; - -/** - * Configure a theme's start hats. - * @param {boolean} startHats True if the theme enables start hats, false - * otherwise. - */ -Theme.prototype.setStartHats = function(startHats) { - this.startHats = startHats; -}; - -/** - * Define a new Blockly theme. - * @param {string} name The name of the theme. - * @param {!Object} themeObj An object containing theme properties. - * @return {!Theme} A new Blockly theme. - */ -Theme.defineTheme = function(name, themeObj) { - const theme = new Theme(name); - let base = themeObj['base']; - if (base) { - if (typeof base === 'string') { - base = registry.getObject(registry.Type.THEME, base); - } - if (base instanceof Theme) { - object.deepMerge(theme, base); - theme.name = name; - } - } - - object.deepMerge(theme.blockStyles, themeObj['blockStyles']); - object.deepMerge(theme.categoryStyles, themeObj['categoryStyles']); - object.deepMerge(theme.componentStyles, themeObj['componentStyles']); - object.deepMerge(theme.fontStyle, themeObj['fontStyle']); - if (themeObj['startHats'] !== null) { - theme.startHats = themeObj['startHats']; - } - - return theme; -}; - exports.Theme = Theme; diff --git a/core/trashcan.js b/core/trashcan.js index 698eb7a74..3fa25e433 100644 --- a/core/trashcan.js +++ b/core/trashcan.js @@ -93,6 +93,70 @@ const Trashcan = function(workspace) { if (this.workspace_.options.maxTrashcanContents <= 0) { return; } + + /** + * Current open/close state of the lid. + * @type {boolean} + */ + this.isLidOpen = false; + + /** + * The minimum openness of the lid. Used to indicate if the trashcan contains + * blocks. + * @type {number} + * @private + */ + this.minOpenness_ = 0; + + /** + * The SVG group containing the trash can. + * @type {SVGElement} + * @private + */ + this.svgGroup_ = null; + + /** + * The SVG image element of the trash can lid. + * @type {SVGElement} + * @private + */ + this.svgLid_ = null; + + /** + * Task ID of opening/closing animation. + * @type {number} + * @private + */ + this.lidTask_ = 0; + + /** + * Current state of lid opening (0.0 = closed, 1.0 = open). + * @type {number} + * @private + */ + this.lidOpen_ = 0; + + /** + * Left coordinate of the trash can. + * @type {number} + * @private + */ + this.left_ = 0; + + /** + * Top coordinate of the trash can. + * @type {number} + * @private + */ + this.top_ = 0; + + /** + * Whether this trash can has been initialized. + * @type {boolean} + * @private + */ + this.initialized_ = false; + // Create flyout options. const flyoutWorkspaceOptions = new Options( /** @type {!BlocklyOptions} */ @@ -202,69 +266,6 @@ const OPACITY_MAX = 0.8; */ const MAX_LID_ANGLE = 45; -/** - * Current open/close state of the lid. - * @type {boolean} - */ -Trashcan.prototype.isLidOpen = false; - -/** - * The minimum openness of the lid. Used to indicate if the trashcan contains - * blocks. - * @type {number} - * @private - */ -Trashcan.prototype.minOpenness_ = 0; - -/** - * The SVG group containing the trash can. - * @type {SVGElement} - * @private - */ -Trashcan.prototype.svgGroup_ = null; - -/** - * The SVG image element of the trash can lid. - * @type {SVGElement} - * @private - */ -Trashcan.prototype.svgLid_ = null; - -/** - * Task ID of opening/closing animation. - * @type {number} - * @private - */ -Trashcan.prototype.lidTask_ = 0; - -/** - * Current state of lid opening (0.0 = closed, 1.0 = open). - * @type {number} - * @private - */ -Trashcan.prototype.lidOpen_ = 0; - -/** - * Left coordinate of the trash can. - * @type {number} - * @private - */ -Trashcan.prototype.left_ = 0; - -/** - * Top coordinate of the trash can. - * @type {number} - * @private - */ -Trashcan.prototype.top_ = 0; - -/** - * Whether this has been initialized. - * @type {boolean} - * @private - */ -Trashcan.prototype.initialized_ = false; - /** * Create the trash can elements. * @return {!SVGElement} The trash can's SVG group. diff --git a/core/variable_map.js b/core/variable_map.js index 797d1a72f..68c5a2826 100644 --- a/core/variable_map.js +++ b/core/variable_map.js @@ -37,390 +37,374 @@ goog.require('Blockly.Events.VarRename'); * Class for a variable map. This contains a dictionary data structure with * variable types as keys and lists of variables as values. The list of * variables are the type indicated by the key. - * @param {!Workspace} workspace The workspace this map belongs to. - * @constructor * @alias Blockly.VariableMap */ -const VariableMap = function(workspace) { +class VariableMap { /** - * A map from variable type to list of variable names. The lists contain all - * of the named variables in the workspace, including variables - * that are not currently in use. - * @type {!Object>} - * @private + * @param {!Workspace} workspace The workspace this map belongs to. */ - this.variableMap_ = Object.create(null); + constructor(workspace) { + /** + * A map from variable type to list of variable names. The lists contain + * all of the named variables in the workspace, including variables that are + * not currently in use. + * @type {!Object>} + * @private + */ + this.variableMap_ = Object.create(null); + /** + * The workspace this map belongs to. + * @type {!Workspace} + */ + this.workspace = workspace; + } /** - * The workspace this map belongs to. - * @type {!Workspace} + * Clear the variable map. */ - this.workspace = workspace; -}; - -/** - * Clear the variable map. - */ -VariableMap.prototype.clear = function() { - this.variableMap_ = Object.create(null); -}; - -/* Begin functions for renaming variables. */ - -/** - * Rename the given variable by updating its name in the variable map. - * @param {!VariableModel} variable Variable to rename. - * @param {string} newName New variable name. - * @package - */ -VariableMap.prototype.renameVariable = function(variable, newName) { - const type = variable.type; - const conflictVar = this.getVariable(newName, type); - const blocks = this.workspace.getAllBlocks(false); - eventUtils.setGroup(true); - try { - // The IDs may match if the rename is a simple case change (name1 -> Name1). - if (!conflictVar || conflictVar.getId() === variable.getId()) { - this.renameVariableAndUses_(variable, newName, blocks); - } else { - this.renameVariableWithConflict_(variable, newName, conflictVar, blocks); - } - } finally { - eventUtils.setGroup(false); + clear() { + this.variableMap_ = Object.create(null); } -}; - -/** - * Rename a variable by updating its name in the variable map. Identify the - * variable to rename with the given ID. - * @param {string} id ID of the variable to rename. - * @param {string} newName New variable name. - */ -VariableMap.prototype.renameVariableById = function(id, newName) { - const variable = this.getVariableById(id); - if (!variable) { - throw Error('Tried to rename a variable that didn\'t exist. ID: ' + id); - } - - this.renameVariable(variable, newName); -}; - -/** - * Update the name of the given variable and refresh all references to it. - * The new name must not conflict with any existing variable names. - * @param {!VariableModel} variable Variable to rename. - * @param {string} newName New variable name. - * @param {!Array} blocks The list of all blocks in the - * workspace. - * @private - */ -VariableMap.prototype.renameVariableAndUses_ = function( - variable, newName, blocks) { - eventUtils.fire( - new (eventUtils.get(eventUtils.VAR_RENAME))(variable, newName)); - variable.name = newName; - for (let i = 0; i < blocks.length; i++) { - blocks[i].updateVarName(variable); - } -}; - -/** - * Update the name of the given variable to the same name as an existing - * variable. The two variables are coalesced into a single variable with the ID - * of the existing variable that was already using newName. - * Refresh all references to the variable. - * @param {!VariableModel} variable Variable to rename. - * @param {string} newName New variable name. - * @param {!VariableModel} conflictVar The variable that was already - * using newName. - * @param {!Array} blocks The list of all blocks in the - * workspace. - * @private - */ -VariableMap.prototype.renameVariableWithConflict_ = function( - variable, newName, conflictVar, blocks) { - const type = variable.type; - const oldCase = conflictVar.name; - - if (newName !== oldCase) { - // Simple rename to change the case and update references. - this.renameVariableAndUses_(conflictVar, newName, blocks); - } - - // These blocks now refer to a different variable. - // These will fire change events. - for (let i = 0; i < blocks.length; i++) { - blocks[i].renameVarById(variable.getId(), conflictVar.getId()); - } - - // Finally delete the original variable, which is now unreferenced. - eventUtils.fire(new (eventUtils.get(eventUtils.VAR_DELETE))(variable)); - // And remove it from the list. - arrayUtils.removeElem(this.variableMap_[type], variable); -}; - -/* End functions for renaming variables. */ - -/** - * Create a variable with a given name, optional type, and optional ID. - * @param {string} name The name of the variable. This must be unique across - * variables and procedures. - * @param {?string=} opt_type The type of the variable like 'int' or 'string'. - * Does not need to be unique. Field_variable can filter variables based on - * their type. This will default to '' which is a specific type. - * @param {?string=} opt_id The unique ID of the variable. This will default to - * a UUID. - * @return {!VariableModel} The newly created variable. - */ -VariableMap.prototype.createVariable = function(name, opt_type, opt_id) { - let variable = this.getVariable(name, opt_type); - if (variable) { - if (opt_id && variable.getId() !== opt_id) { - throw Error( - 'Variable "' + name + '" is already in use and its id is "' + - variable.getId() + '" which conflicts with the passed in ' + - 'id, "' + opt_id + '".'); - } - // The variable already exists and has the same ID. - return variable; - } - if (opt_id && this.getVariableById(opt_id)) { - throw Error('Variable id, "' + opt_id + '", is already in use.'); - } - const id = opt_id || idGenerator.genUid(); - const type = opt_type || ''; - variable = new VariableModel(this.workspace, name, type, id); - - const variables = this.variableMap_[type] || []; - variables.push(variable); - // Delete the list of variables of this type, and re-add it so that - // the most recent addition is at the end. - // This is used so the toolbox's set block is set to the most recent variable. - delete this.variableMap_[type]; - this.variableMap_[type] = variables; - - return variable; -}; - -/* Begin functions for variable deletion. */ - -/** - * Delete a variable. - * @param {!VariableModel} variable Variable to delete. - */ -VariableMap.prototype.deleteVariable = function(variable) { - const variableId = variable.getId(); - const variableList = this.variableMap_[variable.type]; - for (let i = 0; i < variableList.length; i++) { - const tempVar = variableList[i]; - if (tempVar.getId() === variableId) { - variableList.splice(i, 1); - eventUtils.fire(new (eventUtils.get(eventUtils.VAR_DELETE))(variable)); - return; - } - } -}; - -/** - * Delete a variables by the passed in ID and all of its uses from this - * workspace. May prompt the user for confirmation. - * @param {string} id ID of variable to delete. - */ -VariableMap.prototype.deleteVariableById = function(id) { - const variable = this.getVariableById(id); - if (variable) { - // Check whether this variable is a function parameter before deleting. - const variableName = variable.name; - const uses = this.getVariableUsesById(id); - for (let i = 0, block; (block = uses[i]); i++) { - if (block.type === 'procedures_defnoreturn' || - block.type === 'procedures_defreturn') { - const procedureName = String(block.getFieldValue('NAME')); - const deleteText = Msg['CANNOT_DELETE_VARIABLE_PROCEDURE'] - .replace('%1', variableName) - .replace('%2', procedureName); - dialog.alert(deleteText); - return; - } - } - - const map = this; - if (uses.length > 1) { - // Confirm before deleting multiple blocks. - const confirmText = Msg['DELETE_VARIABLE_CONFIRMATION'] - .replace('%1', String(uses.length)) - .replace('%2', variableName); - dialog.confirm(confirmText, function(ok) { - if (ok && variable) { - map.deleteVariableInternal(variable, uses); - } - }); - } else { - // No confirmation necessary for a single block. - map.deleteVariableInternal(variable, uses); - } - } else { - console.warn('Can\'t delete non-existent variable: ' + id); - } -}; - -/** - * Deletes a variable and all of its uses from this workspace without asking the - * user for confirmation. - * @param {!VariableModel} variable Variable to delete. - * @param {!Array} uses An array of uses of the variable. - * @package - */ -VariableMap.prototype.deleteVariableInternal = function(variable, uses) { - const existingGroup = eventUtils.getGroup(); - if (!existingGroup) { + /* Begin functions for renaming variables. */ + /** + * Rename the given variable by updating its name in the variable map. + * @param {!VariableModel} variable Variable to rename. + * @param {string} newName New variable name. + * @package + */ + renameVariable(variable, newName) { + const type = variable.type; + const conflictVar = this.getVariable(newName, type); + const blocks = this.workspace.getAllBlocks(false); eventUtils.setGroup(true); - } - try { - for (let i = 0; i < uses.length; i++) { - uses[i].dispose(true); - } - this.deleteVariable(variable); - } finally { - if (!existingGroup) { + try { + // The IDs may match if the rename is a simple case change (name1 -> + // Name1). + if (!conflictVar || conflictVar.getId() === variable.getId()) { + this.renameVariableAndUses_(variable, newName, blocks); + } else { + this.renameVariableWithConflict_( + variable, newName, conflictVar, blocks); + } + } finally { eventUtils.setGroup(false); } } -}; + /** + * Rename a variable by updating its name in the variable map. Identify the + * variable to rename with the given ID. + * @param {string} id ID of the variable to rename. + * @param {string} newName New variable name. + */ + renameVariableById(id, newName) { + const variable = this.getVariableById(id); + if (!variable) { + throw Error('Tried to rename a variable that didn\'t exist. ID: ' + id); + } -/* End functions for variable deletion. */ + this.renameVariable(variable, newName); + } + /** + * Update the name of the given variable and refresh all references to it. + * The new name must not conflict with any existing variable names. + * @param {!VariableModel} variable Variable to rename. + * @param {string} newName New variable name. + * @param {!Array} blocks The list of all blocks in the + * workspace. + * @private + */ + renameVariableAndUses_(variable, newName, blocks) { + eventUtils.fire( + new (eventUtils.get(eventUtils.VAR_RENAME))(variable, newName)); + variable.name = newName; + for (let i = 0; i < blocks.length; i++) { + blocks[i].updateVarName(variable); + } + } + /** + * Update the name of the given variable to the same name as an existing + * variable. The two variables are coalesced into a single variable with the + * ID of the existing variable that was already using newName. Refresh all + * references to the variable. + * @param {!VariableModel} variable Variable to rename. + * @param {string} newName New variable name. + * @param {!VariableModel} conflictVar The variable that was already + * using newName. + * @param {!Array} blocks The list of all blocks in the + * workspace. + * @private + */ + renameVariableWithConflict_(variable, newName, conflictVar, blocks) { + const type = variable.type; + const oldCase = conflictVar.name; -/** - * Find the variable by the given name and type and return it. Return null if - * it is not found. - * @param {string} name The name to check for. - * @param {?string=} opt_type The type of the variable. If not provided it - * defaults to the empty string, which is a specific type. - * @return {?VariableModel} The variable with the given name, or null if - * it was not found. - */ -VariableMap.prototype.getVariable = function(name, opt_type) { - const type = opt_type || ''; - const list = this.variableMap_[type]; - if (list) { - for (let j = 0, variable; (variable = list[j]); j++) { - if (Names.equals(variable.name, name)) { - return variable; + if (newName !== oldCase) { + // Simple rename to change the case and update references. + this.renameVariableAndUses_(conflictVar, newName, blocks); + } + + // These blocks now refer to a different variable. + // These will fire change events. + for (let i = 0; i < blocks.length; i++) { + blocks[i].renameVarById(variable.getId(), conflictVar.getId()); + } + + // Finally delete the original variable, which is now unreferenced. + eventUtils.fire(new (eventUtils.get(eventUtils.VAR_DELETE))(variable)); + // And remove it from the list. + arrayUtils.removeElem(this.variableMap_[type], variable); + } + /* End functions for renaming variables. */ + /** + * Create a variable with a given name, optional type, and optional ID. + * @param {string} name The name of the variable. This must be unique across + * variables and procedures. + * @param {?string=} opt_type The type of the variable like 'int' or 'string'. + * Does not need to be unique. Field_variable can filter variables based + * on their type. This will default to '' which is a specific type. + * @param {?string=} opt_id The unique ID of the variable. This will default + * to a UUID. + * @return {!VariableModel} The newly created variable. + */ + createVariable(name, opt_type, opt_id) { + let variable = this.getVariable(name, opt_type); + if (variable) { + if (opt_id && variable.getId() !== opt_id) { + throw Error( + 'Variable "' + name + '" is already in use and its id is "' + + variable.getId() + '" which conflicts with the passed in ' + + 'id, "' + opt_id + '".'); + } + // The variable already exists and has the same ID. + return variable; + } + if (opt_id && this.getVariableById(opt_id)) { + throw Error('Variable id, "' + opt_id + '", is already in use.'); + } + const id = opt_id || idGenerator.genUid(); + const type = opt_type || ''; + variable = new VariableModel(this.workspace, name, type, id); + + const variables = this.variableMap_[type] || []; + variables.push(variable); + // Delete the list of variables of this type, and re-add it so that + // the most recent addition is at the end. + // This is used so the toolbox's set block is set to the most recent + // variable. + delete this.variableMap_[type]; + this.variableMap_[type] = variables; + + return variable; + } + /* Begin functions for variable deletion. */ + /** + * Delete a variable. + * @param {!VariableModel} variable Variable to delete. + */ + deleteVariable(variable) { + const variableId = variable.getId(); + const variableList = this.variableMap_[variable.type]; + for (let i = 0; i < variableList.length; i++) { + const tempVar = variableList[i]; + if (tempVar.getId() === variableId) { + variableList.splice(i, 1); + eventUtils.fire(new (eventUtils.get(eventUtils.VAR_DELETE))(variable)); + return; } } } - return null; -}; + /** + * Delete a variables by the passed in ID and all of its uses from this + * workspace. May prompt the user for confirmation. + * @param {string} id ID of variable to delete. + */ + deleteVariableById(id) { + const variable = this.getVariableById(id); + if (variable) { + // Check whether this variable is a function parameter before deleting. + const variableName = variable.name; + const uses = this.getVariableUsesById(id); + for (let i = 0, block; (block = uses[i]); i++) { + if (block.type === 'procedures_defnoreturn' || + block.type === 'procedures_defreturn') { + const procedureName = String(block.getFieldValue('NAME')); + const deleteText = Msg['CANNOT_DELETE_VARIABLE_PROCEDURE'] + .replace('%1', variableName) + .replace('%2', procedureName); + dialog.alert(deleteText); + return; + } + } -/** - * Find the variable by the given ID and return it. Return null if not found. - * @param {string} id The ID to check for. - * @return {?VariableModel} The variable with the given ID. - */ -VariableMap.prototype.getVariableById = function(id) { - const keys = Object.keys(this.variableMap_); - for (let i = 0; i < keys.length; i++) { - const key = keys[i]; - for (let j = 0, variable; (variable = this.variableMap_[key][j]); j++) { - if (variable.getId() === id) { - return variable; + const map = this; + if (uses.length > 1) { + // Confirm before deleting multiple blocks. + const confirmText = Msg['DELETE_VARIABLE_CONFIRMATION'] + .replace('%1', String(uses.length)) + .replace('%2', variableName); + dialog.confirm(confirmText, function(ok) { + if (ok && variable) { + map.deleteVariableInternal(variable, uses); + } + }); + } else { + // No confirmation necessary for a single block. + map.deleteVariableInternal(variable, uses); + } + } else { + console.warn('Can\'t delete non-existent variable: ' + id); + } + } + /** + * Deletes a variable and all of its uses from this workspace without asking + * the user for confirmation. + * @param {!VariableModel} variable Variable to delete. + * @param {!Array} uses An array of uses of the variable. + * @package + */ + deleteVariableInternal(variable, uses) { + const existingGroup = eventUtils.getGroup(); + if (!existingGroup) { + eventUtils.setGroup(true); + } + try { + for (let i = 0; i < uses.length; i++) { + uses[i].dispose(true); + } + this.deleteVariable(variable); + } finally { + if (!existingGroup) { + eventUtils.setGroup(false); } } } - return null; -}; - -/** - * Get a list containing all of the variables of a specified type. If type is - * null, return list of variables with empty string type. - * @param {?string} type Type of the variables to find. - * @return {!Array} The sought after variables of the - * passed in type. An empty array if none are found. - */ -VariableMap.prototype.getVariablesOfType = function(type) { - type = type || ''; - const variableList = this.variableMap_[type]; - if (variableList) { - return variableList.slice(); - } - return []; -}; - -/** - * Return all variable and potential variable types. This list always contains - * the empty string. - * @param {?Workspace} ws The workspace used to look for potential - * variables. This can be different than the workspace stored on this object - * if the passed in ws is a flyout workspace. - * @return {!Array} List of variable types. - * @package - */ -VariableMap.prototype.getVariableTypes = function(ws) { - const variableMap = {}; - object.mixin(variableMap, this.variableMap_); - if (ws && ws.getPotentialVariableMap()) { - object.mixin(variableMap, ws.getPotentialVariableMap().variableMap_); - } - const types = Object.keys(variableMap); - let hasEmpty = false; - for (let i = 0; i < types.length; i++) { - if (types[i] === '') { - hasEmpty = true; - } - } - if (!hasEmpty) { - types.push(''); - } - return types; -}; - -/** - * Return all variables of all types. - * @return {!Array} List of variable models. - */ -VariableMap.prototype.getAllVariables = function() { - let allVariables = []; - for (const key in this.variableMap_) { - allVariables = allVariables.concat(this.variableMap_[key]); - } - return allVariables; -}; - -/** - * Returns all of the variable names of all types. - * @return {!Array} All of the variable names of all types. - */ -VariableMap.prototype.getAllVariableNames = function() { - const allNames = []; - for (const key in this.variableMap_) { - const variables = this.variableMap_[key]; - for (let i = 0, variable; (variable = variables[i]); i++) { - allNames.push(variable.name); - } - } - return allNames; -}; - -/** - * Find all the uses of a named variable. - * @param {string} id ID of the variable to find. - * @return {!Array} Array of block usages. - */ -VariableMap.prototype.getVariableUsesById = function(id) { - const uses = []; - const blocks = this.workspace.getAllBlocks(false); - // Iterate through every block and check the name. - for (let i = 0; i < blocks.length; i++) { - const blockVariables = blocks[i].getVarModels(); - if (blockVariables) { - for (let j = 0; j < blockVariables.length; j++) { - if (blockVariables[j].getId() === id) { - uses.push(blocks[i]); + /* End functions for variable deletion. */ + /** + * Find the variable by the given name and type and return it. Return null if + * it is not found. + * @param {string} name The name to check for. + * @param {?string=} opt_type The type of the variable. If not provided it + * defaults to the empty string, which is a specific type. + * @return {?VariableModel} The variable with the given name, or null if + * it was not found. + */ + getVariable(name, opt_type) { + const type = opt_type || ''; + const list = this.variableMap_[type]; + if (list) { + for (let j = 0, variable; (variable = list[j]); j++) { + if (Names.equals(variable.name, name)) { + return variable; } } } + return null; } - return uses; -}; + /** + * Find the variable by the given ID and return it. Return null if not found. + * @param {string} id The ID to check for. + * @return {?VariableModel} The variable with the given ID. + */ + getVariableById(id) { + const keys = Object.keys(this.variableMap_); + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + for (let j = 0, variable; (variable = this.variableMap_[key][j]); j++) { + if (variable.getId() === id) { + return variable; + } + } + } + return null; + } + /** + * Get a list containing all of the variables of a specified type. If type is + * null, return list of variables with empty string type. + * @param {?string} type Type of the variables to find. + * @return {!Array} The sought after variables of the + * passed in type. An empty array if none are found. + */ + getVariablesOfType(type) { + type = type || ''; + const variableList = this.variableMap_[type]; + if (variableList) { + return variableList.slice(); + } + return []; + } + /** + * Return all variable and potential variable types. This list always + * contains the empty string. + * @param {?Workspace} ws The workspace used to look for potential + * variables. This can be different than the workspace stored on this object + * if the passed in ws is a flyout workspace. + * @return {!Array} List of variable types. + * @package + */ + getVariableTypes(ws) { + const variableMap = {}; + object.mixin(variableMap, this.variableMap_); + if (ws && ws.getPotentialVariableMap()) { + object.mixin(variableMap, ws.getPotentialVariableMap().variableMap_); + } + const types = Object.keys(variableMap); + let hasEmpty = false; + for (let i = 0; i < types.length; i++) { + if (types[i] === '') { + hasEmpty = true; + } + } + if (!hasEmpty) { + types.push(''); + } + return types; + } + /** + * Return all variables of all types. + * @return {!Array} List of variable models. + */ + getAllVariables() { + let allVariables = []; + for (const key in this.variableMap_) { + allVariables = allVariables.concat(this.variableMap_[key]); + } + return allVariables; + } + /** + * Returns all of the variable names of all types. + * @return {!Array} All of the variable names of all types. + */ + getAllVariableNames() { + const allNames = []; + for (const key in this.variableMap_) { + const variables = this.variableMap_[key]; + for (let i = 0, variable; (variable = variables[i]); i++) { + allNames.push(variable.name); + } + } + return allNames; + } + /** + * Find all the uses of a named variable. + * @param {string} id ID of the variable to find. + * @return {!Array} Array of block usages. + */ + getVariableUsesById(id) { + const uses = []; + const blocks = this.workspace.getAllBlocks(false); + // Iterate through every block and check the name. + for (let i = 0; i < blocks.length; i++) { + const blockVariables = blocks[i].getVarModels(); + if (blockVariables) { + for (let j = 0; j < blockVariables.length; j++) { + if (blockVariables[j].getId() === id) { + uses.push(blocks[i]); + } + } + } + } + return uses; + } +} exports.VariableMap = VariableMap; diff --git a/core/variable_model.js b/core/variable_model.js index d169b4a49..b88fe65e7 100644 --- a/core/variable_model.js +++ b/core/variable_model.js @@ -26,70 +26,71 @@ goog.require('Blockly.Events.VarCreate'); /** * Class for a variable model. * Holds information for the variable including name, ID, and type. - * @param {!Workspace} workspace The variable's workspace. - * @param {string} name The name of the variable. This is the user-visible name - * (e.g. 'my var' or '私の変数'), not the generated name. - * @param {string=} opt_type The type of the variable like 'int' or 'string'. - * Does not need to be unique. Field_variable can filter variables based on - * their type. This will default to '' which is a specific type. - * @param {string=} opt_id The unique ID of the variable. This will default to - * a UUID. * @see {Blockly.FieldVariable} - * @constructor * @alias Blockly.VariableModel */ -const VariableModel = function(workspace, name, opt_type, opt_id) { +class VariableModel { /** - * The workspace the variable is in. - * @type {!Workspace} + * @param {!Workspace} workspace The variable's workspace. + * @param {string} name The name of the variable. This is the user-visible + * name (e.g. 'my var' or '私の変数'), not the generated name. + * @param {string=} opt_type The type of the variable like 'int' or 'string'. + * Does not need to be unique. Field_variable can filter variables based + * on their type. This will default to '' which is a specific type. + * @param {string=} opt_id The unique ID of the variable. This will default to + * a UUID. */ - this.workspace = workspace; + constructor(workspace, name, opt_type, opt_id) { + /** + * The workspace the variable is in. + * @type {!Workspace} + */ + this.workspace = workspace; + /** + * The name of the variable, typically defined by the user. It may be + * changed by the user. + * @type {string} + */ + this.name = name; + + /** + * The type of the variable, such as 'int' or 'sound_effect'. This may be + * used to build a list of variables of a specific type. By default this is + * the empty string '', which is a specific type. + * @see {Blockly.FieldVariable} + * @type {string} + */ + this.type = opt_type || ''; + + /** + * A unique ID for the variable. This should be defined at creation and + * not change, even if the name changes. In most cases this should be a + * UUID. + * @type {string} + * @private + */ + this.id_ = opt_id || idGenerator.genUid(); + + eventUtils.fire(new (eventUtils.get(eventUtils.VAR_CREATE))(this)); + } /** - * The name of the variable, typically defined by the user. It may be - * changed by the user. - * @type {string} + * @return {string} The ID for the variable. */ - this.name = name; - + getId() { + return this.id_; + } /** - * The type of the variable, such as 'int' or 'sound_effect'. This may be - * used to build a list of variables of a specific type. By default this is - * the empty string '', which is a specific type. - * @see {Blockly.FieldVariable} - * @type {string} + * A custom compare function for the VariableModel objects. + * @param {VariableModel} var1 First variable to compare. + * @param {VariableModel} var2 Second variable to compare. + * @return {number} -1 if name of var1 is less than name of var2, 0 if equal, + * and 1 if greater. + * @package */ - this.type = opt_type || ''; - - /** - * A unique ID for the variable. This should be defined at creation and - * not change, even if the name changes. In most cases this should be a - * UUID. - * @type {string} - * @private - */ - this.id_ = opt_id || idGenerator.genUid(); - - eventUtils.fire(new (eventUtils.get(eventUtils.VAR_CREATE))(this)); -}; - -/** - * @return {string} The ID for the variable. - */ -VariableModel.prototype.getId = function() { - return this.id_; -}; - -/** - * A custom compare function for the VariableModel objects. - * @param {VariableModel} var1 First variable to compare. - * @param {VariableModel} var2 Second variable to compare. - * @return {number} -1 if name of var1 is less than name of var2, 0 if equal, - * and 1 if greater. - * @package - */ -VariableModel.compareByName = function(var1, var2) { - return var1.name.localeCompare(var2.name, undefined, {sensitivity: 'base'}); -}; + static compareByName(var1, var2) { + return var1.name.localeCompare(var2.name, undefined, {sensitivity: 'base'}); + } +} exports.VariableModel = VariableModel; diff --git a/core/warning.js b/core/warning.js index e58807839..e34e3258f 100644 --- a/core/warning.js +++ b/core/warning.js @@ -43,14 +43,15 @@ const Warning = function(block) { this.createIcon(); // The text_ object can contain multiple warnings. this.text_ = Object.create(null); + + /** + * Does this icon get hidden when the block is collapsed? + * @type {boolean} + */ + this.collapseHidden = false; }; object.inherits(Warning, Icon); -/** - * Does this icon get hidden when the block is collapsed. - */ -Warning.prototype.collapseHidden = false; - /** * Draw the warning icon. * @param {!Element} group The icon group. diff --git a/core/workspace.js b/core/workspace.js index 41d2a1c91..3a4af4359 100644 --- a/core/workspace.js +++ b/core/workspace.js @@ -72,6 +72,33 @@ const Workspace = function(opt_options) { /** @type {toolbox.Position} */ this.toolboxPosition = this.options.toolboxPosition; + /** + * Returns `true` if the workspace is visible and `false` if it's headless. + * @type {boolean} + */ + this.rendered = false; + + /** + * Returns `true` if the workspace is currently in the process of a bulk + * clear. + * @type {boolean} + * @package + */ + this.isClearing = false; + + /** + * Maximum number of undo events in stack. `0` turns off undo, `Infinity` sets + * it to unlimited. + * @type {number} + */ + this.MAX_UNDO = 1024; + + /** + * Set of databases for rapid lookup of connection locations. + * @type {Array} + */ + this.connectionDBList = null; + const connectionCheckerClass = registry.getClassFromOptions( registry.Type.CONNECTION_CHECKER, this.options, true); /** @@ -143,32 +170,6 @@ const Workspace = function(opt_options) { this.potentialVariableMap_ = null; }; -/** - * Returns `true` if the workspace is visible and `false` if it's headless. - * @type {boolean} - */ -Workspace.prototype.rendered = false; - -/** - * Returns `true` if the workspace is currently in the process of a bulk clear. - * @type {boolean} - * @package - */ -Workspace.prototype.isClearing = false; - -/** - * Maximum number of undo events in stack. `0` turns off undo, `Infinity` sets - * it to unlimited. - * @type {number} - */ -Workspace.prototype.MAX_UNDO = 1024; - -/** - * Set of databases for rapid lookup of connection locations. - * @type {Array} - */ -Workspace.prototype.connectionDBList = null; - /** * Dispose of this workspace. * Unlink from all DOM elements to prevent memory leaks. diff --git a/core/workspace_audio.js b/core/workspace_audio.js index 5fd0eff4f..1be8bb5b7 100644 --- a/core/workspace_audio.js +++ b/core/workspace_audio.js @@ -26,138 +26,138 @@ const {globalThis} = goog.require('Blockly.utils.global'); /** * Class for loading, storing, and playing audio for a workspace. - * @param {WorkspaceSvg} parentWorkspace The parent of the workspace - * this audio object belongs to, or null. - * @constructor * @alias Blockly.WorkspaceAudio */ -const WorkspaceAudio = function(parentWorkspace) { +class WorkspaceAudio { /** - * The parent of the workspace this object belongs to, or null. May be - * checked for sounds that this object can't find. - * @type {WorkspaceSvg} - * @private + * @param {WorkspaceSvg} parentWorkspace The parent of the workspace + * this audio object belongs to, or null. */ - this.parentWorkspace_ = parentWorkspace; + constructor(parentWorkspace) { + /** + * The parent of the workspace this object belongs to, or null. May be + * checked for sounds that this object can't find. + * @type {WorkspaceSvg} + * @private + */ + this.parentWorkspace_ = parentWorkspace; + /** + * Database of pre-loaded sounds. + * @private + */ + this.SOUNDS_ = Object.create(null); + + /** + * Time that the last sound was played. + * @type {Date} + * @private + */ + this.lastSound_ = null; + } /** - * Database of pre-loaded sounds. - * @private + * Dispose of this audio manager. + * @package */ - this.SOUNDS_ = Object.create(null); -}; - -/** - * Time that the last sound was played. - * @type {Date} - * @private - */ -WorkspaceAudio.prototype.lastSound_ = null; - -/** - * Dispose of this audio manager. - * @package - */ -WorkspaceAudio.prototype.dispose = function() { - this.parentWorkspace_ = null; - this.SOUNDS_ = null; -}; - -/** - * Load an audio file. Cache it, ready for instantaneous playing. - * @param {!Array} filenames List of file types in decreasing order of - * preference (i.e. increasing size). E.g. ['media/go.mp3', 'media/go.wav'] - * Filenames include path from Blockly's root. File extensions matter. - * @param {string} name Name of sound. - */ -WorkspaceAudio.prototype.load = function(filenames, name) { - if (!filenames.length) { - return; + dispose() { + this.parentWorkspace_ = null; + this.SOUNDS_ = null; } - let audioTest; - try { - audioTest = new globalThis['Audio'](); - } catch (e) { - // No browser support for Audio. - // IE can throw an error even if the Audio object exists. - return; - } - let sound; - for (let i = 0; i < filenames.length; i++) { - const filename = filenames[i]; - const ext = filename.match(/\.(\w+)$/); - if (ext && audioTest.canPlayType('audio/' + ext[1])) { - // Found an audio format we can play. - sound = new globalThis['Audio'](filename); - break; - } - } - if (sound && sound.play) { - this.SOUNDS_[name] = sound; - } -}; - -/** - * Preload all the audio files so that they play quickly when asked for. - * @package - */ -WorkspaceAudio.prototype.preload = function() { - for (const name in this.SOUNDS_) { - const sound = this.SOUNDS_[name]; - sound.volume = 0.01; - const playPromise = sound.play(); - // Edge does not return a promise, so we need to check. - if (playPromise !== undefined) { - // If we don't wait for the play request to complete before calling - // pause() we will get an exception: (DOMException: The play() request was - // interrupted) See more: - // https://developers.google.com/web/updates/2017/06/play-request-was-interrupted - playPromise.then(sound.pause).catch(function() { - // Play without user interaction was prevented. - }); - } else { - sound.pause(); - } - - // iOS can only process one sound at a time. Trying to load more than one - // corrupts the earlier ones. Just load one and leave the others uncached. - if (userAgent.IPAD || userAgent.IPHONE) { - break; - } - } -}; - -/** - * Play a named sound at specified volume. If volume is not specified, - * use full volume (1). - * @param {string} name Name of sound. - * @param {number=} opt_volume Volume of sound (0-1). - */ -WorkspaceAudio.prototype.play = function(name, opt_volume) { - const sound = this.SOUNDS_[name]; - if (sound) { - // Don't play one sound on top of another. - const now = new Date; - if (this.lastSound_ !== null && - now - this.lastSound_ < internalConstants.SOUND_LIMIT) { + /** + * Load an audio file. Cache it, ready for instantaneous playing. + * @param {!Array} filenames List of file types in decreasing order of + * preference (i.e. increasing size). E.g. ['media/go.mp3', 'media/go.wav'] + * Filenames include path from Blockly's root. File extensions matter. + * @param {string} name Name of sound. + */ + load(filenames, name) { + if (!filenames.length) { return; } - this.lastSound_ = now; - let mySound; - if (userAgent.IPAD || userAgent.ANDROID) { - // Creating a new audio node causes lag in Android and iPad. Android - // refetches the file from the server, iPad uses a singleton audio - // node which must be deleted and recreated for each new audio tag. - mySound = sound; - } else { - mySound = sound.cloneNode(); + let audioTest; + try { + audioTest = new globalThis['Audio'](); + } catch (e) { + // No browser support for Audio. + // IE can throw an error even if the Audio object exists. + return; + } + let sound; + for (let i = 0; i < filenames.length; i++) { + const filename = filenames[i]; + const ext = filename.match(/\.(\w+)$/); + if (ext && audioTest.canPlayType('audio/' + ext[1])) { + // Found an audio format we can play. + sound = new globalThis['Audio'](filename); + break; + } + } + if (sound && sound.play) { + this.SOUNDS_[name] = sound; } - mySound.volume = (opt_volume === undefined ? 1 : opt_volume); - mySound.play(); - } else if (this.parentWorkspace_) { - // Maybe a workspace on a lower level knows about this sound. - this.parentWorkspace_.getAudioManager().play(name, opt_volume); } -}; + /** + * Preload all the audio files so that they play quickly when asked for. + * @package + */ + preload() { + for (const name in this.SOUNDS_) { + const sound = this.SOUNDS_[name]; + sound.volume = 0.01; + const playPromise = sound.play(); + // Edge does not return a promise, so we need to check. + if (playPromise !== undefined) { + // If we don't wait for the play request to complete before calling + // pause() we will get an exception: (DOMException: The play() request + // was interrupted) See more: + // https://developers.google.com/web/updates/2017/06/play-request-was-interrupted + playPromise.then(sound.pause).catch(function() { + // Play without user interaction was prevented. + }); + } else { + sound.pause(); + } + + // iOS can only process one sound at a time. Trying to load more than one + // corrupts the earlier ones. Just load one and leave the others + // uncached. + if (userAgent.IPAD || userAgent.IPHONE) { + break; + } + } + } + /** + * Play a named sound at specified volume. If volume is not specified, + * use full volume (1). + * @param {string} name Name of sound. + * @param {number=} opt_volume Volume of sound (0-1). + */ + play(name, opt_volume) { + const sound = this.SOUNDS_[name]; + if (sound) { + // Don't play one sound on top of another. + const now = new Date; + if (this.lastSound_ !== null && + now - this.lastSound_ < internalConstants.SOUND_LIMIT) { + return; + } + this.lastSound_ = now; + let mySound; + if (userAgent.IPAD || userAgent.ANDROID) { + // Creating a new audio node causes lag in Android and iPad. Android + // refetches the file from the server, iPad uses a singleton audio + // node which must be deleted and recreated for each new audio tag. + mySound = sound; + } else { + mySound = sound.cloneNode(); + } + mySound.volume = (opt_volume === undefined ? 1 : opt_volume); + mySound.play(); + } else if (this.parentWorkspace_) { + // Maybe a workspace on a lower level knows about this sound. + this.parentWorkspace_.getAudioManager().play(name, opt_volume); + } + } +} exports.WorkspaceAudio = WorkspaceAudio; diff --git a/core/workspace_drag_surface_svg.js b/core/workspace_drag_surface_svg.js index 586e9676f..51f9a901d 100644 --- a/core/workspace_drag_surface_svg.js +++ b/core/workspace_drag_surface_svg.js @@ -33,155 +33,162 @@ const {Svg} = goog.require('Blockly.utils.Svg'); * Blocks are moved into this SVG during a drag, improving performance. * The entire SVG is translated using CSS transforms instead of SVG so the * blocks are never repainted during drag improving performance. - * @param {!Element} container Containing element. - * @constructor * @alias Blockly.WorkspaceDragSurfaceSvg */ -const WorkspaceDragSurfaceSvg = function(container) { - this.container_ = container; - this.createDom(); -}; - -/** - * The SVG drag surface. Set once by WorkspaceDragSurfaceSvg.createDom. - * @type {SVGElement} - * @private - */ -WorkspaceDragSurfaceSvg.prototype.SVG_ = null; - -/** - * Containing HTML element; parent of the workspace and the drag surface. - * @type {Element} - * @private - */ -WorkspaceDragSurfaceSvg.prototype.container_ = null; - -/** - * Create the drag surface and inject it into the container. - */ -WorkspaceDragSurfaceSvg.prototype.createDom = function() { - if (this.SVG_) { - return; // Already created. - } - +class WorkspaceDragSurfaceSvg { /** - * Dom structure when the workspace is being dragged. If there is no drag in - * progress, the SVG is empty and display: none. - * - * - * /g> - * + * @param {!Element} container Containing element. */ - this.SVG_ = dom.createSvgElement( - Svg.SVG, { - 'xmlns': dom.SVG_NS, - 'xmlns:html': dom.HTML_NS, - 'xmlns:xlink': dom.XLINK_NS, - 'version': '1.1', - 'class': 'blocklyWsDragSurface blocklyOverflowVisible', - }, - null); - this.container_.appendChild(this.SVG_); -}; + constructor(container) { + /** + * The SVG drag surface. Set once by WorkspaceDragSurfaceSvg.createDom. + * @type {SVGElement} + * @private + */ + this.SVG_ = null; -/** - * Translate the entire drag surface during a drag. - * We translate the drag surface instead of the blocks inside the surface - * so that the browser avoids repainting the SVG. - * Because of this, the drag coordinates must be adjusted by scale. - * @param {number} x X translation for the entire surface - * @param {number} y Y translation for the entire surface - * @package - */ -WorkspaceDragSurfaceSvg.prototype.translateSurface = function(x, y) { - // This is a work-around to prevent a the blocks from rendering - // fuzzy while they are being moved on the drag surface. - const fixedX = x.toFixed(0); - const fixedY = y.toFixed(0); + /** + * Containing HTML element; parent of the workspace and the drag surface. + * @type {Element} + * @private + */ + this.container_ = container; - this.SVG_.style.display = 'block'; - dom.setCssTransform( - this.SVG_, 'translate3d(' + fixedX + 'px, ' + fixedY + 'px, 0)'); -}; + /** + * The element to insert the block canvas and bubble canvas after when it + * goes back in the DOM at the end of a drag. + * @type {Element} + * @private + */ + this.previousSibling_ = null; -/** - * Reports the surface translation in scaled workspace coordinates. - * Use this when finishing a drag to return blocks to the correct position. - * @return {!Coordinate} Current translation of the surface - * @package - */ -WorkspaceDragSurfaceSvg.prototype.getSurfaceTranslation = function() { - return svgMath.getRelativeXY(/** @type {!SVGElement} */ (this.SVG_)); -}; - -/** - * Move the blockCanvas and bubbleCanvas out of the surface SVG and on to - * newSurface. - * @param {SVGElement} newSurface The element to put the drag surface contents - * into. - * @package - */ -WorkspaceDragSurfaceSvg.prototype.clearAndHide = function(newSurface) { - if (!newSurface) { - throw Error( - 'Couldn\'t clear and hide the drag surface: missing new surface.'); - } - const blockCanvas = /** @type {!Element} */ (this.SVG_.childNodes[0]); - const bubbleCanvas = /** @type {!Element} */ (this.SVG_.childNodes[1]); - if (!blockCanvas || !bubbleCanvas || - !dom.hasClass(blockCanvas, 'blocklyBlockCanvas') || - !dom.hasClass(bubbleCanvas, 'blocklyBubbleCanvas')) { - throw Error( - 'Couldn\'t clear and hide the drag surface. A node was missing.'); + this.createDom(); } + /** + * Create the drag surface and inject it into the container. + */ + createDom() { + if (this.SVG_) { + return; // Already created. + } - // If there is a previous sibling, put the blockCanvas back right afterwards, - // otherwise insert it as the first child node in newSurface. - if (this.previousSibling_ !== null) { - dom.insertAfter(blockCanvas, this.previousSibling_); - } else { - newSurface.insertBefore(blockCanvas, newSurface.firstChild); + /** + * Dom structure when the workspace is being dragged. If there is no drag in + * progress, the SVG is empty and display: none. + * + * + * /g> + * + */ + this.SVG_ = dom.createSvgElement( + Svg.SVG, { + 'xmlns': dom.SVG_NS, + 'xmlns:html': dom.HTML_NS, + 'xmlns:xlink': dom.XLINK_NS, + 'version': '1.1', + 'class': 'blocklyWsDragSurface blocklyOverflowVisible', + }, + null); + this.container_.appendChild(this.SVG_); } + /** + * Translate the entire drag surface during a drag. + * We translate the drag surface instead of the blocks inside the surface + * so that the browser avoids repainting the SVG. + * Because of this, the drag coordinates must be adjusted by scale. + * @param {number} x X translation for the entire surface + * @param {number} y Y translation for the entire surface + * @package + */ + translateSurface(x, y) { + // This is a work-around to prevent a the blocks from rendering + // fuzzy while they are being moved on the drag surface. + const fixedX = x.toFixed(0); + const fixedY = y.toFixed(0); - // Reattach the bubble canvas after the blockCanvas. - dom.insertAfter(bubbleCanvas, blockCanvas); - // Hide the drag surface. - this.SVG_.style.display = 'none'; - if (this.SVG_.childNodes.length) { - throw Error('Drag surface was not cleared.'); + this.SVG_.style.display = 'block'; + dom.setCssTransform( + this.SVG_, 'translate3d(' + fixedX + 'px, ' + fixedY + 'px, 0)'); } - dom.setCssTransform(this.SVG_, ''); - this.previousSibling_ = null; -}; + /** + * Reports the surface translation in scaled workspace coordinates. + * Use this when finishing a drag to return blocks to the correct position. + * @return {!Coordinate} Current translation of the surface + * @package + */ + getSurfaceTranslation() { + return svgMath.getRelativeXY(/** @type {!SVGElement} */ (this.SVG_)); + } + /** + * Move the blockCanvas and bubbleCanvas out of the surface SVG and on to + * newSurface. + * @param {SVGElement} newSurface The element to put the drag surface contents + * into. + * @package + */ + clearAndHide(newSurface) { + if (!newSurface) { + throw Error( + 'Couldn\'t clear and hide the drag surface: missing new surface.'); + } + const blockCanvas = /** @type {!Element} */ (this.SVG_.childNodes[0]); + const bubbleCanvas = /** @type {!Element} */ (this.SVG_.childNodes[1]); + if (!blockCanvas || !bubbleCanvas || + !dom.hasClass(blockCanvas, 'blocklyBlockCanvas') || + !dom.hasClass(bubbleCanvas, 'blocklyBubbleCanvas')) { + throw Error( + 'Couldn\'t clear and hide the drag surface. A node was missing.'); + } -/** - * Set the SVG to have the block canvas and bubble canvas in it and then - * show the surface. - * @param {!SVGElement} blockCanvas The block canvas element from the - * workspace. - * @param {!SVGElement} bubbleCanvas The element that contains the bubbles. - * @param {Element} previousSibling The element to insert the block canvas and - bubble canvas after when it goes back in the DOM at the end of a drag. - * @param {number} width The width of the workspace SVG element. - * @param {number} height The height of the workspace SVG element. - * @param {number} scale The scale of the workspace being dragged. - * @package - */ -WorkspaceDragSurfaceSvg.prototype.setContentsAndShow = function( - blockCanvas, bubbleCanvas, previousSibling, width, height, scale) { - if (this.SVG_.childNodes.length) { - throw Error('Already dragging a block.'); + // If there is a previous sibling, put the blockCanvas back right + // afterwards, otherwise insert it as the first child node in newSurface. + if (this.previousSibling_ !== null) { + dom.insertAfter(blockCanvas, this.previousSibling_); + } else { + newSurface.insertBefore(blockCanvas, newSurface.firstChild); + } + + // Reattach the bubble canvas after the blockCanvas. + dom.insertAfter(bubbleCanvas, blockCanvas); + // Hide the drag surface. + this.SVG_.style.display = 'none'; + if (this.SVG_.childNodes.length) { + throw Error('Drag surface was not cleared.'); + } + dom.setCssTransform(this.SVG_, ''); + this.previousSibling_ = null; } - this.previousSibling_ = previousSibling; - // Make sure the blocks and bubble canvas are scaled appropriately. - blockCanvas.setAttribute('transform', 'translate(0, 0) scale(' + scale + ')'); - bubbleCanvas.setAttribute( - 'transform', 'translate(0, 0) scale(' + scale + ')'); - this.SVG_.setAttribute('width', width); - this.SVG_.setAttribute('height', height); - this.SVG_.appendChild(blockCanvas); - this.SVG_.appendChild(bubbleCanvas); - this.SVG_.style.display = 'block'; -}; + /** + * Set the SVG to have the block canvas and bubble canvas in it and then + * show the surface. + * @param {!SVGElement} blockCanvas The block canvas element from the + * workspace. + * @param {!SVGElement} bubbleCanvas The element that contains the + bubbles. + * @param {Element} previousSibling The element to insert the block canvas and + bubble canvas after when it goes back in the DOM at the end of a drag. + * @param {number} width The width of the workspace SVG element. + * @param {number} height The height of the workspace SVG element. + * @param {number} scale The scale of the workspace being dragged. + * @package + */ + setContentsAndShow( + blockCanvas, bubbleCanvas, previousSibling, width, height, scale) { + if (this.SVG_.childNodes.length) { + throw Error('Already dragging a block.'); + } + this.previousSibling_ = previousSibling; + // Make sure the blocks and bubble canvas are scaled appropriately. + blockCanvas.setAttribute( + 'transform', 'translate(0, 0) scale(' + scale + ')'); + bubbleCanvas.setAttribute( + 'transform', 'translate(0, 0) scale(' + scale + ')'); + this.SVG_.setAttribute('width', width); + this.SVG_.setAttribute('height', height); + this.SVG_.appendChild(blockCanvas); + this.SVG_.appendChild(bubbleCanvas); + this.SVG_.style.display = 'block'; + } +} exports.WorkspaceDragSurfaceSvg = WorkspaceDragSurfaceSvg; diff --git a/core/workspace_dragger.js b/core/workspace_dragger.js index f888f3514..ce2e5ba26 100644 --- a/core/workspace_dragger.js +++ b/core/workspace_dragger.js @@ -27,90 +27,89 @@ const {WorkspaceSvg} = goog.requireType('Blockly.WorkspaceSvg'); * Note that the workspace itself manages whether or not it has a drag surface * and how to do translations based on that. This simply passes the right * commands based on events. - * @param {!WorkspaceSvg} workspace The workspace to drag. - * @constructor * @alias Blockly.WorkspaceDragger */ -const WorkspaceDragger = function(workspace) { +class WorkspaceDragger { /** - * @type {!WorkspaceSvg} - * @private + * @param {!WorkspaceSvg} workspace The workspace to drag. */ - this.workspace_ = workspace; + constructor(workspace) { + /** + * @type {!WorkspaceSvg} + * @private + */ + this.workspace_ = workspace; - /** - * Whether horizontal scroll is enabled. - * @type {boolean} - * @private - */ - this.horizontalScrollEnabled_ = this.workspace_.isMovableHorizontally(); + /** + * Whether horizontal scroll is enabled. + * @type {boolean} + * @private + */ + this.horizontalScrollEnabled_ = this.workspace_.isMovableHorizontally(); - /** - * Whether vertical scroll is enabled. - * @type {boolean} - * @private - */ - this.verticalScrollEnabled_ = this.workspace_.isMovableVertically(); + /** + * Whether vertical scroll is enabled. + * @type {boolean} + * @private + */ + this.verticalScrollEnabled_ = this.workspace_.isMovableVertically(); - /** - * The scroll position of the workspace at the beginning of the drag. - * Coordinate system: pixel coordinates. - * @type {!Coordinate} - * @protected - */ - this.startScrollXY_ = new Coordinate(workspace.scrollX, workspace.scrollY); -}; - -/** - * Sever all links from this object. - * @package - * @suppress {checkTypes} - */ -WorkspaceDragger.prototype.dispose = function() { - this.workspace_ = null; -}; - -/** - * Start dragging the workspace. - * @package - */ -WorkspaceDragger.prototype.startDrag = function() { - if (common.getSelected()) { - common.getSelected().unselect(); + /** + * The scroll position of the workspace at the beginning of the drag. + * Coordinate system: pixel coordinates. + * @type {!Coordinate} + * @protected + */ + this.startScrollXY_ = new Coordinate(workspace.scrollX, workspace.scrollY); } - this.workspace_.setupDragSurface(); -}; - -/** - * Finish dragging the workspace and put everything back where it belongs. - * @param {!Coordinate} currentDragDeltaXY How far the pointer has - * moved from the position at the start of the drag, in pixel coordinates. - * @package - */ -WorkspaceDragger.prototype.endDrag = function(currentDragDeltaXY) { - // Make sure everything is up to date. - this.drag(currentDragDeltaXY); - this.workspace_.resetDragSurface(); -}; - -/** - * Move the workspace based on the most recent mouse movements. - * @param {!Coordinate} currentDragDeltaXY How far the pointer has - * moved from the position at the start of the drag, in pixel coordinates. - * @package - */ -WorkspaceDragger.prototype.drag = function(currentDragDeltaXY) { - const newXY = Coordinate.sum(this.startScrollXY_, currentDragDeltaXY); - - if (this.horizontalScrollEnabled_ && this.verticalScrollEnabled_) { - this.workspace_.scroll(newXY.x, newXY.y); - } else if (this.horizontalScrollEnabled_) { - this.workspace_.scroll(newXY.x, this.workspace_.scrollY); - } else if (this.verticalScrollEnabled_) { - this.workspace_.scroll(this.workspace_.scrollX, newXY.y); - } else { - throw new TypeError('Invalid state.'); + /** + * Sever all links from this object. + * @package + * @suppress {checkTypes} + */ + dispose() { + this.workspace_ = null; } -}; + /** + * Start dragging the workspace. + * @package + */ + startDrag() { + if (common.getSelected()) { + common.getSelected().unselect(); + } + this.workspace_.setupDragSurface(); + } + /** + * Finish dragging the workspace and put everything back where it belongs. + * @param {!Coordinate} currentDragDeltaXY How far the pointer has + * moved from the position at the start of the drag, in pixel coordinates. + * @package + */ + endDrag(currentDragDeltaXY) { + // Make sure everything is up to date. + this.drag(currentDragDeltaXY); + this.workspace_.resetDragSurface(); + } + /** + * Move the workspace based on the most recent mouse movements. + * @param {!Coordinate} currentDragDeltaXY How far the pointer has + * moved from the position at the start of the drag, in pixel coordinates. + * @package + */ + drag(currentDragDeltaXY) { + const newXY = Coordinate.sum(this.startScrollXY_, currentDragDeltaXY); + + if (this.horizontalScrollEnabled_ && this.verticalScrollEnabled_) { + this.workspace_.scroll(newXY.x, newXY.y); + } else if (this.horizontalScrollEnabled_) { + this.workspace_.scroll(newXY.x, this.workspace_.scrollY); + } else if (this.verticalScrollEnabled_) { + this.workspace_.scroll(this.workspace_.scrollX, newXY.y); + } else { + throw new TypeError('Invalid state.'); + } + } +} exports.WorkspaceDragger = WorkspaceDragger; diff --git a/core/workspace_svg.js b/core/workspace_svg.js index 28b3c8eca..b13d0e56e 100644 --- a/core/workspace_svg.js +++ b/core/workspace_svg.js @@ -130,6 +130,278 @@ const WorkspaceSvg = function( options, opt_blockDragSurface, opt_wsDragSurface) { WorkspaceSvg.superClass_.constructor.call(this, options); + /** + * A wrapper function called when a resize event occurs. + * You can pass the result to `eventHandling.unbind`. + * @type {?browserEvents.Data} + * @private + */ + this.resizeHandlerWrapper_ = null; + + /** + * The render status of an SVG workspace. + * Returns `false` for headless workspaces and true for instances of + * `WorkspaceSvg`. + * @type {boolean} + */ + this.rendered = true; + + /** + * Whether the workspace is visible. False if the workspace has been hidden + * by calling `setVisible(false)`. + * @type {boolean} + * @private + */ + this.isVisible_ = true; + + /** + * Is this workspace the surface for a flyout? + * @type {boolean} + */ + this.isFlyout = false; + + /** + * Is this workspace the surface for a mutator? + * @type {boolean} + * @package + */ + this.isMutator = false; + + /** + * Whether this workspace has resizes enabled. + * Disable during batch operations for a performance improvement. + * @type {boolean} + * @private + */ + this.resizesEnabled_ = true; + + /** + * Current horizontal scrolling offset in pixel units, relative to the + * workspace origin. + * + * It is useful to think about a view, and a canvas moving beneath that + * view. As the canvas moves right, this value becomes more positive, and + * the view is now "seeing" the left side of the canvas. As the canvas moves + * left, this value becomes more negative, and the view is now "seeing" the + * right side of the canvas. + * + * The confusing thing about this value is that it does not, and must not + * include the absoluteLeft offset. This is because it is used to calculate + * the viewLeft value. + * + * The viewLeft is relative to the workspace origin (although in pixel + * units). The workspace origin is the top-left corner of the workspace (at + * least when it is enabled). It is shifted from the top-left of the + * blocklyDiv so as not to be beneath the toolbox. + * + * When the workspace is enabled the viewLeft and workspace origin are at + * the same X location. As the canvas slides towards the right beneath the + * view this value (scrollX) becomes more positive, and the viewLeft becomes + * more negative relative to the workspace origin (imagine the workspace + * origin as a dot on the canvas sliding to the right as the canvas moves). + * + * So if the scrollX were to include the absoluteLeft this would in a way + * "unshift" the workspace origin. This means that the viewLeft would be + * representing the left edge of the blocklyDiv, rather than the left edge + * of the workspace. + * + * @type {number} + */ + this.scrollX = 0; + + /** + * Current vertical scrolling offset in pixel units, relative to the + * workspace origin. + * + * It is useful to think about a view, and a canvas moving beneath that + * view. As the canvas moves down, this value becomes more positive, and the + * view is now "seeing" the upper part of the canvas. As the canvas moves + * up, this value becomes more negative, and the view is "seeing" the lower + * part of the canvas. + * + * This confusing thing about this value is that it does not, and must not + * include the absoluteTop offset. This is because it is used to calculate + * the viewTop value. + * + * The viewTop is relative to the workspace origin (although in pixel + * units). The workspace origin is the top-left corner of the workspace (at + * least when it is enabled). It is shifted from the top-left of the + * blocklyDiv so as not to be beneath the toolbox. + * + * When the workspace is enabled the viewTop and workspace origin are at the + * same Y location. As the canvas slides towards the bottom this value + * (scrollY) becomes more positive, and the viewTop becomes more negative + * relative to the workspace origin (image in the workspace origin as a dot + * on the canvas sliding downwards as the canvas moves). + * + * So if the scrollY were to include the absoluteTop this would in a way + * "unshift" the workspace origin. This means that the viewTop would be + * representing the top edge of the blocklyDiv, rather than the top edge of + * the workspace. + * + * @type {number} + */ + this.scrollY = 0; + + /** + * Horizontal scroll value when scrolling started in pixel units. + * @type {number} + */ + this.startScrollX = 0; + + /** + * Vertical scroll value when scrolling started in pixel units. + * @type {number} + */ + this.startScrollY = 0; + + /** + * Distance from mouse to object being dragged. + * @type {Coordinate} + * @private + */ + this.dragDeltaXY_ = null; + + /** + * Current scale. + * @type {number} + */ + this.scale = 1; + + /** + * Cached scale value. Used to detect changes in viewport. + * @type {number} + * @private + */ + this.oldScale_ = 1; + + /** + * Cached viewport top value. Used to detect changes in viewport. + * @type {number} + * @private + */ + this.oldTop_ = 0; + + /** + * Cached viewport left value. Used to detect changes in viewport. + * @type {number} + * @private + */ + this.oldLeft_ = 0; + + /** + * The workspace's trashcan (if any). + * @type {Trashcan} + */ + this.trashcan = null; + + /** + * This workspace's scrollbars, if they exist. + * @type {ScrollbarPair} + */ + this.scrollbar = null; + + /** + * Fixed flyout providing blocks which may be dragged into this workspace. + * @type {IFlyout} + * @private + */ + this.flyout_ = null; + + /** + * Category-based toolbox providing blocks which may be dragged into this + * workspace. + * @type {IToolbox} + * @private + */ + this.toolbox_ = null; + + /** + * The current gesture in progress on this workspace, if any. + * @type {TouchGesture} + * @private + */ + this.currentGesture_ = null; + + /** + * This workspace's surface for dragging blocks, if it exists. + * @type {BlockDragSurfaceSvg} + * @private + */ + this.blockDragSurface_ = null; + + /** + * This workspace's drag surface, if it exists. + * @type {WorkspaceDragSurfaceSvg} + * @private + */ + this.workspaceDragSurface_ = null; + + /** + * Whether to move workspace to the drag surface when it is dragged. + * True if it should move, false if it should be translated directly. + * @type {boolean} + * @private + */ + this.useWorkspaceDragSurface_ = false; + + /** + * Whether the drag surface is actively in use. When true, calls to + * translate will translate the drag surface instead of the translating the + * workspace directly. + * This is set to true in setupDragSurface and to false in resetDragSurface. + * @type {boolean} + * @private + */ + this.isDragSurfaceActive_ = false; + + /** + * The first parent div with 'injectionDiv' in the name, or null if not set. + * Access this with getInjectionDiv. + * @type {Element} + * @private + */ + this.injectionDiv_ = null; + + /** + * Last known position of the page scroll. + * This is used to determine whether we have recalculated screen coordinate + * stuff since the page scrolled. + * @type {Coordinate} + * @private + */ + this.lastRecordedPageScroll_ = null; + + /** + * Developers may define this function to add custom menu options to the + * workspace's context menu or edit the workspace-created set of menu options. + * @param {!Array} options List of menu options to add to. + * @param {!Event} e The right-click event that triggered the context menu. + */ + this.configureContextMenu; + + /** + * In a flyout, the target workspace where blocks should be placed after a + * drag. Otherwise null. + * @type {WorkspaceSvg} + * @package + */ + this.targetWorkspace = null; + + /** + * Inverted screen CTM, for use in mouseToSvg. + * @type {?SVGMatrix} + * @private + */ + this.inverseScreenCTM_ = null; + + /** + * Inverted screen CTM is dirty, recalculate it. + * @type {boolean} + * @private + */ + this.inverseScreenCTMDirty_ = true; + const MetricsManagerClass = registry.getClassFromOptions( registry.Type.METRICS_MANAGER, options, true); /** @@ -302,278 +574,6 @@ const WorkspaceSvg = function( }; object.inherits(WorkspaceSvg, Workspace); -/** - * A wrapper function called when a resize event occurs. - * You can pass the result to `eventHandling.unbind`. - * @type {?browserEvents.Data} - * @private - */ -WorkspaceSvg.prototype.resizeHandlerWrapper_ = null; - -/** - * The render status of an SVG workspace. - * Returns `false` for headless workspaces and true for instances of - * `WorkspaceSvg`. - * @type {boolean} - */ -WorkspaceSvg.prototype.rendered = true; - -/** - * Whether the workspace is visible. False if the workspace has been hidden - * by calling `setVisible(false)`. - * @type {boolean} - * @private - */ -WorkspaceSvg.prototype.isVisible_ = true; - -/** - * Is this workspace the surface for a flyout? - * @type {boolean} - */ -WorkspaceSvg.prototype.isFlyout = false; - -/** - * Is this workspace the surface for a mutator? - * @type {boolean} - * @package - */ -WorkspaceSvg.prototype.isMutator = false; - -/** - * Whether this workspace has resizes enabled. - * Disable during batch operations for a performance improvement. - * @type {boolean} - * @private - */ -WorkspaceSvg.prototype.resizesEnabled_ = true; - -/** - * Current horizontal scrolling offset in pixel units, relative to the - * workspace origin. - * - * It is useful to think about a view, and a canvas moving beneath that - * view. As the canvas moves right, this value becomes more positive, and - * the view is now "seeing" the left side of the canvas. As the canvas moves - * left, this value becomes more negative, and the view is now "seeing" the - * right side of the canvas. - * - * The confusing thing about this value is that it does not, and must not - * include the absoluteLeft offset. This is because it is used to calculate - * the viewLeft value. - * - * The viewLeft is relative to the workspace origin (although in pixel - * units). The workspace origin is the top-left corner of the workspace (at - * least when it is enabled). It is shifted from the top-left of the blocklyDiv - * so as not to be beneath the toolbox. - * - * When the workspace is enabled the viewLeft and workspace origin are at - * the same X location. As the canvas slides towards the right beneath the view - * this value (scrollX) becomes more positive, and the viewLeft becomes more - * negative relative to the workspace origin (imagine the workspace origin - * as a dot on the canvas sliding to the right as the canvas moves). - * - * So if the scrollX were to include the absoluteLeft this would in a way - * "unshift" the workspace origin. This means that the viewLeft would be - * representing the left edge of the blocklyDiv, rather than the left edge - * of the workspace. - * - * @type {number} - */ -WorkspaceSvg.prototype.scrollX = 0; - -/** - * Current vertical scrolling offset in pixel units, relative to the - * workspace origin. - * - * It is useful to think about a view, and a canvas moving beneath that - * view. As the canvas moves down, this value becomes more positive, and the - * view is now "seeing" the upper part of the canvas. As the canvas moves - * up, this value becomes more negative, and the view is "seeing" the lower - * part of the canvas. - * - * This confusing thing about this value is that it does not, and must not - * include the absoluteTop offset. This is because it is used to calculate - * the viewTop value. - * - * The viewTop is relative to the workspace origin (although in pixel - * units). The workspace origin is the top-left corner of the workspace (at - * least when it is enabled). It is shifted from the top-left of the - * blocklyDiv so as not to be beneath the toolbox. - * - * When the workspace is enabled the viewTop and workspace origin are at the - * same Y location. As the canvas slides towards the bottom this value - * (scrollY) becomes more positive, and the viewTop becomes more negative - * relative to the workspace origin (image in the workspace origin as a dot - * on the canvas sliding downwards as the canvas moves). - * - * So if the scrollY were to include the absoluteTop this would in a way - * "unshift" the workspace origin. This means that the viewTop would be - * representing the top edge of the blocklyDiv, rather than the top edge of - * the workspace. - * - * @type {number} - */ -WorkspaceSvg.prototype.scrollY = 0; - -/** - * Horizontal scroll value when scrolling started in pixel units. - * @type {number} - */ -WorkspaceSvg.prototype.startScrollX = 0; - -/** - * Vertical scroll value when scrolling started in pixel units. - * @type {number} - */ -WorkspaceSvg.prototype.startScrollY = 0; - -/** - * Distance from mouse to object being dragged. - * @type {Coordinate} - * @private - */ -WorkspaceSvg.prototype.dragDeltaXY_ = null; - -/** - * Current scale. - * @type {number} - */ -WorkspaceSvg.prototype.scale = 1; - -/** - * Cached scale value. Used to detect changes in viewport. - * @type {number} - * @private - */ -WorkspaceSvg.prototype.oldScale_ = 1; - -/** - * Cached viewport top value. Used to detect changes in viewport. - * @type {number} - * @private - */ -WorkspaceSvg.prototype.oldTop_ = 0; - -/** - * Cached viewport left value. Used to detect changes in viewport. - * @type {number} - * @private - */ -WorkspaceSvg.prototype.oldLeft_ = 0; - -/** - * The workspace's trashcan (if any). - * @type {Trashcan} - */ -WorkspaceSvg.prototype.trashcan = null; - -/** - * This workspace's scrollbars, if they exist. - * @type {ScrollbarPair} - */ -WorkspaceSvg.prototype.scrollbar = null; - -/** - * Fixed flyout providing blocks which may be dragged into this workspace. - * @type {IFlyout} - * @private - */ -WorkspaceSvg.prototype.flyout_ = null; - -/** - * Category-based toolbox providing blocks which may be dragged into this - * workspace. - * @type {IToolbox} - * @private - */ -WorkspaceSvg.prototype.toolbox_ = null; - -/** - * The current gesture in progress on this workspace, if any. - * @type {TouchGesture} - * @private - */ -WorkspaceSvg.prototype.currentGesture_ = null; - -/** - * This workspace's surface for dragging blocks, if it exists. - * @type {BlockDragSurfaceSvg} - * @private - */ -WorkspaceSvg.prototype.blockDragSurface_ = null; - -/** - * This workspace's drag surface, if it exists. - * @type {WorkspaceDragSurfaceSvg} - * @private - */ -WorkspaceSvg.prototype.workspaceDragSurface_ = null; - -/** - * Whether to move workspace to the drag surface when it is dragged. - * True if it should move, false if it should be translated directly. - * @type {boolean} - * @private - */ -WorkspaceSvg.prototype.useWorkspaceDragSurface_ = false; - -/** - * Whether the drag surface is actively in use. When true, calls to - * translate will translate the drag surface instead of the translating the - * workspace directly. - * This is set to true in setupDragSurface and to false in resetDragSurface. - * @type {boolean} - * @private - */ -WorkspaceSvg.prototype.isDragSurfaceActive_ = false; - -/** - * The first parent div with 'injectionDiv' in the name, or null if not set. - * Access this with getInjectionDiv. - * @type {Element} - * @private - */ -WorkspaceSvg.prototype.injectionDiv_ = null; - -/** - * Last known position of the page scroll. - * This is used to determine whether we have recalculated screen coordinate - * stuff since the page scrolled. - * @type {Coordinate} - * @private - */ -WorkspaceSvg.prototype.lastRecordedPageScroll_ = null; - -/** - * Developers may define this function to add custom menu options to the - * workspace's context menu or edit the workspace-created set of menu options. - * @param {!Array} options List of menu options to add to. - * @param {!Event} e The right-click event that triggered the context menu. - */ -WorkspaceSvg.prototype.configureContextMenu; - -/** - * In a flyout, the target workspace where blocks should be placed after a drag. - * Otherwise null. - * @type {WorkspaceSvg} - * @package - */ -WorkspaceSvg.prototype.targetWorkspace = null; - -/** - * Inverted screen CTM, for use in mouseToSvg. - * @type {?SVGMatrix} - * @private - */ -WorkspaceSvg.prototype.inverseScreenCTM_ = null; - -/** - * Inverted screen CTM is dirty, recalculate it. - * @type {boolean} - * @private - */ -WorkspaceSvg.prototype.inverseScreenCTMDirty_ = true; - /** * Get the marker manager for this workspace. * @return {!MarkerManager} The marker manager. diff --git a/core/zoom_controls.js b/core/zoom_controls.js index 28b2b5c32..3235a8e98 100644 --- a/core/zoom_controls.js +++ b/core/zoom_controls.js @@ -38,462 +38,454 @@ goog.require('Blockly.Events.Click'); /** * Class for a zoom controls. - * @param {!WorkspaceSvg} workspace The workspace to sit in. - * @constructor * @implements {IPositionable} * @alias Blockly.ZoomControls */ -const ZoomControls = function(workspace) { +class ZoomControls { /** - * @type {!WorkspaceSvg} - * @private + * @param {!WorkspaceSvg} workspace The workspace to sit in. */ - this.workspace_ = workspace; + constructor(workspace) { + /** + * @type {!WorkspaceSvg} + * @private + */ + this.workspace_ = workspace; + /** + * The unique id for this component that is used to register with the + * ComponentManager. + * @type {string} + */ + this.id = 'zoomControls'; + + /** + * A handle to use to unbind the mouse down event handler for zoom reset + * button. Opaque data returned from browserEvents.conditionalBind. + * @type {?browserEvents.Data} + * @private + */ + this.onZoomResetWrapper_ = null; + + /** + * A handle to use to unbind the mouse down event handler for zoom in + * button. Opaque data returned from browserEvents.conditionalBind. + * @type {?browserEvents.Data} + * @private + */ + this.onZoomInWrapper_ = null; + + /** + * A handle to use to unbind the mouse down event handler for zoom out + * button. Opaque data returned from browserEvents.conditionalBind. + * @type {?browserEvents.Data} + * @private + */ + this.onZoomOutWrapper_ = null; + + /** + * The zoom in svg element. + * @type {SVGGElement} + * @private + */ + this.zoomInGroup_ = null; + + /** + * The zoom out svg element. + * @type {SVGGElement} + * @private + */ + this.zoomOutGroup_ = null; + + /** + * The zoom reset svg element. + * @type {SVGGElement} + * @private + */ + this.zoomResetGroup_ = null; + + /** + * Width of the zoom controls. + * @type {number} + * @const + * @private + */ + this.WIDTH_ = 32; + + /** + * Height of each zoom control. + * @type {number} + * @const + * @private + */ + this.HEIGHT_ = 32; + + /** + * Small spacing used between the zoom in and out control, in pixels. + * @type {number} + * @const + * @private + */ + this.SMALL_SPACING_ = 2; + + /** + * Large spacing used between the zoom in and reset control, in pixels. + * @type {number} + * @const + * @private + */ + this.LARGE_SPACING_ = 11; + + /** + * Distance between zoom controls and bottom or top edge of workspace. + * @type {number} + * @const + * @private + */ + this.MARGIN_VERTICAL_ = 20; + + /** + * Distance between zoom controls and right or left edge of workspace. + * @type {number} + * @private + */ + this.MARGIN_HORIZONTAL_ = 20; + + /** + * The SVG group containing the zoom controls. + * @type {SVGElement} + * @private + */ + this.svgGroup_ = null; + + /** + * Left coordinate of the zoom controls. + * @type {number} + * @private + */ + this.left_ = 0; + + /** + * Top coordinate of the zoom controls. + * @type {number} + * @private + */ + this.top_ = 0; + + /** + * Whether this has been initialized. + * @type {boolean} + * @private + */ + this.initialized_ = false; + } /** - * The unique id for this component that is used to register with the - * ComponentManager. - * @type {string} + * Create the zoom controls. + * @return {!SVGElement} The zoom controls SVG group. */ - this.id = 'zoomControls'; + createDom() { + this.svgGroup_ = dom.createSvgElement(Svg.G, {}, null); - /** - * A handle to use to unbind the mouse down event handler for zoom reset - * button. Opaque data returned from browserEvents.conditionalBind. - * @type {?browserEvents.Data} - * @private - */ - this.onZoomResetWrapper_ = null; - - /** - * A handle to use to unbind the mouse down event handler for zoom in button. - * Opaque data returned from browserEvents.conditionalBind. - * @type {?browserEvents.Data} - * @private - */ - this.onZoomInWrapper_ = null; - - /** - * A handle to use to unbind the mouse down event handler for zoom out button. - * Opaque data returned from browserEvents.conditionalBind. - * @type {?browserEvents.Data} - * @private - */ - this.onZoomOutWrapper_ = null; - - /** - * The zoom in svg element. - * @type {SVGGElement} - * @private - */ - this.zoomInGroup_ = null; - - /** - * The zoom out svg element. - * @type {SVGGElement} - * @private - */ - this.zoomOutGroup_ = null; - - /** - * The zoom reset svg element. - * @type {SVGGElement} - * @private - */ - this.zoomResetGroup_ = null; -}; - -/** - * Width of the zoom controls. - * @type {number} - * @const - * @private - */ -ZoomControls.prototype.WIDTH_ = 32; - -/** - * Height of each zoom control. - * @type {number} - * @const - * @private - */ -ZoomControls.prototype.HEIGHT_ = 32; - -/** - * Small spacing used between the zoom in and out control, in pixels. - * @type {number} - * @const - * @private - */ -ZoomControls.prototype.SMALL_SPACING_ = 2; - -/** - * Large spacing used between the zoom in and reset control, in pixels. - * @type {number} - * @const - * @private - */ -ZoomControls.prototype.LARGE_SPACING_ = 11; - -/** - * Distance between zoom controls and bottom or top edge of workspace. - * @type {number} - * @const - * @private - */ -ZoomControls.prototype.MARGIN_VERTICAL_ = 20; - -/** - * Distance between zoom controls and right or left edge of workspace. - * @type {number} - * @private - */ -ZoomControls.prototype.MARGIN_HORIZONTAL_ = 20; - -/** - * The SVG group containing the zoom controls. - * @type {SVGElement} - * @private - */ -ZoomControls.prototype.svgGroup_ = null; - -/** - * Left coordinate of the zoom controls. - * @type {number} - * @private - */ -ZoomControls.prototype.left_ = 0; - -/** - * Top coordinate of the zoom controls. - * @type {number} - * @private - */ -ZoomControls.prototype.top_ = 0; - -/** - * Whether this has been initialized. - * @type {boolean} - * @private - */ -ZoomControls.prototype.initialized_ = false; - -/** - * Create the zoom controls. - * @return {!SVGElement} The zoom controls SVG group. - */ -ZoomControls.prototype.createDom = function() { - this.svgGroup_ = dom.createSvgElement(Svg.G, {}, null); - - // Each filter/pattern needs a unique ID for the case of multiple Blockly - // instances on a page. Browser behaviour becomes undefined otherwise. - // https://neil.fraser.name/news/2015/11/01/ - const rnd = String(Math.random()).substring(2); - this.createZoomOutSvg_(rnd); - this.createZoomInSvg_(rnd); - if (this.workspace_.isMovable()) { - // If we zoom to the center and the workspace isn't movable we could - // loose blocks at the edges of the workspace. - this.createZoomResetSvg_(rnd); - } - return this.svgGroup_; -}; - -/** - * Initializes the zoom controls. - */ -ZoomControls.prototype.init = function() { - this.workspace_.getComponentManager().addComponent({ - component: this, - weight: 2, - capabilities: [ComponentManager.Capability.POSITIONABLE], - }); - this.initialized_ = true; -}; - -/** - * Disposes of this zoom controls. - * Unlink from all DOM elements to prevent memory leaks. - */ -ZoomControls.prototype.dispose = function() { - this.workspace_.getComponentManager().removeComponent('zoomControls'); - if (this.svgGroup_) { - dom.removeNode(this.svgGroup_); - } - if (this.onZoomResetWrapper_) { - browserEvents.unbind(this.onZoomResetWrapper_); - } - if (this.onZoomInWrapper_) { - browserEvents.unbind(this.onZoomInWrapper_); - } - if (this.onZoomOutWrapper_) { - browserEvents.unbind(this.onZoomOutWrapper_); - } -}; - -/** - * Returns the bounding rectangle of the UI element in pixel units relative to - * the Blockly injection div. - * @return {?Rect} The UI elements's bounding box. Null if - * bounding box should be ignored by other UI elements. - */ -ZoomControls.prototype.getBoundingRectangle = function() { - let height = this.SMALL_SPACING_ + 2 * this.HEIGHT_; - if (this.zoomResetGroup_) { - height += this.LARGE_SPACING_ + this.HEIGHT_; - } - const bottom = this.top_ + height; - const right = this.left_ + this.WIDTH_; - return new Rect(this.top_, bottom, this.left_, right); -}; - - -/** - * Positions the zoom controls. - * It is positioned in the opposite corner to the corner the - * categories/toolbox starts at. - * @param {!MetricsManager.UiMetrics} metrics The workspace metrics. - * @param {!Array} savedPositions List of rectangles that - * are already on the workspace. - */ -ZoomControls.prototype.position = function(metrics, savedPositions) { - // Not yet initialized. - if (!this.initialized_) { - return; - } - - const cornerPosition = - uiPosition.getCornerOppositeToolbox(this.workspace_, metrics); - let height = this.SMALL_SPACING_ + 2 * this.HEIGHT_; - if (this.zoomResetGroup_) { - height += this.LARGE_SPACING_ + this.HEIGHT_; - } - const startRect = uiPosition.getStartPositionRect( - cornerPosition, new Size(this.WIDTH_, height), this.MARGIN_HORIZONTAL_, - this.MARGIN_VERTICAL_, metrics, this.workspace_); - - const verticalPosition = cornerPosition.vertical; - const bumpDirection = verticalPosition === uiPosition.verticalPosition.TOP ? - uiPosition.bumpDirection.DOWN : - uiPosition.bumpDirection.UP; - const positionRect = uiPosition.bumpPositionRect( - startRect, this.MARGIN_VERTICAL_, bumpDirection, savedPositions); - - if (verticalPosition === uiPosition.verticalPosition.TOP) { - const zoomInTranslateY = this.SMALL_SPACING_ + this.HEIGHT_; - this.zoomInGroup_.setAttribute( - 'transform', 'translate(0, ' + zoomInTranslateY + ')'); - if (this.zoomResetGroup_) { - const zoomResetTranslateY = - zoomInTranslateY + this.LARGE_SPACING_ + this.HEIGHT_; - this.zoomResetGroup_.setAttribute( - 'transform', 'translate(0, ' + zoomResetTranslateY + ')'); + // Each filter/pattern needs a unique ID for the case of multiple Blockly + // instances on a page. Browser behaviour becomes undefined otherwise. + // https://neil.fraser.name/news/2015/11/01/ + const rnd = String(Math.random()).substring(2); + this.createZoomOutSvg_(rnd); + this.createZoomInSvg_(rnd); + if (this.workspace_.isMovable()) { + // If we zoom to the center and the workspace isn't movable we could + // loose blocks at the edges of the workspace. + this.createZoomResetSvg_(rnd); } - } else { - const zoomInTranslateY = - this.zoomResetGroup_ ? this.LARGE_SPACING_ + this.HEIGHT_ : 0; - this.zoomInGroup_.setAttribute( - 'transform', 'translate(0, ' + zoomInTranslateY + ')'); - const zoomOutTranslateY = - zoomInTranslateY + this.SMALL_SPACING_ + this.HEIGHT_; - this.zoomOutGroup_.setAttribute( - 'transform', 'translate(0, ' + zoomOutTranslateY + ')'); + return this.svgGroup_; } + /** + * Initializes the zoom controls. + */ + init() { + this.workspace_.getComponentManager().addComponent({ + component: this, + weight: 2, + capabilities: [ComponentManager.Capability.POSITIONABLE], + }); + this.initialized_ = true; + } + /** + * Disposes of this zoom controls. + * Unlink from all DOM elements to prevent memory leaks. + */ + dispose() { + this.workspace_.getComponentManager().removeComponent('zoomControls'); + if (this.svgGroup_) { + dom.removeNode(this.svgGroup_); + } + if (this.onZoomResetWrapper_) { + browserEvents.unbind(this.onZoomResetWrapper_); + } + if (this.onZoomInWrapper_) { + browserEvents.unbind(this.onZoomInWrapper_); + } + if (this.onZoomOutWrapper_) { + browserEvents.unbind(this.onZoomOutWrapper_); + } + } + /** + * Returns the bounding rectangle of the UI element in pixel units relative to + * the Blockly injection div. + * @return {?Rect} The UI elements's bounding box. Null if + * bounding box should be ignored by other UI elements. + */ + getBoundingRectangle() { + let height = this.SMALL_SPACING_ + 2 * this.HEIGHT_; + if (this.zoomResetGroup_) { + height += this.LARGE_SPACING_ + this.HEIGHT_; + } + const bottom = this.top_ + height; + const right = this.left_ + this.WIDTH_; + return new Rect(this.top_, bottom, this.left_, right); + } + /** + * Positions the zoom controls. + * It is positioned in the opposite corner to the corner the + * categories/toolbox starts at. + * @param {!MetricsManager.UiMetrics} metrics The workspace metrics. + * @param {!Array} savedPositions List of rectangles that + * are already on the workspace. + */ + position(metrics, savedPositions) { + // Not yet initialized. + if (!this.initialized_) { + return; + } - this.top_ = positionRect.top; - this.left_ = positionRect.left; - this.svgGroup_.setAttribute( - 'transform', 'translate(' + this.left_ + ',' + this.top_ + ')'); -}; + const cornerPosition = + uiPosition.getCornerOppositeToolbox(this.workspace_, metrics); + let height = this.SMALL_SPACING_ + 2 * this.HEIGHT_; + if (this.zoomResetGroup_) { + height += this.LARGE_SPACING_ + this.HEIGHT_; + } + const startRect = uiPosition.getStartPositionRect( + cornerPosition, new Size(this.WIDTH_, height), this.MARGIN_HORIZONTAL_, + this.MARGIN_VERTICAL_, metrics, this.workspace_); -/** - * Create the zoom in icon and its event handler. - * @param {string} rnd The random string to use as a suffix in the clip path's - * ID. These IDs must be unique in case there are multiple Blockly - * instances on the same page. - * @private - */ -ZoomControls.prototype.createZoomOutSvg_ = function(rnd) { - /* This markup will be generated and added to the .svgGroup_: - - - - - */ - this.zoomOutGroup_ = - dom.createSvgElement(Svg.G, {'class': 'blocklyZoom'}, this.svgGroup_); - const clip = dom.createSvgElement( - Svg.CLIPPATH, {'id': 'blocklyZoomoutClipPath' + rnd}, this.zoomOutGroup_); - dom.createSvgElement( - Svg.RECT, { - 'width': 32, - 'height': 32, - }, - clip); - const zoomoutSvg = dom.createSvgElement( - Svg.IMAGE, { - 'width': internalConstants.SPRITE.width, - 'height': internalConstants.SPRITE.height, - 'x': -64, - 'y': -92, - 'clip-path': 'url(#blocklyZoomoutClipPath' + rnd + ')', - }, - this.zoomOutGroup_); - zoomoutSvg.setAttributeNS( - dom.XLINK_NS, 'xlink:href', - this.workspace_.options.pathToMedia + internalConstants.SPRITE.url); + const verticalPosition = cornerPosition.vertical; + const bumpDirection = verticalPosition === uiPosition.verticalPosition.TOP ? + uiPosition.bumpDirection.DOWN : + uiPosition.bumpDirection.UP; + const positionRect = uiPosition.bumpPositionRect( + startRect, this.MARGIN_VERTICAL_, bumpDirection, savedPositions); - // Attach listener. - this.onZoomOutWrapper_ = browserEvents.conditionalBind( - this.zoomOutGroup_, 'mousedown', null, this.zoom_.bind(this, -1)); -}; + if (verticalPosition === uiPosition.verticalPosition.TOP) { + const zoomInTranslateY = this.SMALL_SPACING_ + this.HEIGHT_; + this.zoomInGroup_.setAttribute( + 'transform', 'translate(0, ' + zoomInTranslateY + ')'); + if (this.zoomResetGroup_) { + const zoomResetTranslateY = + zoomInTranslateY + this.LARGE_SPACING_ + this.HEIGHT_; + this.zoomResetGroup_.setAttribute( + 'transform', 'translate(0, ' + zoomResetTranslateY + ')'); + } + } else { + const zoomInTranslateY = + this.zoomResetGroup_ ? this.LARGE_SPACING_ + this.HEIGHT_ : 0; + this.zoomInGroup_.setAttribute( + 'transform', 'translate(0, ' + zoomInTranslateY + ')'); + const zoomOutTranslateY = + zoomInTranslateY + this.SMALL_SPACING_ + this.HEIGHT_; + this.zoomOutGroup_.setAttribute( + 'transform', 'translate(0, ' + zoomOutTranslateY + ')'); + } -/** - * Create the zoom out icon and its event handler. - * @param {string} rnd The random string to use as a suffix in the clip path's - * ID. These IDs must be unique in case there are multiple Blockly - * instances on the same page. - * @private - */ -ZoomControls.prototype.createZoomInSvg_ = function(rnd) { - /* This markup will be generated and added to the .svgGroup_: - - - - - - - */ - this.zoomInGroup_ = - dom.createSvgElement(Svg.G, {'class': 'blocklyZoom'}, this.svgGroup_); - const clip = dom.createSvgElement( - Svg.CLIPPATH, {'id': 'blocklyZoominClipPath' + rnd}, this.zoomInGroup_); - dom.createSvgElement( - Svg.RECT, { - 'width': 32, - 'height': 32, - }, - clip); - const zoominSvg = dom.createSvgElement( - Svg.IMAGE, { - 'width': internalConstants.SPRITE.width, - 'height': internalConstants.SPRITE.height, - 'x': -32, - 'y': -92, - 'clip-path': 'url(#blocklyZoominClipPath' + rnd + ')', - }, - this.zoomInGroup_); - zoominSvg.setAttributeNS( - dom.XLINK_NS, 'xlink:href', - this.workspace_.options.pathToMedia + internalConstants.SPRITE.url); + this.top_ = positionRect.top; + this.left_ = positionRect.left; + this.svgGroup_.setAttribute( + 'transform', 'translate(' + this.left_ + ',' + this.top_ + ')'); + } + /** + * Create the zoom in icon and its event handler. + * @param {string} rnd The random string to use as a suffix in the clip path's + * ID. These IDs must be unique in case there are multiple Blockly + * instances on the same page. + * @private + */ + createZoomOutSvg_(rnd) { + /* This markup will be generated and added to the .svgGroup_: + + + + + */ + this.zoomOutGroup_ = + dom.createSvgElement(Svg.G, {'class': 'blocklyZoom'}, this.svgGroup_); + const clip = dom.createSvgElement( + Svg.CLIPPATH, {'id': 'blocklyZoomoutClipPath' + rnd}, + this.zoomOutGroup_); + dom.createSvgElement( + Svg.RECT, { + 'width': 32, + 'height': 32, + }, + clip); + const zoomoutSvg = dom.createSvgElement( + Svg.IMAGE, { + 'width': internalConstants.SPRITE.width, + 'height': internalConstants.SPRITE.height, + 'x': -64, + 'y': -92, + 'clip-path': 'url(#blocklyZoomoutClipPath' + rnd + ')', + }, + this.zoomOutGroup_); + zoomoutSvg.setAttributeNS( + dom.XLINK_NS, 'xlink:href', + this.workspace_.options.pathToMedia + internalConstants.SPRITE.url); - // Attach listener. - this.onZoomInWrapper_ = browserEvents.conditionalBind( - this.zoomInGroup_, 'mousedown', null, this.zoom_.bind(this, 1)); -}; + // Attach listener. + this.onZoomOutWrapper_ = browserEvents.conditionalBind( + this.zoomOutGroup_, 'mousedown', null, this.zoom_.bind(this, -1)); + } + /** + * Create the zoom out icon and its event handler. + * @param {string} rnd The random string to use as a suffix in the clip path's + * ID. These IDs must be unique in case there are multiple Blockly + * instances on the same page. + * @private + */ + createZoomInSvg_(rnd) { + /* This markup will be generated and added to the .svgGroup_: + + + + + + + */ + this.zoomInGroup_ = + dom.createSvgElement(Svg.G, {'class': 'blocklyZoom'}, this.svgGroup_); + const clip = dom.createSvgElement( + Svg.CLIPPATH, {'id': 'blocklyZoominClipPath' + rnd}, this.zoomInGroup_); + dom.createSvgElement( + Svg.RECT, { + 'width': 32, + 'height': 32, + }, + clip); + const zoominSvg = dom.createSvgElement( + Svg.IMAGE, { + 'width': internalConstants.SPRITE.width, + 'height': internalConstants.SPRITE.height, + 'x': -32, + 'y': -92, + 'clip-path': 'url(#blocklyZoominClipPath' + rnd + ')', + }, + this.zoomInGroup_); + zoominSvg.setAttributeNS( + dom.XLINK_NS, 'xlink:href', + this.workspace_.options.pathToMedia + internalConstants.SPRITE.url); -/** - * Handles a mouse down event on the zoom in or zoom out buttons on the - * workspace. - * @param {number} amount Amount of zooming. Negative amount values zoom out, - * and positive amount values zoom in. - * @param {!Event} e A mouse down event. - * @private - */ -ZoomControls.prototype.zoom_ = function(amount, e) { - this.workspace_.markFocused(); - this.workspace_.zoomCenter(amount); - this.fireZoomEvent_(); - Touch.clearTouchIdentifier(); // Don't block future drags. - e.stopPropagation(); // Don't start a workspace scroll. - e.preventDefault(); // Stop double-clicking from selecting text. -}; + // Attach listener. + this.onZoomInWrapper_ = browserEvents.conditionalBind( + this.zoomInGroup_, 'mousedown', null, this.zoom_.bind(this, 1)); + } + /** + * Handles a mouse down event on the zoom in or zoom out buttons on the + * workspace. + * @param {number} amount Amount of zooming. Negative amount values zoom out, + * and positive amount values zoom in. + * @param {!Event} e A mouse down event. + * @private + */ + zoom_(amount, e) { + this.workspace_.markFocused(); + this.workspace_.zoomCenter(amount); + this.fireZoomEvent_(); + Touch.clearTouchIdentifier(); // Don't block future drags. + e.stopPropagation(); // Don't start a workspace scroll. + e.preventDefault(); // Stop double-clicking from selecting text. + } + /** + * Create the zoom reset icon and its event handler. + * @param {string} rnd The random string to use as a suffix in the clip path's + * ID. These IDs must be unique in case there are multiple Blockly + * instances on the same page. + * @private + */ + createZoomResetSvg_(rnd) { + /* This markup will be generated and added to the .svgGroup_: + + + + + + + */ + this.zoomResetGroup_ = + dom.createSvgElement(Svg.G, {'class': 'blocklyZoom'}, this.svgGroup_); + const clip = dom.createSvgElement( + Svg.CLIPPATH, {'id': 'blocklyZoomresetClipPath' + rnd}, + this.zoomResetGroup_); + dom.createSvgElement(Svg.RECT, {'width': 32, 'height': 32}, clip); + const zoomresetSvg = dom.createSvgElement( + Svg.IMAGE, { + 'width': internalConstants.SPRITE.width, + 'height': internalConstants.SPRITE.height, + 'y': -92, + 'clip-path': 'url(#blocklyZoomresetClipPath' + rnd + ')', + }, + this.zoomResetGroup_); + zoomresetSvg.setAttributeNS( + dom.XLINK_NS, 'xlink:href', + this.workspace_.options.pathToMedia + internalConstants.SPRITE.url); -/** - * Create the zoom reset icon and its event handler. - * @param {string} rnd The random string to use as a suffix in the clip path's - * ID. These IDs must be unique in case there are multiple Blockly - * instances on the same page. - * @private - */ -ZoomControls.prototype.createZoomResetSvg_ = function(rnd) { - /* This markup will be generated and added to the .svgGroup_: - - - - - - - */ - this.zoomResetGroup_ = - dom.createSvgElement(Svg.G, {'class': 'blocklyZoom'}, this.svgGroup_); - const clip = dom.createSvgElement( - Svg.CLIPPATH, {'id': 'blocklyZoomresetClipPath' + rnd}, - this.zoomResetGroup_); - dom.createSvgElement(Svg.RECT, {'width': 32, 'height': 32}, clip); - const zoomresetSvg = dom.createSvgElement( - Svg.IMAGE, { - 'width': internalConstants.SPRITE.width, - 'height': internalConstants.SPRITE.height, - 'y': -92, - 'clip-path': 'url(#blocklyZoomresetClipPath' + rnd + ')', - }, - this.zoomResetGroup_); - zoomresetSvg.setAttributeNS( - dom.XLINK_NS, 'xlink:href', - this.workspace_.options.pathToMedia + internalConstants.SPRITE.url); + // Attach event listeners. + this.onZoomResetWrapper_ = browserEvents.conditionalBind( + this.zoomResetGroup_, 'mousedown', null, this.resetZoom_.bind(this)); + } + /** + * Handles a mouse down event on the reset zoom button on the workspace. + * @param {!Event} e A mouse down event. + * @private + */ + resetZoom_(e) { + this.workspace_.markFocused(); - // Attach event listeners. - this.onZoomResetWrapper_ = browserEvents.conditionalBind( - this.zoomResetGroup_, 'mousedown', null, this.resetZoom_.bind(this)); -}; + // zoom is passed amount and computes the new scale using the formula: + // targetScale = currentScale * Math.pow(speed, amount) + const targetScale = this.workspace_.options.zoomOptions.startScale; + const currentScale = this.workspace_.scale; + const speed = this.workspace_.options.zoomOptions.scaleSpeed; + // To compute amount: + // amount = log(speed, (targetScale / currentScale)) + // Math.log computes natural logarithm (ln), to change the base, use + // formula: log(base, value) = ln(value) / ln(base) + const amount = Math.log(targetScale / currentScale) / Math.log(speed); + this.workspace_.beginCanvasTransition(); + this.workspace_.zoomCenter(amount); + this.workspace_.scrollCenter(); -/** - * Handles a mouse down event on the reset zoom button on the workspace. - * @param {!Event} e A mouse down event. - * @private - */ -ZoomControls.prototype.resetZoom_ = function(e) { - this.workspace_.markFocused(); - - // zoom is passed amount and computes the new scale using the formula: - // targetScale = currentScale * Math.pow(speed, amount) - const targetScale = this.workspace_.options.zoomOptions.startScale; - const currentScale = this.workspace_.scale; - const speed = this.workspace_.options.zoomOptions.scaleSpeed; - // To compute amount: - // amount = log(speed, (targetScale / currentScale)) - // Math.log computes natural logarithm (ln), to change the base, use formula: - // log(base, value) = ln(value) / ln(base) - const amount = Math.log(targetScale / currentScale) / Math.log(speed); - this.workspace_.beginCanvasTransition(); - this.workspace_.zoomCenter(amount); - this.workspace_.scrollCenter(); - - setTimeout(this.workspace_.endCanvasTransition.bind(this.workspace_), 500); - this.fireZoomEvent_(); - Touch.clearTouchIdentifier(); // Don't block future drags. - e.stopPropagation(); // Don't start a workspace scroll. - e.preventDefault(); // Stop double-clicking from selecting text. -}; - -/** - * Fires a zoom control UI event. - * @private - */ -ZoomControls.prototype.fireZoomEvent_ = function() { - const uiEvent = new (eventUtils.get(eventUtils.CLICK))( - null, this.workspace_.id, 'zoom_controls'); - eventUtils.fire(uiEvent); -}; + setTimeout(this.workspace_.endCanvasTransition.bind(this.workspace_), 500); + this.fireZoomEvent_(); + Touch.clearTouchIdentifier(); // Don't block future drags. + e.stopPropagation(); // Don't start a workspace scroll. + e.preventDefault(); // Stop double-clicking from selecting text. + } + /** + * Fires a zoom control UI event. + * @private + */ + fireZoomEvent_() { + const uiEvent = new (eventUtils.get(eventUtils.CLICK))( + null, this.workspace_.id, 'zoom_controls'); + eventUtils.fire(uiEvent); + } +} /** * CSS for zoom controls. See css.js for use. diff --git a/scripts/gulpfiles/chunks.json b/scripts/gulpfiles/chunks.json index f63efe1db..a7fcc3cbf 100644 --- a/scripts/gulpfiles/chunks.json +++ b/scripts/gulpfiles/chunks.json @@ -244,10 +244,10 @@ "./core/serialization/priorities.js", "./core/serialization/blocks.js", "./core/utils/toolbox.js", - "./core/mutator.js", - "./core/msg.js", "./core/connection_type.js", "./core/internal_constants.js", + "./core/mutator.js", + "./core/msg.js", "./core/utils/colour.js", "./core/utils/parsing.js", "./core/extensions.js", From 9d8eeb30f681ae42ec38e173972f12d465b3ca05 Mon Sep 17 00:00:00 2001 From: Rachel Fenichel Date: Fri, 7 Jan 2022 14:49:49 -0800 Subject: [PATCH 027/128] refactor: convert some files to es6 classes (#5861) * refactor: convert utils/coordinate.js to ES6 class * refactor: convert utils/rect.js to ES6 class * refactor: convert utils/size.js to ES6 class * refactor: convert block_drag_surface.js to ES6 class * refactor: convert block_dragger.js to ES6 class * refactor: convert bubble_dragger.js to ES6 class * chore: declare bubble property in the constructor * refactor: convert bubble.js to ES6 class * chore: clang-format * chore(lint): lint and format --- core/block_drag_surface.js | 428 ++++----- core/block_dragger.js | 749 ++++++++-------- core/bubble.js | 1726 ++++++++++++++++++------------------ core/bubble_dragger.js | 444 +++++----- core/utils/coordinate.js | 194 ++-- core/utils/rect.js | 80 +- core/utils/size.js | 59 +- 7 files changed, 1867 insertions(+), 1813 deletions(-) diff --git a/core/block_drag_surface.js b/core/block_drag_surface.js index 7c7a64f17..6c03480f3 100644 --- a/core/block_drag_surface.js +++ b/core/block_drag_surface.js @@ -35,233 +35,235 @@ const {Svg} = goog.require('Blockly.utils.Svg'); /** * Class for a drag surface for the currently dragged block. This is a separate * SVG that contains only the currently moving block, or nothing. - * @param {!Element} container Containing element. - * @constructor - * @alias Blockly.BlockDragSurfaceSvg */ -const BlockDragSurfaceSvg = function(container) { +const BlockDragSurfaceSvg = class { /** - * The SVG drag surface. Set once by BlockDragSurfaceSvg.createDom. - * @type {?SVGElement} - * @private + * @param {!Element} container Containing element. + * @alias Blockly.BlockDragSurfaceSvg */ - this.SVG_ = null; + constructor(container) { + /** + * The SVG drag surface. Set once by BlockDragSurfaceSvg.createDom. + * @type {?SVGElement} + * @private + */ + this.SVG_ = null; - /** - * This is where blocks live while they are being dragged if the drag surface - * is enabled. - * @type {?SVGElement} - * @private - */ - this.dragGroup_ = null; + /** + * This is where blocks live while they are being dragged if the drag + * surface is enabled. + * @type {?SVGElement} + * @private + */ + this.dragGroup_ = null; - /** - * Containing HTML element; parent of the workspace and the drag surface. - * @type {!Element} - * @private - */ - this.container_ = container; + /** + * Containing HTML element; parent of the workspace and the drag surface. + * @type {!Element} + * @private + */ + this.container_ = container; - /** - * Cached value for the scale of the drag surface. - * Used to set/get the correct translation during and after a drag. - * @type {number} - * @private - */ - this.scale_ = 1; + /** + * Cached value for the scale of the drag surface. + * Used to set/get the correct translation during and after a drag. + * @type {number} + * @private + */ + this.scale_ = 1; - /** - * Cached value for the translation of the drag surface. - * This translation is in pixel units, because the scale is applied to the - * drag group rather than the top-level SVG. - * @type {?Coordinate} - * @private - */ - this.surfaceXY_ = null; + /** + * Cached value for the translation of the drag surface. + * This translation is in pixel units, because the scale is applied to the + * drag group rather than the top-level SVG. + * @type {?Coordinate} + * @private + */ + this.surfaceXY_ = null; - /** - * Cached value for the translation of the child drag surface in pixel units. - * Since the child drag surface tracks the translation of the workspace this - * is ultimately the translation of the workspace. - * @type {!Coordinate} - * @private - */ - this.childSurfaceXY_ = new Coordinate(0, 0); + /** + * Cached value for the translation of the child drag surface in pixel + * units. Since the child drag surface tracks the translation of the + * workspace this is ultimately the translation of the workspace. + * @type {!Coordinate} + * @private + */ + this.childSurfaceXY_ = new Coordinate(0, 0); - this.createDom(); -}; - - -/** - * Create the drag surface and inject it into the container. - */ -BlockDragSurfaceSvg.prototype.createDom = function() { - if (this.SVG_) { - return; // Already created. + this.createDom(); } - this.SVG_ = dom.createSvgElement( - Svg.SVG, { - 'xmlns': dom.SVG_NS, - 'xmlns:html': dom.HTML_NS, - 'xmlns:xlink': dom.XLINK_NS, - 'version': '1.1', - 'class': 'blocklyBlockDragSurface', - }, - this.container_); - this.dragGroup_ = dom.createSvgElement(Svg.G, {}, this.SVG_); -}; -/** - * Set the SVG blocks on the drag surface's group and show the surface. - * Only one block group should be on the drag surface at a time. - * @param {!SVGElement} blocks Block or group of blocks to place on the drag - * surface. - */ -BlockDragSurfaceSvg.prototype.setBlocksAndShow = function(blocks) { - if (this.dragGroup_.childNodes.length) { - throw Error('Already dragging a block.'); - } - // appendChild removes the blocks from the previous parent - this.dragGroup_.appendChild(blocks); - this.SVG_.style.display = 'block'; - this.surfaceXY_ = new Coordinate(0, 0); -}; - -/** - * Translate and scale the entire drag surface group to the given position, to - * keep in sync with the workspace. - * @param {number} x X translation in pixel coordinates. - * @param {number} y Y translation in pixel coordinates. - * @param {number} scale Scale of the group. - */ -BlockDragSurfaceSvg.prototype.translateAndScaleGroup = function(x, y, scale) { - this.scale_ = scale; - // This is a work-around to prevent a the blocks from rendering - // fuzzy while they are being dragged on the drag surface. - const fixedX = x.toFixed(0); - const fixedY = y.toFixed(0); - - this.childSurfaceXY_.x = parseInt(fixedX, 10); - this.childSurfaceXY_.y = parseInt(fixedY, 10); - - this.dragGroup_.setAttribute( - 'transform', - 'translate(' + fixedX + ',' + fixedY + ') scale(' + scale + ')'); -}; - -/** - * Translate the drag surface's SVG based on its internal state. - * @private - */ -BlockDragSurfaceSvg.prototype.translateSurfaceInternal_ = function() { - let x = this.surfaceXY_.x; - let y = this.surfaceXY_.y; - // This is a work-around to prevent a the blocks from rendering - // fuzzy while they are being dragged on the drag surface. - x = x.toFixed(0); - y = y.toFixed(0); - this.SVG_.style.display = 'block'; - - dom.setCssTransform(this.SVG_, 'translate3d(' + x + 'px, ' + y + 'px, 0)'); -}; - -/** - * Translates the entire surface by a relative offset. - * @param {number} deltaX Horizontal offset in pixel units. - * @param {number} deltaY Vertical offset in pixel units. - */ -BlockDragSurfaceSvg.prototype.translateBy = function(deltaX, deltaY) { - const x = this.surfaceXY_.x + deltaX; - const y = this.surfaceXY_.y + deltaY; - this.surfaceXY_ = new Coordinate(x, y); - this.translateSurfaceInternal_(); -}; - -/** - * Translate the entire drag surface during a drag. - * We translate the drag surface instead of the blocks inside the surface - * so that the browser avoids repainting the SVG. - * Because of this, the drag coordinates must be adjusted by scale. - * @param {number} x X translation for the entire surface. - * @param {number} y Y translation for the entire surface. - */ -BlockDragSurfaceSvg.prototype.translateSurface = function(x, y) { - this.surfaceXY_ = new Coordinate(x * this.scale_, y * this.scale_); - this.translateSurfaceInternal_(); -}; - -/** - * Reports the surface translation in scaled workspace coordinates. - * Use this when finishing a drag to return blocks to the correct position. - * @return {!Coordinate} Current translation of the surface. - */ -BlockDragSurfaceSvg.prototype.getSurfaceTranslation = function() { - const xy = svgMath.getRelativeXY(/** @type {!SVGElement} */ (this.SVG_)); - return new Coordinate(xy.x / this.scale_, xy.y / this.scale_); -}; - -/** - * Provide a reference to the drag group (primarily for - * BlockSvg.getRelativeToSurfaceXY). - * @return {?SVGElement} Drag surface group element. - */ -BlockDragSurfaceSvg.prototype.getGroup = function() { - return this.dragGroup_; -}; - -/** - * Returns the SVG drag surface. - * @returns {?SVGElement} The SVG drag surface. - */ -BlockDragSurfaceSvg.prototype.getSvgRoot = function() { - return this.SVG_; -}; - -/** - * Get the current blocks on the drag surface, if any (primarily - * for BlockSvg.getRelativeToSurfaceXY). - * @return {?Element} Drag surface block DOM element, or null if no blocks - * exist. - */ -BlockDragSurfaceSvg.prototype.getCurrentBlock = function() { - return /** @type {Element} */ (this.dragGroup_.firstChild); -}; - -/** - * Gets the translation of the child block surface - * This surface is in charge of keeping track of how much the workspace has - * moved. - * @return {!Coordinate} The amount the workspace has been moved. - */ -BlockDragSurfaceSvg.prototype.getWsTranslation = function() { - // Returning a copy so the coordinate can not be changed outside this class. - return this.childSurfaceXY_.clone(); -}; - -/** - * Clear the group and hide the surface; move the blocks off onto the provided - * element. - * If the block is being deleted it doesn't need to go back to the original - * surface, since it would be removed immediately during dispose. - * @param {Element=} opt_newSurface Surface the dragging blocks should be moved - * to, or null if the blocks should be removed from this surface without - * being moved to a different surface. - */ -BlockDragSurfaceSvg.prototype.clearAndHide = function(opt_newSurface) { - const currentBlockElement = this.getCurrentBlock(); - if (currentBlockElement) { - if (opt_newSurface) { - // appendChild removes the node from this.dragGroup_ - opt_newSurface.appendChild(currentBlockElement); - } else { - this.dragGroup_.removeChild(currentBlockElement); + /** + * Create the drag surface and inject it into the container. + */ + createDom() { + if (this.SVG_) { + return; // Already created. } + this.SVG_ = dom.createSvgElement( + Svg.SVG, { + 'xmlns': dom.SVG_NS, + 'xmlns:html': dom.HTML_NS, + 'xmlns:xlink': dom.XLINK_NS, + 'version': '1.1', + 'class': 'blocklyBlockDragSurface', + }, + this.container_); + this.dragGroup_ = dom.createSvgElement(Svg.G, {}, this.SVG_); } - this.SVG_.style.display = 'none'; - if (this.dragGroup_.childNodes.length) { - throw Error('Drag group was not cleared.'); + + /** + * Set the SVG blocks on the drag surface's group and show the surface. + * Only one block group should be on the drag surface at a time. + * @param {!SVGElement} blocks Block or group of blocks to place on the drag + * surface. + */ + setBlocksAndShow(blocks) { + if (this.dragGroup_.childNodes.length) { + throw Error('Already dragging a block.'); + } + // appendChild removes the blocks from the previous parent + this.dragGroup_.appendChild(blocks); + this.SVG_.style.display = 'block'; + this.surfaceXY_ = new Coordinate(0, 0); + } + + /** + * Translate and scale the entire drag surface group to the given position, to + * keep in sync with the workspace. + * @param {number} x X translation in pixel coordinates. + * @param {number} y Y translation in pixel coordinates. + * @param {number} scale Scale of the group. + */ + translateAndScaleGroup(x, y, scale) { + this.scale_ = scale; + // This is a work-around to prevent a the blocks from rendering + // fuzzy while they are being dragged on the drag surface. + const fixedX = x.toFixed(0); + const fixedY = y.toFixed(0); + + this.childSurfaceXY_.x = parseInt(fixedX, 10); + this.childSurfaceXY_.y = parseInt(fixedY, 10); + + this.dragGroup_.setAttribute( + 'transform', + 'translate(' + fixedX + ',' + fixedY + ') scale(' + scale + ')'); + } + + /** + * Translate the drag surface's SVG based on its internal state. + * @private + */ + translateSurfaceInternal_() { + let x = this.surfaceXY_.x; + let y = this.surfaceXY_.y; + // This is a work-around to prevent a the blocks from rendering + // fuzzy while they are being dragged on the drag surface. + x = x.toFixed(0); + y = y.toFixed(0); + this.SVG_.style.display = 'block'; + + dom.setCssTransform(this.SVG_, 'translate3d(' + x + 'px, ' + y + 'px, 0)'); + } + + /** + * Translates the entire surface by a relative offset. + * @param {number} deltaX Horizontal offset in pixel units. + * @param {number} deltaY Vertical offset in pixel units. + */ + translateBy(deltaX, deltaY) { + const x = this.surfaceXY_.x + deltaX; + const y = this.surfaceXY_.y + deltaY; + this.surfaceXY_ = new Coordinate(x, y); + this.translateSurfaceInternal_(); + } + + /** + * Translate the entire drag surface during a drag. + * We translate the drag surface instead of the blocks inside the surface + * so that the browser avoids repainting the SVG. + * Because of this, the drag coordinates must be adjusted by scale. + * @param {number} x X translation for the entire surface. + * @param {number} y Y translation for the entire surface. + */ + translateSurface(x, y) { + this.surfaceXY_ = new Coordinate(x * this.scale_, y * this.scale_); + this.translateSurfaceInternal_(); + } + + /** + * Reports the surface translation in scaled workspace coordinates. + * Use this when finishing a drag to return blocks to the correct position. + * @return {!Coordinate} Current translation of the surface. + */ + getSurfaceTranslation() { + const xy = svgMath.getRelativeXY(/** @type {!SVGElement} */ (this.SVG_)); + return new Coordinate(xy.x / this.scale_, xy.y / this.scale_); + } + + /** + * Provide a reference to the drag group (primarily for + * BlockSvg.getRelativeToSurfaceXY). + * @return {?SVGElement} Drag surface group element. + */ + getGroup() { + return this.dragGroup_; + } + + /** + * Returns the SVG drag surface. + * @returns {?SVGElement} The SVG drag surface. + */ + getSvgRoot() { + return this.SVG_; + } + + /** + * Get the current blocks on the drag surface, if any (primarily + * for BlockSvg.getRelativeToSurfaceXY). + * @return {?Element} Drag surface block DOM element, or null if no blocks + * exist. + */ + getCurrentBlock() { + return /** @type {Element} */ (this.dragGroup_.firstChild); + } + + /** + * Gets the translation of the child block surface + * This surface is in charge of keeping track of how much the workspace has + * moved. + * @return {!Coordinate} The amount the workspace has been moved. + */ + getWsTranslation() { + // Returning a copy so the coordinate can not be changed outside this class. + return this.childSurfaceXY_.clone(); + } + + /** + * Clear the group and hide the surface; move the blocks off onto the provided + * element. + * If the block is being deleted it doesn't need to go back to the original + * surface, since it would be removed immediately during dispose. + * @param {Element=} opt_newSurface Surface the dragging blocks should be + * moved to, or null if the blocks should be removed from this surface + * without being moved to a different surface. + */ + clearAndHide(opt_newSurface) { + const currentBlockElement = this.getCurrentBlock(); + if (currentBlockElement) { + if (opt_newSurface) { + // appendChild removes the node from this.dragGroup_ + opt_newSurface.appendChild(currentBlockElement); + } else { + this.dragGroup_.removeChild(currentBlockElement); + } + } + this.SVG_.style.display = 'none'; + if (this.dragGroup_.childNodes.length) { + throw Error('Drag group was not cleared.'); + } + this.surfaceXY_ = null; } - this.surfaceXY_ = null; }; exports.BlockDragSurfaceSvg = BlockDragSurfaceSvg; diff --git a/core/block_dragger.js b/core/block_dragger.js index 817fa10fe..d0ee612d3 100644 --- a/core/block_dragger.js +++ b/core/block_dragger.js @@ -40,76 +40,411 @@ goog.require('Blockly.Events.BlockMove'); /** * Class for a block dragger. It moves blocks around the workspace when they * are being dragged by a mouse or touch. - * @param {!BlockSvg} block The block to drag. - * @param {!WorkspaceSvg} workspace The workspace to drag on. - * @constructor * @implements {IBlockDragger} - * @alias Blockly.BlockDragger */ -const BlockDragger = function(block, workspace) { +const BlockDragger = class { /** - * The top block in the stack that is being dragged. - * @type {!BlockSvg} + * @param {!BlockSvg} block The block to drag. + * @param {!WorkspaceSvg} workspace The workspace to drag on. + * @alias Blockly.BlockDragger + */ + constructor(block, workspace) { + /** + * The top block in the stack that is being dragged. + * @type {!BlockSvg} + * @protected + */ + this.draggingBlock_ = block; + + /** + * The workspace on which the block is being dragged. + * @type {!WorkspaceSvg} + * @protected + */ + this.workspace_ = workspace; + + /** + * Object that keeps track of connections on dragged blocks. + * @type {!InsertionMarkerManager} + * @protected + */ + this.draggedConnectionManager_ = + new InsertionMarkerManager(this.draggingBlock_); + + /** + * Which drag area the mouse pointer is over, if any. + * @type {?IDragTarget} + * @private + */ + this.dragTarget_ = null; + + /** + * Whether the block would be deleted if dropped immediately. + * @type {boolean} + * @protected + */ + this.wouldDeleteBlock_ = false; + + /** + * The location of the top left corner of the dragging block at the + * beginning of the drag in workspace coordinates. + * @type {!Coordinate} + * @protected + */ + this.startXY_ = this.draggingBlock_.getRelativeToSurfaceXY(); + + /** + * A list of all of the icons (comment, warning, and mutator) that are + * on this block and its descendants. Moving an icon moves the bubble that + * extends from it if that bubble is open. + * @type {Array} + * @protected + */ + this.dragIconData_ = initIconData(block); + } + + /** + * Sever all links from this object. + * @package + */ + dispose() { + this.dragIconData_.length = 0; + + if (this.draggedConnectionManager_) { + this.draggedConnectionManager_.dispose(); + } + } + + /** + * Start dragging a block. This includes moving it to the drag surface. + * @param {!Coordinate} currentDragDeltaXY How far the pointer has + * moved from the position at mouse down, in pixel units. + * @param {boolean} healStack Whether or not to heal the stack after + * disconnecting. + * @public + */ + startDrag(currentDragDeltaXY, healStack) { + if (!eventUtils.getGroup()) { + eventUtils.setGroup(true); + } + this.fireDragStartEvent_(); + + // Mutators don't have the same type of z-ordering as the normal workspace + // during a drag. They have to rely on the order of the blocks in the SVG. + // For performance reasons that usually happens at the end of a drag, + // but do it at the beginning for mutators. + if (this.workspace_.isMutator) { + this.draggingBlock_.bringToFront(); + } + + // During a drag there may be a lot of rerenders, but not field changes. + // Turn the cache on so we don't do spurious remeasures during the drag. + dom.startTextWidthCache(); + this.workspace_.setResizesEnabled(false); + blockAnimation.disconnectUiStop(); + + if (this.shouldDisconnect_(healStack)) { + this.disconnectBlock_(healStack, currentDragDeltaXY); + } + this.draggingBlock_.setDragging(true); + // For future consideration: we may be able to put moveToDragSurface inside + // the block dragger, which would also let the block not track the block + // drag surface. + this.draggingBlock_.moveToDragSurface(); + } + + /** + * Whether or not we should disconnect the block when a drag is started. + * @param {boolean} healStack Whether or not to heal the stack after + * disconnecting. + * @return {boolean} True to disconnect the block, false otherwise. * @protected */ - this.draggingBlock_ = block; + shouldDisconnect_(healStack) { + return !!( + this.draggingBlock_.getParent() || + (healStack && this.draggingBlock_.nextConnection && + this.draggingBlock_.nextConnection.targetBlock())); + } /** - * The workspace on which the block is being dragged. - * @type {!WorkspaceSvg} + * Disconnects the block and moves it to a new location. + * @param {boolean} healStack Whether or not to heal the stack after + * disconnecting. + * @param {!Coordinate} currentDragDeltaXY How far the pointer has + * moved from the position at mouse down, in pixel units. * @protected */ - this.workspace_ = workspace; + disconnectBlock_(healStack, currentDragDeltaXY) { + this.draggingBlock_.unplug(healStack); + const delta = this.pixelsToWorkspaceUnits_(currentDragDeltaXY); + const newLoc = Coordinate.sum(this.startXY_, delta); + + this.draggingBlock_.translate(newLoc.x, newLoc.y); + blockAnimation.disconnectUiEffect(this.draggingBlock_); + this.draggedConnectionManager_.updateAvailableConnections(); + } /** - * Object that keeps track of connections on dragged blocks. - * @type {!InsertionMarkerManager} + * Fire a UI event at the start of a block drag. * @protected */ - this.draggedConnectionManager_ = - new InsertionMarkerManager(this.draggingBlock_); + fireDragStartEvent_() { + const event = new (eventUtils.get(eventUtils.BLOCK_DRAG))( + this.draggingBlock_, true, this.draggingBlock_.getDescendants(false)); + eventUtils.fire(event); + } /** - * Which drag area the mouse pointer is over, if any. - * @type {?IDragTarget} - * @private + * Execute a step of block dragging, based on the given event. Update the + * display accordingly. + * @param {!Event} e The most recent move event. + * @param {!Coordinate} currentDragDeltaXY How far the pointer has + * moved from the position at the start of the drag, in pixel units. + * @public */ - this.dragTarget_ = null; + drag(e, currentDragDeltaXY) { + const delta = this.pixelsToWorkspaceUnits_(currentDragDeltaXY); + const newLoc = Coordinate.sum(this.startXY_, delta); + this.draggingBlock_.moveDuringDrag(newLoc); + this.dragIcons_(delta); + + const oldDragTarget = this.dragTarget_; + this.dragTarget_ = this.workspace_.getDragTarget(e); + + this.draggedConnectionManager_.update(delta, this.dragTarget_); + const oldWouldDeleteBlock = this.wouldDeleteBlock_; + this.wouldDeleteBlock_ = this.draggedConnectionManager_.wouldDeleteBlock(); + if (oldWouldDeleteBlock !== this.wouldDeleteBlock_) { + // Prevent unnecessary add/remove class calls. + this.updateCursorDuringBlockDrag_(); + } + + // Call drag enter/exit/over after wouldDeleteBlock is called in + // InsertionMarkerManager.update. + if (this.dragTarget_ !== oldDragTarget) { + oldDragTarget && oldDragTarget.onDragExit(this.draggingBlock_); + this.dragTarget_ && this.dragTarget_.onDragEnter(this.draggingBlock_); + } + this.dragTarget_ && this.dragTarget_.onDragOver(this.draggingBlock_); + } /** - * Whether the block would be deleted if dropped immediately. - * @type {boolean} + * Finish a block drag and put the block back on the workspace. + * @param {!Event} e The mouseup/touchend event. + * @param {!Coordinate} currentDragDeltaXY How far the pointer has + * moved from the position at the start of the drag, in pixel units. + * @public + */ + endDrag(e, currentDragDeltaXY) { + // Make sure internal state is fresh. + this.drag(e, currentDragDeltaXY); + this.dragIconData_ = []; + this.fireDragEndEvent_(); + + dom.stopTextWidthCache(); + + blockAnimation.disconnectUiStop(); + + const preventMove = !!this.dragTarget_ && + this.dragTarget_.shouldPreventMove(this.draggingBlock_); + /** @type {Coordinate} */ + let newLoc; + /** @type {Coordinate} */ + let delta; + if (preventMove) { + newLoc = this.startXY_; + } else { + const newValues = this.getNewLocationAfterDrag_(currentDragDeltaXY); + delta = newValues.delta; + newLoc = newValues.newLocation; + } + this.draggingBlock_.moveOffDragSurface(newLoc); + + if (this.dragTarget_) { + this.dragTarget_.onDrop(this.draggingBlock_); + } + + const deleted = this.maybeDeleteBlock_(); + if (!deleted) { + // These are expensive and don't need to be done if we're deleting. + this.draggingBlock_.setDragging(false); + if (delta) { // !preventMove + this.updateBlockAfterMove_(delta); + } else { + // Blocks dragged directly from a flyout may need to be bumped into + // bounds. + bumpObjects.bumpIntoBounds( + this.draggingBlock_.workspace, + this.workspace_.getMetricsManager().getScrollMetrics(true), + this.draggingBlock_); + } + } + this.workspace_.setResizesEnabled(true); + + eventUtils.setGroup(false); + } + + /** + * Calculates the drag delta and new location values after a block is dragged. + * @param {!Coordinate} currentDragDeltaXY How far the pointer has + * moved from the start of the drag, in pixel units. + * @return {{delta: !Coordinate, newLocation: + * !Coordinate}} New location after drag. delta is in + * workspace units. newLocation is the new coordinate where the block + * should end up. * @protected */ - this.wouldDeleteBlock_ = false; + getNewLocationAfterDrag_(currentDragDeltaXY) { + const newValues = {}; + newValues.delta = this.pixelsToWorkspaceUnits_(currentDragDeltaXY); + newValues.newLocation = Coordinate.sum(this.startXY_, newValues.delta); + return newValues; + } /** - * The location of the top left corner of the dragging block at the beginning - * of the drag in workspace coordinates. - * @type {!Coordinate} + * May delete the dragging block, if allowed. If `this.wouldDeleteBlock_` is + * not true, the block will not be deleted. This should be called at the end + * of a block drag. + * @return {boolean} True if the block was deleted. * @protected */ - this.startXY_ = this.draggingBlock_.getRelativeToSurfaceXY(); + maybeDeleteBlock_() { + if (this.wouldDeleteBlock_) { + // Fire a move event, so we know where to go back to for an undo. + this.fireMoveEvent_(); + this.draggingBlock_.dispose(false, true); + common.draggingConnections.length = 0; + return true; + } + return false; + } /** - * A list of all of the icons (comment, warning, and mutator) that are - * on this block and its descendants. Moving an icon moves the bubble that - * extends from it if that bubble is open. - * @type {Array} + * Updates the necessary information to place a block at a certain location. + * @param {!Coordinate} delta The change in location from where + * the block started the drag to where it ended the drag. * @protected */ - this.dragIconData_ = initIconData(block); -}; + updateBlockAfterMove_(delta) { + this.draggingBlock_.moveConnections(delta.x, delta.y); + this.fireMoveEvent_(); + if (this.draggedConnectionManager_.wouldConnectBlock()) { + // Applying connections also rerenders the relevant blocks. + this.draggedConnectionManager_.applyConnections(); + } else { + this.draggingBlock_.render(); + } + this.draggingBlock_.scheduleSnapAndBump(); + } -/** - * Sever all links from this object. - * @package - */ -BlockDragger.prototype.dispose = function() { - this.dragIconData_.length = 0; + /** + * Fire a UI event at the end of a block drag. + * @protected + */ + fireDragEndEvent_() { + const event = new (eventUtils.get(eventUtils.BLOCK_DRAG))( + this.draggingBlock_, false, this.draggingBlock_.getDescendants(false)); + eventUtils.fire(event); + } - if (this.draggedConnectionManager_) { - this.draggedConnectionManager_.dispose(); + /** + * Adds or removes the style of the cursor for the toolbox. + * This is what changes the cursor to display an x when a deletable block is + * held over the toolbox. + * @param {boolean} isEnd True if we are at the end of a drag, false + * otherwise. + * @protected + */ + updateToolboxStyle_(isEnd) { + const toolbox = this.workspace_.getToolbox(); + + if (toolbox) { + const style = this.draggingBlock_.isDeletable() ? 'blocklyToolboxDelete' : + 'blocklyToolboxGrab'; + + if (isEnd && typeof toolbox.removeStyle === 'function') { + toolbox.removeStyle(style); + } else if (!isEnd && typeof toolbox.addStyle === 'function') { + toolbox.addStyle(style); + } + } + } + + /** + * Fire a move event at the end of a block drag. + * @protected + */ + fireMoveEvent_() { + const event = + new (eventUtils.get(eventUtils.BLOCK_MOVE))(this.draggingBlock_); + event.oldCoordinate = this.startXY_; + event.recordNew(); + eventUtils.fire(event); + } + + /** + * Update the cursor (and possibly the trash can lid) to reflect whether the + * dragging block would be deleted if released immediately. + * @protected + */ + updateCursorDuringBlockDrag_() { + this.draggingBlock_.setDeleteStyle(this.wouldDeleteBlock_); + } + + /** + * Convert a coordinate object from pixels to workspace units, including a + * correction for mutator workspaces. + * This function does not consider differing origins. It simply scales the + * input's x and y values. + * @param {!Coordinate} pixelCoord A coordinate with x and y + * values in CSS pixel units. + * @return {!Coordinate} The input coordinate divided by the + * workspace scale. + * @protected + */ + pixelsToWorkspaceUnits_(pixelCoord) { + const result = new Coordinate( + pixelCoord.x / this.workspace_.scale, + pixelCoord.y / this.workspace_.scale); + if (this.workspace_.isMutator) { + // If we're in a mutator, its scale is always 1, purely because of some + // oddities in our rendering optimizations. The actual scale is the same + // as the scale on the parent workspace. Fix that for dragging. + const mainScale = this.workspace_.options.parentWorkspace.scale; + result.scale(1 / mainScale); + } + return result; + } + + /** + * Move all of the icons connected to this drag. + * @param {!Coordinate} dxy How far to move the icons from their + * original positions, in workspace units. + * @protected + */ + dragIcons_(dxy) { + // Moving icons moves their associated bubbles. + for (let i = 0; i < this.dragIconData_.length; i++) { + const data = this.dragIconData_[i]; + data.icon.setIconLocation(Coordinate.sum(data.location, dxy)); + } + } + + /** + * Get a list of the insertion markers that currently exist. Drags have 0, 1, + * or 2 insertion markers. + * @return {!Array} A possibly empty list of insertion + * marker blocks. + * @public + */ + getInsertionMarkers() { + // No insertion markers with the old style of dragged connection managers. + if (this.draggedConnectionManager_ && + this.draggedConnectionManager_.getInsertionMarkers) { + return this.draggedConnectionManager_.getInsertionMarkers(); + } + return []; } }; @@ -141,340 +476,6 @@ const initIconData = function(block) { return dragIconData; }; -/** - * Start dragging a block. This includes moving it to the drag surface. - * @param {!Coordinate} currentDragDeltaXY How far the pointer has - * moved from the position at mouse down, in pixel units. - * @param {boolean} healStack Whether or not to heal the stack after - * disconnecting. - * @public - */ -BlockDragger.prototype.startDrag = function(currentDragDeltaXY, healStack) { - if (!eventUtils.getGroup()) { - eventUtils.setGroup(true); - } - this.fireDragStartEvent_(); - - // Mutators don't have the same type of z-ordering as the normal workspace - // during a drag. They have to rely on the order of the blocks in the SVG. - // For performance reasons that usually happens at the end of a drag, - // but do it at the beginning for mutators. - if (this.workspace_.isMutator) { - this.draggingBlock_.bringToFront(); - } - - // During a drag there may be a lot of rerenders, but not field changes. - // Turn the cache on so we don't do spurious remeasures during the drag. - dom.startTextWidthCache(); - this.workspace_.setResizesEnabled(false); - blockAnimation.disconnectUiStop(); - - if (this.shouldDisconnect_(healStack)) { - this.disconnectBlock_(healStack, currentDragDeltaXY); - } - this.draggingBlock_.setDragging(true); - // For future consideration: we may be able to put moveToDragSurface inside - // the block dragger, which would also let the block not track the block drag - // surface. - this.draggingBlock_.moveToDragSurface(); -}; - -/** - * Whether or not we should disconnect the block when a drag is started. - * @param {boolean} healStack Whether or not to heal the stack after - * disconnecting. - * @return {boolean} True to disconnect the block, false otherwise. - * @protected - */ -BlockDragger.prototype.shouldDisconnect_ = function(healStack) { - return !!( - this.draggingBlock_.getParent() || - (healStack && this.draggingBlock_.nextConnection && - this.draggingBlock_.nextConnection.targetBlock())); -}; - -/** - * Disconnects the block and moves it to a new location. - * @param {boolean} healStack Whether or not to heal the stack after - * disconnecting. - * @param {!Coordinate} currentDragDeltaXY How far the pointer has - * moved from the position at mouse down, in pixel units. - * @protected - */ -BlockDragger.prototype.disconnectBlock_ = function( - healStack, currentDragDeltaXY) { - this.draggingBlock_.unplug(healStack); - const delta = this.pixelsToWorkspaceUnits_(currentDragDeltaXY); - const newLoc = Coordinate.sum(this.startXY_, delta); - - this.draggingBlock_.translate(newLoc.x, newLoc.y); - blockAnimation.disconnectUiEffect(this.draggingBlock_); - this.draggedConnectionManager_.updateAvailableConnections(); -}; - -/** - * Fire a UI event at the start of a block drag. - * @protected - */ -BlockDragger.prototype.fireDragStartEvent_ = function() { - const event = new (eventUtils.get(eventUtils.BLOCK_DRAG))( - this.draggingBlock_, true, this.draggingBlock_.getDescendants(false)); - eventUtils.fire(event); -}; - -/** - * Execute a step of block dragging, based on the given event. Update the - * display accordingly. - * @param {!Event} e The most recent move event. - * @param {!Coordinate} currentDragDeltaXY How far the pointer has - * moved from the position at the start of the drag, in pixel units. - * @public - */ -BlockDragger.prototype.drag = function(e, currentDragDeltaXY) { - const delta = this.pixelsToWorkspaceUnits_(currentDragDeltaXY); - const newLoc = Coordinate.sum(this.startXY_, delta); - this.draggingBlock_.moveDuringDrag(newLoc); - this.dragIcons_(delta); - - const oldDragTarget = this.dragTarget_; - this.dragTarget_ = this.workspace_.getDragTarget(e); - - this.draggedConnectionManager_.update(delta, this.dragTarget_); - const oldWouldDeleteBlock = this.wouldDeleteBlock_; - this.wouldDeleteBlock_ = this.draggedConnectionManager_.wouldDeleteBlock(); - if (oldWouldDeleteBlock !== this.wouldDeleteBlock_) { - // Prevent unnecessary add/remove class calls. - this.updateCursorDuringBlockDrag_(); - } - - // Call drag enter/exit/over after wouldDeleteBlock is called in - // InsertionMarkerManager.update. - if (this.dragTarget_ !== oldDragTarget) { - oldDragTarget && oldDragTarget.onDragExit(this.draggingBlock_); - this.dragTarget_ && this.dragTarget_.onDragEnter(this.draggingBlock_); - } - this.dragTarget_ && this.dragTarget_.onDragOver(this.draggingBlock_); -}; - -/** - * Finish a block drag and put the block back on the workspace. - * @param {!Event} e The mouseup/touchend event. - * @param {!Coordinate} currentDragDeltaXY How far the pointer has - * moved from the position at the start of the drag, in pixel units. - * @public - */ -BlockDragger.prototype.endDrag = function(e, currentDragDeltaXY) { - // Make sure internal state is fresh. - this.drag(e, currentDragDeltaXY); - this.dragIconData_ = []; - this.fireDragEndEvent_(); - - dom.stopTextWidthCache(); - - blockAnimation.disconnectUiStop(); - - const preventMove = !!this.dragTarget_ && - this.dragTarget_.shouldPreventMove(this.draggingBlock_); - /** @type {Coordinate} */ - let newLoc; - /** @type {Coordinate} */ - let delta; - if (preventMove) { - newLoc = this.startXY_; - } else { - const newValues = this.getNewLocationAfterDrag_(currentDragDeltaXY); - delta = newValues.delta; - newLoc = newValues.newLocation; - } - this.draggingBlock_.moveOffDragSurface(newLoc); - - if (this.dragTarget_) { - this.dragTarget_.onDrop(this.draggingBlock_); - } - - const deleted = this.maybeDeleteBlock_(); - if (!deleted) { - // These are expensive and don't need to be done if we're deleting. - this.draggingBlock_.setDragging(false); - if (delta) { // !preventMove - this.updateBlockAfterMove_(delta); - } else { - // Blocks dragged directly from a flyout may need to be bumped into - // bounds. - bumpObjects.bumpIntoBounds( - this.draggingBlock_.workspace, - this.workspace_.getMetricsManager().getScrollMetrics(true), - this.draggingBlock_); - } - } - this.workspace_.setResizesEnabled(true); - - eventUtils.setGroup(false); -}; - -/** - * Calculates the drag delta and new location values after a block is dragged. - * @param {!Coordinate} currentDragDeltaXY How far the pointer has - * moved from the start of the drag, in pixel units. - * @return {{delta: !Coordinate, newLocation: - * !Coordinate}} New location after drag. delta is in - * workspace units. newLocation is the new coordinate where the block should - * end up. - * @protected - */ -BlockDragger.prototype.getNewLocationAfterDrag_ = function(currentDragDeltaXY) { - const newValues = {}; - newValues.delta = this.pixelsToWorkspaceUnits_(currentDragDeltaXY); - newValues.newLocation = Coordinate.sum(this.startXY_, newValues.delta); - return newValues; -}; - -/** - * May delete the dragging block, if allowed. If `this.wouldDeleteBlock_` is not - * true, the block will not be deleted. This should be called at the end of a - * block drag. - * @return {boolean} True if the block was deleted. - * @protected - */ -BlockDragger.prototype.maybeDeleteBlock_ = function() { - if (this.wouldDeleteBlock_) { - // Fire a move event, so we know where to go back to for an undo. - this.fireMoveEvent_(); - this.draggingBlock_.dispose(false, true); - common.draggingConnections.length = 0; - return true; - } - return false; -}; - -/** - * Updates the necessary information to place a block at a certain location. - * @param {!Coordinate} delta The change in location from where - * the block started the drag to where it ended the drag. - * @protected - */ -BlockDragger.prototype.updateBlockAfterMove_ = function(delta) { - this.draggingBlock_.moveConnections(delta.x, delta.y); - this.fireMoveEvent_(); - if (this.draggedConnectionManager_.wouldConnectBlock()) { - // Applying connections also rerenders the relevant blocks. - this.draggedConnectionManager_.applyConnections(); - } else { - this.draggingBlock_.render(); - } - this.draggingBlock_.scheduleSnapAndBump(); -}; - -/** - * Fire a UI event at the end of a block drag. - * @protected - */ -BlockDragger.prototype.fireDragEndEvent_ = function() { - const event = new (eventUtils.get(eventUtils.BLOCK_DRAG))( - this.draggingBlock_, false, this.draggingBlock_.getDescendants(false)); - eventUtils.fire(event); -}; - -/** - * Adds or removes the style of the cursor for the toolbox. - * This is what changes the cursor to display an x when a deletable block is - * held over the toolbox. - * @param {boolean} isEnd True if we are at the end of a drag, false otherwise. - * @protected - */ -BlockDragger.prototype.updateToolboxStyle_ = function(isEnd) { - const toolbox = this.workspace_.getToolbox(); - - if (toolbox) { - const style = this.draggingBlock_.isDeletable() ? 'blocklyToolboxDelete' : - 'blocklyToolboxGrab'; - - if (isEnd && typeof toolbox.removeStyle === 'function') { - toolbox.removeStyle(style); - } else if (!isEnd && typeof toolbox.addStyle === 'function') { - toolbox.addStyle(style); - } - } -}; - - -/** - * Fire a move event at the end of a block drag. - * @protected - */ -BlockDragger.prototype.fireMoveEvent_ = function() { - const event = - new (eventUtils.get(eventUtils.BLOCK_MOVE))(this.draggingBlock_); - event.oldCoordinate = this.startXY_; - event.recordNew(); - eventUtils.fire(event); -}; - -/** - * Update the cursor (and possibly the trash can lid) to reflect whether the - * dragging block would be deleted if released immediately. - * @protected - */ -BlockDragger.prototype.updateCursorDuringBlockDrag_ = function() { - this.draggingBlock_.setDeleteStyle(this.wouldDeleteBlock_); -}; - -/** - * Convert a coordinate object from pixels to workspace units, including a - * correction for mutator workspaces. - * This function does not consider differing origins. It simply scales the - * input's x and y values. - * @param {!Coordinate} pixelCoord A coordinate with x and y - * values in CSS pixel units. - * @return {!Coordinate} The input coordinate divided by the - * workspace scale. - * @protected - */ -BlockDragger.prototype.pixelsToWorkspaceUnits_ = function(pixelCoord) { - const result = new Coordinate( - pixelCoord.x / this.workspace_.scale, - pixelCoord.y / this.workspace_.scale); - if (this.workspace_.isMutator) { - // If we're in a mutator, its scale is always 1, purely because of some - // oddities in our rendering optimizations. The actual scale is the same as - // the scale on the parent workspace. - // Fix that for dragging. - const mainScale = this.workspace_.options.parentWorkspace.scale; - result.scale(1 / mainScale); - } - return result; -}; - -/** - * Move all of the icons connected to this drag. - * @param {!Coordinate} dxy How far to move the icons from their - * original positions, in workspace units. - * @protected - */ -BlockDragger.prototype.dragIcons_ = function(dxy) { - // Moving icons moves their associated bubbles. - for (let i = 0; i < this.dragIconData_.length; i++) { - const data = this.dragIconData_[i]; - data.icon.setIconLocation(Coordinate.sum(data.location, dxy)); - } -}; - -/** - * Get a list of the insertion markers that currently exist. Drags have 0, 1, - * or 2 insertion markers. - * @return {!Array} A possibly empty list of insertion - * marker blocks. - * @public - */ -BlockDragger.prototype.getInsertionMarkers = function() { - // No insertion markers with the old style of dragged connection managers. - if (this.draggedConnectionManager_ && - this.draggedConnectionManager_.getInsertionMarkers) { - return this.draggedConnectionManager_.getInsertionMarkers(); - } - return []; -}; - registry.register(registry.Type.BLOCK_DRAGGER, registry.DEFAULT, BlockDragger); exports.BlockDragger = BlockDragger; diff --git a/core/bubble.js b/core/bubble.js index 78799c0ec..1f045cf5e 100644 --- a/core/bubble.js +++ b/core/bubble.js @@ -40,133 +40,906 @@ goog.require('Blockly.Workspace'); /** * Class for UI bubble. - * @param {!WorkspaceSvg} workspace The workspace on which to draw the - * bubble. - * @param {!Element} content SVG content for the bubble. - * @param {!Element} shape SVG element to avoid eclipsing. - * @param {!Coordinate} anchorXY Absolute position of bubble's - * anchor point. - * @param {?number} bubbleWidth Width of bubble, or null if not resizable. - * @param {?number} bubbleHeight Height of bubble, or null if not resizable. * @implements {IBubble} - * @constructor - * @alias Blockly.Bubble */ -const Bubble = function( - workspace, content, shape, anchorXY, bubbleWidth, bubbleHeight) { - this.workspace_ = workspace; - this.content_ = content; - this.shape_ = shape; +const Bubble = class { + /** + * @param {!WorkspaceSvg} workspace The workspace on which to draw the + * bubble. + * @param {!Element} content SVG content for the bubble. + * @param {!Element} shape SVG element to avoid eclipsing. + * @param {!Coordinate} anchorXY Absolute position of bubble's + * anchor point. + * @param {?number} bubbleWidth Width of bubble, or null if not resizable. + * @param {?number} bubbleHeight Height of bubble, or null if not resizable. + * @struct + * @alias Blockly.Bubble + */ + constructor(workspace, content, shape, anchorXY, bubbleWidth, bubbleHeight) { + this.workspace_ = workspace; + this.content_ = content; + this.shape_ = shape; + + /** + * Flag to stop incremental rendering during construction. + * @type {boolean} + * @private + */ + this.rendered_ = false; + + /** + * The SVG group containing all parts of the bubble. + * @type {SVGGElement} + * @private + */ + this.bubbleGroup_ = null; + + /** + * The SVG path for the arrow from the bubble to the icon on the block. + * @type {SVGPathElement} + * @private + */ + this.bubbleArrow_ = null; + + /** + * The SVG rect for the main body of the bubble. + * @type {SVGRectElement} + * @private + */ + this.bubbleBack_ = null; + + /** + * The SVG group for the resize hash marks on some bubbles. + * @type {SVGGElement} + * @private + */ + this.resizeGroup_ = null; + + /** + * Absolute coordinate of anchor point, in workspace coordinates. + * @type {Coordinate} + * @private + */ + this.anchorXY_ = null; + + /** + * Relative X coordinate of bubble with respect to the anchor's centre, + * in workspace units. + * In RTL mode the initial value is negated. + * @type {number} + * @private + */ + this.relativeLeft_ = 0; + + /** + * Relative Y coordinate of bubble with respect to the anchor's centre, in + * workspace units. + * @type {number} + * @private + */ + this.relativeTop_ = 0; + + /** + * Width of bubble, in workspace units. + * @type {number} + * @private + */ + this.width_ = 0; + + /** + * Height of bubble, in workspace units. + * @type {number} + * @private + */ + this.height_ = 0; + + /** + * Automatically position and reposition the bubble. + * @type {boolean} + * @private + */ + this.autoLayout_ = true; + + /** + * Method to call on resize of bubble. + * @type {?function()} + * @private + */ + this.resizeCallback_ = null; + + /** + * Method to call on move of bubble. + * @type {?function()} + * @private + */ + this.moveCallback_ = null; + + /** + * Mouse down on bubbleBack_ event data. + * @type {?browserEvents.Data} + * @private + */ + this.onMouseDownBubbleWrapper_ = null; + + /** + * Mouse down on resizeGroup_ event data. + * @type {?browserEvents.Data} + * @private + */ + this.onMouseDownResizeWrapper_ = null; + + /** + * Describes whether this bubble has been disposed of (nodes and event + * listeners removed from the page) or not. + * @type {boolean} + * @package + */ + this.disposed = false; + + let angle = Bubble.ARROW_ANGLE; + if (this.workspace_.RTL) { + angle = -angle; + } + this.arrow_radians_ = math.toRadians(angle); + + const canvas = workspace.getBubbleCanvas(); + canvas.appendChild( + this.createDom_(content, !!(bubbleWidth && bubbleHeight))); + + this.setAnchorLocation(anchorXY); + if (!bubbleWidth || !bubbleHeight) { + const bBox = /** @type {SVGLocatable} */ (this.content_).getBBox(); + bubbleWidth = bBox.width + 2 * Bubble.BORDER_WIDTH; + bubbleHeight = bBox.height + 2 * Bubble.BORDER_WIDTH; + } + this.setBubbleSize(bubbleWidth, bubbleHeight); + + // Render the bubble. + this.positionBubble_(); + this.renderArrow_(); + this.rendered_ = true; + } /** - * Flag to stop incremental rendering during construction. - * @type {boolean} + * Create the bubble's DOM. + * @param {!Element} content SVG content for the bubble. + * @param {boolean} hasResize Add diagonal resize gripper if true. + * @return {!SVGElement} The bubble's SVG group. * @private */ - this.rendered_ = false; + createDom_(content, hasResize) { + /* Create the bubble. Here's the markup that will be generated: + + + + + + + + + + + [...content goes here...] + + */ + this.bubbleGroup_ = dom.createSvgElement(Svg.G, {}, null); + let filter = { + 'filter': 'url(#' + + this.workspace_.getRenderer().getConstants().embossFilterId + ')', + }; + if (userAgent.JAVA_FX) { + // Multiple reports that JavaFX can't handle filters. + // https://github.com/google/blockly/issues/99 + filter = {}; + } + const bubbleEmboss = dom.createSvgElement(Svg.G, filter, this.bubbleGroup_); + this.bubbleArrow_ = dom.createSvgElement(Svg.PATH, {}, bubbleEmboss); + this.bubbleBack_ = dom.createSvgElement( + Svg.RECT, { + 'class': 'blocklyDraggable', + 'x': 0, + 'y': 0, + 'rx': Bubble.BORDER_WIDTH, + 'ry': Bubble.BORDER_WIDTH, + }, + bubbleEmboss); + if (hasResize) { + this.resizeGroup_ = dom.createSvgElement( + Svg.G, { + 'class': this.workspace_.RTL ? 'blocklyResizeSW' : + 'blocklyResizeSE', + }, + this.bubbleGroup_); + const resizeSize = 2 * Bubble.BORDER_WIDTH; + dom.createSvgElement( + Svg.POLYGON, + {'points': '0,x x,x x,0'.replace(/x/g, resizeSize.toString())}, + this.resizeGroup_); + dom.createSvgElement( + Svg.LINE, { + 'class': 'blocklyResizeLine', + 'x1': resizeSize / 3, + 'y1': resizeSize - 1, + 'x2': resizeSize - 1, + 'y2': resizeSize / 3, + }, + this.resizeGroup_); + dom.createSvgElement( + Svg.LINE, { + 'class': 'blocklyResizeLine', + 'x1': resizeSize * 2 / 3, + 'y1': resizeSize - 1, + 'x2': resizeSize - 1, + 'y2': resizeSize * 2 / 3, + }, + this.resizeGroup_); + } else { + this.resizeGroup_ = null; + } + + if (!this.workspace_.options.readOnly) { + this.onMouseDownBubbleWrapper_ = browserEvents.conditionalBind( + this.bubbleBack_, 'mousedown', this, this.bubbleMouseDown_); + if (this.resizeGroup_) { + this.onMouseDownResizeWrapper_ = browserEvents.conditionalBind( + this.resizeGroup_, 'mousedown', this, this.resizeMouseDown_); + } + } + this.bubbleGroup_.appendChild(content); + return this.bubbleGroup_; + } /** - * Absolute coordinate of anchor point, in workspace coordinates. - * @type {Coordinate} + * Return the root node of the bubble's SVG group. + * @return {!SVGElement} The root SVG node of the bubble's group. + */ + getSvgRoot() { + return /** @type {!SVGElement} */ (this.bubbleGroup_); + } + + /** + * Expose the block's ID on the bubble's top-level SVG group. + * @param {string} id ID of block. + */ + setSvgId(id) { + if (this.bubbleGroup_.dataset) { + this.bubbleGroup_.dataset['blockId'] = id; + } + } + + /** + * Handle a mouse-down on bubble's border. + * @param {!Event} e Mouse down event. * @private */ - this.anchorXY_ = null; + bubbleMouseDown_(e) { + const gesture = this.workspace_.getGesture(e); + if (gesture) { + gesture.handleBubbleStart(e, this); + } + } /** - * Relative X coordinate of bubble with respect to the anchor's centre, - * in workspace units. - * In RTL mode the initial value is negated. - * @type {number} - * @private - */ - this.relativeLeft_ = 0; - - /** - * Relative Y coordinate of bubble with respect to the anchor's centre, in - * workspace units. - * @type {number} - * @private - */ - this.relativeTop_ = 0; - - /** - * Width of bubble, in workspace units. - * @type {number} - * @private - */ - this.width_ = 0; - - /** - * Height of bubble, in workspace units. - * @type {number} - * @private - */ - this.height_ = 0; - - /** - * Automatically position and reposition the bubble. - * @type {boolean} - * @private - */ - this.autoLayout_ = true; - - /** - * Method to call on resize of bubble. - * @type {?function()} - * @private - */ - this.resizeCallback_ = null; - - /** - * Method to call on move of bubble. - * @type {?function()} - * @private - */ - this.moveCallback_ = null; - - /** - * Mouse down on bubbleBack_ event data. - * @type {?browserEvents.Data} - * @private - */ - this.onMouseDownBubbleWrapper_ = null; - - /** - * Mouse down on resizeGroup_ event data. - * @type {?browserEvents.Data} - * @private - */ - this.onMouseDownResizeWrapper_ = null; - - /** - * Describes whether this bubble has been disposed of (nodes and event - * listeners removed from the page) or not. - * @type {boolean} + * Show the context menu for this bubble. + * @param {!Event} _e Mouse event. * @package */ - this.disposed = false; - - let angle = Bubble.ARROW_ANGLE; - if (this.workspace_.RTL) { - angle = -angle; + showContextMenu(_e) { + // NOP on bubbles, but used by the bubble dragger to pass events to + // workspace comments. } - this.arrow_radians_ = math.toRadians(angle); - const canvas = workspace.getBubbleCanvas(); - canvas.appendChild(this.createDom_(content, !!(bubbleWidth && bubbleHeight))); - - this.setAnchorLocation(anchorXY); - if (!bubbleWidth || !bubbleHeight) { - const bBox = /** @type {SVGLocatable} */ (this.content_).getBBox(); - bubbleWidth = bBox.width + 2 * Bubble.BORDER_WIDTH; - bubbleHeight = bBox.height + 2 * Bubble.BORDER_WIDTH; + /** + * Get whether this bubble is deletable or not. + * @return {boolean} True if deletable. + * @package + */ + isDeletable() { + return false; } - this.setBubbleSize(bubbleWidth, bubbleHeight); - // Render the bubble. - this.positionBubble_(); - this.renderArrow_(); - this.rendered_ = true; + /** + * Update the style of this bubble when it is dragged over a delete area. + * @param {boolean} _enable True if the bubble is about to be deleted, false + * otherwise. + */ + setDeleteStyle(_enable) { + // NOP if bubble is not deletable. + } + + /** + * Handle a mouse-down on bubble's resize corner. + * @param {!Event} e Mouse down event. + * @private + */ + resizeMouseDown_(e) { + this.promote(); + Bubble.unbindDragEvents_(); + if (browserEvents.isRightButton(e)) { + // No right-click. + e.stopPropagation(); + return; + } + // Left-click (or middle click) + this.workspace_.startDrag( + e, + new Coordinate( + this.workspace_.RTL ? -this.width_ : this.width_, this.height_)); + + Bubble.onMouseUpWrapper_ = browserEvents.conditionalBind( + document, 'mouseup', this, Bubble.bubbleMouseUp_); + Bubble.onMouseMoveWrapper_ = browserEvents.conditionalBind( + document, 'mousemove', this, this.resizeMouseMove_); + this.workspace_.hideChaff(); + // This event has been handled. No need to bubble up to the document. + e.stopPropagation(); + } + + /** + * Resize this bubble to follow the mouse. + * @param {!Event} e Mouse move event. + * @private + */ + resizeMouseMove_(e) { + this.autoLayout_ = false; + const newXY = this.workspace_.moveDrag(e); + this.setBubbleSize(this.workspace_.RTL ? -newXY.x : newXY.x, newXY.y); + if (this.workspace_.RTL) { + // RTL requires the bubble to move its left edge. + this.positionBubble_(); + } + } + + /** + * Register a function as a callback event for when the bubble is resized. + * @param {!Function} callback The function to call on resize. + */ + registerResizeEvent(callback) { + this.resizeCallback_ = callback; + } + + /** + * Register a function as a callback event for when the bubble is moved. + * @param {!Function} callback The function to call on move. + */ + registerMoveEvent(callback) { + this.moveCallback_ = callback; + } + + /** + * Move this bubble to the top of the stack. + * @return {boolean} Whether or not the bubble has been moved. + * @package + */ + promote() { + const svgGroup = this.bubbleGroup_.parentNode; + if (svgGroup.lastChild !== this.bubbleGroup_) { + svgGroup.appendChild(this.bubbleGroup_); + return true; + } + return false; + } + + /** + * Notification that the anchor has moved. + * Update the arrow and bubble accordingly. + * @param {!Coordinate} xy Absolute location. + */ + setAnchorLocation(xy) { + this.anchorXY_ = xy; + if (this.rendered_) { + this.positionBubble_(); + } + } + + /** + * Position the bubble so that it does not fall off-screen. + * @private + */ + layoutBubble_() { + // Get the metrics in workspace units. + const viewMetrics = + this.workspace_.getMetricsManager().getViewMetrics(true); + + const optimalLeft = this.getOptimalRelativeLeft_(viewMetrics); + const optimalTop = this.getOptimalRelativeTop_(viewMetrics); + const bbox = this.shape_.getBBox(); + + const topPosition = { + x: optimalLeft, + y: -this.height_ - + this.workspace_.getRenderer().getConstants().MIN_BLOCK_HEIGHT, + }; + const startPosition = {x: -this.width_ - 30, y: optimalTop}; + const endPosition = {x: bbox.width, y: optimalTop}; + const bottomPosition = {x: optimalLeft, y: bbox.height}; + + const closerPosition = + bbox.width < bbox.height ? endPosition : bottomPosition; + const fartherPosition = + bbox.width < bbox.height ? bottomPosition : endPosition; + + const topPositionOverlap = this.getOverlap_(topPosition, viewMetrics); + const startPositionOverlap = this.getOverlap_(startPosition, viewMetrics); + const closerPositionOverlap = this.getOverlap_(closerPosition, viewMetrics); + const fartherPositionOverlap = + this.getOverlap_(fartherPosition, viewMetrics); + + // Set the position to whichever position shows the most of the bubble, + // with tiebreaks going in the order: top > start > close > far. + const mostOverlap = Math.max( + topPositionOverlap, startPositionOverlap, closerPositionOverlap, + fartherPositionOverlap); + if (topPositionOverlap === mostOverlap) { + this.relativeLeft_ = topPosition.x; + this.relativeTop_ = topPosition.y; + return; + } + if (startPositionOverlap === mostOverlap) { + this.relativeLeft_ = startPosition.x; + this.relativeTop_ = startPosition.y; + return; + } + if (closerPositionOverlap === mostOverlap) { + this.relativeLeft_ = closerPosition.x; + this.relativeTop_ = closerPosition.y; + return; + } + // TODO: I believe relativeLeft_ should actually be called relativeStart_ + // and then the math should be fixed to reflect this. (hopefully it'll + // make it look simpler) + this.relativeLeft_ = fartherPosition.x; + this.relativeTop_ = fartherPosition.y; + } + + /** + * Calculate the what percentage of the bubble overlaps with the visible + * workspace (what percentage of the bubble is visible). + * @param {!{x: number, y: number}} relativeMin The position of the top-left + * corner of the bubble relative to the anchor point. + * @param {!MetricsManager.ContainerRegion} viewMetrics The view metrics + * of the workspace the bubble will appear in. + * @return {number} The percentage of the bubble that is visible. + * @private + */ + getOverlap_(relativeMin, viewMetrics) { + // The position of the top-left corner of the bubble in workspace units. + const bubbleMin = { + x: this.workspace_.RTL ? + (this.anchorXY_.x - relativeMin.x - this.width_) : + (relativeMin.x + this.anchorXY_.x), + y: relativeMin.y + this.anchorXY_.y, + }; + // The position of the bottom-right corner of the bubble in workspace units. + const bubbleMax = { + x: bubbleMin.x + this.width_, + y: bubbleMin.y + this.height_, + }; + + // We could adjust these values to account for the scrollbars, but the + // bubbles should have been adjusted to not collide with them anyway, so + // giving the workspace a slightly larger "bounding box" shouldn't affect + // the calculation. + + // The position of the top-left corner of the workspace. + const workspaceMin = {x: viewMetrics.left, y: viewMetrics.top}; + // The position of the bottom-right corner of the workspace. + const workspaceMax = { + x: viewMetrics.left + viewMetrics.width, + y: viewMetrics.top + viewMetrics.height, + }; + + const overlapWidth = Math.min(bubbleMax.x, workspaceMax.x) - + Math.max(bubbleMin.x, workspaceMin.x); + const overlapHeight = Math.min(bubbleMax.y, workspaceMax.y) - + Math.max(bubbleMin.y, workspaceMin.y); + return Math.max( + 0, + Math.min( + 1, (overlapWidth * overlapHeight) / (this.width_ * this.height_))); + } + + /** + * Calculate what the optimal horizontal position of the top-left corner of + * the bubble is (relative to the anchor point) so that the most area of the + * bubble is shown. + * @param {!MetricsManager.ContainerRegion} viewMetrics The view metrics + * of the workspace the bubble will appear in. + * @return {number} The optimal horizontal position of the top-left corner + * of the bubble. + * @private + */ + getOptimalRelativeLeft_(viewMetrics) { + let relativeLeft = -this.width_ / 4; + + // No amount of sliding left or right will give us a better overlap. + if (this.width_ > viewMetrics.width) { + return relativeLeft; + } + + if (this.workspace_.RTL) { + // Bubble coordinates are flipped in RTL. + const bubbleRight = this.anchorXY_.x - relativeLeft; + const bubbleLeft = bubbleRight - this.width_; + + const workspaceRight = viewMetrics.left + viewMetrics.width; + const workspaceLeft = viewMetrics.left + + // Thickness in workspace units. + (Scrollbar.scrollbarThickness / this.workspace_.scale); + + if (bubbleLeft < workspaceLeft) { + // Slide the bubble right until it is onscreen. + relativeLeft = -(workspaceLeft - this.anchorXY_.x + this.width_); + } else if (bubbleRight > workspaceRight) { + // Slide the bubble left until it is onscreen. + relativeLeft = -(workspaceRight - this.anchorXY_.x); + } + } else { + const bubbleLeft = relativeLeft + this.anchorXY_.x; + const bubbleRight = bubbleLeft + this.width_; + + const workspaceLeft = viewMetrics.left; + const workspaceRight = viewMetrics.left + viewMetrics.width - + // Thickness in workspace units. + (Scrollbar.scrollbarThickness / this.workspace_.scale); + + if (bubbleLeft < workspaceLeft) { + // Slide the bubble right until it is onscreen. + relativeLeft = workspaceLeft - this.anchorXY_.x; + } else if (bubbleRight > workspaceRight) { + // Slide the bubble left until it is onscreen. + relativeLeft = workspaceRight - this.anchorXY_.x - this.width_; + } + } + + return relativeLeft; + } + + /** + * Calculate what the optimal vertical position of the top-left corner of + * the bubble is (relative to the anchor point) so that the most area of the + * bubble is shown. + * @param {!MetricsManager.ContainerRegion} viewMetrics The view metrics + * of the workspace the bubble will appear in. + * @return {number} The optimal vertical position of the top-left corner + * of the bubble. + * @private + */ + getOptimalRelativeTop_(viewMetrics) { + let relativeTop = -this.height_ / 4; + + // No amount of sliding up or down will give us a better overlap. + if (this.height_ > viewMetrics.height) { + return relativeTop; + } + + const bubbleTop = this.anchorXY_.y + relativeTop; + const bubbleBottom = bubbleTop + this.height_; + const workspaceTop = viewMetrics.top; + const workspaceBottom = viewMetrics.top + viewMetrics.height - + // Thickness in workspace units. + (Scrollbar.scrollbarThickness / this.workspace_.scale); + + const anchorY = this.anchorXY_.y; + if (bubbleTop < workspaceTop) { + // Slide the bubble down until it is onscreen. + relativeTop = workspaceTop - anchorY; + } else if (bubbleBottom > workspaceBottom) { + // Slide the bubble up until it is onscreen. + relativeTop = workspaceBottom - anchorY - this.height_; + } + + return relativeTop; + } + + /** + * Move the bubble to a location relative to the anchor's centre. + * @private + */ + positionBubble_() { + let left = this.anchorXY_.x; + if (this.workspace_.RTL) { + left -= this.relativeLeft_ + this.width_; + } else { + left += this.relativeLeft_; + } + const top = this.relativeTop_ + this.anchorXY_.y; + this.moveTo(left, top); + } + + /** + * Move the bubble group to the specified location in workspace coordinates. + * @param {number} x The x position to move to. + * @param {number} y The y position to move to. + * @package + */ + moveTo(x, y) { + this.bubbleGroup_.setAttribute( + 'transform', 'translate(' + x + ',' + y + ')'); + } + + /** + * Triggers a move callback if one exists at the end of a drag. + * @param {boolean} adding True if adding, false if removing. + * @package + */ + setDragging(adding) { + if (!adding && this.moveCallback_) { + this.moveCallback_(); + } + } + + /** + * Get the dimensions of this bubble. + * @return {!Size} The height and width of the bubble. + */ + getBubbleSize() { + return new Size(this.width_, this.height_); + } + + /** + * Size this bubble. + * @param {number} width Width of the bubble. + * @param {number} height Height of the bubble. + */ + setBubbleSize(width, height) { + const doubleBorderWidth = 2 * Bubble.BORDER_WIDTH; + // Minimum size of a bubble. + width = Math.max(width, doubleBorderWidth + 45); + height = Math.max(height, doubleBorderWidth + 20); + this.width_ = width; + this.height_ = height; + this.bubbleBack_.setAttribute('width', width); + this.bubbleBack_.setAttribute('height', height); + if (this.resizeGroup_) { + if (this.workspace_.RTL) { + // Mirror the resize group. + const resizeSize = 2 * Bubble.BORDER_WIDTH; + this.resizeGroup_.setAttribute( + 'transform', + 'translate(' + resizeSize + ',' + (height - doubleBorderWidth) + + ') scale(-1 1)'); + } else { + this.resizeGroup_.setAttribute( + 'transform', + 'translate(' + (width - doubleBorderWidth) + ',' + + (height - doubleBorderWidth) + ')'); + } + } + if (this.autoLayout_) { + this.layoutBubble_(); + } + this.positionBubble_(); + this.renderArrow_(); + + // Allow the contents to resize. + if (this.resizeCallback_) { + this.resizeCallback_(); + } + } + + /** + * Draw the arrow between the bubble and the origin. + * @private + */ + renderArrow_() { + const steps = []; + // Find the relative coordinates of the center of the bubble. + const relBubbleX = this.width_ / 2; + const relBubbleY = this.height_ / 2; + // Find the relative coordinates of the center of the anchor. + let relAnchorX = -this.relativeLeft_; + let relAnchorY = -this.relativeTop_; + if (relBubbleX === relAnchorX && relBubbleY === relAnchorY) { + // Null case. Bubble is directly on top of the anchor. + // Short circuit this rather than wade through divide by zeros. + steps.push('M ' + relBubbleX + ',' + relBubbleY); + } else { + // Compute the angle of the arrow's line. + const rise = relAnchorY - relBubbleY; + let run = relAnchorX - relBubbleX; + if (this.workspace_.RTL) { + run *= -1; + } + const hypotenuse = Math.sqrt(rise * rise + run * run); + let angle = Math.acos(run / hypotenuse); + if (rise < 0) { + angle = 2 * Math.PI - angle; + } + // Compute a line perpendicular to the arrow. + let rightAngle = angle + Math.PI / 2; + if (rightAngle > Math.PI * 2) { + rightAngle -= Math.PI * 2; + } + const rightRise = Math.sin(rightAngle); + const rightRun = Math.cos(rightAngle); + + // Calculate the thickness of the base of the arrow. + const bubbleSize = this.getBubbleSize(); + let thickness = + (bubbleSize.width + bubbleSize.height) / Bubble.ARROW_THICKNESS; + thickness = Math.min(thickness, bubbleSize.width, bubbleSize.height) / 4; + + // Back the tip of the arrow off of the anchor. + const backoffRatio = 1 - Bubble.ANCHOR_RADIUS / hypotenuse; + relAnchorX = relBubbleX + backoffRatio * run; + relAnchorY = relBubbleY + backoffRatio * rise; + + // Coordinates for the base of the arrow. + const baseX1 = relBubbleX + thickness * rightRun; + const baseY1 = relBubbleY + thickness * rightRise; + const baseX2 = relBubbleX - thickness * rightRun; + const baseY2 = relBubbleY - thickness * rightRise; + + // Distortion to curve the arrow. + let swirlAngle = angle + this.arrow_radians_; + if (swirlAngle > Math.PI * 2) { + swirlAngle -= Math.PI * 2; + } + const swirlRise = Math.sin(swirlAngle) * hypotenuse / Bubble.ARROW_BEND; + const swirlRun = Math.cos(swirlAngle) * hypotenuse / Bubble.ARROW_BEND; + + steps.push('M' + baseX1 + ',' + baseY1); + steps.push( + 'C' + (baseX1 + swirlRun) + ',' + (baseY1 + swirlRise) + ' ' + + relAnchorX + ',' + relAnchorY + ' ' + relAnchorX + ',' + relAnchorY); + steps.push( + 'C' + relAnchorX + ',' + relAnchorY + ' ' + (baseX2 + swirlRun) + + ',' + (baseY2 + swirlRise) + ' ' + baseX2 + ',' + baseY2); + } + steps.push('z'); + this.bubbleArrow_.setAttribute('d', steps.join(' ')); + } + + /** + * Change the colour of a bubble. + * @param {string} hexColour Hex code of colour. + */ + setColour(hexColour) { + this.bubbleBack_.setAttribute('fill', hexColour); + this.bubbleArrow_.setAttribute('fill', hexColour); + } + + /** + * Dispose of this bubble. + */ + dispose() { + if (this.onMouseDownBubbleWrapper_) { + browserEvents.unbind(this.onMouseDownBubbleWrapper_); + } + if (this.onMouseDownResizeWrapper_) { + browserEvents.unbind(this.onMouseDownResizeWrapper_); + } + Bubble.unbindDragEvents_(); + dom.removeNode(this.bubbleGroup_); + this.disposed = true; + } + + /** + * Move this bubble during a drag, taking into account whether or not there is + * a drag surface. + * @param {BlockDragSurfaceSvg} dragSurface The surface that carries + * rendered items during a drag, or null if no drag surface is in use. + * @param {!Coordinate} newLoc The location to translate to, in + * workspace coordinates. + * @package + */ + moveDuringDrag(dragSurface, newLoc) { + if (dragSurface) { + dragSurface.translateSurface(newLoc.x, newLoc.y); + } else { + this.moveTo(newLoc.x, newLoc.y); + } + if (this.workspace_.RTL) { + this.relativeLeft_ = this.anchorXY_.x - newLoc.x - this.width_; + } else { + this.relativeLeft_ = newLoc.x - this.anchorXY_.x; + } + this.relativeTop_ = newLoc.y - this.anchorXY_.y; + this.renderArrow_(); + } + + /** + * Return the coordinates of the top-left corner of this bubble's body + * relative to the drawing surface's origin (0,0), in workspace units. + * @return {!Coordinate} Object with .x and .y properties. + */ + getRelativeToSurfaceXY() { + return new Coordinate( + this.workspace_.RTL ? + -this.relativeLeft_ + this.anchorXY_.x - this.width_ : + this.anchorXY_.x + this.relativeLeft_, + this.anchorXY_.y + this.relativeTop_); + } + + /** + * Set whether auto-layout of this bubble is enabled. The first time a bubble + * is shown it positions itself to not cover any blocks. Once a user has + * dragged it to reposition, it renders where the user put it. + * @param {boolean} enable True if auto-layout should be enabled, false + * otherwise. + * @package + */ + setAutoLayout(enable) { + this.autoLayout_ = enable; + } + + /** + * Stop binding to the global mouseup and mousemove events. + * @private + */ + static unbindDragEvents_() { + if (Bubble.onMouseUpWrapper_) { + browserEvents.unbind(Bubble.onMouseUpWrapper_); + Bubble.onMouseUpWrapper_ = null; + } + if (Bubble.onMouseMoveWrapper_) { + browserEvents.unbind(Bubble.onMouseMoveWrapper_); + Bubble.onMouseMoveWrapper_ = null; + } + } + + /** + * Handle a mouse-up event while dragging a bubble's border or resize handle. + * @param {!Event} _e Mouse up event. + * @private + */ + static bubbleMouseUp_(_e) { + Touch.clearTouchIdentifier(); + Bubble.unbindDragEvents_(); + } + + /** + * Create the text for a non editable bubble. + * @param {string} text The text to display. + * @return {!SVGTextElement} The top-level node of the text. + * @package + */ + static textToDom(text) { + const paragraph = dom.createSvgElement( + Svg.TEXT, { + 'class': 'blocklyText blocklyBubbleText blocklyNoPointerEvents', + 'y': Bubble.BORDER_WIDTH, + }, + null); + const lines = text.split('\n'); + for (let i = 0; i < lines.length; i++) { + const tspanElement = dom.createSvgElement( + Svg.TSPAN, {'dy': '1em', 'x': Bubble.BORDER_WIDTH}, paragraph); + const textNode = document.createTextNode(lines[i]); + tspanElement.appendChild(textNode); + } + return paragraph; + } + + /** + * Creates a bubble that can not be edited. + * @param {!SVGTextElement} paragraphElement The text element for the non + * editable bubble. + * @param {!BlockSvg} block The block that the bubble is attached to. + * @param {!Coordinate} iconXY The coordinate of the icon. + * @return {!Bubble} The non editable bubble. + * @package + */ + static createNonEditableBubble(paragraphElement, block, iconXY) { + const bubble = new Bubble( + /** @type {!WorkspaceSvg} */ (block.workspace), paragraphElement, + block.pathObject.svgPath, + /** @type {!Coordinate} */ (iconXY), null, null); + // Expose this bubble's block's ID on its top-level SVG group. + bubble.setSvgId(block.id); + if (block.RTL) { + // Right-align the paragraph. + // This cannot be done until the bubble is rendered on screen. + const maxWidth = paragraphElement.getBBox().width; + for (let i = 0, textElement; + (textElement = paragraphElement.childNodes[i]); i++) { + textElement.setAttribute('text-anchor', 'end'); + textElement.setAttribute('x', maxWidth + Bubble.BORDER_WIDTH); + } + } + return bubble; + } }; /** @@ -209,739 +982,4 @@ Bubble.onMouseUpWrapper_ = null; */ Bubble.onMouseMoveWrapper_ = null; -/** - * Stop binding to the global mouseup and mousemove events. - * @private - */ -Bubble.unbindDragEvents_ = function() { - if (Bubble.onMouseUpWrapper_) { - browserEvents.unbind(Bubble.onMouseUpWrapper_); - Bubble.onMouseUpWrapper_ = null; - } - if (Bubble.onMouseMoveWrapper_) { - browserEvents.unbind(Bubble.onMouseMoveWrapper_); - Bubble.onMouseMoveWrapper_ = null; - } -}; - -/** - * Handle a mouse-up event while dragging a bubble's border or resize handle. - * @param {!Event} _e Mouse up event. - * @private - */ -Bubble.bubbleMouseUp_ = function(_e) { - Touch.clearTouchIdentifier(); - Bubble.unbindDragEvents_(); -}; - -/** - * Create the bubble's DOM. - * @param {!Element} content SVG content for the bubble. - * @param {boolean} hasResize Add diagonal resize gripper if true. - * @return {!SVGElement} The bubble's SVG group. - * @private - */ -Bubble.prototype.createDom_ = function(content, hasResize) { - /* Create the bubble. Here's the markup that will be generated: - - - - - - - - - - - [...content goes here...] - - */ - this.bubbleGroup_ = dom.createSvgElement(Svg.G, {}, null); - let filter = { - 'filter': 'url(#' + - this.workspace_.getRenderer().getConstants().embossFilterId + ')', - }; - if (userAgent.JAVA_FX) { - // Multiple reports that JavaFX can't handle filters. - // https://github.com/google/blockly/issues/99 - filter = {}; - } - const bubbleEmboss = dom.createSvgElement(Svg.G, filter, this.bubbleGroup_); - this.bubbleArrow_ = dom.createSvgElement(Svg.PATH, {}, bubbleEmboss); - this.bubbleBack_ = dom.createSvgElement( - Svg.RECT, { - 'class': 'blocklyDraggable', - 'x': 0, - 'y': 0, - 'rx': Bubble.BORDER_WIDTH, - 'ry': Bubble.BORDER_WIDTH, - }, - bubbleEmboss); - if (hasResize) { - this.resizeGroup_ = dom.createSvgElement( - Svg.G, - {'class': this.workspace_.RTL ? 'blocklyResizeSW' : 'blocklyResizeSE'}, - this.bubbleGroup_); - const resizeSize = 2 * Bubble.BORDER_WIDTH; - dom.createSvgElement( - Svg.POLYGON, - {'points': '0,x x,x x,0'.replace(/x/g, resizeSize.toString())}, - this.resizeGroup_); - dom.createSvgElement( - Svg.LINE, { - 'class': 'blocklyResizeLine', - 'x1': resizeSize / 3, - 'y1': resizeSize - 1, - 'x2': resizeSize - 1, - 'y2': resizeSize / 3, - }, - this.resizeGroup_); - dom.createSvgElement( - Svg.LINE, { - 'class': 'blocklyResizeLine', - 'x1': resizeSize * 2 / 3, - 'y1': resizeSize - 1, - 'x2': resizeSize - 1, - 'y2': resizeSize * 2 / 3, - }, - this.resizeGroup_); - } else { - this.resizeGroup_ = null; - } - - if (!this.workspace_.options.readOnly) { - this.onMouseDownBubbleWrapper_ = browserEvents.conditionalBind( - this.bubbleBack_, 'mousedown', this, this.bubbleMouseDown_); - if (this.resizeGroup_) { - this.onMouseDownResizeWrapper_ = browserEvents.conditionalBind( - this.resizeGroup_, 'mousedown', this, this.resizeMouseDown_); - } - } - this.bubbleGroup_.appendChild(content); - return this.bubbleGroup_; -}; - -/** - * Return the root node of the bubble's SVG group. - * @return {!SVGElement} The root SVG node of the bubble's group. - */ -Bubble.prototype.getSvgRoot = function() { - return this.bubbleGroup_; -}; - -/** - * Expose the block's ID on the bubble's top-level SVG group. - * @param {string} id ID of block. - */ -Bubble.prototype.setSvgId = function(id) { - if (this.bubbleGroup_.dataset) { - this.bubbleGroup_.dataset['blockId'] = id; - } -}; - -/** - * Handle a mouse-down on bubble's border. - * @param {!Event} e Mouse down event. - * @private - */ -Bubble.prototype.bubbleMouseDown_ = function(e) { - const gesture = this.workspace_.getGesture(e); - if (gesture) { - gesture.handleBubbleStart(e, this); - } -}; - -/** - * Show the context menu for this bubble. - * @param {!Event} _e Mouse event. - * @package - */ -Bubble.prototype.showContextMenu = function(_e) { - // NOP on bubbles, but used by the bubble dragger to pass events to - // workspace comments. -}; - -/** - * Get whether this bubble is deletable or not. - * @return {boolean} True if deletable. - * @package - */ -Bubble.prototype.isDeletable = function() { - return false; -}; - -/** - * Update the style of this bubble when it is dragged over a delete area. - * @param {boolean} _enable True if the bubble is about to be deleted, false - * otherwise. - */ -Bubble.prototype.setDeleteStyle = function(_enable) { - // NOP if bubble is not deletable. -}; - -/** - * Handle a mouse-down on bubble's resize corner. - * @param {!Event} e Mouse down event. - * @private - */ -Bubble.prototype.resizeMouseDown_ = function(e) { - this.promote(); - Bubble.unbindDragEvents_(); - if (browserEvents.isRightButton(e)) { - // No right-click. - e.stopPropagation(); - return; - } - // Left-click (or middle click) - this.workspace_.startDrag( - e, - new Coordinate( - this.workspace_.RTL ? -this.width_ : this.width_, this.height_)); - - Bubble.onMouseUpWrapper_ = browserEvents.conditionalBind( - document, 'mouseup', this, Bubble.bubbleMouseUp_); - Bubble.onMouseMoveWrapper_ = browserEvents.conditionalBind( - document, 'mousemove', this, this.resizeMouseMove_); - this.workspace_.hideChaff(); - // This event has been handled. No need to bubble up to the document. - e.stopPropagation(); -}; - -/** - * Resize this bubble to follow the mouse. - * @param {!Event} e Mouse move event. - * @private - */ -Bubble.prototype.resizeMouseMove_ = function(e) { - this.autoLayout_ = false; - const newXY = this.workspace_.moveDrag(e); - this.setBubbleSize(this.workspace_.RTL ? -newXY.x : newXY.x, newXY.y); - if (this.workspace_.RTL) { - // RTL requires the bubble to move its left edge. - this.positionBubble_(); - } -}; - -/** - * Register a function as a callback event for when the bubble is resized. - * @param {!Function} callback The function to call on resize. - */ -Bubble.prototype.registerResizeEvent = function(callback) { - this.resizeCallback_ = callback; -}; - -/** - * Register a function as a callback event for when the bubble is moved. - * @param {!Function} callback The function to call on move. - */ -Bubble.prototype.registerMoveEvent = function(callback) { - this.moveCallback_ = callback; -}; - -/** - * Move this bubble to the top of the stack. - * @return {boolean} Whether or not the bubble has been moved. - * @package - */ -Bubble.prototype.promote = function() { - const svgGroup = this.bubbleGroup_.parentNode; - if (svgGroup.lastChild !== this.bubbleGroup_) { - svgGroup.appendChild(this.bubbleGroup_); - return true; - } - return false; -}; - -/** - * Notification that the anchor has moved. - * Update the arrow and bubble accordingly. - * @param {!Coordinate} xy Absolute location. - */ -Bubble.prototype.setAnchorLocation = function(xy) { - this.anchorXY_ = xy; - if (this.rendered_) { - this.positionBubble_(); - } -}; - -/** - * Position the bubble so that it does not fall off-screen. - * @private - */ -Bubble.prototype.layoutBubble_ = function() { - // Get the metrics in workspace units. - const viewMetrics = this.workspace_.getMetricsManager().getViewMetrics(true); - - const optimalLeft = this.getOptimalRelativeLeft_(viewMetrics); - const optimalTop = this.getOptimalRelativeTop_(viewMetrics); - const bbox = this.shape_.getBBox(); - - const topPosition = { - x: optimalLeft, - y: -this.height_ - - this.workspace_.getRenderer().getConstants().MIN_BLOCK_HEIGHT, - }; - const startPosition = {x: -this.width_ - 30, y: optimalTop}; - const endPosition = {x: bbox.width, y: optimalTop}; - const bottomPosition = {x: optimalLeft, y: bbox.height}; - - const closerPosition = - bbox.width < bbox.height ? endPosition : bottomPosition; - const fartherPosition = - bbox.width < bbox.height ? bottomPosition : endPosition; - - const topPositionOverlap = this.getOverlap_(topPosition, viewMetrics); - const startPositionOverlap = this.getOverlap_(startPosition, viewMetrics); - const closerPositionOverlap = this.getOverlap_(closerPosition, viewMetrics); - const fartherPositionOverlap = this.getOverlap_(fartherPosition, viewMetrics); - - // Set the position to whichever position shows the most of the bubble, - // with tiebreaks going in the order: top > start > close > far. - const mostOverlap = Math.max( - topPositionOverlap, startPositionOverlap, closerPositionOverlap, - fartherPositionOverlap); - if (topPositionOverlap === mostOverlap) { - this.relativeLeft_ = topPosition.x; - this.relativeTop_ = topPosition.y; - return; - } - if (startPositionOverlap === mostOverlap) { - this.relativeLeft_ = startPosition.x; - this.relativeTop_ = startPosition.y; - return; - } - if (closerPositionOverlap === mostOverlap) { - this.relativeLeft_ = closerPosition.x; - this.relativeTop_ = closerPosition.y; - return; - } - // TODO: I believe relativeLeft_ should actually be called relativeStart_ - // and then the math should be fixed to reflect this. (hopefully it'll - // make it look simpler) - this.relativeLeft_ = fartherPosition.x; - this.relativeTop_ = fartherPosition.y; -}; - -/** - * Calculate the what percentage of the bubble overlaps with the visible - * workspace (what percentage of the bubble is visible). - * @param {!{x: number, y: number}} relativeMin The position of the top-left - * corner of the bubble relative to the anchor point. - * @param {!MetricsManager.ContainerRegion} viewMetrics The view metrics - * of the workspace the bubble will appear in. - * @return {number} The percentage of the bubble that is visible. - * @private - */ -Bubble.prototype.getOverlap_ = function(relativeMin, viewMetrics) { - // The position of the top-left corner of the bubble in workspace units. - const bubbleMin = { - x: this.workspace_.RTL ? (this.anchorXY_.x - relativeMin.x - this.width_) : - (relativeMin.x + this.anchorXY_.x), - y: relativeMin.y + this.anchorXY_.y, - }; - // The position of the bottom-right corner of the bubble in workspace units. - const bubbleMax = { - x: bubbleMin.x + this.width_, - y: bubbleMin.y + this.height_, - }; - - // We could adjust these values to account for the scrollbars, but the - // bubbles should have been adjusted to not collide with them anyway, so - // giving the workspace a slightly larger "bounding box" shouldn't affect the - // calculation. - - // The position of the top-left corner of the workspace. - const workspaceMin = {x: viewMetrics.left, y: viewMetrics.top}; - // The position of the bottom-right corner of the workspace. - const workspaceMax = { - x: viewMetrics.left + viewMetrics.width, - y: viewMetrics.top + viewMetrics.height, - }; - - const overlapWidth = Math.min(bubbleMax.x, workspaceMax.x) - - Math.max(bubbleMin.x, workspaceMin.x); - const overlapHeight = Math.min(bubbleMax.y, workspaceMax.y) - - Math.max(bubbleMin.y, workspaceMin.y); - return Math.max( - 0, - Math.min( - 1, (overlapWidth * overlapHeight) / (this.width_ * this.height_))); -}; - -/** - * Calculate what the optimal horizontal position of the top-left corner of the - * bubble is (relative to the anchor point) so that the most area of the - * bubble is shown. - * @param {!MetricsManager.ContainerRegion} viewMetrics The view metrics - * of the workspace the bubble will appear in. - * @return {number} The optimal horizontal position of the top-left corner - * of the bubble. - * @private - */ -Bubble.prototype.getOptimalRelativeLeft_ = function(viewMetrics) { - let relativeLeft = -this.width_ / 4; - - // No amount of sliding left or right will give us a better overlap. - if (this.width_ > viewMetrics.width) { - return relativeLeft; - } - - if (this.workspace_.RTL) { - // Bubble coordinates are flipped in RTL. - const bubbleRight = this.anchorXY_.x - relativeLeft; - const bubbleLeft = bubbleRight - this.width_; - - const workspaceRight = viewMetrics.left + viewMetrics.width; - const workspaceLeft = viewMetrics.left + - // Thickness in workspace units. - (Scrollbar.scrollbarThickness / this.workspace_.scale); - - if (bubbleLeft < workspaceLeft) { - // Slide the bubble right until it is onscreen. - relativeLeft = -(workspaceLeft - this.anchorXY_.x + this.width_); - } else if (bubbleRight > workspaceRight) { - // Slide the bubble left until it is onscreen. - relativeLeft = -(workspaceRight - this.anchorXY_.x); - } - } else { - const bubbleLeft = relativeLeft + this.anchorXY_.x; - const bubbleRight = bubbleLeft + this.width_; - - const workspaceLeft = viewMetrics.left; - const workspaceRight = viewMetrics.left + viewMetrics.width - - // Thickness in workspace units. - (Scrollbar.scrollbarThickness / this.workspace_.scale); - - if (bubbleLeft < workspaceLeft) { - // Slide the bubble right until it is onscreen. - relativeLeft = workspaceLeft - this.anchorXY_.x; - } else if (bubbleRight > workspaceRight) { - // Slide the bubble left until it is onscreen. - relativeLeft = workspaceRight - this.anchorXY_.x - this.width_; - } - } - - return relativeLeft; -}; - -/** - * Calculate what the optimal vertical position of the top-left corner of - * the bubble is (relative to the anchor point) so that the most area of the - * bubble is shown. - * @param {!MetricsManager.ContainerRegion} viewMetrics The view metrics - * of the workspace the bubble will appear in. - * @return {number} The optimal vertical position of the top-left corner - * of the bubble. - * @private - */ -Bubble.prototype.getOptimalRelativeTop_ = function(viewMetrics) { - let relativeTop = -this.height_ / 4; - - // No amount of sliding up or down will give us a better overlap. - if (this.height_ > viewMetrics.height) { - return relativeTop; - } - - const bubbleTop = this.anchorXY_.y + relativeTop; - const bubbleBottom = bubbleTop + this.height_; - const workspaceTop = viewMetrics.top; - const workspaceBottom = viewMetrics.top + viewMetrics.height - - // Thickness in workspace units. - (Scrollbar.scrollbarThickness / this.workspace_.scale); - - const anchorY = this.anchorXY_.y; - if (bubbleTop < workspaceTop) { - // Slide the bubble down until it is onscreen. - relativeTop = workspaceTop - anchorY; - } else if (bubbleBottom > workspaceBottom) { - // Slide the bubble up until it is onscreen. - relativeTop = workspaceBottom - anchorY - this.height_; - } - - return relativeTop; -}; - -/** - * Move the bubble to a location relative to the anchor's centre. - * @private - */ -Bubble.prototype.positionBubble_ = function() { - let left = this.anchorXY_.x; - if (this.workspace_.RTL) { - left -= this.relativeLeft_ + this.width_; - } else { - left += this.relativeLeft_; - } - const top = this.relativeTop_ + this.anchorXY_.y; - this.moveTo(left, top); -}; - -/** - * Move the bubble group to the specified location in workspace coordinates. - * @param {number} x The x position to move to. - * @param {number} y The y position to move to. - * @package - */ -Bubble.prototype.moveTo = function(x, y) { - this.bubbleGroup_.setAttribute('transform', 'translate(' + x + ',' + y + ')'); -}; - -/** - * Triggers a move callback if one exists at the end of a drag. - * @param {boolean} adding True if adding, false if removing. - * @package - */ -Bubble.prototype.setDragging = function(adding) { - if (!adding && this.moveCallback_) { - this.moveCallback_(); - } -}; - -/** - * Get the dimensions of this bubble. - * @return {!Size} The height and width of the bubble. - */ -Bubble.prototype.getBubbleSize = function() { - return new Size(this.width_, this.height_); -}; - -/** - * Size this bubble. - * @param {number} width Width of the bubble. - * @param {number} height Height of the bubble. - */ -Bubble.prototype.setBubbleSize = function(width, height) { - const doubleBorderWidth = 2 * Bubble.BORDER_WIDTH; - // Minimum size of a bubble. - width = Math.max(width, doubleBorderWidth + 45); - height = Math.max(height, doubleBorderWidth + 20); - this.width_ = width; - this.height_ = height; - this.bubbleBack_.setAttribute('width', width); - this.bubbleBack_.setAttribute('height', height); - if (this.resizeGroup_) { - if (this.workspace_.RTL) { - // Mirror the resize group. - const resizeSize = 2 * Bubble.BORDER_WIDTH; - this.resizeGroup_.setAttribute( - 'transform', - 'translate(' + resizeSize + ',' + (height - doubleBorderWidth) + - ') scale(-1 1)'); - } else { - this.resizeGroup_.setAttribute( - 'transform', - 'translate(' + (width - doubleBorderWidth) + ',' + - (height - doubleBorderWidth) + ')'); - } - } - if (this.autoLayout_) { - this.layoutBubble_(); - } - this.positionBubble_(); - this.renderArrow_(); - - // Allow the contents to resize. - if (this.resizeCallback_) { - this.resizeCallback_(); - } -}; - -/** - * Draw the arrow between the bubble and the origin. - * @private - */ -Bubble.prototype.renderArrow_ = function() { - const steps = []; - // Find the relative coordinates of the center of the bubble. - const relBubbleX = this.width_ / 2; - const relBubbleY = this.height_ / 2; - // Find the relative coordinates of the center of the anchor. - let relAnchorX = -this.relativeLeft_; - let relAnchorY = -this.relativeTop_; - if (relBubbleX === relAnchorX && relBubbleY === relAnchorY) { - // Null case. Bubble is directly on top of the anchor. - // Short circuit this rather than wade through divide by zeros. - steps.push('M ' + relBubbleX + ',' + relBubbleY); - } else { - // Compute the angle of the arrow's line. - const rise = relAnchorY - relBubbleY; - let run = relAnchorX - relBubbleX; - if (this.workspace_.RTL) { - run *= -1; - } - const hypotenuse = Math.sqrt(rise * rise + run * run); - let angle = Math.acos(run / hypotenuse); - if (rise < 0) { - angle = 2 * Math.PI - angle; - } - // Compute a line perpendicular to the arrow. - let rightAngle = angle + Math.PI / 2; - if (rightAngle > Math.PI * 2) { - rightAngle -= Math.PI * 2; - } - const rightRise = Math.sin(rightAngle); - const rightRun = Math.cos(rightAngle); - - // Calculate the thickness of the base of the arrow. - const bubbleSize = this.getBubbleSize(); - let thickness = - (bubbleSize.width + bubbleSize.height) / Bubble.ARROW_THICKNESS; - thickness = Math.min(thickness, bubbleSize.width, bubbleSize.height) / 4; - - // Back the tip of the arrow off of the anchor. - const backoffRatio = 1 - Bubble.ANCHOR_RADIUS / hypotenuse; - relAnchorX = relBubbleX + backoffRatio * run; - relAnchorY = relBubbleY + backoffRatio * rise; - - // Coordinates for the base of the arrow. - const baseX1 = relBubbleX + thickness * rightRun; - const baseY1 = relBubbleY + thickness * rightRise; - const baseX2 = relBubbleX - thickness * rightRun; - const baseY2 = relBubbleY - thickness * rightRise; - - // Distortion to curve the arrow. - let swirlAngle = angle + this.arrow_radians_; - if (swirlAngle > Math.PI * 2) { - swirlAngle -= Math.PI * 2; - } - const swirlRise = Math.sin(swirlAngle) * hypotenuse / Bubble.ARROW_BEND; - const swirlRun = Math.cos(swirlAngle) * hypotenuse / Bubble.ARROW_BEND; - - steps.push('M' + baseX1 + ',' + baseY1); - steps.push( - 'C' + (baseX1 + swirlRun) + ',' + (baseY1 + swirlRise) + ' ' + - relAnchorX + ',' + relAnchorY + ' ' + relAnchorX + ',' + relAnchorY); - steps.push( - 'C' + relAnchorX + ',' + relAnchorY + ' ' + (baseX2 + swirlRun) + ',' + - (baseY2 + swirlRise) + ' ' + baseX2 + ',' + baseY2); - } - steps.push('z'); - this.bubbleArrow_.setAttribute('d', steps.join(' ')); -}; - -/** - * Change the colour of a bubble. - * @param {string} hexColour Hex code of colour. - */ -Bubble.prototype.setColour = function(hexColour) { - this.bubbleBack_.setAttribute('fill', hexColour); - this.bubbleArrow_.setAttribute('fill', hexColour); -}; - -/** - * Dispose of this bubble. - */ -Bubble.prototype.dispose = function() { - if (this.onMouseDownBubbleWrapper_) { - browserEvents.unbind(this.onMouseDownBubbleWrapper_); - } - if (this.onMouseDownResizeWrapper_) { - browserEvents.unbind(this.onMouseDownResizeWrapper_); - } - Bubble.unbindDragEvents_(); - dom.removeNode(this.bubbleGroup_); - this.disposed = true; -}; - -/** - * Move this bubble during a drag, taking into account whether or not there is - * a drag surface. - * @param {BlockDragSurfaceSvg} dragSurface The surface that carries - * rendered items during a drag, or null if no drag surface is in use. - * @param {!Coordinate} newLoc The location to translate to, in - * workspace coordinates. - * @package - */ -Bubble.prototype.moveDuringDrag = function(dragSurface, newLoc) { - if (dragSurface) { - dragSurface.translateSurface(newLoc.x, newLoc.y); - } else { - this.moveTo(newLoc.x, newLoc.y); - } - if (this.workspace_.RTL) { - this.relativeLeft_ = this.anchorXY_.x - newLoc.x - this.width_; - } else { - this.relativeLeft_ = newLoc.x - this.anchorXY_.x; - } - this.relativeTop_ = newLoc.y - this.anchorXY_.y; - this.renderArrow_(); -}; - -/** - * Return the coordinates of the top-left corner of this bubble's body relative - * to the drawing surface's origin (0,0), in workspace units. - * @return {!Coordinate} Object with .x and .y properties. - */ -Bubble.prototype.getRelativeToSurfaceXY = function() { - return new Coordinate( - this.workspace_.RTL ? - -this.relativeLeft_ + this.anchorXY_.x - this.width_ : - this.anchorXY_.x + this.relativeLeft_, - this.anchorXY_.y + this.relativeTop_); -}; - -/** - * Set whether auto-layout of this bubble is enabled. The first time a bubble - * is shown it positions itself to not cover any blocks. Once a user has - * dragged it to reposition, it renders where the user put it. - * @param {boolean} enable True if auto-layout should be enabled, false - * otherwise. - * @package - */ -Bubble.prototype.setAutoLayout = function(enable) { - this.autoLayout_ = enable; -}; - -/** - * Create the text for a non editable bubble. - * @param {string} text The text to display. - * @return {!SVGTextElement} The top-level node of the text. - * @package - */ -Bubble.textToDom = function(text) { - const paragraph = dom.createSvgElement( - Svg.TEXT, { - 'class': 'blocklyText blocklyBubbleText blocklyNoPointerEvents', - 'y': Bubble.BORDER_WIDTH, - }, - null); - const lines = text.split('\n'); - for (let i = 0; i < lines.length; i++) { - const tspanElement = dom.createSvgElement( - Svg.TSPAN, {'dy': '1em', 'x': Bubble.BORDER_WIDTH}, paragraph); - const textNode = document.createTextNode(lines[i]); - tspanElement.appendChild(textNode); - } - return paragraph; -}; - -/** - * Creates a bubble that can not be edited. - * @param {!SVGTextElement} paragraphElement The text element for the non - * editable bubble. - * @param {!BlockSvg} block The block that the bubble is attached to. - * @param {!Coordinate} iconXY The coordinate of the icon. - * @return {!Bubble} The non editable bubble. - * @package - */ -Bubble.createNonEditableBubble = function(paragraphElement, block, iconXY) { - const bubble = new Bubble( - /** @type {!WorkspaceSvg} */ (block.workspace), paragraphElement, - block.pathObject.svgPath, - /** @type {!Coordinate} */ (iconXY), null, null); - // Expose this bubble's block's ID on its top-level SVG group. - bubble.setSvgId(block.id); - if (block.RTL) { - // Right-align the paragraph. - // This cannot be done until the bubble is rendered on screen. - const maxWidth = paragraphElement.getBBox().width; - for (let i = 0, textElement; (textElement = paragraphElement.childNodes[i]); - i++) { - textElement.setAttribute('text-anchor', 'end'); - textElement.setAttribute('x', maxWidth + Bubble.BORDER_WIDTH); - } - } - return bubble; -}; - exports.Bubble = Bubble; diff --git a/core/bubble_dragger.js b/core/bubble_dragger.js index e312ecdc2..7a716d3db 100644 --- a/core/bubble_dragger.js +++ b/core/bubble_dragger.js @@ -43,249 +43,253 @@ goog.require('Blockly.constants'); * Class for a bubble dragger. It moves things on the bubble canvas around the * workspace when they are being dragged by a mouse or touch. These can be * block comments, mutators, warnings, or workspace comments. - * @param {!IBubble} bubble The item on the bubble canvas to drag. - * @param {!WorkspaceSvg} workspace The workspace to drag on. - * @constructor - * @alias Blockly.BubbleDragger */ -const BubbleDragger = function(bubble, workspace) { +const BubbleDragger = class { /** - * The item on the bubble canvas that is being dragged. - * @type {!IBubble} - * @private + * @param {!IBubble} bubble The item on the bubble canvas to drag. + * @param {!WorkspaceSvg} workspace The workspace to drag on. + * @alias Blockly.BubbleDragger */ - this.draggingBubble_ = bubble; + constructor(bubble, workspace) { + /** + * The item on the bubble canvas that is being dragged. + * @type {!IBubble} + * @private + */ + this.draggingBubble_ = bubble; - /** - * The workspace on which the bubble is being dragged. - * @type {!WorkspaceSvg} - * @private - */ - this.workspace_ = workspace; + /** + * The workspace on which the bubble is being dragged. + * @type {!WorkspaceSvg} + * @private + */ + this.workspace_ = workspace; - /** - * Which drag target the mouse pointer is over, if any. - * @type {?IDragTarget} - * @private - */ - this.dragTarget_ = null; + /** + * Which drag target the mouse pointer is over, if any. + * @type {?IDragTarget} + * @private + */ + this.dragTarget_ = null; - /** - * Whether the bubble would be deleted if dropped immediately. - * @type {boolean} - * @private - */ - this.wouldDeleteBubble_ = false; + /** + * Whether the bubble would be deleted if dropped immediately. + * @type {boolean} + * @private + */ + this.wouldDeleteBubble_ = false; - /** - * The location of the top left corner of the dragging bubble's body at the - * beginning of the drag, in workspace coordinates. - * @type {!Coordinate} - * @private - */ - this.startXY_ = this.draggingBubble_.getRelativeToSurfaceXY(); + /** + * The location of the top left corner of the dragging bubble's body at the + * beginning of the drag, in workspace coordinates. + * @type {!Coordinate} + * @private + */ + this.startXY_ = this.draggingBubble_.getRelativeToSurfaceXY(); - /** - * The drag surface to move bubbles to during a drag, or null if none should - * be used. Block dragging and bubble dragging use the same surface. - * @type {BlockDragSurfaceSvg} - * @private - */ - this.dragSurface_ = - svgMath.is3dSupported() && !!workspace.getBlockDragSurface() ? - workspace.getBlockDragSurface() : - null; -}; - -/** - * Sever all links from this object. - * @package - * @suppress {checkTypes} - */ -BubbleDragger.prototype.dispose = function() { - this.draggingBubble_ = null; - this.workspace_ = null; - this.dragSurface_ = null; -}; - -/** - * Start dragging a bubble. This includes moving it to the drag surface. - * @package - */ -BubbleDragger.prototype.startBubbleDrag = function() { - if (!eventUtils.getGroup()) { - eventUtils.setGroup(true); + /** + * The drag surface to move bubbles to during a drag, or null if none should + * be used. Block dragging and bubble dragging use the same surface. + * @type {BlockDragSurfaceSvg} + * @private + */ + this.dragSurface_ = + svgMath.is3dSupported() && !!workspace.getBlockDragSurface() ? + workspace.getBlockDragSurface() : + null; } - this.workspace_.setResizesEnabled(false); - this.draggingBubble_.setAutoLayout(false); - if (this.dragSurface_) { - this.moveToDragSurface_(); + /** + * Sever all links from this object. + * @package + * @suppress {checkTypes} + */ + dispose() { + this.draggingBubble_ = null; + this.workspace_ = null; + this.dragSurface_ = null; } - this.draggingBubble_.setDragging && this.draggingBubble_.setDragging(true); -}; - -/** - * Execute a step of bubble dragging, based on the given event. Update the - * display accordingly. - * @param {!Event} e The most recent move event. - * @param {!Coordinate} currentDragDeltaXY How far the pointer has - * moved from the position at the start of the drag, in pixel units. - * @package - */ -BubbleDragger.prototype.dragBubble = function(e, currentDragDeltaXY) { - const delta = this.pixelsToWorkspaceUnits_(currentDragDeltaXY); - const newLoc = Coordinate.sum(this.startXY_, delta); - this.draggingBubble_.moveDuringDrag(this.dragSurface_, newLoc); - - const oldDragTarget = this.dragTarget_; - this.dragTarget_ = this.workspace_.getDragTarget(e); - - const oldWouldDeleteBubble = this.wouldDeleteBubble_; - this.wouldDeleteBubble_ = this.shouldDelete_(this.dragTarget_); - if (oldWouldDeleteBubble !== this.wouldDeleteBubble_) { - // Prevent unnecessary add/remove class calls. - this.updateCursorDuringBubbleDrag_(); - } - - // Call drag enter/exit/over after wouldDeleteBlock is called in shouldDelete_ - if (this.dragTarget_ !== oldDragTarget) { - oldDragTarget && oldDragTarget.onDragExit(this.draggingBubble_); - this.dragTarget_ && this.dragTarget_.onDragEnter(this.draggingBubble_); - } - this.dragTarget_ && this.dragTarget_.onDragOver(this.draggingBubble_); -}; - -/** - * Whether ending the drag would delete the bubble. - * @param {?IDragTarget} dragTarget The drag target that the bubblee is - * currently over. - * @return {boolean} Whether dropping the bubble immediately would delete the - * block. - * @private - */ -BubbleDragger.prototype.shouldDelete_ = function(dragTarget) { - if (dragTarget) { - const componentManager = this.workspace_.getComponentManager(); - const isDeleteArea = componentManager.hasCapability( - dragTarget.id, ComponentManager.Capability.DELETE_AREA); - if (isDeleteArea) { - return (/** @type {!IDeleteArea} */ (dragTarget)) - .wouldDelete(this.draggingBubble_, false); + /** + * Start dragging a bubble. This includes moving it to the drag surface. + * @package + */ + startBubbleDrag() { + if (!eventUtils.getGroup()) { + eventUtils.setGroup(true); } - } - return false; -}; -/** - * Update the cursor (and possibly the trash can lid) to reflect whether the - * dragging bubble would be deleted if released immediately. - * @private - */ -BubbleDragger.prototype.updateCursorDuringBubbleDrag_ = function() { - this.draggingBubble_.setDeleteStyle(this.wouldDeleteBubble_); -}; - -/** - * Finish a bubble drag and put the bubble back on the workspace. - * @param {!Event} e The mouseup/touchend event. - * @param {!Coordinate} currentDragDeltaXY How far the pointer has - * moved from the position at the start of the drag, in pixel units. - * @package - */ -BubbleDragger.prototype.endBubbleDrag = function(e, currentDragDeltaXY) { - // Make sure internal state is fresh. - this.dragBubble(e, currentDragDeltaXY); - - const preventMove = this.dragTarget_ && - this.dragTarget_.shouldPreventMove(this.draggingBubble_); - let newLoc; - if (preventMove) { - newLoc = this.startXY_; - } else { - const delta = this.pixelsToWorkspaceUnits_(currentDragDeltaXY); - newLoc = Coordinate.sum(this.startXY_, delta); - } - // Move the bubble to its final location. - this.draggingBubble_.moveTo(newLoc.x, newLoc.y); - - if (this.dragTarget_) { - this.dragTarget_.onDrop(this.draggingBubble_); - } - - if (this.wouldDeleteBubble_) { - // Fire a move event, so we know where to go back to for an undo. - this.fireMoveEvent_(); - this.draggingBubble_.dispose(false, true); - } else { - // Put everything back onto the bubble canvas. + this.workspace_.setResizesEnabled(false); + this.draggingBubble_.setAutoLayout(false); if (this.dragSurface_) { - this.dragSurface_.clearAndHide(this.workspace_.getBubbleCanvas()); + this.moveToDragSurface_(); } - if (this.draggingBubble_.setDragging) { - this.draggingBubble_.setDragging(false); + + this.draggingBubble_.setDragging && this.draggingBubble_.setDragging(true); + } + + /** + * Execute a step of bubble dragging, based on the given event. Update the + * display accordingly. + * @param {!Event} e The most recent move event. + * @param {!Coordinate} currentDragDeltaXY How far the pointer has + * moved from the position at the start of the drag, in pixel units. + * @package + */ + dragBubble(e, currentDragDeltaXY) { + const delta = this.pixelsToWorkspaceUnits_(currentDragDeltaXY); + const newLoc = Coordinate.sum(this.startXY_, delta); + this.draggingBubble_.moveDuringDrag(this.dragSurface_, newLoc); + + const oldDragTarget = this.dragTarget_; + this.dragTarget_ = this.workspace_.getDragTarget(e); + + const oldWouldDeleteBubble = this.wouldDeleteBubble_; + this.wouldDeleteBubble_ = this.shouldDelete_(this.dragTarget_); + if (oldWouldDeleteBubble !== this.wouldDeleteBubble_) { + // Prevent unnecessary add/remove class calls. + this.updateCursorDuringBubbleDrag_(); } - this.fireMoveEvent_(); + + // Call drag enter/exit/over after wouldDeleteBlock is called in + // shouldDelete_ + if (this.dragTarget_ !== oldDragTarget) { + oldDragTarget && oldDragTarget.onDragExit(this.draggingBubble_); + this.dragTarget_ && this.dragTarget_.onDragEnter(this.draggingBubble_); + } + this.dragTarget_ && this.dragTarget_.onDragOver(this.draggingBubble_); } - this.workspace_.setResizesEnabled(true); - eventUtils.setGroup(false); -}; - -/** - * Fire a move event at the end of a bubble drag. - * @private - */ -BubbleDragger.prototype.fireMoveEvent_ = function() { - if (this.draggingBubble_.isComment) { - // TODO (adodson): Resolve build errors when requiring WorkspaceCommentSvg. - const event = new (eventUtils.get(eventUtils.COMMENT_MOVE))( - /** @type {!WorkspaceCommentSvg} */ (this.draggingBubble_)); - event.setOldCoordinate(this.startXY_); - event.recordNew(); - eventUtils.fire(event); + /** + * Whether ending the drag would delete the bubble. + * @param {?IDragTarget} dragTarget The drag target that the bubblee is + * currently over. + * @return {boolean} Whether dropping the bubble immediately would delete the + * block. + * @private + */ + shouldDelete_(dragTarget) { + if (dragTarget) { + const componentManager = this.workspace_.getComponentManager(); + const isDeleteArea = componentManager.hasCapability( + dragTarget.id, ComponentManager.Capability.DELETE_AREA); + if (isDeleteArea) { + return (/** @type {!IDeleteArea} */ (dragTarget)) + .wouldDelete(this.draggingBubble_, false); + } + } + return false; } - // TODO (fenichel): move events for comments. - return; -}; -/** - * Convert a coordinate object from pixels to workspace units, including a - * correction for mutator workspaces. - * This function does not consider differing origins. It simply scales the - * input's x and y values. - * @param {!Coordinate} pixelCoord A coordinate with x and y - * values in CSS pixel units. - * @return {!Coordinate} The input coordinate divided by the - * workspace scale. - * @private - */ -BubbleDragger.prototype.pixelsToWorkspaceUnits_ = function(pixelCoord) { - const result = new Coordinate( - pixelCoord.x / this.workspace_.scale, - pixelCoord.y / this.workspace_.scale); - if (this.workspace_.isMutator) { - // If we're in a mutator, its scale is always 1, purely because of some - // oddities in our rendering optimizations. The actual scale is the same as - // the scale on the parent workspace. - // Fix that for dragging. - const mainScale = this.workspace_.options.parentWorkspace.scale; - result.scale(1 / mainScale); + /** + * Update the cursor (and possibly the trash can lid) to reflect whether the + * dragging bubble would be deleted if released immediately. + * @private + */ + updateCursorDuringBubbleDrag_() { + this.draggingBubble_.setDeleteStyle(this.wouldDeleteBubble_); } - return result; -}; -/** - * Move the bubble onto the drag surface at the beginning of a drag. Move the - * drag surface to preserve the apparent location of the bubble. - * @private - */ -BubbleDragger.prototype.moveToDragSurface_ = function() { - this.draggingBubble_.moveTo(0, 0); - this.dragSurface_.translateSurface(this.startXY_.x, this.startXY_.y); - // Execute the move on the top-level SVG component. - this.dragSurface_.setBlocksAndShow(this.draggingBubble_.getSvgRoot()); + /** + * Finish a bubble drag and put the bubble back on the workspace. + * @param {!Event} e The mouseup/touchend event. + * @param {!Coordinate} currentDragDeltaXY How far the pointer has + * moved from the position at the start of the drag, in pixel units. + * @package + */ + endBubbleDrag(e, currentDragDeltaXY) { + // Make sure internal state is fresh. + this.dragBubble(e, currentDragDeltaXY); + + const preventMove = this.dragTarget_ && + this.dragTarget_.shouldPreventMove(this.draggingBubble_); + let newLoc; + if (preventMove) { + newLoc = this.startXY_; + } else { + const delta = this.pixelsToWorkspaceUnits_(currentDragDeltaXY); + newLoc = Coordinate.sum(this.startXY_, delta); + } + // Move the bubble to its final location. + this.draggingBubble_.moveTo(newLoc.x, newLoc.y); + + if (this.dragTarget_) { + this.dragTarget_.onDrop(this.draggingBubble_); + } + + if (this.wouldDeleteBubble_) { + // Fire a move event, so we know where to go back to for an undo. + this.fireMoveEvent_(); + this.draggingBubble_.dispose(false, true); + } else { + // Put everything back onto the bubble canvas. + if (this.dragSurface_) { + this.dragSurface_.clearAndHide(this.workspace_.getBubbleCanvas()); + } + if (this.draggingBubble_.setDragging) { + this.draggingBubble_.setDragging(false); + } + this.fireMoveEvent_(); + } + this.workspace_.setResizesEnabled(true); + + eventUtils.setGroup(false); + } + + /** + * Fire a move event at the end of a bubble drag. + * @private + */ + fireMoveEvent_() { + if (this.draggingBubble_.isComment) { + // TODO (adodson): Resolve build errors when requiring + // WorkspaceCommentSvg. + const event = new (eventUtils.get(eventUtils.COMMENT_MOVE))( + /** @type {!WorkspaceCommentSvg} */ (this.draggingBubble_)); + event.setOldCoordinate(this.startXY_); + event.recordNew(); + eventUtils.fire(event); + } + // TODO (fenichel): move events for comments. + return; + } + + /** + * Convert a coordinate object from pixels to workspace units, including a + * correction for mutator workspaces. + * This function does not consider differing origins. It simply scales the + * input's x and y values. + * @param {!Coordinate} pixelCoord A coordinate with x and y + * values in CSS pixel units. + * @return {!Coordinate} The input coordinate divided by the + * workspace scale. + * @private + */ + pixelsToWorkspaceUnits_(pixelCoord) { + const result = new Coordinate( + pixelCoord.x / this.workspace_.scale, + pixelCoord.y / this.workspace_.scale); + if (this.workspace_.isMutator) { + // If we're in a mutator, its scale is always 1, purely because of some + // oddities in our rendering optimizations. The actual scale is the same + // as the scale on the parent workspace. Fix that for dragging. + const mainScale = this.workspace_.options.parentWorkspace.scale; + result.scale(1 / mainScale); + } + return result; + } + + /** + * Move the bubble onto the drag surface at the beginning of a drag. Move the + * drag surface to preserve the apparent location of the bubble. + * @private + */ + moveToDragSurface_() { + this.draggingBubble_.moveTo(0, 0); + this.dragSurface_.translateSurface(this.startXY_.x, this.startXY_.y); + // Execute the move on the top-level SVG component. + this.dragSurface_.setBlocksAndShow(this.draggingBubble_.getSvgRoot()); + } }; exports.BubbleDragger = BubbleDragger; diff --git a/core/utils/coordinate.js b/core/utils/coordinate.js index 1a8dece05..8f3cffe1f 100644 --- a/core/utils/coordinate.js +++ b/core/utils/coordinate.js @@ -21,116 +21,118 @@ goog.module('Blockly.utils.Coordinate'); /** * Class for representing coordinates and positions. - * @param {number} x Left. - * @param {number} y Top. - * @struct - * @constructor - * @alias Blockly.utils.Coordinate */ -const Coordinate = function(x, y) { +const Coordinate = class { /** - * X-value - * @type {number} + * @param {number} x Left. + * @param {number} y Top. + * @alias Blockly.utils.Coordinate */ - this.x = x; + constructor(x, y) { + /** + * X-value + * @type {number} + */ + this.x = x; + + /** + * Y-value + * @type {number} + */ + this.y = y; + } /** - * Y-value - * @type {number} + * Creates a new copy of this coordinate. + * @return {!Coordinate} A copy of this coordinate. */ - this.y = y; -}; - -/** - * Compares coordinates for equality. - * @param {?Coordinate} a A Coordinate. - * @param {?Coordinate} b A Coordinate. - * @return {boolean} True iff the coordinates are equal, or if both are null. - */ -Coordinate.equals = function(a, b) { - if (a === b) { - return true; + clone() { + return new Coordinate(this.x, this.y); } - if (!a || !b) { - return false; + + /** + * Scales this coordinate by the given scale factor. + * @param {number} s The scale factor to use for both x and y dimensions. + * @return {!Coordinate} This coordinate after scaling. + */ + scale(s) { + this.x *= s; + this.y *= s; + return this; } - return a.x === b.x && a.y === b.y; -}; -/** - * Returns the distance between two coordinates. - * @param {!Coordinate} a A Coordinate. - * @param {!Coordinate} b A Coordinate. - * @return {number} The distance between `a` and `b`. - */ -Coordinate.distance = function(a, b) { - const dx = a.x - b.x; - const dy = a.y - b.y; - return Math.sqrt(dx * dx + dy * dy); -}; + /** + * Translates this coordinate by the given offsets. + * respectively. + * @param {number} tx The value to translate x by. + * @param {number} ty The value to translate y by. + * @return {!Coordinate} This coordinate after translating. + */ + translate(tx, ty) { + this.x += tx; + this.y += ty; + return this; + } -/** - * Returns the magnitude of a coordinate. - * @param {!Coordinate} a A Coordinate. - * @return {number} The distance between the origin and `a`. - */ -Coordinate.magnitude = function(a) { - return Math.sqrt(a.x * a.x + a.y * a.y); -}; + /** + * Compares coordinates for equality. + * @param {?Coordinate} a A Coordinate. + * @param {?Coordinate} b A Coordinate. + * @return {boolean} True iff the coordinates are equal, or if both are null. + */ + static equals(a, b) { + if (a === b) { + return true; + } + if (!a || !b) { + return false; + } + return a.x === b.x && a.y === b.y; + } -/** - * Returns the difference between two coordinates as a new - * Coordinate. - * @param {!Coordinate|!SVGPoint} a An x/y coordinate. - * @param {!Coordinate|!SVGPoint} b An x/y coordinate. - * @return {!Coordinate} A Coordinate representing the difference - * between `a` and `b`. - */ -Coordinate.difference = function(a, b) { - return new Coordinate(a.x - b.x, a.y - b.y); -}; + /** + * Returns the distance between two coordinates. + * @param {!Coordinate} a A Coordinate. + * @param {!Coordinate} b A Coordinate. + * @return {number} The distance between `a` and `b`. + */ + static distance(a, b) { + const dx = a.x - b.x; + const dy = a.y - b.y; + return Math.sqrt(dx * dx + dy * dy); + } -/** - * Returns the sum of two coordinates as a new Coordinate. - * @param {!Coordinate|!SVGPoint} a An x/y coordinate. - * @param {!Coordinate|!SVGPoint} b An x/y coordinate. - * @return {!Coordinate} A Coordinate representing the sum of - * the two coordinates. - */ -Coordinate.sum = function(a, b) { - return new Coordinate(a.x + b.x, a.y + b.y); -}; + /** + * Returns the magnitude of a coordinate. + * @param {!Coordinate} a A Coordinate. + * @return {number} The distance between the origin and `a`. + */ + static magnitude(a) { + return Math.sqrt(a.x * a.x + a.y * a.y); + } -/** - * Creates a new copy of this coordinate. - * @return {!Coordinate} A copy of this coordinate. - */ -Coordinate.prototype.clone = function() { - return new Coordinate(this.x, this.y); -}; + /** + * Returns the difference between two coordinates as a new + * Coordinate. + * @param {!Coordinate|!SVGPoint} a An x/y coordinate. + * @param {!Coordinate|!SVGPoint} b An x/y coordinate. + * @return {!Coordinate} A Coordinate representing the difference + * between `a` and `b`. + */ + static difference(a, b) { + return new Coordinate(a.x - b.x, a.y - b.y); + } -/** - * Scales this coordinate by the given scale factor. - * @param {number} s The scale factor to use for both x and y dimensions. - * @return {!Coordinate} This coordinate after scaling. - */ -Coordinate.prototype.scale = function(s) { - this.x *= s; - this.y *= s; - return this; -}; - -/** - * Translates this coordinate by the given offsets. - * respectively. - * @param {number} tx The value to translate x by. - * @param {number} ty The value to translate y by. - * @return {!Coordinate} This coordinate after translating. - */ -Coordinate.prototype.translate = function(tx, ty) { - this.x += tx; - this.y += ty; - return this; + /** + * Returns the sum of two coordinates as a new Coordinate. + * @param {!Coordinate|!SVGPoint} a An x/y coordinate. + * @param {!Coordinate|!SVGPoint} b An x/y coordinate. + * @return {!Coordinate} A Coordinate representing the sum of + * the two coordinates. + */ + static sum(a, b) { + return new Coordinate(a.x + b.x, a.y + b.y); + } }; exports.Coordinate = Coordinate; diff --git a/core/utils/rect.js b/core/utils/rect.js index 8ecf7d358..1089ce102 100644 --- a/core/utils/rect.js +++ b/core/utils/rect.js @@ -22,50 +22,54 @@ goog.module('Blockly.utils.Rect'); /** * Class for representing rectangular regions. - * @param {number} top Top. - * @param {number} bottom Bottom. - * @param {number} left Left. - * @param {number} right Right. - * @struct - * @constructor - * @alias Blockly.utils.Rect */ -const Rect = function(top, bottom, left, right) { - /** @type {number} */ - this.top = top; +const Rect = class { + /** + * @param {number} top Top. + * @param {number} bottom Bottom. + * @param {number} left Left. + * @param {number} right Right. + * @struct + * @alias Blockly.utils.Rect + */ + constructor(top, bottom, left, right) { + /** @type {number} */ + this.top = top; - /** @type {number} */ - this.bottom = bottom; + /** @type {number} */ + this.bottom = bottom; - /** @type {number} */ - this.left = left; + /** @type {number} */ + this.left = left; - /** @type {number} */ - this.right = right; -}; + /** @type {number} */ + this.right = right; + } -/** - * Tests whether this rectangle contains a x/y coordinate. - * - * @param {number} x The x coordinate to test for containment. - * @param {number} y The y coordinate to test for containment. - * @return {boolean} Whether this rectangle contains given coordinate. - */ -Rect.prototype.contains = function(x, y) { - return x >= this.left && x <= this.right && y >= this.top && y <= this.bottom; -}; + /** + * Tests whether this rectangle contains a x/y coordinate. + * + * @param {number} x The x coordinate to test for containment. + * @param {number} y The y coordinate to test for containment. + * @return {boolean} Whether this rectangle contains given coordinate. + */ + contains(x, y) { + return x >= this.left && x <= this.right && y >= this.top && + y <= this.bottom; + } -/** - * Tests whether this rectangle intersects the provided rectangle. - * Assumes that the coordinate system increases going down and left. - * @param {!Rect} other The other rectangle to check for - * intersection with. - * @return {boolean} Whether this rectangle intersects the provided rectangle. - */ -Rect.prototype.intersects = function(other) { - return !( - this.left > other.right || this.right < other.left || - this.top > other.bottom || this.bottom < other.top); + /** + * Tests whether this rectangle intersects the provided rectangle. + * Assumes that the coordinate system increases going down and left. + * @param {!Rect} other The other rectangle to check for + * intersection with. + * @return {boolean} Whether this rectangle intersects the provided rectangle. + */ + intersects(other) { + return !( + this.left > other.right || this.right < other.left || + this.top > other.bottom || this.bottom < other.top); + } }; exports.Rect = Rect; diff --git a/core/utils/size.js b/core/utils/size.js index 13c5e40f4..b59a66283 100644 --- a/core/utils/size.js +++ b/core/utils/size.js @@ -22,41 +22,44 @@ goog.module('Blockly.utils.Size'); /** * Class for representing sizes consisting of a width and height. - * @param {number} width Width. - * @param {number} height Height. - * @struct - * @constructor - * @alias Blockly.utils.Size */ -const Size = function(width, height) { +const Size = class { /** - * Width - * @type {number} + * @param {number} width Width. + * @param {number} height Height. + * @struct + * @alias Blockly.utils.Size */ - this.width = width; + constructor(width, height) { + /** + * Width + * @type {number} + */ + this.width = width; + + /** + * Height + * @type {number} + */ + this.height = height; + } /** - * Height - * @type {number} + * Compares sizes for equality. + * @param {?Size} a A Size. + * @param {?Size} b A Size. + * @return {boolean} True iff the sizes have equal widths and equal + * heights, or if both are null. */ - this.height = height; -}; - -/** - * Compares sizes for equality. - * @param {?Size} a A Size. - * @param {?Size} b A Size. - * @return {boolean} True iff the sizes have equal widths and equal - * heights, or if both are null. - */ -Size.equals = function(a, b) { - if (a === b) { - return true; + static equals(a, b) { + if (a === b) { + return true; + } + if (!a || !b) { + return false; + } + return a.width === b.width && a.height === b.height; } - if (!a || !b) { - return false; - } - return a.width === b.width && a.height === b.height; }; exports.Size = Size; From 6ee63894b3bbf4d4c2f2049995cf3a26c7a2c4b3 Mon Sep 17 00:00:00 2001 From: Rachel Fenichel Date: Fri, 7 Jan 2022 15:58:23 -0800 Subject: [PATCH 028/128] chore: declare properties in the constructor instead of at first use (#5862) --- core/block.js | 13 ++++++++++++ core/block_svg.js | 6 ++++++ core/comment.js | 22 ++++++++++++++++++++ core/icon.js | 53 ++++++++++++++++++++++++----------------------- core/mutator.js | 28 +++++++++++++++++++++++-- core/warning.js | 7 +++++++ 6 files changed, 101 insertions(+), 28 deletions(-) diff --git a/core/block.js b/core/block.js index 0b0226035..082ca4296 100644 --- a/core/block.js +++ b/core/block.js @@ -290,6 +290,19 @@ const Block = function(workspace, prototypeName, opt_id) { /** @type {?boolean} */ this.rendered = null; + /** + * String for block help, or function that returns a URL. Null for no help. + * @type {string|Function} + */ + this.helpUrl = null; + + /** + * A bound callback function to use when the parent workspace changes. + * @type {?function(Abstract)} + * @private + */ + this.onchangeWrapper_ = null; + /** * A count of statement inputs on the block. * @type {number} diff --git a/core/block_svg.js b/core/block_svg.js index 54dbdbefd..5fd46d8a7 100644 --- a/core/block_svg.js +++ b/core/block_svg.js @@ -209,6 +209,12 @@ const BlockSvg = function(workspace, prototypeName, opt_id) { */ this.renderIsInProgress_ = false; + /** + * Whether mousedown events have been bound yet. + * @type {boolean} + * @private + */ + this.eventsInit_ = false; /** @type {!WorkspaceSvg} */ this.workspace = workspace; diff --git a/core/comment.js b/core/comment.js index 8dc56bdb8..30f9aac36 100644 --- a/core/comment.js +++ b/core/comment.js @@ -98,6 +98,28 @@ const Comment = function(block) { */ this.onInputWrapper_ = null; + /** + * The SVG element that contains the text edit area, or null if not created. + * @type {?SVGForeignObjectElement} + * @private + */ + this.foreignObject_ = null; + + /** + * The editable text area, or null if not created. + * @type {?Element} + * @private + */ + this.textarea_ = null; + + /** + * The top-level node of the comment text, or null if not created. + * @type {?SVGTextElement} + * @private + */ + this.paragraphElement_ = null; + + this.createIcon(); }; object.inherits(Comment, Icon); diff --git a/core/icon.js b/core/icon.js index aa7195749..3f81e9795 100644 --- a/core/icon.js +++ b/core/icon.js @@ -47,33 +47,34 @@ const Icon = function(block) { * @type {?SVGGElement} */ this.iconGroup_ = null; + + /** + * Whether this icon gets hidden when the block is collapsed. + * @type {boolean} + */ + this.collapseHidden = true; + + /** + * Height and width of icons. + * @const + */ + this.SIZE = 17; + + /** + * Bubble UI (if visible). + * @type {?Bubble} + * @protected + */ + this.bubble_ = null; + + /** + * Absolute coordinate of icon's center. + * @type {?Coordinate} + * @protected + */ + this.iconXY_ = null; }; -/** - * Does this icon get hidden when the block is collapsed. - */ -Icon.prototype.collapseHidden = true; - -/** - * Height and width of icons. - * @const - */ -Icon.prototype.SIZE = 17; - -/** - * Bubble UI (if visible). - * @type {?Bubble} - * @protected - */ -Icon.prototype.bubble_ = null; - -/** - * Absolute coordinate of icon's center. - * @type {?Coordinate} - * @protected - */ -Icon.prototype.iconXY_ = null; - /** * Create the icon on the block. */ @@ -197,7 +198,7 @@ Icon.prototype.getIconLocation = function() { */ // TODO (#2562): Remove getCorrectedSize. Icon.prototype.getCorrectedSize = function() { - return new Size(Icon.prototype.SIZE, Icon.prototype.SIZE - 2); + return new Size(this.SIZE, this.SIZE - 2); }; /** diff --git a/core/mutator.js b/core/mutator.js index bbadd41ea..d1c2ba07d 100644 --- a/core/mutator.js +++ b/core/mutator.js @@ -78,6 +78,30 @@ const Mutator = function(quarkNames) { * @private */ this.workspaceHeight_ = 0; + + /** + * The SVG element that is the parent of the mutator workspace, or null if + * not created. + * @type {?SVGSVGElement} + * @private + */ + this.svgDialog_ = null; + + /** + * The root block of the mutator workspace, created by decomposing the source + * block. + * @type {?BlockSvg} + * @private + */ + this.rootBlock_ = null; + + /** + * Function registered on the main workspace to update the mutator contents + * when the main workspace changes. + * @type {?Function} + * @private + */ + this.sourceListener_ = null; }; object.inherits(Mutator, Icon); @@ -341,12 +365,12 @@ Mutator.prototype.setVisible = function(visible) { this.rootBlock_.moveBy(x, margin); // Save the initial connections, then listen for further changes. if (this.block_.saveConnections) { - const thisMutator = this; + const thisRootBlock = this.rootBlock_; const mutatorBlock = /** @type {{saveConnections: function(!Block)}} */ (this.block_); mutatorBlock.saveConnections(this.rootBlock_); this.sourceListener_ = function() { - mutatorBlock.saveConnections(thisMutator.rootBlock_); + mutatorBlock.saveConnections(thisRootBlock); }; this.block_.workspace.addChangeListener(this.sourceListener_); } diff --git a/core/warning.js b/core/warning.js index e34e3258f..1b273bd92 100644 --- a/core/warning.js +++ b/core/warning.js @@ -44,6 +44,13 @@ const Warning = function(block) { // The text_ object can contain multiple warnings. this.text_ = Object.create(null); + /** + * The top-level node of the warning text, or null if not created. + * @type {?SVGTextElement} + * @private + */ + this.paragraphElement_ = null; + /** * Does this icon get hidden when the block is collapsed? * @type {boolean} From 1c74679d83dbe942388e499f2781e92c729fe295 Mon Sep 17 00:00:00 2001 From: Rachel Fenichel Date: Mon, 10 Jan 2022 09:18:11 -0800 Subject: [PATCH 029/128] refactor: convert some files to es6 classes (#5863) * refactor: convert menu.js to ES6 class * refactor: convert menuitem.js to ES6 class * refactor: convert scrollbar_pair.js to ES6 class * chore: define properties in the constructor in names.js * refactor: convert names.js to ES6 class * chore: run clang-format --- core/menu.js | 800 +++++++++++++++++++++-------------------- core/menuitem.js | 459 +++++++++++------------ core/names.js | 415 +++++++++++---------- core/scrollbar_pair.js | 541 ++++++++++++++-------------- 4 files changed, 1132 insertions(+), 1083 deletions(-) diff --git a/core/menu.js b/core/menu.js index a39b9c52c..b4e3e1377 100644 --- a/core/menu.js +++ b/core/menu.js @@ -29,449 +29,453 @@ const {Size} = goog.requireType('Blockly.utils.Size'); /** * A basic menu class. - * @constructor - * @alias Blockly.Menu */ -const Menu = function() { +const Menu = class { /** - * Array of menu items. - * (Nulls are never in the array, but typing the array as nullable prevents - * the compiler from objecting to .indexOf(null)) - * @type {!Array} - * @private + * @alias Blockly.Menu */ - this.menuItems_ = []; + constructor() { + /** + * Array of menu items. + * (Nulls are never in the array, but typing the array as nullable prevents + * the compiler from objecting to .indexOf(null)) + * @type {!Array} + * @private + */ + this.menuItems_ = []; + + /** + * Coordinates of the mousedown event that caused this menu to open. Used to + * prevent the consequent mouseup event due to a simple click from + * activating a menu item immediately. + * @type {?Coordinate} + * @package + */ + this.openingCoords = null; + + /** + * This is the element that we will listen to the real focus events on. + * A value of null means no menu item is highlighted. + * @type {?MenuItem} + * @private + */ + this.highlightedItem_ = null; + + /** + * Mouse over event data. + * @type {?browserEvents.Data} + * @private + */ + this.mouseOverHandler_ = null; + + /** + * Click event data. + * @type {?browserEvents.Data} + * @private + */ + this.clickHandler_ = null; + + /** + * Mouse enter event data. + * @type {?browserEvents.Data} + * @private + */ + this.mouseEnterHandler_ = null; + + /** + * Mouse leave event data. + * @type {?browserEvents.Data} + * @private + */ + this.mouseLeaveHandler_ = null; + + /** + * Key down event data. + * @type {?browserEvents.Data} + * @private + */ + this.onKeyDownHandler_ = null; + + /** + * The menu's root DOM element. + * @type {?Element} + * @private + */ + this.element_ = null; + + /** + * ARIA name for this menu. + * @type {?aria.Role} + * @private + */ + this.roleName_ = null; + } /** - * Coordinates of the mousedown event that caused this menu to open. Used to - * prevent the consequent mouseup event due to a simple click from activating - * a menu item immediately. - * @type {?Coordinate} + * Add a new menu item to the bottom of this menu. + * @param {!MenuItem} menuItem Menu item to append. + */ + addChild(menuItem) { + this.menuItems_.push(menuItem); + } + + /** + * Creates the menu DOM. + * @param {!Element} container Element upon which to append this menu. + */ + render(container) { + const element = + /** @type {!HTMLDivElement} */ (document.createElement('div')); + // goog-menu is deprecated, use blocklyMenu. May 2020. + element.className = 'blocklyMenu goog-menu blocklyNonSelectable'; + element.tabIndex = 0; + if (this.roleName_) { + aria.setRole(element, this.roleName_); + } + this.element_ = element; + + // Add menu items. + for (let i = 0, menuItem; (menuItem = this.menuItems_[i]); i++) { + element.appendChild(menuItem.createDom()); + } + + // Add event handlers. + this.mouseOverHandler_ = browserEvents.conditionalBind( + element, 'mouseover', this, this.handleMouseOver_, true); + this.clickHandler_ = browserEvents.conditionalBind( + element, 'click', this, this.handleClick_, true); + this.mouseEnterHandler_ = browserEvents.conditionalBind( + element, 'mouseenter', this, this.handleMouseEnter_, true); + this.mouseLeaveHandler_ = browserEvents.conditionalBind( + element, 'mouseleave', this, this.handleMouseLeave_, true); + this.onKeyDownHandler_ = browserEvents.conditionalBind( + element, 'keydown', this, this.handleKeyEvent_); + + container.appendChild(element); + } + + /** + * Gets the menu's element. + * @return {?Element} The DOM element. * @package */ - this.openingCoords = null; + getElement() { + return this.element_; + } /** - * This is the element that we will listen to the real focus events on. - * A value of null means no menu item is highlighted. - * @type {?MenuItem} - * @private + * Focus the menu element. + * @package */ - this.highlightedItem_ = null; + focus() { + const el = this.getElement(); + if (el) { + el.focus({preventScroll: true}); + dom.addClass(el, 'blocklyFocused'); + } + } /** - * Mouse over event data. - * @type {?browserEvents.Data} + * Blur the menu element. * @private */ - this.mouseOverHandler_ = null; + blur_() { + const el = this.getElement(); + if (el) { + el.blur(); + dom.removeClass(el, 'blocklyFocused'); + } + } /** - * Click event data. - * @type {?browserEvents.Data} - * @private + * Set the menu accessibility role. + * @param {!aria.Role} roleName role name. + * @package */ - this.clickHandler_ = null; + setRole(roleName) { + this.roleName_ = roleName; + } /** - * Mouse enter event data. - * @type {?browserEvents.Data} - * @private + * Dispose of this menu. */ - this.mouseEnterHandler_ = null; + dispose() { + // Remove event handlers. + if (this.mouseOverHandler_) { + browserEvents.unbind(this.mouseOverHandler_); + this.mouseOverHandler_ = null; + } + if (this.clickHandler_) { + browserEvents.unbind(this.clickHandler_); + this.clickHandler_ = null; + } + if (this.mouseEnterHandler_) { + browserEvents.unbind(this.mouseEnterHandler_); + this.mouseEnterHandler_ = null; + } + if (this.mouseLeaveHandler_) { + browserEvents.unbind(this.mouseLeaveHandler_); + this.mouseLeaveHandler_ = null; + } + if (this.onKeyDownHandler_) { + browserEvents.unbind(this.onKeyDownHandler_); + this.onKeyDownHandler_ = null; + } + + // Remove menu items. + for (let i = 0, menuItem; (menuItem = this.menuItems_[i]); i++) { + menuItem.dispose(); + } + this.element_ = null; + } + + // Child component management. /** - * Mouse leave event data. - * @type {?browserEvents.Data} + * Returns the child menu item that owns the given DOM element, + * or null if no such menu item is found. + * @param {Element} elem DOM element whose owner is to be returned. + * @return {?MenuItem} Menu item for which the DOM element belongs to. * @private */ - this.mouseLeaveHandler_ = null; - - /** - * Key down event data. - * @type {?browserEvents.Data} - * @private - */ - this.onKeyDownHandler_ = null; - - /** - * The menu's root DOM element. - * @type {?Element} - * @private - */ - this.element_ = null; - - /** - * ARIA name for this menu. - * @type {?aria.Role} - * @private - */ - this.roleName_ = null; -}; - - -/** - * Add a new menu item to the bottom of this menu. - * @param {!MenuItem} menuItem Menu item to append. - */ -Menu.prototype.addChild = function(menuItem) { - this.menuItems_.push(menuItem); -}; - -/** - * Creates the menu DOM. - * @param {!Element} container Element upon which to append this menu. - */ -Menu.prototype.render = function(container) { - const element = - /** @type {!HTMLDivElement} */ (document.createElement('div')); - // goog-menu is deprecated, use blocklyMenu. May 2020. - element.className = 'blocklyMenu goog-menu blocklyNonSelectable'; - element.tabIndex = 0; - if (this.roleName_) { - aria.setRole(element, this.roleName_); - } - this.element_ = element; - - // Add menu items. - for (let i = 0, menuItem; (menuItem = this.menuItems_[i]); i++) { - element.appendChild(menuItem.createDom()); - } - - // Add event handlers. - this.mouseOverHandler_ = browserEvents.conditionalBind( - element, 'mouseover', this, this.handleMouseOver_, true); - this.clickHandler_ = browserEvents.conditionalBind( - element, 'click', this, this.handleClick_, true); - this.mouseEnterHandler_ = browserEvents.conditionalBind( - element, 'mouseenter', this, this.handleMouseEnter_, true); - this.mouseLeaveHandler_ = browserEvents.conditionalBind( - element, 'mouseleave', this, this.handleMouseLeave_, true); - this.onKeyDownHandler_ = browserEvents.conditionalBind( - element, 'keydown', this, this.handleKeyEvent_); - - container.appendChild(element); -}; - -/** - * Gets the menu's element. - * @return {?Element} The DOM element. - * @package - */ -Menu.prototype.getElement = function() { - return this.element_; -}; - -/** - * Focus the menu element. - * @package - */ -Menu.prototype.focus = function() { - const el = this.getElement(); - if (el) { - el.focus({preventScroll: true}); - dom.addClass(el, 'blocklyFocused'); - } -}; - -/** - * Blur the menu element. - * @private - */ -Menu.prototype.blur_ = function() { - const el = this.getElement(); - if (el) { - el.blur(); - dom.removeClass(el, 'blocklyFocused'); - } -}; - -/** - * Set the menu accessibility role. - * @param {!aria.Role} roleName role name. - * @package - */ -Menu.prototype.setRole = function(roleName) { - this.roleName_ = roleName; -}; - -/** - * Dispose of this menu. - */ -Menu.prototype.dispose = function() { - // Remove event handlers. - if (this.mouseOverHandler_) { - browserEvents.unbind(this.mouseOverHandler_); - this.mouseOverHandler_ = null; - } - if (this.clickHandler_) { - browserEvents.unbind(this.clickHandler_); - this.clickHandler_ = null; - } - if (this.mouseEnterHandler_) { - browserEvents.unbind(this.mouseEnterHandler_); - this.mouseEnterHandler_ = null; - } - if (this.mouseLeaveHandler_) { - browserEvents.unbind(this.mouseLeaveHandler_); - this.mouseLeaveHandler_ = null; - } - if (this.onKeyDownHandler_) { - browserEvents.unbind(this.onKeyDownHandler_); - this.onKeyDownHandler_ = null; - } - - // Remove menu items. - for (let i = 0, menuItem; (menuItem = this.menuItems_[i]); i++) { - menuItem.dispose(); - } - this.element_ = null; -}; - -// Child component management. - -/** - * Returns the child menu item that owns the given DOM element, - * or null if no such menu item is found. - * @param {Element} elem DOM element whose owner is to be returned. - * @return {?MenuItem} Menu item for which the DOM element belongs to. - * @private - */ -Menu.prototype.getMenuItem_ = function(elem) { - const menuElem = this.getElement(); - // Node might be the menu border (resulting in no associated menu item), or - // a menu item's div, or some element within the menu item. - // Walk up parents until one meets either the menu's root element, or - // a menu item's div. - while (elem && elem !== menuElem) { - if (dom.hasClass(elem, 'blocklyMenuItem')) { - // Having found a menu item's div, locate that menu item in this menu. - for (let i = 0, menuItem; (menuItem = this.menuItems_[i]); i++) { - if (menuItem.getElement() === elem) { - return menuItem; + getMenuItem_(elem) { + const menuElem = this.getElement(); + // Node might be the menu border (resulting in no associated menu item), or + // a menu item's div, or some element within the menu item. + // Walk up parents until one meets either the menu's root element, or + // a menu item's div. + while (elem && elem !== menuElem) { + if (dom.hasClass(elem, 'blocklyMenuItem')) { + // Having found a menu item's div, locate that menu item in this menu. + for (let i = 0, menuItem; (menuItem = this.menuItems_[i]); i++) { + if (menuItem.getElement() === elem) { + return menuItem; + } } } + elem = elem.parentElement; } - elem = elem.parentElement; + return null; } - return null; -}; -// Highlight management. + // Highlight management. -/** - * Highlights the given menu item, or clears highlighting if null. - * @param {?MenuItem} item Item to highlight, or null. - * @package - */ -Menu.prototype.setHighlighted = function(item) { - const currentHighlighted = this.highlightedItem_; - if (currentHighlighted) { - currentHighlighted.setHighlighted(false); - this.highlightedItem_ = null; - } - if (item) { - item.setHighlighted(true); - this.highlightedItem_ = item; - // Bring the highlighted item into view. This has no effect if the menu is - // not scrollable. - const el = /** @type {!Element} */ (this.getElement()); - style.scrollIntoContainerView( - /** @type {!Element} */ (item.getElement()), el); - - aria.setState(el, aria.State.ACTIVEDESCENDANT, item.getId()); - } -}; - -/** - * Highlights the next highlightable item (or the first if nothing is currently - * highlighted). - * @package - */ -Menu.prototype.highlightNext = function() { - const index = this.menuItems_.indexOf(this.highlightedItem_); - this.highlightHelper_(index, 1); -}; - -/** - * Highlights the previous highlightable item (or the last if nothing is - * currently highlighted). - * @package - */ -Menu.prototype.highlightPrevious = function() { - const index = this.menuItems_.indexOf(this.highlightedItem_); - this.highlightHelper_(index < 0 ? this.menuItems_.length : index, -1); -}; - -/** - * Highlights the first highlightable item. - * @private - */ -Menu.prototype.highlightFirst_ = function() { - this.highlightHelper_(-1, 1); -}; - -/** - * Highlights the last highlightable item. - * @private - */ -Menu.prototype.highlightLast_ = function() { - this.highlightHelper_(this.menuItems_.length, -1); -}; - -/** - * Helper function that manages the details of moving the highlight among - * child menuitems in response to keyboard events. - * @param {number} startIndex Start index. - * @param {number} delta Step direction: 1 to go down, -1 to go up. - * @private - */ -Menu.prototype.highlightHelper_ = function(startIndex, delta) { - let index = startIndex + delta; - let menuItem; - while ((menuItem = this.menuItems_[index])) { - if (menuItem.isEnabled()) { - this.setHighlighted(menuItem); - break; + /** + * Highlights the given menu item, or clears highlighting if null. + * @param {?MenuItem} item Item to highlight, or null. + * @package + */ + setHighlighted(item) { + const currentHighlighted = this.highlightedItem_; + if (currentHighlighted) { + currentHighlighted.setHighlighted(false); + this.highlightedItem_ = null; + } + if (item) { + item.setHighlighted(true); + this.highlightedItem_ = item; + // Bring the highlighted item into view. This has no effect if the menu is + // not scrollable. + const el = /** @type {!Element} */ (this.getElement()); + style.scrollIntoContainerView( + /** @type {!Element} */ (item.getElement()), el); + + aria.setState(el, aria.State.ACTIVEDESCENDANT, item.getId()); } - index += delta; } -}; -// Mouse events. + /** + * Highlights the next highlightable item (or the first if nothing is + * currently highlighted). + * @package + */ + highlightNext() { + const index = this.menuItems_.indexOf(this.highlightedItem_); + this.highlightHelper_(index, 1); + } -/** - * Handles mouseover events. Highlight menuitems as the user hovers over them. - * @param {!Event} e Mouse event to handle. - * @private - */ -Menu.prototype.handleMouseOver_ = function(e) { - const menuItem = this.getMenuItem_(/** @type {Element} */ (e.target)); + /** + * Highlights the previous highlightable item (or the last if nothing is + * currently highlighted). + * @package + */ + highlightPrevious() { + const index = this.menuItems_.indexOf(this.highlightedItem_); + this.highlightHelper_(index < 0 ? this.menuItems_.length : index, -1); + } - if (menuItem) { - if (menuItem.isEnabled()) { - if (this.highlightedItem_ !== menuItem) { + /** + * Highlights the first highlightable item. + * @private + */ + highlightFirst_() { + this.highlightHelper_(-1, 1); + } + + /** + * Highlights the last highlightable item. + * @private + */ + highlightLast_() { + this.highlightHelper_(this.menuItems_.length, -1); + } + + /** + * Helper function that manages the details of moving the highlight among + * child menuitems in response to keyboard events. + * @param {number} startIndex Start index. + * @param {number} delta Step direction: 1 to go down, -1 to go up. + * @private + */ + highlightHelper_(startIndex, delta) { + let index = startIndex + delta; + let menuItem; + while ((menuItem = this.menuItems_[index])) { + if (menuItem.isEnabled()) { this.setHighlighted(menuItem); + break; } - } else { + index += delta; + } + } + + // Mouse events. + + /** + * Handles mouseover events. Highlight menuitems as the user hovers over them. + * @param {!Event} e Mouse event to handle. + * @private + */ + handleMouseOver_(e) { + const menuItem = this.getMenuItem_(/** @type {Element} */ (e.target)); + + if (menuItem) { + if (menuItem.isEnabled()) { + if (this.highlightedItem_ !== menuItem) { + this.setHighlighted(menuItem); + } + } else { + this.setHighlighted(null); + } + } + } + + /** + * Handles click events. Pass the event onto the child menuitem to handle. + * @param {!Event} e Click event to handle. + * @private + */ + handleClick_(e) { + const oldCoords = this.openingCoords; + // Clear out the saved opening coords immediately so they're not used twice. + this.openingCoords = null; + if (oldCoords && typeof e.clientX === 'number') { + const newCoords = new Coordinate(e.clientX, e.clientY); + if (Coordinate.distance(oldCoords, newCoords) < 1) { + // This menu was opened by a mousedown and we're handling the consequent + // click event. The coords haven't changed, meaning this was the same + // opening event. Don't do the usual behavior because the menu just + // popped up under the mouse and the user didn't mean to activate this + // item. + return; + } + } + + const menuItem = this.getMenuItem_(/** @type {Element} */ (e.target)); + if (menuItem) { + menuItem.performAction(); + } + } + + /** + * Handles mouse enter events. Focus the element. + * @param {!Event} _e Mouse event to handle. + * @private + */ + handleMouseEnter_(_e) { + this.focus(); + } + + /** + * Handles mouse leave events. Blur and clear highlight. + * @param {!Event} _e Mouse event to handle. + * @private + */ + handleMouseLeave_(_e) { + if (this.getElement()) { + this.blur_(); this.setHighlighted(null); } } -}; -/** - * Handles click events. Pass the event onto the child menuitem to handle. - * @param {!Event} e Click event to handle. - * @private - */ -Menu.prototype.handleClick_ = function(e) { - const oldCoords = this.openingCoords; - // Clear out the saved opening coords immediately so they're not used twice. - this.openingCoords = null; - if (oldCoords && typeof e.clientX === 'number') { - const newCoords = new Coordinate(e.clientX, e.clientY); - if (Coordinate.distance(oldCoords, newCoords) < 1) { - // This menu was opened by a mousedown and we're handling the consequent - // click event. The coords haven't changed, meaning this was the same - // opening event. Don't do the usual behavior because the menu just popped - // up under the mouse and the user didn't mean to activate this item. + // Keyboard events. + + /** + * Attempts to handle a keyboard event, if the menu item is enabled, by + * calling + * {@link handleKeyEventInternal_}. + * @param {!Event} e Key event to handle. + * @private + */ + handleKeyEvent_(e) { + if (!this.menuItems_.length) { + // Empty menu. return; } - } - - const menuItem = this.getMenuItem_(/** @type {Element} */ (e.target)); - if (menuItem) { - menuItem.performAction(); - } -}; - -/** - * Handles mouse enter events. Focus the element. - * @param {!Event} _e Mouse event to handle. - * @private - */ -Menu.prototype.handleMouseEnter_ = function(_e) { - this.focus(); -}; - -/** - * Handles mouse leave events. Blur and clear highlight. - * @param {!Event} _e Mouse event to handle. - * @private - */ -Menu.prototype.handleMouseLeave_ = function(_e) { - if (this.getElement()) { - this.blur_(); - this.setHighlighted(null); - } -}; - -// Keyboard events. - -/** - * Attempts to handle a keyboard event, if the menu item is enabled, by calling - * {@link handleKeyEventInternal_}. - * @param {!Event} e Key event to handle. - * @private - */ -Menu.prototype.handleKeyEvent_ = function(e) { - if (!this.menuItems_.length) { - // Empty menu. - return; - } - if (e.shiftKey || e.ctrlKey || e.metaKey || e.altKey) { - // Do not handle the key event if any modifier key is pressed. - return; - } - - const highlighted = this.highlightedItem_; - switch (e.keyCode) { - case KeyCodes.ENTER: - case KeyCodes.SPACE: - if (highlighted) { - highlighted.performAction(); - } - break; - - case KeyCodes.UP: - this.highlightPrevious(); - break; - - case KeyCodes.DOWN: - this.highlightNext(); - break; - - case KeyCodes.PAGE_UP: - case KeyCodes.HOME: - this.highlightFirst_(); - break; - - case KeyCodes.PAGE_DOWN: - case KeyCodes.END: - this.highlightLast_(); - break; - - default: - // Not a key the menu is interested in. + if (e.shiftKey || e.ctrlKey || e.metaKey || e.altKey) { + // Do not handle the key event if any modifier key is pressed. return; - } - // The menu used this key, don't let it have secondary effects. - e.preventDefault(); - e.stopPropagation(); -}; + } -/** - * Get the size of a rendered menu. - * @return {!Size} Object with width and height properties. - * @package - */ -Menu.prototype.getSize = function() { - const menuDom = this.getElement(); - const menuSize = style.getSize(/** @type {!Element} */ - (menuDom)); - // Recalculate height for the total content, not only box height. - menuSize.height = menuDom.scrollHeight; - return menuSize; + const highlighted = this.highlightedItem_; + switch (e.keyCode) { + case KeyCodes.ENTER: + case KeyCodes.SPACE: + if (highlighted) { + highlighted.performAction(); + } + break; + + case KeyCodes.UP: + this.highlightPrevious(); + break; + + case KeyCodes.DOWN: + this.highlightNext(); + break; + + case KeyCodes.PAGE_UP: + case KeyCodes.HOME: + this.highlightFirst_(); + break; + + case KeyCodes.PAGE_DOWN: + case KeyCodes.END: + this.highlightLast_(); + break; + + default: + // Not a key the menu is interested in. + return; + } + // The menu used this key, don't let it have secondary effects. + e.preventDefault(); + e.stopPropagation(); + } + + /** + * Get the size of a rendered menu. + * @return {!Size} Object with width and height properties. + * @package + */ + getSize() { + const menuDom = this.getElement(); + const menuSize = style.getSize(/** @type {!Element} */ + (menuDom)); + // Recalculate height for the total content, not only box height. + menuSize.height = menuDom.scrollHeight; + return menuSize; + } }; exports.Menu = Menu; diff --git a/core/menuitem.js b/core/menuitem.js index f82f49922..8d86ab1ab 100644 --- a/core/menuitem.js +++ b/core/menuitem.js @@ -22,265 +22,268 @@ const idGenerator = goog.require('Blockly.utils.idGenerator'); /** * Class representing an item in a menu. - * - * @param {string|!HTMLElement} content Text caption to display as the content - * of the item, or a HTML element to display. - * @param {string=} opt_value Data/model associated with the menu item. - * @constructor - * @alias Blockly.MenuItem */ -const MenuItem = function(content, opt_value) { +const MenuItem = class { /** - * Human-readable text of this menu item, or the HTML element to display. - * @type {string|!HTMLElement} - * @private + * @param {string|!HTMLElement} content Text caption to display as the content + * of the item, or a HTML element to display. + * @param {string=} opt_value Data/model associated with the menu item. + * @alias Blockly.MenuItem */ - this.content_ = content; + constructor(content, opt_value) { + /** + * Human-readable text of this menu item, or the HTML element to display. + * @type {string|!HTMLElement} + * @private + */ + this.content_ = content; - /** - * Machine-readable value of this menu item. - * @type {string|undefined} - * @private - */ - this.value_ = opt_value; + /** + * Machine-readable value of this menu item. + * @type {string|undefined} + * @private + */ + this.value_ = opt_value; - /** - * Is the menu item clickable, as opposed to greyed-out. - * @type {boolean} - * @private - */ - this.enabled_ = true; + /** + * Is the menu item clickable, as opposed to greyed-out. + * @type {boolean} + * @private + */ + this.enabled_ = true; - /** - * The DOM element for the menu item. - * @type {?Element} - * @private - */ - this.element_ = null; + /** + * The DOM element for the menu item. + * @type {?Element} + * @private + */ + this.element_ = null; - /** - * Whether the menu item is rendered right-to-left. - * @type {boolean} - * @private - */ - this.rightToLeft_ = false; + /** + * Whether the menu item is rendered right-to-left. + * @type {boolean} + * @private + */ + this.rightToLeft_ = false; - /** - * ARIA name for this menu. - * @type {?aria.Role} - * @private - */ - this.roleName_ = null; + /** + * ARIA name for this menu. + * @type {?aria.Role} + * @private + */ + this.roleName_ = null; - /** - * Is this menu item checkable. - * @type {boolean} - * @private - */ - this.checkable_ = false; + /** + * Is this menu item checkable. + * @type {boolean} + * @private + */ + this.checkable_ = false; - /** - * Is this menu item currently checked. - * @type {boolean} - * @private - */ - this.checked_ = false; + /** + * Is this menu item currently checked. + * @type {boolean} + * @private + */ + this.checked_ = false; - /** - * Is this menu item currently highlighted. - * @type {boolean} - * @private - */ - this.highlight_ = false; + /** + * Is this menu item currently highlighted. + * @type {boolean} + * @private + */ + this.highlight_ = false; - /** - * Bound function to call when this menu item is clicked. - * @type {?Function} - * @private - */ - this.actionHandler_ = null; -}; - - -/** - * Creates the menuitem's DOM. - * @return {!Element} Completed DOM. - */ -MenuItem.prototype.createDom = function() { - const element = document.createElement('div'); - element.id = idGenerator.getNextUniqueId(); - this.element_ = element; - - // Set class and style - // goog-menuitem* is deprecated, use blocklyMenuItem*. May 2020. - element.className = 'blocklyMenuItem goog-menuitem ' + - (this.enabled_ ? '' : 'blocklyMenuItemDisabled goog-menuitem-disabled ') + - (this.checked_ ? 'blocklyMenuItemSelected goog-option-selected ' : '') + - (this.highlight_ ? 'blocklyMenuItemHighlight goog-menuitem-highlight ' : - '') + - (this.rightToLeft_ ? 'blocklyMenuItemRtl goog-menuitem-rtl ' : ''); - - const content = document.createElement('div'); - content.className = 'blocklyMenuItemContent goog-menuitem-content'; - // Add a checkbox for checkable menu items. - if (this.checkable_) { - const checkbox = document.createElement('div'); - checkbox.className = 'blocklyMenuItemCheckbox goog-menuitem-checkbox'; - content.appendChild(checkbox); + /** + * Bound function to call when this menu item is clicked. + * @type {?Function} + * @private + */ + this.actionHandler_ = null; } - let contentDom = /** @type {!HTMLElement} */ (this.content_); - if (typeof this.content_ === 'string') { - contentDom = document.createTextNode(this.content_); + /** + * Creates the menuitem's DOM. + * @return {!Element} Completed DOM. + */ + createDom() { + const element = document.createElement('div'); + element.id = idGenerator.getNextUniqueId(); + this.element_ = element; + + // Set class and style + // goog-menuitem* is deprecated, use blocklyMenuItem*. May 2020. + element.className = 'blocklyMenuItem goog-menuitem ' + + (this.enabled_ ? '' : + 'blocklyMenuItemDisabled goog-menuitem-disabled ') + + (this.checked_ ? 'blocklyMenuItemSelected goog-option-selected ' : '') + + (this.highlight_ ? 'blocklyMenuItemHighlight goog-menuitem-highlight ' : + '') + + (this.rightToLeft_ ? 'blocklyMenuItemRtl goog-menuitem-rtl ' : ''); + + const content = document.createElement('div'); + content.className = 'blocklyMenuItemContent goog-menuitem-content'; + // Add a checkbox for checkable menu items. + if (this.checkable_) { + const checkbox = document.createElement('div'); + checkbox.className = 'blocklyMenuItemCheckbox goog-menuitem-checkbox'; + content.appendChild(checkbox); + } + + let contentDom = /** @type {!HTMLElement} */ (this.content_); + if (typeof this.content_ === 'string') { + contentDom = document.createTextNode(this.content_); + } + content.appendChild(contentDom); + element.appendChild(content); + + // Initialize ARIA role and state. + if (this.roleName_) { + aria.setRole(element, this.roleName_); + } + aria.setState( + element, aria.State.SELECTED, + (this.checkable_ && this.checked_) || false); + aria.setState(element, aria.State.DISABLED, !this.enabled_); + + return element; } - content.appendChild(contentDom); - element.appendChild(content); - // Initialize ARIA role and state. - if (this.roleName_) { - aria.setRole(element, this.roleName_); + /** + * Dispose of this menu item. + */ + dispose() { + this.element_ = null; } - aria.setState( - element, aria.State.SELECTED, - (this.checkable_ && this.checked_) || false); - aria.setState(element, aria.State.DISABLED, !this.enabled_); - return element; -}; + /** + * Gets the menu item's element. + * @return {?Element} The DOM element. + * @package + */ + getElement() { + return this.element_; + } -/** - * Dispose of this menu item. - */ -MenuItem.prototype.dispose = function() { - this.element_ = null; -}; + /** + * Gets the unique ID for this menu item. + * @return {string} Unique component ID. + * @package + */ + getId() { + return this.element_.id; + } -/** - * Gets the menu item's element. - * @return {?Element} The DOM element. - * @package - */ -MenuItem.prototype.getElement = function() { - return this.element_; -}; + /** + * Gets the value associated with the menu item. + * @return {*} value Value associated with the menu item. + * @package + */ + getValue() { + return this.value_; + } -/** - * Gets the unique ID for this menu item. - * @return {string} Unique component ID. - * @package - */ -MenuItem.prototype.getId = function() { - return this.element_.id; -}; + /** + * Set menu item's rendering direction. + * @param {boolean} rtl True if RTL, false if LTR. + * @package + */ + setRightToLeft(rtl) { + this.rightToLeft_ = rtl; + } -/** - * Gets the value associated with the menu item. - * @return {*} value Value associated with the menu item. - * @package - */ -MenuItem.prototype.getValue = function() { - return this.value_; -}; + /** + * Set the menu item's accessibility role. + * @param {!aria.Role} roleName Role name. + * @package + */ + setRole(roleName) { + this.roleName_ = roleName; + } -/** - * Set menu item's rendering direction. - * @param {boolean} rtl True if RTL, false if LTR. - * @package - */ -MenuItem.prototype.setRightToLeft = function(rtl) { - this.rightToLeft_ = rtl; -}; + /** + * Sets the menu item to be checkable or not. Set to true for menu items + * that represent checkable options. + * @param {boolean} checkable Whether the menu item is checkable. + * @package + */ + setCheckable(checkable) { + this.checkable_ = checkable; + } -/** - * Set the menu item's accessibility role. - * @param {!aria.Role} roleName Role name. - * @package - */ -MenuItem.prototype.setRole = function(roleName) { - this.roleName_ = roleName; -}; + /** + * Checks or unchecks the component. + * @param {boolean} checked Whether to check or uncheck the component. + * @package + */ + setChecked(checked) { + this.checked_ = checked; + } -/** - * Sets the menu item to be checkable or not. Set to true for menu items - * that represent checkable options. - * @param {boolean} checkable Whether the menu item is checkable. - * @package - */ -MenuItem.prototype.setCheckable = function(checkable) { - this.checkable_ = checkable; -}; + /** + * Highlights or unhighlights the component. + * @param {boolean} highlight Whether to highlight or unhighlight the + * component. + * @package + */ + setHighlighted(highlight) { + this.highlight_ = highlight; -/** - * Checks or unchecks the component. - * @param {boolean} checked Whether to check or uncheck the component. - * @package - */ -MenuItem.prototype.setChecked = function(checked) { - this.checked_ = checked; -}; - -/** - * Highlights or unhighlights the component. - * @param {boolean} highlight Whether to highlight or unhighlight the component. - * @package - */ -MenuItem.prototype.setHighlighted = function(highlight) { - this.highlight_ = highlight; - - const el = this.getElement(); - if (el && this.isEnabled()) { - // goog-menuitem-highlight is deprecated, use blocklyMenuItemHighlight. - // May 2020. - const name = 'blocklyMenuItemHighlight'; - const nameDep = 'goog-menuitem-highlight'; - if (highlight) { - dom.addClass(el, name); - dom.addClass(el, nameDep); - } else { - dom.removeClass(el, name); - dom.removeClass(el, nameDep); + const el = this.getElement(); + if (el && this.isEnabled()) { + // goog-menuitem-highlight is deprecated, use blocklyMenuItemHighlight. + // May 2020. + const name = 'blocklyMenuItemHighlight'; + const nameDep = 'goog-menuitem-highlight'; + if (highlight) { + dom.addClass(el, name); + dom.addClass(el, nameDep); + } else { + dom.removeClass(el, name); + dom.removeClass(el, nameDep); + } } } -}; -/** - * Returns true if the menu item is enabled, false otherwise. - * @return {boolean} Whether the menu item is enabled. - * @package - */ -MenuItem.prototype.isEnabled = function() { - return this.enabled_; -}; - -/** - * Enables or disables the menu item. - * @param {boolean} enabled Whether to enable or disable the menu item. - * @package - */ -MenuItem.prototype.setEnabled = function(enabled) { - this.enabled_ = enabled; -}; - -/** - * Performs the appropriate action when the menu item is activated - * by the user. - * @package - */ -MenuItem.prototype.performAction = function() { - if (this.isEnabled() && this.actionHandler_) { - this.actionHandler_(this); + /** + * Returns true if the menu item is enabled, false otherwise. + * @return {boolean} Whether the menu item is enabled. + * @package + */ + isEnabled() { + return this.enabled_; } -}; -/** - * Set the handler that's called when the menu item is activated by the user. - * `obj` will be used as the 'this' object in the function when called. - * @param {function(!MenuItem)} fn The handler. - * @param {!Object} obj Used as the 'this' object in fn when called. - * @package - */ -MenuItem.prototype.onAction = function(fn, obj) { - this.actionHandler_ = fn.bind(obj); + /** + * Enables or disables the menu item. + * @param {boolean} enabled Whether to enable or disable the menu item. + * @package + */ + setEnabled(enabled) { + this.enabled_ = enabled; + } + + /** + * Performs the appropriate action when the menu item is activated + * by the user. + * @package + */ + performAction() { + if (this.isEnabled() && this.actionHandler_) { + this.actionHandler_(this); + } + } + + /** + * Set the handler that's called when the menu item is activated by the user. + * `obj` will be used as the 'this' object in the function when called. + * @param {function(!MenuItem)} fn The handler. + * @param {!Object} obj Used as the 'this' object in fn when called. + * @package + */ + onAction(fn, obj) { + this.actionHandler_ = fn.bind(obj); + } }; exports.MenuItem = MenuItem; diff --git a/core/names.js b/core/names.js index 1fad1e00f..f8c073220 100644 --- a/core/names.js +++ b/core/names.js @@ -27,23 +27,235 @@ goog.requireType('Blockly.Procedures'); /** * Class for a database of entity names (variables, procedures, etc). - * @param {string} reservedWords A comma-separated string of words that are - * illegal for use as names in a language (e.g. 'new,if,this,...'). - * @param {string=} opt_variablePrefix Some languages need a '$' or a namespace - * before all variable names (but not procedure names). - * @constructor - * @alias Blockly.Names */ -const Names = function(reservedWords, opt_variablePrefix) { - this.variablePrefix_ = opt_variablePrefix || ''; - this.reservedDict_ = Object.create(null); - if (reservedWords) { - const splitWords = reservedWords.split(','); - for (let i = 0; i < splitWords.length; i++) { - this.reservedDict_[splitWords[i]] = true; +const Names = class { + /** + * @param {string} reservedWords A comma-separated string of words that are + * illegal for use as names in a language (e.g. 'new,if,this,...'). + * @param {string=} opt_variablePrefix Some languages need a '$' or a + * namespace before all variable names (but not procedure names). + * @alias Blockly.Names + */ + constructor(reservedWords, opt_variablePrefix) { + /** + * The prefix to attach to variable names in generated code. + * @type {string} + * @private + */ + this.variablePrefix_ = opt_variablePrefix || ''; + + /** + * A dictionary of reserved words. + * @type {Object} + * @private + */ + this.reservedDict_ = Object.create(null); + + /** + * A map from type (e.g. name, procedure) to maps from names to generated + * names. + * @type {Object>} + * @private + */ + this.db_ = Object.create(null); + + /** + * A map from used names to booleans to avoid collisions. + * @type {Object} + * @private + */ + this.dbReverse_ = Object.create(null); + + /** + * The variable map from the workspace, containing Blockly variable models. + * @type {?VariableMap} + * @private + */ + this.variableMap_ = null; + + if (reservedWords) { + const splitWords = reservedWords.split(','); + for (let i = 0; i < splitWords.length; i++) { + this.reservedDict_[splitWords[i]] = true; + } + } + this.reset(); + } + + /** + * Empty the database and start from scratch. The reserved words are kept. + */ + reset() { + this.db_ = Object.create(null); + this.dbReverse_ = Object.create(null); + this.variableMap_ = null; + } + + /** + * Set the variable map that maps from variable name to variable object. + * @param {!VariableMap} map The map to track. + */ + setVariableMap(map) { + this.variableMap_ = map; + } + + /** + * Get the name for a user-defined variable, based on its ID. + * This should only be used for variables of NameType VARIABLE. + * @param {string} id The ID to look up in the variable map. + * @return {?string} The name of the referenced variable, or null if there was + * no variable map or the variable was not found in the map. + * @private + */ + getNameForUserVariable_(id) { + if (!this.variableMap_) { + console.warn( + 'Deprecated call to Names.prototype.getName without ' + + 'defining a variable map. To fix, add the following code in your ' + + 'generator\'s init() function:\n' + + 'Blockly.YourGeneratorName.nameDB_.setVariableMap(' + + 'workspace.getVariableMap());'); + return null; + } + const variable = this.variableMap_.getVariableById(id); + if (variable) { + return variable.name; + } + return null; + } + + /** + * Generate names for user variables, but only ones that are being used. + * @param {!Workspace} workspace Workspace to generate variables from. + */ + populateVariables(workspace) { + const variables = Variables.allUsedVarModels(workspace); + for (let i = 0; i < variables.length; i++) { + this.getName(variables[i].getId(), NameType.VARIABLE); } } - this.reset(); + + /** + * Generate names for procedures. + * @param {!Workspace} workspace Workspace to generate procedures from. + */ + populateProcedures(workspace) { + let procedures = + goog.module.get('Blockly.Procedures').allProcedures(workspace); + // Flatten the return vs no-return procedure lists. + procedures = procedures[0].concat(procedures[1]); + for (let i = 0; i < procedures.length; i++) { + this.getName(procedures[i][0], NameType.PROCEDURE); + } + } + + /** + * Convert a Blockly entity name to a legal exportable entity name. + * @param {string} nameOrId The Blockly entity name (no constraints) or + * variable ID. + * @param {NameType|string} type The type of the name in Blockly + * ('VARIABLE', 'PROCEDURE', 'DEVELOPER_VARIABLE', etc...). + * @return {string} An entity name that is legal in the exported language. + */ + getName(nameOrId, type) { + let name = nameOrId; + if (type === NameType.VARIABLE) { + const varName = this.getNameForUserVariable_(nameOrId); + if (varName) { + // Successful ID lookup. + name = varName; + } + } + const normalizedName = name.toLowerCase(); + + const isVar = + type === NameType.VARIABLE || type === NameType.DEVELOPER_VARIABLE; + + const prefix = isVar ? this.variablePrefix_ : ''; + if (!(type in this.db_)) { + this.db_[type] = Object.create(null); + } + const typeDb = this.db_[type]; + if (normalizedName in typeDb) { + return prefix + typeDb[normalizedName]; + } + const safeName = this.getDistinctName(name, type); + typeDb[normalizedName] = safeName.substr(prefix.length); + return safeName; + } + + /** + * Return a list of all known user-created names of a specified name type. + * @param {NameType|string} type The type of entity in Blockly + * ('VARIABLE', 'PROCEDURE', 'DEVELOPER_VARIABLE', etc...). + * @return {!Array} A list of Blockly entity names (no constraints). + */ + getUserNames(type) { + const typeDb = this.db_[type] || {}; + return Object.keys(typeDb); + } + + /** + * Convert a Blockly entity name to a legal exportable entity name. + * Ensure that this is a new name not overlapping any previously defined name. + * Also check against list of reserved words for the current language and + * ensure name doesn't collide. + * @param {string} name The Blockly entity name (no constraints). + * @param {NameType|string} type The type of entity in Blockly + * ('VARIABLE', 'PROCEDURE', 'DEVELOPER_VARIABLE', etc...). + * @return {string} An entity name that is legal in the exported language. + */ + getDistinctName(name, type) { + let safeName = this.safeName_(name); + let i = ''; + while (this.dbReverse_[safeName + i] || + (safeName + i) in this.reservedDict_) { + // Collision with existing name. Create a unique name. + i = i ? i + 1 : 2; + } + safeName += i; + this.dbReverse_[safeName] = true; + const isVar = + type === NameType.VARIABLE || type === NameType.DEVELOPER_VARIABLE; + const prefix = isVar ? this.variablePrefix_ : ''; + return prefix + safeName; + } + + /** + * Given a proposed entity name, generate a name that conforms to the + * [_A-Za-z][_A-Za-z0-9]* format that most languages consider legal for + * variable and function names. + * @param {string} name Potentially illegal entity name. + * @return {string} Safe entity name. + * @private + */ + safeName_(name) { + if (!name) { + name = Msg['UNNAMED_KEY'] || 'unnamed'; + } else { + // Unfortunately names in non-latin characters will look like + // _E9_9F_B3_E4_B9_90 which is pretty meaningless. + // https://github.com/google/blockly/issues/1654 + name = encodeURI(name.replace(/ /g, '_')).replace(/[^\w]/g, '_'); + // Most languages don't allow names with leading numbers. + if ('0123456789'.indexOf(name[0]) !== -1) { + name = 'my_' + name; + } + } + return name; + } + + /** + * Do the given two entity names refer to the same entity? + * Blockly names are case-insensitive. + * @param {string} name1 First name. + * @param {string} name2 Second name. + * @return {boolean} True if names are the same. + */ + static equals(name1, name2) { + // name1.localeCompare(name2) is slower. + return name1.toLowerCase() === name2.toLowerCase(); + } }; /** @@ -74,179 +286,4 @@ exports.NameType = NameType; */ Names.DEVELOPER_VARIABLE_TYPE = NameType.DEVELOPER_VARIABLE; -/** - * Empty the database and start from scratch. The reserved words are kept. - */ -Names.prototype.reset = function() { - this.db_ = Object.create(null); - this.dbReverse_ = Object.create(null); - this.variableMap_ = null; -}; - -/** - * Set the variable map that maps from variable name to variable object. - * @param {!VariableMap} map The map to track. - */ -Names.prototype.setVariableMap = function(map) { - this.variableMap_ = map; -}; - -/** - * Get the name for a user-defined variable, based on its ID. - * This should only be used for variables of NameType VARIABLE. - * @param {string} id The ID to look up in the variable map. - * @return {?string} The name of the referenced variable, or null if there was - * no variable map or the variable was not found in the map. - * @private - */ -Names.prototype.getNameForUserVariable_ = function(id) { - if (!this.variableMap_) { - console.warn( - 'Deprecated call to Names.prototype.getName without ' + - 'defining a variable map. To fix, add the following code in your ' + - 'generator\'s init() function:\n' + - 'Blockly.YourGeneratorName.nameDB_.setVariableMap(' + - 'workspace.getVariableMap());'); - return null; - } - const variable = this.variableMap_.getVariableById(id); - if (variable) { - return variable.name; - } - return null; -}; - -/** - * Generate names for user variables, but only ones that are being used. - * @param {!Workspace} workspace Workspace to generate variables from. - */ -Names.prototype.populateVariables = function(workspace) { - const variables = Variables.allUsedVarModels(workspace); - for (let i = 0; i < variables.length; i++) { - this.getName(variables[i].getId(), NameType.VARIABLE); - } -}; - -/** - * Generate names for procedures. - * @param {!Workspace} workspace Workspace to generate procedures from. - */ -Names.prototype.populateProcedures = function(workspace) { - let procedures = - goog.module.get('Blockly.Procedures').allProcedures(workspace); - // Flatten the return vs no-return procedure lists. - procedures = procedures[0].concat(procedures[1]); - for (let i = 0; i < procedures.length; i++) { - this.getName(procedures[i][0], NameType.PROCEDURE); - } -}; - -/** - * Convert a Blockly entity name to a legal exportable entity name. - * @param {string} nameOrId The Blockly entity name (no constraints) or - * variable ID. - * @param {NameType|string} type The type of the name in Blockly - * ('VARIABLE', 'PROCEDURE', 'DEVELOPER_VARIABLE', etc...). - * @return {string} An entity name that is legal in the exported language. - */ -Names.prototype.getName = function(nameOrId, type) { - let name = nameOrId; - if (type === NameType.VARIABLE) { - const varName = this.getNameForUserVariable_(nameOrId); - if (varName) { - // Successful ID lookup. - name = varName; - } - } - const normalizedName = name.toLowerCase(); - - const isVar = - type === NameType.VARIABLE || type === NameType.DEVELOPER_VARIABLE; - - const prefix = isVar ? this.variablePrefix_ : ''; - if (!(type in this.db_)) { - this.db_[type] = Object.create(null); - } - const typeDb = this.db_[type]; - if (normalizedName in typeDb) { - return prefix + typeDb[normalizedName]; - } - const safeName = this.getDistinctName(name, type); - typeDb[normalizedName] = safeName.substr(prefix.length); - return safeName; -}; - -/** - * Return a list of all known user-created names of a specified name type. - * @param {NameType|string} type The type of entity in Blockly - * ('VARIABLE', 'PROCEDURE', 'DEVELOPER_VARIABLE', etc...). - * @return {!Array} A list of Blockly entity names (no constraints). - */ -Names.prototype.getUserNames = function(type) { - const typeDb = this.db_[type] || {}; - return Object.keys(typeDb); -}; - -/** - * Convert a Blockly entity name to a legal exportable entity name. - * Ensure that this is a new name not overlapping any previously defined name. - * Also check against list of reserved words for the current language and - * ensure name doesn't collide. - * @param {string} name The Blockly entity name (no constraints). - * @param {NameType|string} type The type of entity in Blockly - * ('VARIABLE', 'PROCEDURE', 'DEVELOPER_VARIABLE', etc...). - * @return {string} An entity name that is legal in the exported language. - */ -Names.prototype.getDistinctName = function(name, type) { - let safeName = this.safeName_(name); - let i = ''; - while (this.dbReverse_[safeName + i] || - (safeName + i) in this.reservedDict_) { - // Collision with existing name. Create a unique name. - i = i ? i + 1 : 2; - } - safeName += i; - this.dbReverse_[safeName] = true; - const isVar = - type === NameType.VARIABLE || type === NameType.DEVELOPER_VARIABLE; - const prefix = isVar ? this.variablePrefix_ : ''; - return prefix + safeName; -}; - -/** - * Given a proposed entity name, generate a name that conforms to the - * [_A-Za-z][_A-Za-z0-9]* format that most languages consider legal for - * variable and function names. - * @param {string} name Potentially illegal entity name. - * @return {string} Safe entity name. - * @private - */ -Names.prototype.safeName_ = function(name) { - if (!name) { - name = Msg['UNNAMED_KEY'] || 'unnamed'; - } else { - // Unfortunately names in non-latin characters will look like - // _E9_9F_B3_E4_B9_90 which is pretty meaningless. - // https://github.com/google/blockly/issues/1654 - name = encodeURI(name.replace(/ /g, '_')).replace(/[^\w]/g, '_'); - // Most languages don't allow names with leading numbers. - if ('0123456789'.indexOf(name[0]) !== -1) { - name = 'my_' + name; - } - } - return name; -}; - -/** - * Do the given two entity names refer to the same entity? - * Blockly names are case-insensitive. - * @param {string} name1 First name. - * @param {string} name2 Second name. - * @return {boolean} True if names are the same. - */ -Names.equals = function(name1, name2) { - // name1.localeCompare(name2) is slower. - return name1.toLowerCase() === name2.toLowerCase(); -}; - exports.Names = Names; diff --git a/core/scrollbar_pair.js b/core/scrollbar_pair.js index 52de6e413..b53813dc0 100644 --- a/core/scrollbar_pair.js +++ b/core/scrollbar_pair.js @@ -27,297 +27,302 @@ const {WorkspaceSvg} = goog.requireType('Blockly.WorkspaceSvg'); /** * Class for a pair of scrollbars. Horizontal and vertical. - * @param {!WorkspaceSvg} workspace Workspace to bind the scrollbars to. - * @param {boolean=} addHorizontal Whether to add a horizontal scrollbar. - * Defaults to true. - * @param {boolean=} addVertical Whether to add a vertical scrollbar. Defaults - * to true. - * @param {string=} opt_class A class to be applied to these scrollbars. - * @param {number=} opt_margin The margin to apply to these scrollbars. - * @constructor - * @alias Blockly.ScrollbarPair */ -const ScrollbarPair = function( - workspace, addHorizontal, addVertical, opt_class, opt_margin) { +const ScrollbarPair = class { /** - * The workspace this scrollbar pair is bound to. - * @type {!WorkspaceSvg} - * @private + * @param {!WorkspaceSvg} workspace Workspace to bind the scrollbars to. + * @param {boolean=} addHorizontal Whether to add a horizontal scrollbar. + * Defaults to true. + * @param {boolean=} addVertical Whether to add a vertical scrollbar. Defaults + * to true. + * @param {string=} opt_class A class to be applied to these scrollbars. + * @param {number=} opt_margin The margin to apply to these scrollbars. + * @alias Blockly.ScrollbarPair */ - this.workspace_ = workspace; + constructor(workspace, addHorizontal, addVertical, opt_class, opt_margin) { + /** + * The workspace this scrollbar pair is bound to. + * @type {!WorkspaceSvg} + * @private + */ + this.workspace_ = workspace; - addHorizontal = addHorizontal === undefined ? true : addHorizontal; - addVertical = addVertical === undefined ? true : addVertical; - const isPair = addHorizontal && addVertical; + addHorizontal = addHorizontal === undefined ? true : addHorizontal; + addVertical = addVertical === undefined ? true : addVertical; + const isPair = addHorizontal && addVertical; - if (addHorizontal) { - this.hScroll = - new Scrollbar(workspace, true, isPair, opt_class, opt_margin); - } - if (addVertical) { - this.vScroll = - new Scrollbar(workspace, false, isPair, opt_class, opt_margin); - } + if (addHorizontal) { + this.hScroll = + new Scrollbar(workspace, true, isPair, opt_class, opt_margin); + } + if (addVertical) { + this.vScroll = + new Scrollbar(workspace, false, isPair, opt_class, opt_margin); + } - if (isPair) { - this.corner_ = dom.createSvgElement( - Svg.RECT, { - 'height': Scrollbar.scrollbarThickness, - 'width': Scrollbar.scrollbarThickness, - 'class': 'blocklyScrollbarBackground', - }, - null); - dom.insertAfter(this.corner_, workspace.getBubbleCanvas()); + if (isPair) { + this.corner_ = dom.createSvgElement( + Svg.RECT, { + 'height': Scrollbar.scrollbarThickness, + 'width': Scrollbar.scrollbarThickness, + 'class': 'blocklyScrollbarBackground', + }, + null); + dom.insertAfter(this.corner_, workspace.getBubbleCanvas()); + } + + /** + * Previously recorded metrics from the workspace. + * @type {?Metrics} + * @private + */ + this.oldHostMetrics_ = null; } /** - * Previously recorded metrics from the workspace. - * @type {?Metrics} - * @private + * Dispose of this pair of scrollbars. + * Unlink from all DOM elements to prevent memory leaks. + * @suppress {checkTypes} */ - this.oldHostMetrics_ = null; -}; - -/** - * Dispose of this pair of scrollbars. - * Unlink from all DOM elements to prevent memory leaks. - * @suppress {checkTypes} - */ -ScrollbarPair.prototype.dispose = function() { - dom.removeNode(this.corner_); - this.corner_ = null; - this.workspace_ = null; - this.oldHostMetrics_ = null; - if (this.hScroll) { - this.hScroll.dispose(); - this.hScroll = null; - } - if (this.vScroll) { - this.vScroll.dispose(); - this.vScroll = null; - } -}; - -/** - * Recalculate both of the scrollbars' locations and lengths. - * Also reposition the corner rectangle. - */ -ScrollbarPair.prototype.resize = function() { - // Look up the host metrics once, and use for both scrollbars. - const hostMetrics = this.workspace_.getMetrics(); - if (!hostMetrics) { - // Host element is likely not visible. - return; - } - - // Only change the scrollbars if there has been a change in metrics. - let resizeH = false; - let resizeV = false; - if (!this.oldHostMetrics_ || - this.oldHostMetrics_.viewWidth !== hostMetrics.viewWidth || - this.oldHostMetrics_.viewHeight !== hostMetrics.viewHeight || - this.oldHostMetrics_.absoluteTop !== hostMetrics.absoluteTop || - this.oldHostMetrics_.absoluteLeft !== hostMetrics.absoluteLeft) { - // The window has been resized or repositioned. - resizeH = true; - resizeV = true; - } else { - // Has the content been resized or moved? - if (!this.oldHostMetrics_ || - this.oldHostMetrics_.scrollWidth !== hostMetrics.scrollWidth || - this.oldHostMetrics_.viewLeft !== hostMetrics.viewLeft || - this.oldHostMetrics_.scrollLeft !== hostMetrics.scrollLeft) { - resizeH = true; - } - if (!this.oldHostMetrics_ || - this.oldHostMetrics_.scrollHeight !== hostMetrics.scrollHeight || - this.oldHostMetrics_.viewTop !== hostMetrics.viewTop || - this.oldHostMetrics_.scrollTop !== hostMetrics.scrollTop) { - resizeV = true; - } - } - - if (resizeH || resizeV) { - try { - eventUtils.disable(); - if (this.hScroll && resizeH) { - this.hScroll.resize(hostMetrics); - } - if (this.vScroll && resizeV) { - this.vScroll.resize(hostMetrics); - } - } finally { - eventUtils.enable(); - } - this.workspace_.maybeFireViewportChangeEvent(); - } - - if (this.hScroll && this.vScroll) { - // Reposition the corner square. - if (!this.oldHostMetrics_ || - this.oldHostMetrics_.viewWidth !== hostMetrics.viewWidth || - this.oldHostMetrics_.absoluteLeft !== hostMetrics.absoluteLeft) { - this.corner_.setAttribute('x', this.vScroll.position.x); - } - if (!this.oldHostMetrics_ || - this.oldHostMetrics_.viewHeight !== hostMetrics.viewHeight || - this.oldHostMetrics_.absoluteTop !== hostMetrics.absoluteTop) { - this.corner_.setAttribute('y', this.hScroll.position.y); - } - } - - // Cache the current metrics to potentially short-cut the next resize event. - this.oldHostMetrics_ = hostMetrics; -}; - -/** - * Returns whether scrolling horizontally is enabled. - * @return {boolean} True if horizontal scroll is enabled. - */ -ScrollbarPair.prototype.canScrollHorizontally = function() { - return !!this.hScroll; -}; - -/** - * Returns whether scrolling vertically is enabled. - * @return {boolean} True if vertical scroll is enabled. - */ -ScrollbarPair.prototype.canScrollVertically = function() { - return !!this.vScroll; -}; - -/** - * Record the origin of the workspace that the scrollbar is in, in pixels - * relative to the injection div origin. This is for times when the scrollbar is - * used in an object whose origin isn't the same as the main workspace - * (e.g. in a flyout.) - * @param {number} x The x coordinate of the scrollbar's origin, in CSS pixels. - * @param {number} y The y coordinate of the scrollbar's origin, in CSS pixels. - * @package - */ -ScrollbarPair.prototype.setOrigin = function(x, y) { - if (this.hScroll) { - this.hScroll.setOrigin(x, y); - } - if (this.vScroll) { - this.vScroll.setOrigin(x, y); - } -}; - -/** - * Set the handles of both scrollbars. - * @param {number} x The horizontal content displacement, relative to the view - * in pixels. - * @param {number} y The vertical content displacement, relative to the view in - * pixels. - * @param {boolean} updateMetrics Whether to update metrics on this set call. - * Defaults to true. - */ -ScrollbarPair.prototype.set = function(x, y, updateMetrics) { - // This function is equivalent to: - // this.hScroll.set(x); - // this.vScroll.set(y); - // However, that calls setMetrics twice which causes a chain of - // getAttribute->setAttribute->getAttribute resulting in an extra layout pass. - // Combining them speeds up rendering. - if (this.hScroll) { - this.hScroll.set(x, false); - } - if (this.vScroll) { - this.vScroll.set(y, false); - } - - if (updateMetrics || updateMetrics === undefined) { - // Update metrics. - const xyRatio = {}; + dispose() { + dom.removeNode(this.corner_); + this.corner_ = null; + this.workspace_ = null; + this.oldHostMetrics_ = null; if (this.hScroll) { - xyRatio.x = this.hScroll.getRatio_(); + this.hScroll.dispose(); + this.hScroll = null; } if (this.vScroll) { - xyRatio.y = this.vScroll.getRatio_(); + this.vScroll.dispose(); + this.vScroll = null; } - this.workspace_.setMetrics(xyRatio); } -}; -/** - * Set the handle of the horizontal scrollbar to be at a certain position in - * CSS pixels relative to its parents. - * @param {number} x Horizontal scroll value. - */ -ScrollbarPair.prototype.setX = function(x) { - if (this.hScroll) { - this.hScroll.set(x, true); - } -}; + /** + * Recalculate both of the scrollbars' locations and lengths. + * Also reposition the corner rectangle. + */ + resize() { + // Look up the host metrics once, and use for both scrollbars. + const hostMetrics = this.workspace_.getMetrics(); + if (!hostMetrics) { + // Host element is likely not visible. + return; + } -/** - * Set the handle of the vertical scrollbar to be at a certain position in - * CSS pixels relative to its parents. - * @param {number} y Vertical scroll value. - */ -ScrollbarPair.prototype.setY = function(y) { - if (this.vScroll) { - this.vScroll.set(y, true); - } -}; + // Only change the scrollbars if there has been a change in metrics. + let resizeH = false; + let resizeV = false; + if (!this.oldHostMetrics_ || + this.oldHostMetrics_.viewWidth !== hostMetrics.viewWidth || + this.oldHostMetrics_.viewHeight !== hostMetrics.viewHeight || + this.oldHostMetrics_.absoluteTop !== hostMetrics.absoluteTop || + this.oldHostMetrics_.absoluteLeft !== hostMetrics.absoluteLeft) { + // The window has been resized or repositioned. + resizeH = true; + resizeV = true; + } else { + // Has the content been resized or moved? + if (!this.oldHostMetrics_ || + this.oldHostMetrics_.scrollWidth !== hostMetrics.scrollWidth || + this.oldHostMetrics_.viewLeft !== hostMetrics.viewLeft || + this.oldHostMetrics_.scrollLeft !== hostMetrics.scrollLeft) { + resizeH = true; + } + if (!this.oldHostMetrics_ || + this.oldHostMetrics_.scrollHeight !== hostMetrics.scrollHeight || + this.oldHostMetrics_.viewTop !== hostMetrics.viewTop || + this.oldHostMetrics_.scrollTop !== hostMetrics.scrollTop) { + resizeV = true; + } + } -/** - * Set whether this scrollbar's container is visible. - * @param {boolean} visible Whether the container is visible. - */ -ScrollbarPair.prototype.setContainerVisible = function(visible) { - if (this.hScroll) { - this.hScroll.setContainerVisible(visible); - } - if (this.vScroll) { - this.vScroll.setContainerVisible(visible); - } -}; + if (resizeH || resizeV) { + try { + eventUtils.disable(); + if (this.hScroll && resizeH) { + this.hScroll.resize(hostMetrics); + } + if (this.vScroll && resizeV) { + this.vScroll.resize(hostMetrics); + } + } finally { + eventUtils.enable(); + } + this.workspace_.maybeFireViewportChangeEvent(); + } -/** - * If any of the scrollbars are visible. Non-paired scrollbars may disappear - * when they aren't needed. - * @return {boolean} True if visible. - */ -ScrollbarPair.prototype.isVisible = function() { - let isVisible = false; - if (this.hScroll) { - isVisible = this.hScroll.isVisible(); - } - if (this.vScroll) { - isVisible = isVisible || this.vScroll.isVisible(); - } - return isVisible; -}; + if (this.hScroll && this.vScroll) { + // Reposition the corner square. + if (!this.oldHostMetrics_ || + this.oldHostMetrics_.viewWidth !== hostMetrics.viewWidth || + this.oldHostMetrics_.absoluteLeft !== hostMetrics.absoluteLeft) { + this.corner_.setAttribute('x', this.vScroll.position.x); + } + if (!this.oldHostMetrics_ || + this.oldHostMetrics_.viewHeight !== hostMetrics.viewHeight || + this.oldHostMetrics_.absoluteTop !== hostMetrics.absoluteTop) { + this.corner_.setAttribute('y', this.hScroll.position.y); + } + } -/** - * Recalculates the scrollbars' locations within their path and length. - * This should be called when the contents of the workspace have changed. - * @param {!Metrics} hostMetrics A data structure describing all - * the required dimensions, possibly fetched from the host object. - */ -ScrollbarPair.prototype.resizeContent = function(hostMetrics) { - if (this.hScroll) { - this.hScroll.resizeContentHorizontal(hostMetrics); + // Cache the current metrics to potentially short-cut the next resize event. + this.oldHostMetrics_ = hostMetrics; } - if (this.vScroll) { - this.vScroll.resizeContentVertical(hostMetrics); - } -}; -/** - * Recalculates the scrollbars' locations on the screen and path length. - * This should be called when the layout or size of the window has changed. - * @param {!Metrics} hostMetrics A data structure describing all - * the required dimensions, possibly fetched from the host object. - */ -ScrollbarPair.prototype.resizeView = function(hostMetrics) { - if (this.hScroll) { - this.hScroll.resizeViewHorizontal(hostMetrics); + /** + * Returns whether scrolling horizontally is enabled. + * @return {boolean} True if horizontal scroll is enabled. + */ + canScrollHorizontally() { + return !!this.hScroll; } - if (this.vScroll) { - this.vScroll.resizeViewVertical(hostMetrics); + + /** + * Returns whether scrolling vertically is enabled. + * @return {boolean} True if vertical scroll is enabled. + */ + canScrollVertically() { + return !!this.vScroll; + } + + /** + * Record the origin of the workspace that the scrollbar is in, in pixels + * relative to the injection div origin. This is for times when the scrollbar + * is used in an object whose origin isn't the same as the main workspace + * (e.g. in a flyout.) + * @param {number} x The x coordinate of the scrollbar's origin, in CSS + * pixels. + * @param {number} y The y coordinate of the scrollbar's origin, in CSS + * pixels. + * @package + */ + setOrigin(x, y) { + if (this.hScroll) { + this.hScroll.setOrigin(x, y); + } + if (this.vScroll) { + this.vScroll.setOrigin(x, y); + } + } + + /** + * Set the handles of both scrollbars. + * @param {number} x The horizontal content displacement, relative to the view + * in pixels. + * @param {number} y The vertical content displacement, relative to the view + * in + * pixels. + * @param {boolean} updateMetrics Whether to update metrics on this set call. + * Defaults to true. + */ + set(x, y, updateMetrics) { + // This function is equivalent to: + // this.hScroll.set(x); + // this.vScroll.set(y); + // However, that calls setMetrics twice which causes a chain of + // getAttribute->setAttribute->getAttribute resulting in an extra layout + // pass. Combining them speeds up rendering. + if (this.hScroll) { + this.hScroll.set(x, false); + } + if (this.vScroll) { + this.vScroll.set(y, false); + } + + if (updateMetrics || updateMetrics === undefined) { + // Update metrics. + const xyRatio = {}; + if (this.hScroll) { + xyRatio.x = this.hScroll.getRatio_(); + } + if (this.vScroll) { + xyRatio.y = this.vScroll.getRatio_(); + } + this.workspace_.setMetrics(xyRatio); + } + } + + /** + * Set the handle of the horizontal scrollbar to be at a certain position in + * CSS pixels relative to its parents. + * @param {number} x Horizontal scroll value. + */ + setX(x) { + if (this.hScroll) { + this.hScroll.set(x, true); + } + } + + /** + * Set the handle of the vertical scrollbar to be at a certain position in + * CSS pixels relative to its parents. + * @param {number} y Vertical scroll value. + */ + setY(y) { + if (this.vScroll) { + this.vScroll.set(y, true); + } + } + + /** + * Set whether this scrollbar's container is visible. + * @param {boolean} visible Whether the container is visible. + */ + setContainerVisible(visible) { + if (this.hScroll) { + this.hScroll.setContainerVisible(visible); + } + if (this.vScroll) { + this.vScroll.setContainerVisible(visible); + } + } + + /** + * If any of the scrollbars are visible. Non-paired scrollbars may disappear + * when they aren't needed. + * @return {boolean} True if visible. + */ + isVisible() { + let isVisible = false; + if (this.hScroll) { + isVisible = this.hScroll.isVisible(); + } + if (this.vScroll) { + isVisible = isVisible || this.vScroll.isVisible(); + } + return isVisible; + } + + /** + * Recalculates the scrollbars' locations within their path and length. + * This should be called when the contents of the workspace have changed. + * @param {!Metrics} hostMetrics A data structure describing all + * the required dimensions, possibly fetched from the host object. + */ + resizeContent(hostMetrics) { + if (this.hScroll) { + this.hScroll.resizeContentHorizontal(hostMetrics); + } + if (this.vScroll) { + this.vScroll.resizeContentVertical(hostMetrics); + } + } + + /** + * Recalculates the scrollbars' locations on the screen and path length. + * This should be called when the layout or size of the window has changed. + * @param {!Metrics} hostMetrics A data structure describing all + * the required dimensions, possibly fetched from the host object. + */ + resizeView(hostMetrics) { + if (this.hScroll) { + this.hScroll.resizeViewHorizontal(hostMetrics); + } + if (this.vScroll) { + this.vScroll.resizeViewVertical(hostMetrics); + } } }; From 29fb7b78930d82619f54dff120c18324750abfe2 Mon Sep 17 00:00:00 2001 From: Rachel Fenichel Date: Wed, 12 Jan 2022 09:29:30 -0800 Subject: [PATCH 030/128] refactor: convert leaf event classes to es6 classes (#5870) * chore(tests): update event assert functions to pass in types directly * refactor: move event types from prototypes to constructors * refactor: convert events/events_block_change.js to ES6 class * refactor: convert events/events_block_create.js to ES6 class * refactor: convert events/events_block_delete.js to ES6 class * refactor: convert events/events_block_drag.js to ES6 class * refactor: convert events/events_block_move.js to ES6 class * refactor: convert events/events_click.js to ES6 class * refactor: convert events/events_comment_change.js to ES6 class * refactor: convert events/events_comment_create.js to ES6 class * refactor: convert events/events_comment_delete.js to ES6 class * refactor: convert events/events_comment_move.js to ES6 class * refactor: convert events/events_marker_move.js to ES6 class * refactor: convert events/events_selected.js to ES6 class * refactor: convert events/events_theme_change.js to ES6 class * refactor: convert events/events_toolbox_item_select.js to ES6 class * refactor: convert events/events_trashcan_open.js to ES6 class * refactor: convert events/events_ui.js to ES6 class * refactor: convert events/events_var_create.js to ES6 class * refactor: convert events/events_var_delete.js to ES6 class * refactor: convert events/events_var_rename.js to ES6 class * refactor: convert events/events_viewport.js to ES6 class * chore: rebuild * chore: run clang-format --- core/events/events_abstract.js | 12 +- core/events/events_block_change.js | 267 +++++++++---------- core/events/events_block_create.js | 146 ++++++----- core/events/events_block_delete.js | 180 ++++++------- core/events/events_block_drag.js | 101 ++++---- core/events/events_block_move.js | 303 +++++++++++----------- core/events/events_bubble_open.js | 12 +- core/events/events_click.js | 96 +++---- core/events/events_comment_change.js | 134 +++++----- core/events/events_comment_create.js | 90 +++---- core/events/events_comment_delete.js | 86 +++--- core/events/events_comment_move.js | 220 ++++++++-------- core/events/events_marker_move.js | 135 +++++----- core/events/events_selected.js | 93 +++---- core/events/events_theme_change.js | 75 +++--- core/events/events_toolbox_item_select.js | 93 +++---- core/events/events_trashcan_open.js | 77 +++--- core/events/events_ui.js | 97 +++---- core/events/events_ui_base.js | 12 +- core/events/events_var_create.js | 106 ++++---- core/events/events_var_delete.js | 106 ++++---- core/events/events_var_rename.js | 108 ++++---- core/events/events_viewport.js | 139 +++++----- tests/deps.js | 40 +-- tests/deps.mocha.js | 14 +- tests/mocha/block_create_event_test.js | 3 +- tests/mocha/comment_test.js | 15 +- tests/mocha/gesture_test.js | 5 +- tests/mocha/jso_deserialization_test.js | 46 ++-- tests/mocha/test_helpers.js | 2 - tests/mocha/theme_test.js | 3 +- tests/mocha/trashcan_test.js | 14 +- tests/mocha/workspace_svg_test.js | 13 +- tests/mocha/zoom_controls_test.js | 13 +- 34 files changed, 1452 insertions(+), 1404 deletions(-) diff --git a/core/events/events_abstract.js b/core/events/events_abstract.js index d88d8efab..c20d894db 100644 --- a/core/events/events_abstract.js +++ b/core/events/events_abstract.js @@ -53,13 +53,13 @@ const Abstract = function() { * @type {boolean} */ this.recordUndo = eventUtils.getRecordUndo(); -}; -/** - * Whether or not the event is a UI event. - * @type {boolean} - */ -Abstract.prototype.isUiEvent = false; + /** + * Whether or not the event is a UI event. + * @type {boolean} + */ + this.isUiEvent = false; +}; /** * Encode the event as JSON. diff --git a/core/events/events_block_change.js b/core/events/events_block_change.js index 4a9720ad8..cf8b6d0e9 100644 --- a/core/events/events_block_change.js +++ b/core/events/events_block_change.js @@ -17,7 +17,6 @@ goog.module('Blockly.Events.BlockChange'); const Xml = goog.require('Blockly.Xml'); const eventUtils = goog.require('Blockly.Events.utils'); -const object = goog.require('Blockly.utils.object'); const registry = goog.require('Blockly.registry'); const {BlockBase} = goog.require('Blockly.Events.BlockBase'); /* eslint-disable-next-line no-unused-vars */ @@ -28,145 +27,149 @@ const {Block} = goog.requireType('Blockly.Block'); /** * Class for a block change event. - * @param {!Block=} opt_block The changed block. Undefined for a blank - * event. - * @param {string=} opt_element One of 'field', 'comment', 'disabled', etc. - * @param {?string=} opt_name Name of input or field affected, or null. - * @param {*=} opt_oldValue Previous value of element. - * @param {*=} opt_newValue New value of element. * @extends {BlockBase} - * @constructor - * @alias Blockly.Events.BlockChange */ -const BlockChange = function( - opt_block, opt_element, opt_name, opt_oldValue, opt_newValue) { - BlockChange.superClass_.constructor.call(this, opt_block); - if (!opt_block) { - return; // Blank event to be populated by fromJson. - } - this.element = typeof opt_element === 'undefined' ? '' : opt_element; - this.name = typeof opt_name === 'undefined' ? '' : opt_name; - this.oldValue = typeof opt_oldValue === 'undefined' ? '' : opt_oldValue; - this.newValue = typeof opt_newValue === 'undefined' ? '' : opt_newValue; -}; -object.inherits(BlockChange, BlockBase); +class BlockChange extends BlockBase { + /** + * @param {!Block=} opt_block The changed block. Undefined for a blank + * event. + * @param {string=} opt_element One of 'field', 'comment', 'disabled', etc. + * @param {?string=} opt_name Name of input or field affected, or null. + * @param {*=} opt_oldValue Previous value of element. + * @param {*=} opt_newValue New value of element. + * @alias Blockly.Events.BlockChange + */ + constructor(opt_block, opt_element, opt_name, opt_oldValue, opt_newValue) { + super(opt_block); -/** - * Type of this event. - * @type {string} - */ -BlockChange.prototype.type = eventUtils.BLOCK_CHANGE; + /** + * Type of this event. + * @type {string} + */ + this.type = eventUtils.BLOCK_CHANGE; -/** - * Encode the event as JSON. - * @return {!Object} JSON representation. - */ -BlockChange.prototype.toJson = function() { - const json = BlockChange.superClass_.toJson.call(this); - json['element'] = this.element; - if (this.name) { - json['name'] = this.name; - } - json['oldValue'] = this.oldValue; - json['newValue'] = this.newValue; - return json; -}; - -/** - * Decode the JSON event. - * @param {!Object} json JSON representation. - */ -BlockChange.prototype.fromJson = function(json) { - BlockChange.superClass_.fromJson.call(this, json); - this.element = json['element']; - this.name = json['name']; - this.oldValue = json['oldValue']; - this.newValue = json['newValue']; -}; - -/** - * Does this event record any change of state? - * @return {boolean} False if something changed. - */ -BlockChange.prototype.isNull = function() { - return this.oldValue === this.newValue; -}; - -/** - * Run a change event. - * @param {boolean} forward True if run forward, false if run backward (undo). - */ -BlockChange.prototype.run = function(forward) { - const workspace = this.getEventWorkspace_(); - const block = workspace.getBlockById(this.blockId); - if (!block) { - console.warn('Can\'t change non-existent block: ' + this.blockId); - return; - } - if (block.mutator) { - // Close the mutator (if open) since we don't want to update it. - block.mutator.setVisible(false); - } - const value = forward ? this.newValue : this.oldValue; - switch (this.element) { - case 'field': { - const field = block.getField(this.name); - if (field) { - field.setValue(value); - } else { - console.warn('Can\'t set non-existent field: ' + this.name); - } - break; + if (!opt_block) { + return; // Blank event to be populated by fromJson. } - case 'comment': - block.setCommentText(/** @type {string} */ (value) || null); - break; - case 'collapsed': - block.setCollapsed(!!value); - break; - case 'disabled': - block.setEnabled(!value); - break; - case 'inline': - block.setInputsInline(!!value); - break; - case 'mutation': { - const oldState = BlockChange.getExtraBlockState_( - /** @type {!BlockSvg} */ (block)); - if (block.loadExtraState) { - block.loadExtraState(JSON.parse(/** @type {string} */ (value) || '{}')); - } else if (block.domToMutation) { - block.domToMutation( - Xml.textToDom(/** @type {string} */ (value) || '')); - } - eventUtils.fire( - new BlockChange(block, 'mutation', null, oldState, value)); - break; - } - default: - console.warn('Unknown change type: ' + this.element); + this.element = typeof opt_element === 'undefined' ? '' : opt_element; + this.name = typeof opt_name === 'undefined' ? '' : opt_name; + this.oldValue = typeof opt_oldValue === 'undefined' ? '' : opt_oldValue; + this.newValue = typeof opt_newValue === 'undefined' ? '' : opt_newValue; } -}; -// TODO (#5397): Encapsulate this in the BlocklyMutationChange event when -// refactoring change events. -/** - * Returns the extra state of the given block (either as XML or a JSO, depending - * on the block's definition). - * @param {!BlockSvg} block The block to get the extra state of. - * @return {string} A stringified version of the extra state of the given block. - * @package - */ -BlockChange.getExtraBlockState_ = function(block) { - if (block.saveExtraState) { - const state = block.saveExtraState(); - return state ? JSON.stringify(state) : ''; - } else if (block.mutationToDom) { - const state = block.mutationToDom(); - return state ? Xml.domToText(state) : ''; + /** + * Encode the event as JSON. + * @return {!Object} JSON representation. + */ + toJson() { + const json = super.toJson(); + json['element'] = this.element; + if (this.name) { + json['name'] = this.name; + } + json['oldValue'] = this.oldValue; + json['newValue'] = this.newValue; + return json; } - return ''; -}; + + /** + * Decode the JSON event. + * @param {!Object} json JSON representation. + */ + fromJson(json) { + super.fromJson(json); + this.element = json['element']; + this.name = json['name']; + this.oldValue = json['oldValue']; + this.newValue = json['newValue']; + } + + /** + * Does this event record any change of state? + * @return {boolean} False if something changed. + */ + isNull() { + return this.oldValue === this.newValue; + } + + /** + * Run a change event. + * @param {boolean} forward True if run forward, false if run backward (undo). + */ + run(forward) { + const workspace = this.getEventWorkspace_(); + const block = workspace.getBlockById(this.blockId); + if (!block) { + console.warn('Can\'t change non-existent block: ' + this.blockId); + return; + } + if (block.mutator) { + // Close the mutator (if open) since we don't want to update it. + block.mutator.setVisible(false); + } + const value = forward ? this.newValue : this.oldValue; + switch (this.element) { + case 'field': { + const field = block.getField(this.name); + if (field) { + field.setValue(value); + } else { + console.warn('Can\'t set non-existent field: ' + this.name); + } + break; + } + case 'comment': + block.setCommentText(/** @type {string} */ (value) || null); + break; + case 'collapsed': + block.setCollapsed(!!value); + break; + case 'disabled': + block.setEnabled(!value); + break; + case 'inline': + block.setInputsInline(!!value); + break; + case 'mutation': { + const oldState = BlockChange.getExtraBlockState_( + /** @type {!BlockSvg} */ (block)); + if (block.loadExtraState) { + block.loadExtraState( + JSON.parse(/** @type {string} */ (value) || '{}')); + } else if (block.domToMutation) { + block.domToMutation( + Xml.textToDom(/** @type {string} */ (value) || '')); + } + eventUtils.fire( + new BlockChange(block, 'mutation', null, oldState, value)); + break; + } + default: + console.warn('Unknown change type: ' + this.element); + } + } + + // TODO (#5397): Encapsulate this in the BlocklyMutationChange event when + // refactoring change events. + /** + * Returns the extra state of the given block (either as XML or a JSO, + * depending on the block's definition). + * @param {!BlockSvg} block The block to get the extra state of. + * @return {string} A stringified version of the extra state of the given + * block. + * @package + */ + static getExtraBlockState_(block) { + if (block.saveExtraState) { + const state = block.saveExtraState(); + return state ? JSON.stringify(state) : ''; + } else if (block.mutationToDom) { + const state = block.mutationToDom(); + return state ? Xml.domToText(state) : ''; + } + return ''; + } +} registry.register(registry.Type.EVENT, eventUtils.CHANGE, BlockChange); diff --git a/core/events/events_block_create.js b/core/events/events_block_create.js index 9a3254358..19ae8128d 100644 --- a/core/events/events_block_create.js +++ b/core/events/events_block_create.js @@ -18,7 +18,6 @@ goog.module('Blockly.Events.BlockCreate'); const Xml = goog.require('Blockly.Xml'); const blocks = goog.require('Blockly.serialization.blocks'); const eventUtils = goog.require('Blockly.Events.utils'); -const object = goog.require('Blockly.utils.object'); const registry = goog.require('Blockly.registry'); const {BlockBase} = goog.require('Blockly.Events.BlockBase'); /* eslint-disable-next-line no-unused-vars */ @@ -27,90 +26,93 @@ const {Block} = goog.requireType('Blockly.Block'); /** * Class for a block creation event. - * @param {!Block=} opt_block The created block. Undefined for a blank - * event. * @extends {BlockBase} - * @constructor - * @alias Blockly.Events.BlockCreate */ -const BlockCreate = function(opt_block) { - BlockCreate.superClass_.constructor.call(this, opt_block); - if (!opt_block) { - return; // Blank event to be populated by fromJson. - } - if (opt_block.isShadow()) { - // Moving shadow blocks is handled via disconnection. - this.recordUndo = false; - } +class BlockCreate extends BlockBase { + /** + * @param {!Block=} opt_block The created block. Undefined for a blank + * event. + * @alias Blockly.Events.BlockCreate + */ + constructor(opt_block) { + super(opt_block); - this.xml = Xml.blockToDomWithXY(opt_block); - this.ids = eventUtils.getDescendantIds(opt_block); + /** + * Type of this event. + * @type {string} + */ + this.type = eventUtils.BLOCK_CREATE; + + if (!opt_block) { + return; // Blank event to be populated by fromJson. + } + if (opt_block.isShadow()) { + // Moving shadow blocks is handled via disconnection. + this.recordUndo = false; + } + + this.xml = Xml.blockToDomWithXY(opt_block); + this.ids = eventUtils.getDescendantIds(opt_block); + + /** + * JSON representation of the block that was just created. + * @type {!blocks.State} + */ + this.json = /** @type {!blocks.State} */ ( + blocks.save(opt_block, {addCoordinates: true})); + } /** - * JSON representation of the block that was just created. - * @type {!blocks.State} + * Encode the event as JSON. + * @return {!Object} JSON representation. */ - this.json = /** @type {!blocks.State} */ ( - blocks.save(opt_block, {addCoordinates: true})); -}; -object.inherits(BlockCreate, BlockBase); - -/** - * Type of this event. - * @type {string} - */ -BlockCreate.prototype.type = eventUtils.BLOCK_CREATE; - -/** - * Encode the event as JSON. - * @return {!Object} JSON representation. - */ -BlockCreate.prototype.toJson = function() { - const json = BlockCreate.superClass_.toJson.call(this); - json['xml'] = Xml.domToText(this.xml); - json['ids'] = this.ids; - json['json'] = this.json; - if (!this.recordUndo) { - json['recordUndo'] = this.recordUndo; + toJson() { + const json = super.toJson(); + json['xml'] = Xml.domToText(this.xml); + json['ids'] = this.ids; + json['json'] = this.json; + if (!this.recordUndo) { + json['recordUndo'] = this.recordUndo; + } + return json; } - return json; -}; -/** - * Decode the JSON event. - * @param {!Object} json JSON representation. - */ -BlockCreate.prototype.fromJson = function(json) { - BlockCreate.superClass_.fromJson.call(this, json); - this.xml = Xml.textToDom(json['xml']); - this.ids = json['ids']; - this.json = /** @type {!blocks.State} */ (json['json']); - if (json['recordUndo'] !== undefined) { - this.recordUndo = json['recordUndo']; + /** + * Decode the JSON event. + * @param {!Object} json JSON representation. + */ + fromJson(json) { + super.fromJson(json); + this.xml = Xml.textToDom(json['xml']); + this.ids = json['ids']; + this.json = /** @type {!blocks.State} */ (json['json']); + if (json['recordUndo'] !== undefined) { + this.recordUndo = json['recordUndo']; + } } -}; -/** - * Run a creation event. - * @param {boolean} forward True if run forward, false if run backward (undo). - */ -BlockCreate.prototype.run = function(forward) { - const workspace = this.getEventWorkspace_(); - if (forward) { - blocks.append(this.json, workspace); - } else { - for (let i = 0; i < this.ids.length; i++) { - const id = this.ids[i]; - const block = workspace.getBlockById(id); - if (block) { - block.dispose(false); - } else if (id === this.blockId) { - // Only complain about root-level block. - console.warn('Can\'t uncreate non-existent block: ' + id); + /** + * Run a creation event. + * @param {boolean} forward True if run forward, false if run backward (undo). + */ + run(forward) { + const workspace = this.getEventWorkspace_(); + if (forward) { + blocks.append(this.json, workspace); + } else { + for (let i = 0; i < this.ids.length; i++) { + const id = this.ids[i]; + const block = workspace.getBlockById(id); + if (block) { + block.dispose(false); + } else if (id === this.blockId) { + // Only complain about root-level block. + console.warn('Can\'t uncreate non-existent block: ' + id); + } } } } -}; +} registry.register(registry.Type.EVENT, eventUtils.CREATE, BlockCreate); diff --git a/core/events/events_block_delete.js b/core/events/events_block_delete.js index 80ef65d5e..633433980 100644 --- a/core/events/events_block_delete.js +++ b/core/events/events_block_delete.js @@ -18,7 +18,6 @@ goog.module('Blockly.Events.BlockDelete'); const Xml = goog.require('Blockly.Xml'); const blocks = goog.require('Blockly.serialization.blocks'); const eventUtils = goog.require('Blockly.Events.utils'); -const object = goog.require('Blockly.utils.object'); const registry = goog.require('Blockly.registry'); const {BlockBase} = goog.require('Blockly.Events.BlockBase'); /* eslint-disable-next-line no-unused-vars */ @@ -27,102 +26,105 @@ const {Block} = goog.requireType('Blockly.Block'); /** * Class for a block deletion event. - * @param {!Block=} opt_block The deleted block. Undefined for a blank - * event. * @extends {BlockBase} - * @constructor - * @alias Blockly.Events.BlockDelete */ -const BlockDelete = function(opt_block) { - BlockDelete.superClass_.constructor.call(this, opt_block); - if (!opt_block) { - return; // Blank event to be populated by fromJson. - } - if (opt_block.getParent()) { - throw Error('Connected blocks cannot be deleted.'); - } - if (opt_block.isShadow()) { - // Respawning shadow blocks is handled via disconnection. - this.recordUndo = false; - } - - this.oldXml = Xml.blockToDomWithXY(opt_block); - this.ids = eventUtils.getDescendantIds(opt_block); - +class BlockDelete extends BlockBase { /** - * Was the block that was just deleted a shadow? - * @type {boolean} + * @param {!Block=} opt_block The deleted block. Undefined for a blank + * event. + * @alias Blockly.Events.BlockDelete */ - this.wasShadow = opt_block.isShadow(); + constructor(opt_block) { + super(opt_block); - /** - * JSON representation of the block that was just deleted. - * @type {!blocks.State} - */ - this.oldJson = /** @type {!blocks.State} */ ( - blocks.save(opt_block, {addCoordinates: true})); -}; -object.inherits(BlockDelete, BlockBase); + /** + * Type of this event. + * @type {string} + */ + this.type = eventUtils.BLOCK_DELETE; -/** - * Type of this event. - * @type {string} - */ -BlockDelete.prototype.type = eventUtils.BLOCK_DELETE; - -/** - * Encode the event as JSON. - * @return {!Object} JSON representation. - */ -BlockDelete.prototype.toJson = function() { - const json = BlockDelete.superClass_.toJson.call(this); - json['oldXml'] = Xml.domToText(this.oldXml); - json['ids'] = this.ids; - json['wasShadow'] = this.wasShadow; - json['oldJson'] = this.oldJson; - if (!this.recordUndo) { - json['recordUndo'] = this.recordUndo; - } - return json; -}; - -/** - * Decode the JSON event. - * @param {!Object} json JSON representation. - */ -BlockDelete.prototype.fromJson = function(json) { - BlockDelete.superClass_.fromJson.call(this, json); - this.oldXml = Xml.textToDom(json['oldXml']); - this.ids = json['ids']; - this.wasShadow = - json['wasShadow'] || this.oldXml.tagName.toLowerCase() === 'shadow'; - this.oldJson = /** @type {!blocks.State} */ (json['oldJson']); - if (json['recordUndo'] !== undefined) { - this.recordUndo = json['recordUndo']; - } -}; - -/** - * Run a deletion event. - * @param {boolean} forward True if run forward, false if run backward (undo). - */ -BlockDelete.prototype.run = function(forward) { - const workspace = this.getEventWorkspace_(); - if (forward) { - for (let i = 0; i < this.ids.length; i++) { - const id = this.ids[i]; - const block = workspace.getBlockById(id); - if (block) { - block.dispose(false); - } else if (id === this.blockId) { - // Only complain about root-level block. - console.warn('Can\'t delete non-existent block: ' + id); - } + if (!opt_block) { + return; // Blank event to be populated by fromJson. } - } else { - blocks.append(this.oldJson, workspace); + if (opt_block.getParent()) { + throw Error('Connected blocks cannot be deleted.'); + } + if (opt_block.isShadow()) { + // Respawning shadow blocks is handled via disconnection. + this.recordUndo = false; + } + + this.oldXml = Xml.blockToDomWithXY(opt_block); + this.ids = eventUtils.getDescendantIds(opt_block); + + /** + * Was the block that was just deleted a shadow? + * @type {boolean} + */ + this.wasShadow = opt_block.isShadow(); + + /** + * JSON representation of the block that was just deleted. + * @type {!blocks.State} + */ + this.oldJson = /** @type {!blocks.State} */ ( + blocks.save(opt_block, {addCoordinates: true})); } -}; + + /** + * Encode the event as JSON. + * @return {!Object} JSON representation. + */ + toJson() { + const json = super.toJson(); + json['oldXml'] = Xml.domToText(this.oldXml); + json['ids'] = this.ids; + json['wasShadow'] = this.wasShadow; + json['oldJson'] = this.oldJson; + if (!this.recordUndo) { + json['recordUndo'] = this.recordUndo; + } + return json; + } + + /** + * Decode the JSON event. + * @param {!Object} json JSON representation. + */ + fromJson(json) { + super.fromJson(json); + this.oldXml = Xml.textToDom(json['oldXml']); + this.ids = json['ids']; + this.wasShadow = + json['wasShadow'] || this.oldXml.tagName.toLowerCase() === 'shadow'; + this.oldJson = /** @type {!blocks.State} */ (json['oldJson']); + if (json['recordUndo'] !== undefined) { + this.recordUndo = json['recordUndo']; + } + } + + /** + * Run a deletion event. + * @param {boolean} forward True if run forward, false if run backward (undo). + */ + run(forward) { + const workspace = this.getEventWorkspace_(); + if (forward) { + for (let i = 0; i < this.ids.length; i++) { + const id = this.ids[i]; + const block = workspace.getBlockById(id); + if (block) { + block.dispose(false); + } else if (id === this.blockId) { + // Only complain about root-level block. + console.warn('Can\'t delete non-existent block: ' + id); + } + } + } else { + blocks.append(this.oldJson, workspace); + } + } +} registry.register(registry.Type.EVENT, eventUtils.DELETE, BlockDelete); diff --git a/core/events/events_block_drag.js b/core/events/events_block_drag.js index 432246eb8..42fb45bee 100644 --- a/core/events/events_block_drag.js +++ b/core/events/events_block_drag.js @@ -16,7 +16,6 @@ goog.module('Blockly.Events.BlockDrag'); const eventUtils = goog.require('Blockly.Events.utils'); -const object = goog.require('Blockly.utils.object'); const registry = goog.require('Blockly.registry'); /* eslint-disable-next-line no-unused-vars */ const {Block} = goog.requireType('Blockly.Block'); @@ -25,63 +24,65 @@ const {UiBase} = goog.require('Blockly.Events.UiBase'); /** * Class for a block drag event. - * @param {!Block=} opt_block The top block in the stack that is being - * dragged. Undefined for a blank event. - * @param {boolean=} opt_isStart Whether this is the start of a block drag. - * Undefined for a blank event. - * @param {!Array=} opt_blocks The blocks affected by this - * drag. Undefined for a blank event. * @extends {UiBase} - * @constructor - * @alias Blockly.Events.BlockDrag */ -const BlockDrag = function(opt_block, opt_isStart, opt_blocks) { - const workspaceId = opt_block ? opt_block.workspace.id : undefined; - BlockDrag.superClass_.constructor.call(this, workspaceId); - this.blockId = opt_block ? opt_block.id : null; +class BlockDrag extends UiBase { + /** + * @param {!Block=} opt_block The top block in the stack that is being + * dragged. Undefined for a blank event. + * @param {boolean=} opt_isStart Whether this is the start of a block drag. + * Undefined for a blank event. + * @param {!Array=} opt_blocks The blocks affected by this + * drag. Undefined for a blank event. + * @alias Blockly.Events.BlockDrag + */ + constructor(opt_block, opt_isStart, opt_blocks) { + const workspaceId = opt_block ? opt_block.workspace.id : undefined; + super(workspaceId); + this.blockId = opt_block ? opt_block.id : null; + + /** + * Whether this is the start of a block drag. + * @type {boolean|undefined} + */ + this.isStart = opt_isStart; + + /** + * The blocks affected by this drag event. + * @type {!Array|undefined} + */ + this.blocks = opt_blocks; + + /** + * Type of this event. + * @type {string} + */ + this.type = eventUtils.BLOCK_DRAG; + } /** - * Whether this is the start of a block drag. - * @type {boolean|undefined} + * Encode the event as JSON. + * @return {!Object} JSON representation. */ - this.isStart = opt_isStart; + toJson() { + const json = super.toJson(); + json['isStart'] = this.isStart; + json['blockId'] = this.blockId; + json['blocks'] = this.blocks; + return json; + } /** - * The blocks affected by this drag event. - * @type {!Array|undefined} + * Decode the JSON event. + * @param {!Object} json JSON representation. */ - this.blocks = opt_blocks; -}; -object.inherits(BlockDrag, UiBase); - -/** - * Type of this event. - * @type {string} - */ -BlockDrag.prototype.type = eventUtils.BLOCK_DRAG; - -/** - * Encode the event as JSON. - * @return {!Object} JSON representation. - */ -BlockDrag.prototype.toJson = function() { - const json = BlockDrag.superClass_.toJson.call(this); - json['isStart'] = this.isStart; - json['blockId'] = this.blockId; - json['blocks'] = this.blocks; - return json; -}; - -/** - * Decode the JSON event. - * @param {!Object} json JSON representation. - */ -BlockDrag.prototype.fromJson = function(json) { - BlockDrag.superClass_.fromJson.call(this, json); - this.isStart = json['isStart']; - this.blockId = json['blockId']; - this.blocks = json['blocks']; -}; + fromJson(json) { + super.fromJson(json); + this.isStart = json['isStart']; + this.blockId = json['blockId']; + this.blocks = json['blocks']; + } +} registry.register(registry.Type.EVENT, eventUtils.BLOCK_DRAG, BlockDrag); diff --git a/core/events/events_block_move.js b/core/events/events_block_move.js index a90d74bd2..c0a7adb95 100644 --- a/core/events/events_block_move.js +++ b/core/events/events_block_move.js @@ -16,7 +16,6 @@ goog.module('Blockly.Events.BlockMove'); const eventUtils = goog.require('Blockly.Events.utils'); -const object = goog.require('Blockly.utils.object'); const registry = goog.require('Blockly.registry'); const {BlockBase} = goog.require('Blockly.Events.BlockBase'); /* eslint-disable-next-line no-unused-vars */ @@ -27,168 +26,176 @@ const {Coordinate} = goog.require('Blockly.utils.Coordinate'); /** * Class for a block move event. Created before the move. - * @param {!Block=} opt_block The moved block. Undefined for a blank - * event. * @extends {BlockBase} - * @constructor - * @alias Blockly.Events.BlockMove */ -const BlockMove = function(opt_block) { - BlockMove.superClass_.constructor.call(this, opt_block); - if (!opt_block) { - return; // Blank event to be populated by fromJson. - } - if (opt_block.isShadow()) { - // Moving shadow blocks is handled via disconnection. - this.recordUndo = false; - } +class BlockMove extends BlockBase { + /** + * @param {!Block=} opt_block The moved block. Undefined for a blank + * event. + * @alias Blockly.Events.BlockMove + */ + constructor(opt_block) { + super(opt_block); - const location = this.currentLocation_(); - this.oldParentId = location.parentId; - this.oldInputName = location.inputName; - this.oldCoordinate = location.coordinate; -}; -object.inherits(BlockMove, BlockBase); + /** + * Type of this event. + * @type {string} + */ + this.type = eventUtils.BLOCK_MOVE; -/** - * Type of this event. - * @type {string} - */ -BlockMove.prototype.type = eventUtils.BLOCK_MOVE; - -/** - * Encode the event as JSON. - * @return {!Object} JSON representation. - */ -BlockMove.prototype.toJson = function() { - const json = BlockMove.superClass_.toJson.call(this); - if (this.newParentId) { - json['newParentId'] = this.newParentId; - } - if (this.newInputName) { - json['newInputName'] = this.newInputName; - } - if (this.newCoordinate) { - json['newCoordinate'] = Math.round(this.newCoordinate.x) + ',' + - Math.round(this.newCoordinate.y); - } - if (!this.recordUndo) { - json['recordUndo'] = this.recordUndo; - } - return json; -}; - -/** - * Decode the JSON event. - * @param {!Object} json JSON representation. - */ -BlockMove.prototype.fromJson = function(json) { - BlockMove.superClass_.fromJson.call(this, json); - this.newParentId = json['newParentId']; - this.newInputName = json['newInputName']; - if (json['newCoordinate']) { - const xy = json['newCoordinate'].split(','); - this.newCoordinate = new Coordinate(Number(xy[0]), Number(xy[1])); - } - if (json['recordUndo'] !== undefined) { - this.recordUndo = json['recordUndo']; - } -}; - -/** - * Record the block's new location. Called after the move. - */ -BlockMove.prototype.recordNew = function() { - const location = this.currentLocation_(); - this.newParentId = location.parentId; - this.newInputName = location.inputName; - this.newCoordinate = location.coordinate; -}; - -/** - * Returns the parentId and input if the block is connected, - * or the XY location if disconnected. - * @return {!Object} Collection of location info. - * @private - */ -BlockMove.prototype.currentLocation_ = function() { - const workspace = this.getEventWorkspace_(); - const block = workspace.getBlockById(this.blockId); - const location = {}; - const parent = block.getParent(); - if (parent) { - location.parentId = parent.id; - const input = parent.getInputWithBlock(block); - if (input) { - location.inputName = input.name; + if (!opt_block) { + return; // Blank event to be populated by fromJson. + } + if (opt_block.isShadow()) { + // Moving shadow blocks is handled via disconnection. + this.recordUndo = false; } - } else { - location.coordinate = block.getRelativeToSurfaceXY(); - } - return location; -}; -/** - * Does this event record any change of state? - * @return {boolean} False if something changed. - */ -BlockMove.prototype.isNull = function() { - return this.oldParentId === this.newParentId && - this.oldInputName === this.newInputName && - Coordinate.equals(this.oldCoordinate, this.newCoordinate); -}; + const location = this.currentLocation_(); + this.oldParentId = location.parentId; + this.oldInputName = location.inputName; + this.oldCoordinate = location.coordinate; -/** - * Run a move event. - * @param {boolean} forward True if run forward, false if run backward (undo). - */ -BlockMove.prototype.run = function(forward) { - const workspace = this.getEventWorkspace_(); - const block = workspace.getBlockById(this.blockId); - if (!block) { - console.warn('Can\'t move non-existent block: ' + this.blockId); - return; + this.newParentId = null; + this.newInputName = null; + this.newCoordinate = null; } - const parentId = forward ? this.newParentId : this.oldParentId; - const inputName = forward ? this.newInputName : this.oldInputName; - const coordinate = forward ? this.newCoordinate : this.oldCoordinate; - let parentBlock; - if (parentId) { - parentBlock = workspace.getBlockById(parentId); - if (!parentBlock) { - console.warn('Can\'t connect to non-existent block: ' + parentId); + + /** + * Encode the event as JSON. + * @return {!Object} JSON representation. + */ + toJson() { + const json = super.toJson(); + if (this.newParentId) { + json['newParentId'] = this.newParentId; + } + if (this.newInputName) { + json['newInputName'] = this.newInputName; + } + if (this.newCoordinate) { + json['newCoordinate'] = Math.round(this.newCoordinate.x) + ',' + + Math.round(this.newCoordinate.y); + } + if (!this.recordUndo) { + json['recordUndo'] = this.recordUndo; + } + return json; + } + + /** + * Decode the JSON event. + * @param {!Object} json JSON representation. + */ + fromJson(json) { + super.fromJson(json); + this.newParentId = json['newParentId']; + this.newInputName = json['newInputName']; + if (json['newCoordinate']) { + const xy = json['newCoordinate'].split(','); + this.newCoordinate = new Coordinate(Number(xy[0]), Number(xy[1])); + } + if (json['recordUndo'] !== undefined) { + this.recordUndo = json['recordUndo']; + } + } + + /** + * Record the block's new location. Called after the move. + */ + recordNew() { + const location = this.currentLocation_(); + this.newParentId = location.parentId; + this.newInputName = location.inputName; + this.newCoordinate = location.coordinate; + } + + /** + * Returns the parentId and input if the block is connected, + * or the XY location if disconnected. + * @return {!Object} Collection of location info. + * @private + */ + currentLocation_() { + const workspace = this.getEventWorkspace_(); + const block = workspace.getBlockById(this.blockId); + const location = {}; + const parent = block.getParent(); + if (parent) { + location.parentId = parent.id; + const input = parent.getInputWithBlock(block); + if (input) { + location.inputName = input.name; + } + } else { + location.coordinate = block.getRelativeToSurfaceXY(); + } + return location; + } + + /** + * Does this event record any change of state? + * @return {boolean} False if something changed. + */ + isNull() { + return this.oldParentId === this.newParentId && + this.oldInputName === this.newInputName && + Coordinate.equals(this.oldCoordinate, this.newCoordinate); + } + + /** + * Run a move event. + * @param {boolean} forward True if run forward, false if run backward (undo). + */ + run(forward) { + const workspace = this.getEventWorkspace_(); + const block = workspace.getBlockById(this.blockId); + if (!block) { + console.warn('Can\'t move non-existent block: ' + this.blockId); return; } - } - if (block.getParent()) { - block.unplug(); - } - if (coordinate) { - const xy = block.getRelativeToSurfaceXY(); - block.moveBy(coordinate.x - xy.x, coordinate.y - xy.y); - } else { - let blockConnection = block.outputConnection; - if (!blockConnection || - (block.previousConnection && block.previousConnection.isConnected())) { - blockConnection = block.previousConnection; - } - let parentConnection; - const connectionType = blockConnection.type; - if (inputName) { - const input = parentBlock.getInput(inputName); - if (input) { - parentConnection = input.connection; + const parentId = forward ? this.newParentId : this.oldParentId; + const inputName = forward ? this.newInputName : this.oldInputName; + const coordinate = forward ? this.newCoordinate : this.oldCoordinate; + let parentBlock; + if (parentId) { + parentBlock = workspace.getBlockById(parentId); + if (!parentBlock) { + console.warn('Can\'t connect to non-existent block: ' + parentId); + return; } - } else if (connectionType === ConnectionType.PREVIOUS_STATEMENT) { - parentConnection = parentBlock.nextConnection; } - if (parentConnection) { - blockConnection.connect(parentConnection); + if (block.getParent()) { + block.unplug(); + } + if (coordinate) { + const xy = block.getRelativeToSurfaceXY(); + block.moveBy(coordinate.x - xy.x, coordinate.y - xy.y); } else { - console.warn('Can\'t connect to non-existent input: ' + inputName); + let blockConnection = block.outputConnection; + if (!blockConnection || + (block.previousConnection && + block.previousConnection.isConnected())) { + blockConnection = block.previousConnection; + } + let parentConnection; + const connectionType = blockConnection.type; + if (inputName) { + const input = parentBlock.getInput(inputName); + if (input) { + parentConnection = input.connection; + } + } else if (connectionType === ConnectionType.PREVIOUS_STATEMENT) { + parentConnection = parentBlock.nextConnection; + } + if (parentConnection) { + blockConnection.connect(parentConnection); + } else { + console.warn('Can\'t connect to non-existent input: ' + inputName); + } } } -}; +} registry.register(registry.Type.EVENT, eventUtils.MOVE, BlockMove); diff --git a/core/events/events_bubble_open.js b/core/events/events_bubble_open.js index 9c76fd751..95099951c 100644 --- a/core/events/events_bubble_open.js +++ b/core/events/events_bubble_open.js @@ -52,15 +52,15 @@ const BubbleOpen = function(opt_block, opt_isOpen, opt_bubbleType) { * @type {string|undefined} */ this.bubbleType = opt_bubbleType; + + /** + * Type of this event. + * @type {string} + */ + this.type = eventUtils.BUBBLE_OPEN; }; object.inherits(BubbleOpen, UiBase); -/** - * Type of this event. - * @type {string} - */ -BubbleOpen.prototype.type = eventUtils.BUBBLE_OPEN; - /** * Encode the event as JSON. * @return {!Object} JSON representation. diff --git a/core/events/events_click.js b/core/events/events_click.js index 0bc9aa972..a855ea63c 100644 --- a/core/events/events_click.js +++ b/core/events/events_click.js @@ -16,7 +16,6 @@ goog.module('Blockly.Events.Click'); const eventUtils = goog.require('Blockly.Events.utils'); -const object = goog.require('Blockly.utils.object'); const registry = goog.require('Blockly.registry'); /* eslint-disable-next-line no-unused-vars */ const {Block} = goog.requireType('Blockly.Block'); @@ -25,58 +24,63 @@ const {UiBase} = goog.require('Blockly.Events.UiBase'); /** * Class for a click event. - * @param {?Block=} opt_block The affected block. Null for click events - * that do not have an associated block (i.e. workspace click). Undefined - * for a blank event. - * @param {?string=} opt_workspaceId The workspace identifier for this event. - * Not used if block is passed. Undefined for a blank event. - * @param {string=} opt_targetType The type of element targeted by this click - * event. Undefined for a blank event. * @extends {UiBase} - * @constructor - * @alias Blockly.Events.Click */ -const Click = function(opt_block, opt_workspaceId, opt_targetType) { - const workspaceId = opt_block ? opt_block.workspace.id : opt_workspaceId; - Click.superClass_.constructor.call(this, workspaceId); - this.blockId = opt_block ? opt_block.id : null; +class Click extends UiBase { + /** + * @param {?Block=} opt_block The affected block. Null for click events + * that do not have an associated block (i.e. workspace click). Undefined + * for a blank event. + * @param {?string=} opt_workspaceId The workspace identifier for this event. + * Not used if block is passed. Undefined for a blank event. + * @param {string=} opt_targetType The type of element targeted by this click + * event. Undefined for a blank event. + * @alias Blockly.Events.Click + */ + constructor(opt_block, opt_workspaceId, opt_targetType) { + let workspaceId = opt_block ? opt_block.workspace.id : opt_workspaceId; + if (workspaceId === null) { + workspaceId = undefined; + } + super(workspaceId); + this.blockId = opt_block ? opt_block.id : null; + + /** + * The type of element targeted by this click event. + * @type {string|undefined} + */ + this.targetType = opt_targetType; + + /** + * Type of this event. + * @type {string} + */ + this.type = eventUtils.CLICK; + } /** - * The type of element targeted by this click event. - * @type {string|undefined} + * Encode the event as JSON. + * @return {!Object} JSON representation. */ - this.targetType = opt_targetType; -}; -object.inherits(Click, UiBase); - -/** - * Type of this event. - * @type {string} - */ -Click.prototype.type = eventUtils.CLICK; - -/** - * Encode the event as JSON. - * @return {!Object} JSON representation. - */ -Click.prototype.toJson = function() { - const json = Click.superClass_.toJson.call(this); - json['targetType'] = this.targetType; - if (this.blockId) { - json['blockId'] = this.blockId; + toJson() { + const json = super.toJson(); + json['targetType'] = this.targetType; + if (this.blockId) { + json['blockId'] = this.blockId; + } + return json; } - return json; -}; -/** - * Decode the JSON event. - * @param {!Object} json JSON representation. - */ -Click.prototype.fromJson = function(json) { - Click.superClass_.fromJson.call(this, json); - this.targetType = json['targetType']; - this.blockId = json['blockId']; -}; + /** + * Decode the JSON event. + * @param {!Object} json JSON representation. + */ + fromJson(json) { + super.fromJson(json); + this.targetType = json['targetType']; + this.blockId = json['blockId']; + } +} registry.register(registry.Type.EVENT, eventUtils.CLICK, Click); diff --git a/core/events/events_comment_change.js b/core/events/events_comment_change.js index 1f6b44ba3..ec6b54e05 100644 --- a/core/events/events_comment_change.js +++ b/core/events/events_comment_change.js @@ -16,7 +16,6 @@ goog.module('Blockly.Events.CommentChange'); const eventUtils = goog.require('Blockly.Events.utils'); -const object = goog.require('Blockly.utils.object'); const registry = goog.require('Blockly.registry'); const {CommentBase} = goog.require('Blockly.Events.CommentBase'); /* eslint-disable-next-line no-unused-vars */ @@ -25,77 +24,80 @@ const {WorkspaceComment} = goog.requireType('Blockly.WorkspaceComment'); /** * Class for a comment change event. - * @param {!WorkspaceComment=} opt_comment The comment that is being - * changed. Undefined for a blank event. - * @param {string=} opt_oldContents Previous contents of the comment. - * @param {string=} opt_newContents New contents of the comment. * @extends {CommentBase} - * @constructor - * @alias Blockly.Events.CommentChange */ -const CommentChange = function(opt_comment, opt_oldContents, opt_newContents) { - CommentChange.superClass_.constructor.call(this, opt_comment); - if (!opt_comment) { - return; // Blank event to be populated by fromJson. +class CommentChange extends CommentBase { + /** + * @param {!WorkspaceComment=} opt_comment The comment that is being + * changed. Undefined for a blank event. + * @param {string=} opt_oldContents Previous contents of the comment. + * @param {string=} opt_newContents New contents of the comment. + * @alias Blockly.Events.CommentChange + */ + constructor(opt_comment, opt_oldContents, opt_newContents) { + super(opt_comment); + + /** + * Type of this event. + * @type {string} + */ + this.type = eventUtils.COMMENT_CHANGE; + + if (!opt_comment) { + return; // Blank event to be populated by fromJson. + } + + this.oldContents_ = + typeof opt_oldContents === 'undefined' ? '' : opt_oldContents; + this.newContents_ = + typeof opt_newContents === 'undefined' ? '' : opt_newContents; } - this.oldContents_ = - typeof opt_oldContents === 'undefined' ? '' : opt_oldContents; - this.newContents_ = - typeof opt_newContents === 'undefined' ? '' : opt_newContents; -}; -object.inherits(CommentChange, CommentBase); - -/** - * Type of this event. - * @type {string} - */ -CommentChange.prototype.type = eventUtils.COMMENT_CHANGE; - -/** - * Encode the event as JSON. - * @return {!Object} JSON representation. - */ -CommentChange.prototype.toJson = function() { - const json = CommentChange.superClass_.toJson.call(this); - json['oldContents'] = this.oldContents_; - json['newContents'] = this.newContents_; - return json; -}; - -/** - * Decode the JSON event. - * @param {!Object} json JSON representation. - */ -CommentChange.prototype.fromJson = function(json) { - CommentChange.superClass_.fromJson.call(this, json); - this.oldContents_ = json['oldContents']; - this.newContents_ = json['newContents']; -}; - -/** - * Does this event record any change of state? - * @return {boolean} False if something changed. - */ -CommentChange.prototype.isNull = function() { - return this.oldContents_ === this.newContents_; -}; - -/** - * Run a change event. - * @param {boolean} forward True if run forward, false if run backward (undo). - */ -CommentChange.prototype.run = function(forward) { - const workspace = this.getEventWorkspace_(); - const comment = workspace.getCommentById(this.commentId); - if (!comment) { - console.warn('Can\'t change non-existent comment: ' + this.commentId); - return; + /** + * Encode the event as JSON. + * @return {!Object} JSON representation. + */ + toJson() { + const json = super.toJson(); + json['oldContents'] = this.oldContents_; + json['newContents'] = this.newContents_; + return json; } - const contents = forward ? this.newContents_ : this.oldContents_; - comment.setContent(contents); -}; + /** + * Decode the JSON event. + * @param {!Object} json JSON representation. + */ + fromJson(json) { + super.fromJson(json); + this.oldContents_ = json['oldContents']; + this.newContents_ = json['newContents']; + } + + /** + * Does this event record any change of state? + * @return {boolean} False if something changed. + */ + isNull() { + return this.oldContents_ === this.newContents_; + } + + /** + * Run a change event. + * @param {boolean} forward True if run forward, false if run backward (undo). + */ + run(forward) { + const workspace = this.getEventWorkspace_(); + const comment = workspace.getCommentById(this.commentId); + if (!comment) { + console.warn('Can\'t change non-existent comment: ' + this.commentId); + return; + } + const contents = forward ? this.newContents_ : this.oldContents_; + + comment.setContent(contents); + } +} registry.register( registry.Type.EVENT, eventUtils.COMMENT_CHANGE, CommentChange); diff --git a/core/events/events_comment_create.js b/core/events/events_comment_create.js index 5d9cb8d79..f3d15659b 100644 --- a/core/events/events_comment_create.js +++ b/core/events/events_comment_create.js @@ -17,7 +17,6 @@ goog.module('Blockly.Events.CommentCreate'); const Xml = goog.require('Blockly.Xml'); const eventUtils = goog.require('Blockly.Events.utils'); -const object = goog.require('Blockly.utils.object'); const registry = goog.require('Blockly.registry'); const {CommentBase} = goog.require('Blockly.Events.CommentBase'); /* eslint-disable-next-line no-unused-vars */ @@ -26,55 +25,58 @@ const {WorkspaceComment} = goog.requireType('Blockly.WorkspaceComment'); /** * Class for a comment creation event. - * @param {!WorkspaceComment=} opt_comment The created comment. - * Undefined for a blank event. * @extends {CommentBase} - * @constructor - * @alias Blockly.Events.CommentCreate */ -const CommentCreate = function(opt_comment) { - CommentCreate.superClass_.constructor.call(this, opt_comment); - if (!opt_comment) { - return; // Blank event to be populated by fromJson. +class CommentCreate extends CommentBase { + /** + * @param {!WorkspaceComment=} opt_comment The created comment. + * Undefined for a blank event. + * @alias Blockly.Events.CommentCreate + */ + constructor(opt_comment) { + super(opt_comment); + + /** + * Type of this event. + * @type {string} + */ + this.type = eventUtils.COMMENT_CREATE; + + if (!opt_comment) { + return; // Blank event to be populated by fromJson. + } + + this.xml = opt_comment.toXmlWithXY(); } - this.xml = opt_comment.toXmlWithXY(); -}; -object.inherits(CommentCreate, CommentBase); + // TODO (#1266): "Full" and "minimal" serialization. + /** + * Encode the event as JSON. + * @return {!Object} JSON representation. + */ + toJson() { + const json = super.toJson(); + json['xml'] = Xml.domToText(this.xml); + return json; + } -/** - * Type of this event. - * @type {string} - */ -CommentCreate.prototype.type = eventUtils.COMMENT_CREATE; + /** + * Decode the JSON event. + * @param {!Object} json JSON representation. + */ + fromJson(json) { + super.fromJson(json); + this.xml = Xml.textToDom(json['xml']); + } -/** - * Encode the event as JSON. - * @return {!Object} JSON representation. - */ -// TODO (#1266): "Full" and "minimal" serialization. -CommentCreate.prototype.toJson = function() { - const json = CommentCreate.superClass_.toJson.call(this); - json['xml'] = Xml.domToText(this.xml); - return json; -}; - -/** - * Decode the JSON event. - * @param {!Object} json JSON representation. - */ -CommentCreate.prototype.fromJson = function(json) { - CommentCreate.superClass_.fromJson.call(this, json); - this.xml = Xml.textToDom(json['xml']); -}; - -/** - * Run a creation event. - * @param {boolean} forward True if run forward, false if run backward (undo). - */ -CommentCreate.prototype.run = function(forward) { - CommentBase.CommentCreateDeleteHelper(this, forward); -}; + /** + * Run a creation event. + * @param {boolean} forward True if run forward, false if run backward (undo). + */ + run(forward) { + CommentBase.CommentCreateDeleteHelper(this, forward); + } +} registry.register( registry.Type.EVENT, eventUtils.COMMENT_CREATE, CommentCreate); diff --git a/core/events/events_comment_delete.js b/core/events/events_comment_delete.js index 54e1df4ba..fc426ca5e 100644 --- a/core/events/events_comment_delete.js +++ b/core/events/events_comment_delete.js @@ -16,7 +16,6 @@ goog.module('Blockly.Events.CommentDelete'); const eventUtils = goog.require('Blockly.Events.utils'); -const object = goog.require('Blockly.utils.object'); const registry = goog.require('Blockly.registry'); const {CommentBase} = goog.require('Blockly.Events.CommentBase'); /* eslint-disable-next-line no-unused-vars */ @@ -25,53 +24,56 @@ const {WorkspaceComment} = goog.requireType('Blockly.WorkspaceComment'); /** * Class for a comment deletion event. - * @param {!WorkspaceComment=} opt_comment The deleted comment. - * Undefined for a blank event. * @extends {CommentBase} - * @constructor - * @alias Blockly.Events.CommentDelete */ -const CommentDelete = function(opt_comment) { - CommentDelete.superClass_.constructor.call(this, opt_comment); - if (!opt_comment) { - return; // Blank event to be populated by fromJson. +class CommentDelete extends CommentBase { + /** + * @param {!WorkspaceComment=} opt_comment The deleted comment. + * Undefined for a blank event. + * @alias Blockly.Events.CommentDelete + */ + constructor(opt_comment) { + super(opt_comment); + + /** + * Type of this event. + * @type {string} + */ + this.type = eventUtils.COMMENT_DELETE; + + if (!opt_comment) { + return; // Blank event to be populated by fromJson. + } + + this.xml = opt_comment.toXmlWithXY(); } - this.xml = opt_comment.toXmlWithXY(); -}; -object.inherits(CommentDelete, CommentBase); + // TODO (#1266): "Full" and "minimal" serialization. + /** + * Encode the event as JSON. + * @return {!Object} JSON representation. + */ + toJson() { + const json = super.toJson(); + return json; + } -/** - * Type of this event. - * @type {string} - */ -CommentDelete.prototype.type = eventUtils.COMMENT_DELETE; + /** + * Decode the JSON event. + * @param {!Object} json JSON representation. + */ + fromJson(json) { + super.fromJson(json); + } -/** - * Encode the event as JSON. - * @return {!Object} JSON representation. - */ -// TODO (#1266): "Full" and "minimal" serialization. -CommentDelete.prototype.toJson = function() { - const json = CommentDelete.superClass_.toJson.call(this); - return json; -}; - -/** - * Decode the JSON event. - * @param {!Object} json JSON representation. - */ -CommentDelete.prototype.fromJson = function(json) { - CommentDelete.superClass_.fromJson.call(this, json); -}; - -/** - * Run a creation event. - * @param {boolean} forward True if run forward, false if run backward (undo). - */ -CommentDelete.prototype.run = function(forward) { - CommentBase.CommentCreateDeleteHelper(this, !forward); -}; + /** + * Run a creation event. + * @param {boolean} forward True if run forward, false if run backward (undo). + */ + run(forward) { + CommentBase.CommentCreateDeleteHelper(this, !forward); + } +} registry.register( registry.Type.EVENT, eventUtils.COMMENT_DELETE, CommentDelete); diff --git a/core/events/events_comment_move.js b/core/events/events_comment_move.js index 51ba01ab6..7545c619f 100644 --- a/core/events/events_comment_move.js +++ b/core/events/events_comment_move.js @@ -16,7 +16,6 @@ goog.module('Blockly.Events.CommentMove'); const eventUtils = goog.require('Blockly.Events.utils'); -const object = goog.require('Blockly.utils.object'); const registry = goog.require('Blockly.registry'); const {CommentBase} = goog.require('Blockly.Events.CommentBase'); const {Coordinate} = goog.require('Blockly.utils.Coordinate'); @@ -26,129 +25,132 @@ const {WorkspaceComment} = goog.requireType('Blockly.WorkspaceComment'); /** * Class for a comment move event. Created before the move. - * @param {!WorkspaceComment=} opt_comment The comment that is being - * moved. Undefined for a blank event. * @extends {CommentBase} - * @constructor - * @alias Blockly.Events.CommentMove */ -const CommentMove = function(opt_comment) { - CommentMove.superClass_.constructor.call(this, opt_comment); - if (!opt_comment) { - return; // Blank event to be populated by fromJson. +class CommentMove extends CommentBase { + /** + * @param {!WorkspaceComment=} opt_comment The comment that is being + * moved. Undefined for a blank event. + * @alias Blockly.Events.CommentMove + */ + constructor(opt_comment) { + super(opt_comment); + + /** + * Type of this event. + * @type {string} + */ + this.type = eventUtils.COMMENT_MOVE; + + if (!opt_comment) { + return; // Blank event to be populated by fromJson. + } + + /** + * The comment that is being moved. Will be cleared after recording the new + * location. + * @type {WorkspaceComment} + */ + this.comment_ = opt_comment; + + /** + * The location before the move, in workspace coordinates. + * @type {!Coordinate} + */ + this.oldCoordinate_ = opt_comment.getXY(); + + /** + * The location after the move, in workspace coordinates. + * @type {Coordinate} + */ + this.newCoordinate_ = null; } /** - * The comment that is being moved. Will be cleared after recording the new - * location. - * @type {WorkspaceComment} + * Record the comment's new location. Called after the move. Can only be + * called once. */ - this.comment_ = opt_comment; + recordNew() { + 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; + } /** - * The location before the move, in workspace coordinates. - * @type {!Coordinate} + * Override the location before the move. Use this if you don't create the + * event until the end of the move, but you know the original location. + * @param {!Coordinate} xy The location before the move, + * in workspace coordinates. */ - this.oldCoordinate_ = opt_comment.getXY(); + setOldCoordinate(xy) { + this.oldCoordinate_ = xy; + } + + // TODO (#1266): "Full" and "minimal" serialization. + /** + * Encode the event as JSON. + * @return {!Object} JSON representation. + */ + toJson() { + const json = super.toJson(); + if (this.oldCoordinate_) { + json['oldCoordinate'] = Math.round(this.oldCoordinate_.x) + ',' + + Math.round(this.oldCoordinate_.y); + } + if (this.newCoordinate_) { + json['newCoordinate'] = Math.round(this.newCoordinate_.x) + ',' + + Math.round(this.newCoordinate_.y); + } + return json; + } /** - * The location after the move, in workspace coordinates. - * @type {Coordinate} + * Decode the JSON event. + * @param {!Object} json JSON representation. */ - this.newCoordinate_ = null; -}; -object.inherits(CommentMove, CommentBase); + fromJson(json) { + super.fromJson(json); -/** - * Record the comment's new location. Called after the move. Can only be - * called once. - */ -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; -}; - -/** - * Type of this event. - * @type {string} - */ -CommentMove.prototype.type = eventUtils.COMMENT_MOVE; - -/** - * Override the location before the move. Use this if you don't create the - * event until the end of the move, but you know the original location. - * @param {!Coordinate} xy The location before the move, - * in workspace coordinates. - */ -CommentMove.prototype.setOldCoordinate = function(xy) { - this.oldCoordinate_ = xy; -}; - -/** - * Encode the event as JSON. - * @return {!Object} JSON representation. - */ -// TODO (#1266): "Full" and "minimal" serialization. -CommentMove.prototype.toJson = function() { - const json = CommentMove.superClass_.toJson.call(this); - if (this.oldCoordinate_) { - json['oldCoordinate'] = Math.round(this.oldCoordinate_.x) + ',' + - Math.round(this.oldCoordinate_.y); - } - if (this.newCoordinate_) { - json['newCoordinate'] = Math.round(this.newCoordinate_.x) + ',' + - Math.round(this.newCoordinate_.y); - } - return json; -}; - -/** - * Decode the JSON event. - * @param {!Object} json JSON representation. - */ -CommentMove.prototype.fromJson = function(json) { - CommentMove.superClass_.fromJson.call(this, json); - - if (json['oldCoordinate']) { - const xy = json['oldCoordinate'].split(','); - this.oldCoordinate_ = new Coordinate(Number(xy[0]), Number(xy[1])); - } - if (json['newCoordinate']) { - const xy = json['newCoordinate'].split(','); - this.newCoordinate_ = new Coordinate(Number(xy[0]), Number(xy[1])); - } -}; - -/** - * Does this event record any change of state? - * @return {boolean} False if something changed. - */ -CommentMove.prototype.isNull = function() { - return Coordinate.equals(this.oldCoordinate_, this.newCoordinate_); -}; - -/** - * Run a move event. - * @param {boolean} forward True if run forward, false if run backward (undo). - */ -CommentMove.prototype.run = function(forward) { - const workspace = this.getEventWorkspace_(); - const comment = workspace.getCommentById(this.commentId); - if (!comment) { - console.warn('Can\'t move non-existent comment: ' + this.commentId); - return; + if (json['oldCoordinate']) { + const xy = json['oldCoordinate'].split(','); + this.oldCoordinate_ = new Coordinate(Number(xy[0]), Number(xy[1])); + } + if (json['newCoordinate']) { + const xy = json['newCoordinate'].split(','); + this.newCoordinate_ = new Coordinate(Number(xy[0]), Number(xy[1])); + } } - const target = forward ? this.newCoordinate_ : this.oldCoordinate_; - // TODO: Check if the comment is being dragged, and give up if so. - const current = comment.getXY(); - comment.moveBy(target.x - current.x, target.y - current.y); -}; + /** + * Does this event record any change of state? + * @return {boolean} False if something changed. + */ + isNull() { + return Coordinate.equals(this.oldCoordinate_, this.newCoordinate_); + } + + /** + * Run a move event. + * @param {boolean} forward True if run forward, false if run backward (undo). + */ + run(forward) { + const workspace = this.getEventWorkspace_(); + const comment = workspace.getCommentById(this.commentId); + if (!comment) { + console.warn('Can\'t move non-existent comment: ' + this.commentId); + return; + } + + const target = forward ? this.newCoordinate_ : this.oldCoordinate_; + // TODO: Check if the comment is being dragged, and give up if so. + const current = comment.getXY(); + comment.moveBy(target.x - current.x, target.y - current.y); + } +} registry.register(registry.Type.EVENT, eventUtils.COMMENT_MOVE, CommentMove); diff --git a/core/events/events_marker_move.js b/core/events/events_marker_move.js index 97f473d95..214d666ee 100644 --- a/core/events/events_marker_move.js +++ b/core/events/events_marker_move.js @@ -16,7 +16,6 @@ goog.module('Blockly.Events.MarkerMove'); const eventUtils = goog.require('Blockly.Events.utils'); -const object = goog.require('Blockly.utils.object'); const registry = goog.require('Blockly.registry'); const {ASTNode} = goog.require('Blockly.ASTNode'); /* eslint-disable-next-line no-unused-vars */ @@ -28,81 +27,83 @@ const {Workspace} = goog.requireType('Blockly.Workspace'); /** * Class for a marker move event. - * @param {?Block=} opt_block The affected block. Null if current node - * is of type workspace. Undefined for a blank event. - * @param {boolean=} isCursor Whether this is a cursor event. Undefined for a - * blank event. - * @param {?ASTNode=} opt_oldNode The old node the marker used to be on. - * Undefined for a blank event. - * @param {!ASTNode=} opt_newNode The new node the marker is now on. - * Undefined for a blank event. * @extends {UiBase} - * @constructor - * @alias Blockly.Events.MarkerMove */ -const MarkerMove = function(opt_block, isCursor, opt_oldNode, opt_newNode) { - let workspaceId = opt_block ? opt_block.workspace.id : undefined; - if (opt_newNode && opt_newNode.getType() === ASTNode.types.WORKSPACE) { - workspaceId = (/** @type {!Workspace} */ (opt_newNode.getLocation())).id; +class MarkerMove extends UiBase { + /** + * @param {?Block=} opt_block The affected block. Null if current node + * is of type workspace. Undefined for a blank event. + * @param {boolean=} isCursor Whether this is a cursor event. Undefined for a + * blank event. + * @param {?ASTNode=} opt_oldNode The old node the marker used to be on. + * Undefined for a blank event. + * @param {!ASTNode=} opt_newNode The new node the marker is now on. + * Undefined for a blank event. + * @alias Blockly.Events.MarkerMove + */ + constructor(opt_block, isCursor, opt_oldNode, opt_newNode) { + let workspaceId = opt_block ? opt_block.workspace.id : undefined; + if (opt_newNode && opt_newNode.getType() === ASTNode.types.WORKSPACE) { + workspaceId = (/** @type {!Workspace} */ (opt_newNode.getLocation())).id; + } + super(workspaceId); + + /** + * The workspace identifier for this event. + * @type {?string} + */ + this.blockId = opt_block ? opt_block.id : null; + + /** + * The old node the marker used to be on. + * @type {?ASTNode|undefined} + */ + this.oldNode = opt_oldNode; + + /** + * The new node the marker is now on. + * @type {ASTNode|undefined} + */ + this.newNode = opt_newNode; + + /** + * Whether this is a cursor event. + * @type {boolean|undefined} + */ + this.isCursor = isCursor; + + /** + * Type of this event. + * @type {string} + */ + this.type = eventUtils.MARKER_MOVE; } - MarkerMove.superClass_.constructor.call(this, workspaceId); /** - * The workspace identifier for this event. - * @type {?string} + * Encode the event as JSON. + * @return {!Object} JSON representation. */ - this.blockId = opt_block ? opt_block.id : null; + toJson() { + const json = super.toJson(); + json['isCursor'] = this.isCursor; + json['blockId'] = this.blockId; + json['oldNode'] = this.oldNode; + json['newNode'] = this.newNode; + return json; + } /** - * The old node the marker used to be on. - * @type {?ASTNode|undefined} + * Decode the JSON event. + * @param {!Object} json JSON representation. */ - this.oldNode = opt_oldNode; - - /** - * The new node the marker is now on. - * @type {ASTNode|undefined} - */ - this.newNode = opt_newNode; - - /** - * Whether this is a cursor event. - * @type {boolean|undefined} - */ - this.isCursor = isCursor; -}; -object.inherits(MarkerMove, UiBase); - -/** - * Type of this event. - * @type {string} - */ -MarkerMove.prototype.type = eventUtils.MARKER_MOVE; - -/** - * Encode the event as JSON. - * @return {!Object} JSON representation. - */ -MarkerMove.prototype.toJson = function() { - const json = MarkerMove.superClass_.toJson.call(this); - json['isCursor'] = this.isCursor; - json['blockId'] = this.blockId; - json['oldNode'] = this.oldNode; - json['newNode'] = this.newNode; - return json; -}; - -/** - * Decode the JSON event. - * @param {!Object} json JSON representation. - */ -MarkerMove.prototype.fromJson = function(json) { - MarkerMove.superClass_.fromJson.call(this, json); - this.isCursor = json['isCursor']; - this.blockId = json['blockId']; - this.oldNode = json['oldNode']; - this.newNode = json['newNode']; -}; + fromJson(json) { + super.fromJson(json); + this.isCursor = json['isCursor']; + this.blockId = json['blockId']; + this.oldNode = json['oldNode']; + this.newNode = json['newNode']; + } +} registry.register(registry.Type.EVENT, eventUtils.MARKER_MOVE, MarkerMove); diff --git a/core/events/events_selected.js b/core/events/events_selected.js index 7009a8549..fbf0d07a5 100644 --- a/core/events/events_selected.js +++ b/core/events/events_selected.js @@ -16,66 +16,67 @@ goog.module('Blockly.Events.Selected'); const eventUtils = goog.require('Blockly.Events.utils'); -const object = goog.require('Blockly.utils.object'); const registry = goog.require('Blockly.registry'); const {UiBase} = goog.require('Blockly.Events.UiBase'); /** * Class for a selected event. - * @param {?string=} opt_oldElementId The ID of the previously selected - * element. Null if no element last selected. Undefined for a blank event. - * @param {?string=} opt_newElementId The ID of the selected element. Null if no - * element currently selected (deselect). Undefined for a blank event. - * @param {string=} opt_workspaceId The workspace identifier for this event. - * Null if no element previously selected. Undefined for a blank event. * @extends {UiBase} - * @constructor - * @alias Blockly.Events.Selected */ -const Selected = function(opt_oldElementId, opt_newElementId, opt_workspaceId) { - Selected.superClass_.constructor.call(this, opt_workspaceId); +class Selected extends UiBase { + /** + * @param {?string=} opt_oldElementId The ID of the previously selected + * element. Null if no element last selected. Undefined for a blank event. + * @param {?string=} opt_newElementId The ID of the selected element. Null if + * no element currently selected (deselect). Undefined for a blank event. + * @param {string=} opt_workspaceId The workspace identifier for this event. + * Null if no element previously selected. Undefined for a blank event. + * @alias Blockly.Events.Selected + */ + constructor(opt_oldElementId, opt_newElementId, opt_workspaceId) { + super(opt_workspaceId); + + /** + * The id of the last selected element. + * @type {?string|undefined} + */ + this.oldElementId = opt_oldElementId; + + /** + * The id of the selected element. + * @type {?string|undefined} + */ + this.newElementId = opt_newElementId; + + /** + * Type of this event. + * @type {string} + */ + this.type = eventUtils.SELECTED; + } /** - * The id of the last selected element. - * @type {?string|undefined} + * Encode the event as JSON. + * @return {!Object} JSON representation. */ - this.oldElementId = opt_oldElementId; + toJson() { + const json = super.toJson(); + json['oldElementId'] = this.oldElementId; + json['newElementId'] = this.newElementId; + return json; + } /** - * The id of the selected element. - * @type {?string|undefined} + * Decode the JSON event. + * @param {!Object} json JSON representation. */ - this.newElementId = opt_newElementId; -}; -object.inherits(Selected, UiBase); - -/** - * Type of this event. - * @type {string} - */ -Selected.prototype.type = eventUtils.SELECTED; - -/** - * Encode the event as JSON. - * @return {!Object} JSON representation. - */ -Selected.prototype.toJson = function() { - const json = Selected.superClass_.toJson.call(this); - json['oldElementId'] = this.oldElementId; - json['newElementId'] = this.newElementId; - return json; -}; - -/** - * Decode the JSON event. - * @param {!Object} json JSON representation. - */ -Selected.prototype.fromJson = function(json) { - Selected.superClass_.fromJson.call(this, json); - this.oldElementId = json['oldElementId']; - this.newElementId = json['newElementId']; -}; + fromJson(json) { + super.fromJson(json); + this.oldElementId = json['oldElementId']; + this.newElementId = json['newElementId']; + } +} registry.register(registry.Type.EVENT, eventUtils.SELECTED, Selected); diff --git a/core/events/events_theme_change.js b/core/events/events_theme_change.js index e1cba44c2..247bd0da8 100644 --- a/core/events/events_theme_change.js +++ b/core/events/events_theme_change.js @@ -16,55 +16,56 @@ goog.module('Blockly.Events.ThemeChange'); const eventUtils = goog.require('Blockly.Events.utils'); -const object = goog.require('Blockly.utils.object'); const registry = goog.require('Blockly.registry'); const {UiBase} = goog.require('Blockly.Events.UiBase'); /** * Class for a theme change event. - * @param {string=} opt_themeName The theme name. Undefined for a blank event. - * @param {string=} opt_workspaceId The workspace identifier for this event. - * event. Undefined for a blank event. * @extends {UiBase} - * @constructor - * @alias Blockly.Events.ThemeChange */ -const ThemeChange = function(opt_themeName, opt_workspaceId) { - ThemeChange.superClass_.constructor.call(this, opt_workspaceId); +class ThemeChange extends UiBase { + /** + * @param {string=} opt_themeName The theme name. Undefined for a blank event. + * @param {string=} opt_workspaceId The workspace identifier for this event. + * event. Undefined for a blank event. + * @alias Blockly.Events.ThemeChange + */ + constructor(opt_themeName, opt_workspaceId) { + super(opt_workspaceId); + + /** + * The theme name. + * @type {string|undefined} + */ + this.themeName = opt_themeName; + + /** + * Type of this event. + * @type {string} + */ + this.type = eventUtils.THEME_CHANGE; + } /** - * The theme name. - * @type {string|undefined} + * Encode the event as JSON. + * @return {!Object} JSON representation. */ - this.themeName = opt_themeName; -}; -object.inherits(ThemeChange, UiBase); + toJson() { + const json = super.toJson(); + json['themeName'] = this.themeName; + return json; + } -/** - * Type of this event. - * @type {string} - */ -ThemeChange.prototype.type = eventUtils.THEME_CHANGE; - -/** - * Encode the event as JSON. - * @return {!Object} JSON representation. - */ -ThemeChange.prototype.toJson = function() { - const json = ThemeChange.superClass_.toJson.call(this); - json['themeName'] = this.themeName; - return json; -}; - -/** - * Decode the JSON event. - * @param {!Object} json JSON representation. - */ -ThemeChange.prototype.fromJson = function(json) { - ThemeChange.superClass_.fromJson.call(this, json); - this.themeName = json['themeName']; -}; + /** + * Decode the JSON event. + * @param {!Object} json JSON representation. + */ + fromJson(json) { + super.fromJson(json); + this.themeName = json['themeName']; + } +} registry.register(registry.Type.EVENT, eventUtils.THEME_CHANGE, ThemeChange); diff --git a/core/events/events_toolbox_item_select.js b/core/events/events_toolbox_item_select.js index f2ba9bf19..6a6509316 100644 --- a/core/events/events_toolbox_item_select.js +++ b/core/events/events_toolbox_item_select.js @@ -16,66 +16,67 @@ goog.module('Blockly.Events.ToolboxItemSelect'); const eventUtils = goog.require('Blockly.Events.utils'); -const object = goog.require('Blockly.utils.object'); const registry = goog.require('Blockly.registry'); const {UiBase} = goog.require('Blockly.Events.UiBase'); /** * Class for a toolbox item select event. - * @param {?string=} opt_oldItem The previously selected toolbox item. Undefined - * for a blank event. - * @param {?string=} opt_newItem The newly selected toolbox item. Undefined for - * a blank event. - * @param {string=} opt_workspaceId The workspace identifier for this event. - * Undefined for a blank event. * @extends {UiBase} - * @constructor - * @alias Blockly.Events.ToolboxItemSelect */ -const ToolboxItemSelect = function(opt_oldItem, opt_newItem, opt_workspaceId) { - ToolboxItemSelect.superClass_.constructor.call(this, opt_workspaceId); +class ToolboxItemSelect extends UiBase { + /** + * @param {?string=} opt_oldItem The previously selected toolbox item. + * Undefined for a blank event. + * @param {?string=} opt_newItem The newly selected toolbox item. Undefined + * for a blank event. + * @param {string=} opt_workspaceId The workspace identifier for this event. + * Undefined for a blank event. + * @alias Blockly.Events.ToolboxItemSelect + */ + constructor(opt_oldItem, opt_newItem, opt_workspaceId) { + super(opt_workspaceId); + + /** + * The previously selected toolbox item. + * @type {?string|undefined} + */ + this.oldItem = opt_oldItem; + + /** + * The newly selected toolbox item. + * @type {?string|undefined} + */ + this.newItem = opt_newItem; + + /** + * Type of this event. + * @type {string} + */ + this.type = eventUtils.TOOLBOX_ITEM_SELECT; + } /** - * The previously selected toolbox item. - * @type {?string|undefined} + * Encode the event as JSON. + * @return {!Object} JSON representation. */ - this.oldItem = opt_oldItem; + toJson() { + const json = super.toJson(); + json['oldItem'] = this.oldItem; + json['newItem'] = this.newItem; + return json; + } /** - * The newly selected toolbox item. - * @type {?string|undefined} + * Decode the JSON event. + * @param {!Object} json JSON representation. */ - this.newItem = opt_newItem; -}; -object.inherits(ToolboxItemSelect, UiBase); - -/** - * Type of this event. - * @type {string} - */ -ToolboxItemSelect.prototype.type = eventUtils.TOOLBOX_ITEM_SELECT; - -/** - * Encode the event as JSON. - * @return {!Object} JSON representation. - */ -ToolboxItemSelect.prototype.toJson = function() { - const json = ToolboxItemSelect.superClass_.toJson.call(this); - json['oldItem'] = this.oldItem; - json['newItem'] = this.newItem; - return json; -}; - -/** - * Decode the JSON event. - * @param {!Object} json JSON representation. - */ -ToolboxItemSelect.prototype.fromJson = function(json) { - ToolboxItemSelect.superClass_.fromJson.call(this, json); - this.oldItem = json['oldItem']; - this.newItem = json['newItem']; -}; + fromJson(json) { + super.fromJson(json); + this.oldItem = json['oldItem']; + this.newItem = json['newItem']; + } +} registry.register( registry.Type.EVENT, eventUtils.TOOLBOX_ITEM_SELECT, ToolboxItemSelect); diff --git a/core/events/events_trashcan_open.js b/core/events/events_trashcan_open.js index 21fd0d3b3..565cee307 100644 --- a/core/events/events_trashcan_open.js +++ b/core/events/events_trashcan_open.js @@ -16,56 +16,57 @@ goog.module('Blockly.Events.TrashcanOpen'); const eventUtils = goog.require('Blockly.Events.utils'); -const object = goog.require('Blockly.utils.object'); const registry = goog.require('Blockly.registry'); const {UiBase} = goog.require('Blockly.Events.UiBase'); /** * Class for a trashcan open event. - * @param {boolean=} opt_isOpen Whether the trashcan flyout is opening (false if - * opening). Undefined for a blank event. - * @param {string=} opt_workspaceId The workspace identifier for this event. - * Undefined for a blank event. * @extends {UiBase} - * @constructor - * @alias Blockly.Events.TrashcanOpen */ -const TrashcanOpen = function(opt_isOpen, opt_workspaceId) { - TrashcanOpen.superClass_.constructor.call(this, opt_workspaceId); +class TrashcanOpen extends UiBase { + /** + * @param {boolean=} opt_isOpen Whether the trashcan flyout is opening (false + * if opening). Undefined for a blank event. + * @param {string=} opt_workspaceId The workspace identifier for this event. + * Undefined for a blank event. + * @alias Blockly.Events.TrashcanOpen + */ + constructor(opt_isOpen, opt_workspaceId) { + super(opt_workspaceId); + + /** + * Whether the trashcan flyout is opening (false if closing). + * @type {boolean|undefined} + */ + this.isOpen = opt_isOpen; + + /** + * Type of this event. + * @type {string} + */ + this.type = eventUtils.TRASHCAN_OPEN; + } /** - * Whether the trashcan flyout is opening (false if closing). - * @type {boolean|undefined} + * Encode the event as JSON. + * @return {!Object} JSON representation. */ - this.isOpen = opt_isOpen; -}; -object.inherits(TrashcanOpen, UiBase); + toJson() { + const json = super.toJson(); + json['isOpen'] = this.isOpen; + return json; + } -/** - * Type of this event. - * @type {string} - */ -TrashcanOpen.prototype.type = eventUtils.TRASHCAN_OPEN; - -/** - * Encode the event as JSON. - * @return {!Object} JSON representation. - */ -TrashcanOpen.prototype.toJson = function() { - const json = TrashcanOpen.superClass_.toJson.call(this); - json['isOpen'] = this.isOpen; - return json; -}; - -/** - * Decode the JSON event. - * @param {!Object} json JSON representation. - */ -TrashcanOpen.prototype.fromJson = function(json) { - TrashcanOpen.superClass_.fromJson.call(this, json); - this.isOpen = json['isOpen']; -}; + /** + * Decode the JSON event. + * @param {!Object} json JSON representation. + */ + fromJson(json) { + super.fromJson(json); + this.isOpen = json['isOpen']; + } +} registry.register(registry.Type.EVENT, eventUtils.TRASHCAN_OPEN, TrashcanOpen); diff --git a/core/events/events_ui.js b/core/events/events_ui.js index b505d3b20..2acb2fa4e 100644 --- a/core/events/events_ui.js +++ b/core/events/events_ui.js @@ -18,7 +18,6 @@ goog.module('Blockly.Events.Ui'); const eventUtils = goog.require('Blockly.Events.utils'); -const object = goog.require('Blockly.utils.object'); const registry = goog.require('Blockly.registry'); /* eslint-disable-next-line no-unused-vars */ const {Block} = goog.requireType('Blockly.Block'); @@ -27,60 +26,62 @@ const {UiBase} = goog.require('Blockly.Events.UiBase'); /** * Class for a UI event. - * @param {?Block=} opt_block The affected block. Null for UI events - * that do not have an associated block. Undefined for a blank event. - * @param {string=} opt_element One of 'selected', 'comment', 'mutatorOpen', - * etc. - * @param {*=} opt_oldValue Previous value of element. - * @param {*=} opt_newValue New value of element. * @extends {UiBase} * @deprecated December 2020. Instead use a more specific UI event. - * @constructor - * @alias Blockly.Events.Ui */ -const Ui = function(opt_block, opt_element, opt_oldValue, opt_newValue) { - const workspaceId = opt_block ? opt_block.workspace.id : undefined; - Ui.superClass_.constructor.call(this, workspaceId); +class Ui extends UiBase { + /** + * @param {?Block=} opt_block The affected block. Null for UI events + * that do not have an associated block. Undefined for a blank event. + * @param {string=} opt_element One of 'selected', 'comment', 'mutatorOpen', + * etc. + * @param {*=} opt_oldValue Previous value of element. + * @param {*=} opt_newValue New value of element. + * @alias Blockly.Events.Ui + */ + constructor(opt_block, opt_element, opt_oldValue, opt_newValue) { + const workspaceId = opt_block ? opt_block.workspace.id : undefined; + super(workspaceId); - this.blockId = opt_block ? opt_block.id : null; - this.element = typeof opt_element === 'undefined' ? '' : opt_element; - this.oldValue = typeof opt_oldValue === 'undefined' ? '' : opt_oldValue; - this.newValue = typeof opt_newValue === 'undefined' ? '' : opt_newValue; -}; -object.inherits(Ui, UiBase); + this.blockId = opt_block ? opt_block.id : null; + this.element = typeof opt_element === 'undefined' ? '' : opt_element; + this.oldValue = typeof opt_oldValue === 'undefined' ? '' : opt_oldValue; + this.newValue = typeof opt_newValue === 'undefined' ? '' : opt_newValue; -/** - * Type of this event. - * @type {string} - */ -Ui.prototype.type = eventUtils.UI; - -/** - * Encode the event as JSON. - * @return {!Object} JSON representation. - */ -Ui.prototype.toJson = function() { - const json = Ui.superClass_.toJson.call(this); - json['element'] = this.element; - if (this.newValue !== undefined) { - json['newValue'] = this.newValue; + /** + * Type of this event. + * @type {string} + */ + this.type = eventUtils.UI; } - if (this.blockId) { - json['blockId'] = this.blockId; - } - return json; -}; -/** - * Decode the JSON event. - * @param {!Object} json JSON representation. - */ -Ui.prototype.fromJson = function(json) { - Ui.superClass_.fromJson.call(this, json); - this.element = json['element']; - this.newValue = json['newValue']; - this.blockId = json['blockId']; -}; + /** + * Encode the event as JSON. + * @return {!Object} JSON representation. + */ + toJson() { + const json = super.toJson(); + json['element'] = this.element; + if (this.newValue !== undefined) { + json['newValue'] = this.newValue; + } + if (this.blockId) { + json['blockId'] = this.blockId; + } + return json; + } + + /** + * Decode the JSON event. + * @param {!Object} json JSON representation. + */ + fromJson(json) { + super.fromJson(json); + this.element = json['element']; + this.newValue = json['newValue']; + this.blockId = json['blockId']; + } +} registry.register(registry.Type.EVENT, eventUtils.UI, Ui); diff --git a/core/events/events_ui_base.js b/core/events/events_ui_base.js index 1618f2876..cd7ad1d2e 100644 --- a/core/events/events_ui_base.js +++ b/core/events/events_ui_base.js @@ -50,13 +50,13 @@ const UiBase = function(opt_workspaceId) { // UI events do not undo or redo. this.recordUndo = false; + + /** + * Whether or not the event is a UI event. + * @type {boolean} + */ + this.isUiEvent = true; }; object.inherits(UiBase, Abstract); -/** - * Whether or not the event is a UI event. - * @type {boolean} - */ -UiBase.prototype.isUiEvent = true; - exports.UiBase = UiBase; diff --git a/core/events/events_var_create.js b/core/events/events_var_create.js index f924fd98d..0de02d99c 100644 --- a/core/events/events_var_create.js +++ b/core/events/events_var_create.js @@ -16,7 +16,6 @@ goog.module('Blockly.Events.VarCreate'); const eventUtils = goog.require('Blockly.Events.utils'); -const object = goog.require('Blockly.utils.object'); const registry = goog.require('Blockly.registry'); const {VarBase} = goog.require('Blockly.Events.VarBase'); /* eslint-disable-next-line no-unused-vars */ @@ -25,62 +24,65 @@ const {VariableModel} = goog.requireType('Blockly.VariableModel'); /** * Class for a variable creation event. - * @param {!VariableModel=} opt_variable The created variable. Undefined - * for a blank event. * @extends {VarBase} - * @constructor - * @alias Blockly.Events.VarCreate */ -const VarCreate = function(opt_variable) { - VarCreate.superClass_.constructor.call(this, opt_variable); - if (!opt_variable) { - return; // Blank event to be populated by fromJson. +class VarCreate extends VarBase { + /** + * @param {!VariableModel=} opt_variable The created variable. Undefined + * for a blank event. + * @alias Blockly.Events.VarCreate + */ + constructor(opt_variable) { + super(opt_variable); + + /** + * Type of this event. + * @type {string} + */ + this.type = eventUtils.VAR_CREATE; + + if (!opt_variable) { + return; // Blank event to be populated by fromJson. + } + + this.varType = opt_variable.type; + this.varName = opt_variable.name; } - this.varType = opt_variable.type; - this.varName = opt_variable.name; -}; -object.inherits(VarCreate, VarBase); - -/** - * Type of this event. - * @type {string} - */ -VarCreate.prototype.type = eventUtils.VAR_CREATE; - -/** - * Encode the event as JSON. - * @return {!Object} JSON representation. - */ -VarCreate.prototype.toJson = function() { - const json = VarCreate.superClass_.toJson.call(this); - json['varType'] = this.varType; - json['varName'] = this.varName; - return json; -}; - -/** - * Decode the JSON event. - * @param {!Object} json JSON representation. - */ -VarCreate.prototype.fromJson = function(json) { - VarCreate.superClass_.fromJson.call(this, json); - this.varType = json['varType']; - this.varName = json['varName']; -}; - -/** - * Run a variable creation event. - * @param {boolean} forward True if run forward, false if run backward (undo). - */ -VarCreate.prototype.run = function(forward) { - const workspace = this.getEventWorkspace_(); - if (forward) { - workspace.createVariable(this.varName, this.varType, this.varId); - } else { - workspace.deleteVariableById(this.varId); + /** + * Encode the event as JSON. + * @return {!Object} JSON representation. + */ + toJson() { + const json = super.toJson(); + json['varType'] = this.varType; + json['varName'] = this.varName; + return json; } -}; + + /** + * Decode the JSON event. + * @param {!Object} json JSON representation. + */ + fromJson(json) { + super.fromJson(json); + this.varType = json['varType']; + this.varName = json['varName']; + } + + /** + * Run a variable creation event. + * @param {boolean} forward True if run forward, false if run backward (undo). + */ + run(forward) { + const workspace = this.getEventWorkspace_(); + if (forward) { + workspace.createVariable(this.varName, this.varType, this.varId); + } else { + workspace.deleteVariableById(this.varId); + } + } +} registry.register(registry.Type.EVENT, eventUtils.VAR_CREATE, VarCreate); diff --git a/core/events/events_var_delete.js b/core/events/events_var_delete.js index 2c8b34fb2..3c0eb2a58 100644 --- a/core/events/events_var_delete.js +++ b/core/events/events_var_delete.js @@ -16,7 +16,6 @@ goog.module('Blockly.Events.VarDelete'); const eventUtils = goog.require('Blockly.Events.utils'); -const object = goog.require('Blockly.utils.object'); const registry = goog.require('Blockly.registry'); const {VarBase} = goog.require('Blockly.Events.VarBase'); /* eslint-disable-next-line no-unused-vars */ @@ -25,62 +24,65 @@ const {VariableModel} = goog.requireType('Blockly.VariableModel'); /** * Class for a variable deletion event. - * @param {!VariableModel=} opt_variable The deleted variable. Undefined - * for a blank event. * @extends {VarBase} - * @constructor - * @alias Blockly.Events.VarDelete */ -const VarDelete = function(opt_variable) { - VarDelete.superClass_.constructor.call(this, opt_variable); - if (!opt_variable) { - return; // Blank event to be populated by fromJson. +class VarDelete extends VarBase { + /** + * @param {!VariableModel=} opt_variable The deleted variable. Undefined + * for a blank event. + * @alias Blockly.Events.VarDelete + */ + constructor(opt_variable) { + super(opt_variable); + + /** + * Type of this event. + * @type {string} + */ + this.type = eventUtils.VAR_DELETE; + + if (!opt_variable) { + return; // Blank event to be populated by fromJson. + } + + this.varType = opt_variable.type; + this.varName = opt_variable.name; } - this.varType = opt_variable.type; - this.varName = opt_variable.name; -}; -object.inherits(VarDelete, VarBase); - -/** - * Type of this event. - * @type {string} - */ -VarDelete.prototype.type = eventUtils.VAR_DELETE; - -/** - * Encode the event as JSON. - * @return {!Object} JSON representation. - */ -VarDelete.prototype.toJson = function() { - const json = VarDelete.superClass_.toJson.call(this); - json['varType'] = this.varType; - json['varName'] = this.varName; - return json; -}; - -/** - * Decode the JSON event. - * @param {!Object} json JSON representation. - */ -VarDelete.prototype.fromJson = function(json) { - VarDelete.superClass_.fromJson.call(this, json); - this.varType = json['varType']; - this.varName = json['varName']; -}; - -/** - * Run a variable deletion event. - * @param {boolean} forward True if run forward, false if run backward (undo). - */ -VarDelete.prototype.run = function(forward) { - const workspace = this.getEventWorkspace_(); - if (forward) { - workspace.deleteVariableById(this.varId); - } else { - workspace.createVariable(this.varName, this.varType, this.varId); + /** + * Encode the event as JSON. + * @return {!Object} JSON representation. + */ + toJson() { + const json = super.toJson(); + json['varType'] = this.varType; + json['varName'] = this.varName; + return json; } -}; + + /** + * Decode the JSON event. + * @param {!Object} json JSON representation. + */ + fromJson(json) { + super.fromJson(json); + this.varType = json['varType']; + this.varName = json['varName']; + } + + /** + * Run a variable deletion event. + * @param {boolean} forward True if run forward, false if run backward (undo). + */ + run(forward) { + const workspace = this.getEventWorkspace_(); + if (forward) { + workspace.deleteVariableById(this.varId); + } else { + workspace.createVariable(this.varName, this.varType, this.varId); + } + } +} registry.register(registry.Type.EVENT, eventUtils.VAR_DELETE, VarDelete); diff --git a/core/events/events_var_rename.js b/core/events/events_var_rename.js index 97d8fd882..17d3774e5 100644 --- a/core/events/events_var_rename.js +++ b/core/events/events_var_rename.js @@ -16,7 +16,6 @@ goog.module('Blockly.Events.VarRename'); const eventUtils = goog.require('Blockly.Events.utils'); -const object = goog.require('Blockly.utils.object'); const registry = goog.require('Blockly.registry'); const {VarBase} = goog.require('Blockly.Events.VarBase'); /* eslint-disable-next-line no-unused-vars */ @@ -25,63 +24,66 @@ const {VariableModel} = goog.requireType('Blockly.VariableModel'); /** * Class for a variable rename event. - * @param {!VariableModel=} opt_variable The renamed variable. Undefined - * for a blank event. - * @param {string=} newName The new name the variable will be changed to. * @extends {VarBase} - * @constructor - * @alias Blockly.Events.VarRename */ -const VarRename = function(opt_variable, newName) { - VarRename.superClass_.constructor.call(this, opt_variable); - if (!opt_variable) { - return; // Blank event to be populated by fromJson. +class VarRename extends VarBase { + /** + * @param {!VariableModel=} opt_variable The renamed variable. Undefined + * for a blank event. + * @param {string=} newName The new name the variable will be changed to. + * @alias Blockly.Events.VarRename + */ + constructor(opt_variable, newName) { + super(opt_variable); + + /** + * Type of this event. + * @type {string} + */ + this.type = eventUtils.VAR_RENAME; + + if (!opt_variable) { + return; // Blank event to be populated by fromJson. + } + + this.oldName = opt_variable.name; + this.newName = typeof newName === 'undefined' ? '' : newName; } - this.oldName = opt_variable.name; - this.newName = typeof newName === 'undefined' ? '' : newName; -}; -object.inherits(VarRename, VarBase); - -/** - * Type of this event. - * @type {string} - */ -VarRename.prototype.type = eventUtils.VAR_RENAME; - -/** - * Encode the event as JSON. - * @return {!Object} JSON representation. - */ -VarRename.prototype.toJson = function() { - const json = VarRename.superClass_.toJson.call(this); - json['oldName'] = this.oldName; - json['newName'] = this.newName; - return json; -}; - -/** - * Decode the JSON event. - * @param {!Object} json JSON representation. - */ -VarRename.prototype.fromJson = function(json) { - VarRename.superClass_.fromJson.call(this, json); - this.oldName = json['oldName']; - this.newName = json['newName']; -}; - -/** - * Run a variable rename event. - * @param {boolean} forward True if run forward, false if run backward (undo). - */ -VarRename.prototype.run = function(forward) { - const workspace = this.getEventWorkspace_(); - if (forward) { - workspace.renameVariableById(this.varId, this.newName); - } else { - workspace.renameVariableById(this.varId, this.oldName); + /** + * Encode the event as JSON. + * @return {!Object} JSON representation. + */ + toJson() { + const json = super.toJson(); + json['oldName'] = this.oldName; + json['newName'] = this.newName; + return json; } -}; + + /** + * Decode the JSON event. + * @param {!Object} json JSON representation. + */ + fromJson(json) { + super.fromJson(json); + this.oldName = json['oldName']; + this.newName = json['newName']; + } + + /** + * Run a variable rename event. + * @param {boolean} forward True if run forward, false if run backward (undo). + */ + run(forward) { + const workspace = this.getEventWorkspace_(); + if (forward) { + workspace.renameVariableById(this.varId, this.newName); + } else { + workspace.renameVariableById(this.varId, this.oldName); + } + } +} registry.register(registry.Type.EVENT, eventUtils.VAR_RENAME, VarRename); diff --git a/core/events/events_viewport.js b/core/events/events_viewport.js index 71ac3d3c7..bde96edf8 100644 --- a/core/events/events_viewport.js +++ b/core/events/events_viewport.js @@ -16,89 +16,90 @@ goog.module('Blockly.Events.ViewportChange'); const eventUtils = goog.require('Blockly.Events.utils'); -const object = goog.require('Blockly.utils.object'); const registry = goog.require('Blockly.registry'); const {UiBase} = goog.require('Blockly.Events.UiBase'); /** * Class for a viewport change event. - * @param {number=} opt_top Top-edge of the visible portion of the workspace, - * relative to the workspace origin. Undefined for a blank event. - * @param {number=} opt_left Left-edge of the visible portion of the workspace, - * relative to the workspace origin. Undefined for a blank event. - * @param {number=} opt_scale The scale of the workspace. Undefined for a blank - * event. - * @param {string=} opt_workspaceId The workspace identifier for this event. - * Undefined for a blank event. - * @param {number=} opt_oldScale The old scale of the workspace. Undefined for a - * blank event. * @extends {UiBase} - * @constructor - * @alias Blockly.Events.ViewportChange */ -const ViewportChange = function( - opt_top, opt_left, opt_scale, opt_workspaceId, opt_oldScale) { - ViewportChange.superClass_.constructor.call(this, opt_workspaceId); +class ViewportChange extends UiBase { + /** + * @param {number=} opt_top Top-edge of the visible portion of the workspace, + * relative to the workspace origin. Undefined for a blank event. + * @param {number=} opt_left Left-edge of the visible portion of the + * workspace relative to the workspace origin. Undefined for a blank + * event. + * @param {number=} opt_scale The scale of the workspace. Undefined for a + * blank event. + * @param {string=} opt_workspaceId The workspace identifier for this event. + * Undefined for a blank event. + * @param {number=} opt_oldScale The old scale of the workspace. Undefined for + * a blank event. + * @alias Blockly.Events.ViewportChange + */ + constructor(opt_top, opt_left, opt_scale, opt_workspaceId, opt_oldScale) { + super(opt_workspaceId); + + /** + * Top-edge of the visible portion of the workspace, relative to the + * workspace origin. + * @type {number|undefined} + */ + this.viewTop = opt_top; + + /** + * Left-edge of the visible portion of the workspace, relative to the + * workspace origin. + * @type {number|undefined} + */ + this.viewLeft = opt_left; + + /** + * The scale of the workspace. + * @type {number|undefined} + */ + this.scale = opt_scale; + + /** + * The old scale of the workspace. + * @type {number|undefined} + */ + this.oldScale = opt_oldScale; + + /** + * Type of this event. + * @type {string} + */ + this.type = eventUtils.VIEWPORT_CHANGE; + } /** - * Top-edge of the visible portion of the workspace, relative to the workspace - * origin. - * @type {number|undefined} + * Encode the event as JSON. + * @return {!Object} JSON representation. */ - this.viewTop = opt_top; + toJson() { + const json = super.toJson(); + json['viewTop'] = this.viewTop; + json['viewLeft'] = this.viewLeft; + json['scale'] = this.scale; + json['oldScale'] = this.oldScale; + return json; + } /** - * Left-edge of the visible portion of the workspace, relative to the - * workspace origin. - * @type {number|undefined} + * Decode the JSON event. + * @param {!Object} json JSON representation. */ - this.viewLeft = opt_left; - - /** - * The scale of the workspace. - * @type {number|undefined} - */ - this.scale = opt_scale; - - /** - * The old scale of the workspace. - * @type {number|undefined} - */ - this.oldScale = opt_oldScale; -}; -object.inherits(ViewportChange, UiBase); - -/** - * Type of this event. - * @type {string} - */ -ViewportChange.prototype.type = eventUtils.VIEWPORT_CHANGE; - -/** - * Encode the event as JSON. - * @return {!Object} JSON representation. - */ -ViewportChange.prototype.toJson = function() { - const json = ViewportChange.superClass_.toJson.call(this); - json['viewTop'] = this.viewTop; - json['viewLeft'] = this.viewLeft; - json['scale'] = this.scale; - json['oldScale'] = this.oldScale; - return json; -}; - -/** - * Decode the JSON event. - * @param {!Object} json JSON representation. - */ -ViewportChange.prototype.fromJson = function(json) { - ViewportChange.superClass_.fromJson.call(this, json); - this.viewTop = json['viewTop']; - this.viewLeft = json['viewLeft']; - this.scale = json['scale']; - this.oldScale = json['oldScale']; -}; + fromJson(json) { + super.fromJson(json); + this.viewTop = json['viewTop']; + this.viewLeft = json['viewLeft']; + this.scale = json['scale']; + this.oldScale = json['oldScale']; + } +} registry.register( registry.Type.EVENT, eventUtils.VIEWPORT_CHANGE, ViewportChange); diff --git a/tests/deps.js b/tests/deps.js index 55bfc76b6..ab5c32064 100644 --- a/tests/deps.js +++ b/tests/deps.js @@ -40,30 +40,30 @@ goog.addDependency('../../core/dropdowndiv.js', ['Blockly.DropDownDiv'], ['Block goog.addDependency('../../core/events/events.js', ['Blockly.Events'], ['Blockly.Events.Abstract', 'Blockly.Events.BlockBase', 'Blockly.Events.BlockChange', 'Blockly.Events.BlockCreate', 'Blockly.Events.BlockDelete', 'Blockly.Events.BlockDrag', 'Blockly.Events.BlockMove', 'Blockly.Events.BubbleOpen', 'Blockly.Events.Click', 'Blockly.Events.CommentBase', 'Blockly.Events.CommentChange', 'Blockly.Events.CommentCreate', 'Blockly.Events.CommentDelete', 'Blockly.Events.CommentMove', 'Blockly.Events.FinishedLoading', 'Blockly.Events.MarkerMove', 'Blockly.Events.Selected', 'Blockly.Events.ThemeChange', 'Blockly.Events.ToolboxItemSelect', 'Blockly.Events.TrashcanOpen', 'Blockly.Events.Ui', 'Blockly.Events.UiBase', 'Blockly.Events.VarBase', 'Blockly.Events.VarCreate', 'Blockly.Events.VarDelete', 'Blockly.Events.VarRename', 'Blockly.Events.ViewportChange', 'Blockly.Events.utils', 'Blockly.utils.deprecation'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/events/events_abstract.js', ['Blockly.Events.Abstract'], ['Blockly.Events.utils'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/events/events_block_base.js', ['Blockly.Events.BlockBase'], ['Blockly.Events.Abstract', 'Blockly.utils.object'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/events/events_block_change.js', ['Blockly.Events.BlockChange'], ['Blockly.Events.BlockBase', 'Blockly.Events.utils', 'Blockly.Xml', 'Blockly.registry', 'Blockly.utils.object'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/events/events_block_create.js', ['Blockly.Events.BlockCreate'], ['Blockly.Events.BlockBase', 'Blockly.Events.utils', 'Blockly.Xml', 'Blockly.registry', 'Blockly.serialization.blocks', 'Blockly.utils.object'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/events/events_block_delete.js', ['Blockly.Events.BlockDelete'], ['Blockly.Events.BlockBase', 'Blockly.Events.utils', 'Blockly.Xml', 'Blockly.registry', 'Blockly.serialization.blocks', 'Blockly.utils.object'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/events/events_block_drag.js', ['Blockly.Events.BlockDrag'], ['Blockly.Events.UiBase', 'Blockly.Events.utils', 'Blockly.registry', 'Blockly.utils.object'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/events/events_block_move.js', ['Blockly.Events.BlockMove'], ['Blockly.ConnectionType', 'Blockly.Events.BlockBase', 'Blockly.Events.utils', 'Blockly.registry', 'Blockly.utils.Coordinate', 'Blockly.utils.object'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/events/events_block_change.js', ['Blockly.Events.BlockChange'], ['Blockly.Events.BlockBase', 'Blockly.Events.utils', 'Blockly.Xml', 'Blockly.registry'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/events/events_block_create.js', ['Blockly.Events.BlockCreate'], ['Blockly.Events.BlockBase', 'Blockly.Events.utils', 'Blockly.Xml', 'Blockly.registry', 'Blockly.serialization.blocks'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/events/events_block_delete.js', ['Blockly.Events.BlockDelete'], ['Blockly.Events.BlockBase', 'Blockly.Events.utils', 'Blockly.Xml', 'Blockly.registry', 'Blockly.serialization.blocks'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/events/events_block_drag.js', ['Blockly.Events.BlockDrag'], ['Blockly.Events.UiBase', 'Blockly.Events.utils', 'Blockly.registry'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/events/events_block_move.js', ['Blockly.Events.BlockMove'], ['Blockly.ConnectionType', 'Blockly.Events.BlockBase', 'Blockly.Events.utils', 'Blockly.registry', 'Blockly.utils.Coordinate'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/events/events_bubble_open.js', ['Blockly.Events.BubbleOpen'], ['Blockly.Events.UiBase', 'Blockly.Events.utils', 'Blockly.registry', 'Blockly.utils.object'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/events/events_click.js', ['Blockly.Events.Click'], ['Blockly.Events.UiBase', 'Blockly.Events.utils', 'Blockly.registry', 'Blockly.utils.object'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/events/events_click.js', ['Blockly.Events.Click'], ['Blockly.Events.UiBase', 'Blockly.Events.utils', 'Blockly.registry'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/events/events_comment_base.js', ['Blockly.Events.CommentBase'], ['Blockly.Events.Abstract', 'Blockly.Events.utils', 'Blockly.Xml', 'Blockly.utils.object', 'Blockly.utils.xml'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/events/events_comment_change.js', ['Blockly.Events.CommentChange'], ['Blockly.Events.CommentBase', 'Blockly.Events.utils', 'Blockly.registry', 'Blockly.utils.object'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/events/events_comment_create.js', ['Blockly.Events.CommentCreate'], ['Blockly.Events.CommentBase', 'Blockly.Events.utils', 'Blockly.Xml', 'Blockly.registry', 'Blockly.utils.object'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/events/events_comment_delete.js', ['Blockly.Events.CommentDelete'], ['Blockly.Events.CommentBase', 'Blockly.Events.utils', 'Blockly.registry', 'Blockly.utils.object'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/events/events_comment_move.js', ['Blockly.Events.CommentMove'], ['Blockly.Events.CommentBase', 'Blockly.Events.utils', 'Blockly.registry', 'Blockly.utils.Coordinate', 'Blockly.utils.object'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/events/events_marker_move.js', ['Blockly.Events.MarkerMove'], ['Blockly.ASTNode', 'Blockly.Events.UiBase', 'Blockly.Events.utils', 'Blockly.registry', 'Blockly.utils.object'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/events/events_selected.js', ['Blockly.Events.Selected'], ['Blockly.Events.UiBase', 'Blockly.Events.utils', 'Blockly.registry', 'Blockly.utils.object'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/events/events_theme_change.js', ['Blockly.Events.ThemeChange'], ['Blockly.Events.UiBase', 'Blockly.Events.utils', 'Blockly.registry', 'Blockly.utils.object'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/events/events_toolbox_item_select.js', ['Blockly.Events.ToolboxItemSelect'], ['Blockly.Events.UiBase', 'Blockly.Events.utils', 'Blockly.registry', 'Blockly.utils.object'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/events/events_trashcan_open.js', ['Blockly.Events.TrashcanOpen'], ['Blockly.Events.UiBase', 'Blockly.Events.utils', 'Blockly.registry', 'Blockly.utils.object'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/events/events_ui.js', ['Blockly.Events.Ui'], ['Blockly.Events.UiBase', 'Blockly.Events.utils', 'Blockly.registry', 'Blockly.utils.object'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/events/events_comment_change.js', ['Blockly.Events.CommentChange'], ['Blockly.Events.CommentBase', 'Blockly.Events.utils', 'Blockly.registry'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/events/events_comment_create.js', ['Blockly.Events.CommentCreate'], ['Blockly.Events.CommentBase', 'Blockly.Events.utils', 'Blockly.Xml', 'Blockly.registry'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/events/events_comment_delete.js', ['Blockly.Events.CommentDelete'], ['Blockly.Events.CommentBase', 'Blockly.Events.utils', 'Blockly.registry'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/events/events_comment_move.js', ['Blockly.Events.CommentMove'], ['Blockly.Events.CommentBase', 'Blockly.Events.utils', 'Blockly.registry', 'Blockly.utils.Coordinate'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/events/events_marker_move.js', ['Blockly.Events.MarkerMove'], ['Blockly.ASTNode', 'Blockly.Events.UiBase', 'Blockly.Events.utils', 'Blockly.registry'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/events/events_selected.js', ['Blockly.Events.Selected'], ['Blockly.Events.UiBase', 'Blockly.Events.utils', 'Blockly.registry'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/events/events_theme_change.js', ['Blockly.Events.ThemeChange'], ['Blockly.Events.UiBase', 'Blockly.Events.utils', 'Blockly.registry'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/events/events_toolbox_item_select.js', ['Blockly.Events.ToolboxItemSelect'], ['Blockly.Events.UiBase', 'Blockly.Events.utils', 'Blockly.registry'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/events/events_trashcan_open.js', ['Blockly.Events.TrashcanOpen'], ['Blockly.Events.UiBase', 'Blockly.Events.utils', 'Blockly.registry'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/events/events_ui.js', ['Blockly.Events.Ui'], ['Blockly.Events.UiBase', 'Blockly.Events.utils', 'Blockly.registry'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/events/events_ui_base.js', ['Blockly.Events.UiBase'], ['Blockly.Events.Abstract', 'Blockly.utils.object'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/events/events_var_base.js', ['Blockly.Events.VarBase'], ['Blockly.Events.Abstract', 'Blockly.utils.object'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/events/events_var_create.js', ['Blockly.Events.VarCreate'], ['Blockly.Events.VarBase', 'Blockly.Events.utils', 'Blockly.registry', 'Blockly.utils.object'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/events/events_var_delete.js', ['Blockly.Events.VarDelete'], ['Blockly.Events.VarBase', 'Blockly.Events.utils', 'Blockly.registry', 'Blockly.utils.object'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/events/events_var_rename.js', ['Blockly.Events.VarRename'], ['Blockly.Events.VarBase', 'Blockly.Events.utils', 'Blockly.registry', 'Blockly.utils.object'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/events/events_viewport.js', ['Blockly.Events.ViewportChange'], ['Blockly.Events.UiBase', 'Blockly.Events.utils', 'Blockly.registry', 'Blockly.utils.object'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/events/events_var_create.js', ['Blockly.Events.VarCreate'], ['Blockly.Events.VarBase', 'Blockly.Events.utils', 'Blockly.registry'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/events/events_var_delete.js', ['Blockly.Events.VarDelete'], ['Blockly.Events.VarBase', 'Blockly.Events.utils', 'Blockly.registry'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/events/events_var_rename.js', ['Blockly.Events.VarRename'], ['Blockly.Events.VarBase', 'Blockly.Events.utils', 'Blockly.registry'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/events/events_viewport.js', ['Blockly.Events.ViewportChange'], ['Blockly.Events.UiBase', 'Blockly.Events.utils', 'Blockly.registry'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/events/utils.js', ['Blockly.Events.utils'], ['Blockly.registry', 'Blockly.utils.idGenerator'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/events/workspace_events.js', ['Blockly.Events.FinishedLoading'], ['Blockly.Events.Abstract', 'Blockly.Events.utils', 'Blockly.registry', 'Blockly.utils.object'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/extensions.js', ['Blockly.Extensions'], ['Blockly.utils.parsing'], {'lang': 'es6', 'module': 'goog'}); diff --git a/tests/deps.mocha.js b/tests/deps.mocha.js index 4be80abef..a686fdda7 100644 --- a/tests/deps.mocha.js +++ b/tests/deps.mocha.js @@ -1,10 +1,10 @@ goog.addDependency('../../tests/mocha/.mocharc.js', [], []); goog.addDependency('../../tests/mocha/astnode_test.js', ['Blockly.test.astNode'], ['Blockly.ASTNode', 'Blockly.test.helpers'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../tests/mocha/block_change_event_test.js', ['Blockly.test.blockChangeEvent'], ['Blockly.test.helpers'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../tests/mocha/block_create_event_test.js', ['Blockly.test.blockCreateEvent'], ['Blockly.test.helpers'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../tests/mocha/block_create_event_test.js', ['Blockly.test.blockCreateEvent'], ['Blockly.Events.utils', 'Blockly.test.helpers'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../tests/mocha/block_json_test.js', ['Blockly.test.blockJson'], ['Blockly.Input'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../tests/mocha/block_test.js', ['Blockly.test.blocks'], ['Blockly.ConnectionType', 'Blockly.Events.utils', 'Blockly.blocks', 'Blockly.test.helpers'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../tests/mocha/comment_test.js', ['Blockly.test.comments'], ['Blockly.test.helpers'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../tests/mocha/comment_test.js', ['Blockly.test.comments'], ['Blockly.Events.utils', 'Blockly.test.helpers'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../tests/mocha/connection_checker_test.js', ['Blockly.test.connectionChecker'], ['Blockly.ConnectionType', 'Blockly.test.helpers'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../tests/mocha/connection_db_test.js', ['Blockly.test.connectionDb'], ['Blockly.ConnectionType', 'Blockly.test.helpers'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../tests/mocha/connection_test.js', ['Blockly.test.connection'], ['Blockly.test.helpers'], {'lang': 'es6', 'module': 'goog'}); @@ -28,10 +28,10 @@ goog.addDependency('../../tests/mocha/field_textinput_test.js', ['Blockly.test.f goog.addDependency('../../tests/mocha/field_variable_test.js', ['Blockly.test.fieldVariable'], ['Blockly.test.helpers'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../tests/mocha/flyout_test.js', ['Blockly.test.flyout'], ['Blockly.test.helpers', 'Blockly.test.toolboxHelpers'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../tests/mocha/generator_test.js', ['Blockly.test.generator'], ['Blockly.Dart', 'Blockly.JavaScript', 'Blockly.Lua', 'Blockly.PHP', 'Blockly.Python', 'Blockly.test.helpers'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../tests/mocha/gesture_test.js', ['Blockly.test.gesture'], ['Blockly.test.helpers'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../tests/mocha/gesture_test.js', ['Blockly.test.gesture'], ['Blockly.Events.utils', 'Blockly.test.helpers'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../tests/mocha/input_test.js', ['Blockly.test.input'], ['Blockly.test.helpers'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../tests/mocha/insertion_marker_test.js', ['Blockly.test.insertionMarker'], ['Blockly.test.helpers'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../tests/mocha/jso_deserialization_test.js', ['Blockly.test.jsoDeserialization'], ['Blockly.test.helpers'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../tests/mocha/jso_deserialization_test.js', ['Blockly.test.jsoDeserialization'], ['Blockly.Events.utils', 'Blockly.test.helpers'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../tests/mocha/jso_serialization_test.js', ['Blockly.test.jsoSerialization'], ['Blockly.test.helpers'], {'lang': 'es8', 'module': 'goog'}); goog.addDependency('../../tests/mocha/json_test.js', ['Blockly.test.json'], ['Blockly.test.helpers'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../tests/mocha/keydown_test.js', ['Blockly.test.keydown'], ['Blockly.test.helpers'], {'lang': 'es6', 'module': 'goog'}); @@ -46,7 +46,7 @@ goog.addDependency('../../tests/mocha/run_mocha_tests_in_browser.js', [], [], {' goog.addDependency('../../tests/mocha/serializer_test.js', ['Blockly.test.serialization'], ['Blockly.test.helpers'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../tests/mocha/shortcut_registry_test.js', ['Blockly.test.shortcutRegistry'], ['Blockly.test.helpers'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../tests/mocha/test_helpers.js', ['Blockly.test.helpers'], ['Blockly.Events.utils', 'Blockly.blocks', 'Blockly.utils.KeyCodes'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../tests/mocha/theme_test.js', ['Blockly.test.theme'], ['Blockly.test.helpers'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../tests/mocha/theme_test.js', ['Blockly.test.theme'], ['Blockly.Events.utils', 'Blockly.test.helpers'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../tests/mocha/toolbox_helper.js', ['Blockly.test.toolboxHelpers'], [], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../tests/mocha/toolbox_test.js', ['Blockly.test.toolbox'], ['Blockly.test.helpers', 'Blockly.test.toolboxHelpers'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../tests/mocha/tooltip_test.js', ['Blockly.test.tooltip'], ['Blockly.test.helpers'], {'lang': 'es6', 'module': 'goog'}); @@ -58,7 +58,7 @@ goog.addDependency('../../tests/mocha/variables_test.js', ['Blockly.test.variabl goog.addDependency('../../tests/mocha/widget_div_test.js', ['Blockly.test.widgetDiv'], ['Blockly.test.helpers'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../tests/mocha/workspace_comment_test.js', ['Blockly.test.workspaceComment'], ['Blockly.WorkspaceComment', 'Blockly.test.helpers'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../tests/mocha/workspace_helpers.js', ['Blockly.test.workspaceHelpers'], ['Blockly.Events.utils', 'Blockly.test.helpers'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../tests/mocha/workspace_svg_test.js', ['Blockly.test.workspaceSvg'], ['Blockly.test.helpers', 'Blockly.test.workspaceHelpers'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../tests/mocha/workspace_svg_test.js', ['Blockly.test.workspaceSvg'], ['Blockly.Events.utils', 'Blockly.test.helpers', 'Blockly.test.workspaceHelpers'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../tests/mocha/workspace_test.js', ['Blockly.test.workspace'], ['Blockly.test.helpers', 'Blockly.test.workspaceHelpers'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../tests/mocha/xml_test.js', ['Blockly.test.xml'], ['Blockly.test.helpers'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../tests/mocha/zoom_controls_test.js', ['Blockly.test.zoomControls'], ['Blockly.test.helpers'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../tests/mocha/zoom_controls_test.js', ['Blockly.test.zoomControls'], ['Blockly.Events.utils', 'Blockly.test.helpers'], {'lang': 'es6', 'module': 'goog'}); diff --git a/tests/mocha/block_create_event_test.js b/tests/mocha/block_create_event_test.js index 91a84af3e..69debed96 100644 --- a/tests/mocha/block_create_event_test.js +++ b/tests/mocha/block_create_event_test.js @@ -6,6 +6,7 @@ goog.module('Blockly.test.blockCreateEvent'); +const eventUtils = goog.require('Blockly.Events.utils'); const {assertEventFired, sharedTestSetup, sharedTestTeardown} = goog.require('Blockly.test.helpers'); @@ -48,7 +49,7 @@ suite('Block Create Event', function() { assertEventFired( this.eventsFireStub, Blockly.Events.BlockCreate, - {'recordUndo': false}, + {'recordUndo': false, 'type': eventUtils.BLOCK_CREATE}, this.workspace.id, 'shadowId'); const calls = this.eventsFireStub.getCalls(); diff --git a/tests/mocha/comment_test.js b/tests/mocha/comment_test.js index fa3a86d6b..94a496637 100644 --- a/tests/mocha/comment_test.js +++ b/tests/mocha/comment_test.js @@ -6,6 +6,7 @@ goog.module('Blockly.test.comments'); +const eventUtils = goog.require('Blockly.Events.utils'); const {assertEventFired, sharedTestSetup, sharedTestTeardown} = goog.require('Blockly.test.helpers'); @@ -54,7 +55,7 @@ suite('Comments', function() { assertEditable(this.comment); assertEventFired( this.eventsFireStub, Blockly.Events.BubbleOpen, - {bubbleType: 'comment', isOpen: true}, this.workspace.id, + {bubbleType: 'comment', isOpen: true, type: eventUtils.BUBBLE_OPEN}, this.workspace.id, this.block.id); }); test('Not Editable', function() { @@ -66,8 +67,8 @@ suite('Comments', function() { assertNotEditable(this.comment); assertEventFired( this.eventsFireStub, Blockly.Events.BubbleOpen, - {bubbleType: 'comment', isOpen: true}, this.workspace.id, - this.block.id); + {bubbleType: 'comment', isOpen: true, type: eventUtils.BUBBLE_OPEN}, + this.workspace.id, this.block.id); }); test('Editable -> Not Editable', function() { this.comment.setVisible(true); @@ -79,8 +80,8 @@ suite('Comments', function() { assertNotEditable(this.comment); assertEventFired( this.eventsFireStub, Blockly.Events.BubbleOpen, - {bubbleType: 'comment', isOpen: true}, this.workspace.id, - this.block.id); + {bubbleType: 'comment', isOpen: true, type: eventUtils.BUBBLE_OPEN}, + this.workspace.id, this.block.id); }); test('Not Editable -> Editable', function() { const editableStub = sinon.stub(this.block, 'isEditable').returns(false); @@ -94,8 +95,8 @@ suite('Comments', function() { assertEditable(this.comment); assertEventFired( this.eventsFireStub, Blockly.Events.BubbleOpen, - {bubbleType: 'comment', isOpen: true}, this.workspace.id, - this.block.id); + {bubbleType: 'comment', isOpen: true, type: eventUtils.BUBBLE_OPEN}, + this.workspace.id, this.block.id); }); }); suite('Set/Get Bubble Size', function() { diff --git a/tests/mocha/gesture_test.js b/tests/mocha/gesture_test.js index 8ecaee0de..16a6cadda 100644 --- a/tests/mocha/gesture_test.js +++ b/tests/mocha/gesture_test.js @@ -6,6 +6,7 @@ goog.module('Blockly.test.gesture'); +const eventUtils = goog.require('Blockly.Events.utils'); const {assertEventFired, assertEventNotFired, defineBasicBlockWithField, dispatchPointerEvent, sharedTestSetup, sharedTestTeardown} = goog.require('Blockly.test.helpers'); @@ -34,8 +35,8 @@ suite('Gesture', function() { assertEventFired(eventsFireStub, Blockly.Events.Selected, - {oldElementId: null, newElementId: block.id}, fieldWorkspace.id); - assertEventNotFired(eventsFireStub, Blockly.Events.Click, {}); + {oldElementId: null, newElementId: block.id, type: eventUtils.SELECTED}, fieldWorkspace.id); + assertEventNotFired(eventsFireStub, Blockly.Events.Click, {type: eventUtils.CLICK}); } function getTopFlyoutBlock(flyout) { diff --git a/tests/mocha/jso_deserialization_test.js b/tests/mocha/jso_deserialization_test.js index 3a0d51f8e..02eace4af 100644 --- a/tests/mocha/jso_deserialization_test.js +++ b/tests/mocha/jso_deserialization_test.js @@ -6,6 +6,7 @@ goog.module('Blockly.test.jsoDeserialization'); +const eventUtils = goog.require('Blockly.Events.utils'); const {assertEventFired, sharedTestSetup, sharedTestTeardown, workspaceTeardown} = goog.require('Blockly.test.helpers'); @@ -38,7 +39,7 @@ suite('JSO Deserialization', function() { assertEventFired( this.eventsFireStub, Blockly.Events.FinishedLoading, - {}, + {type: eventUtils.FINISHED_LOADING}, this.workspace.id); }); @@ -58,9 +59,8 @@ suite('JSO Deserialization', function() { Blockly.Events.setGroup('my group'); Blockly.serialization.workspaces.load(state, this.workspace); assertEventFired( - this.eventsFireStub, - Blockly.Events.FinishedLoading, - {'group': 'my group'}, + this.eventsFireStub, Blockly.Events.FinishedLoading, + {'group': 'my group', "type": eventUtils.FINISHED_LOADING}, this.workspace.id); }); @@ -107,13 +107,12 @@ suite('JSO Deserialization', function() { }; Blockly.serialization.workspaces.load(state, this.workspace); assertEventFired( - this.eventsFireStub, - Blockly.Events.VarCreate, - { + this.eventsFireStub, Blockly.Events.VarCreate, { 'varName': 'test', 'varId': 'testId', 'varType': '', 'recordUndo': false, + "type": eventUtils.VAR_CREATE, }, this.workspace.id); }); @@ -129,13 +128,12 @@ suite('JSO Deserialization', function() { }; Blockly.serialization.workspaces.load(state, this.workspace, {recordUndo: true}); assertEventFired( - this.eventsFireStub, - Blockly.Events.VarCreate, - { + this.eventsFireStub, Blockly.Events.VarCreate, { 'varName': 'test', 'varId': 'testId', 'varType': '', 'recordUndo': true, + "type": eventUtils.VAR_CREATE, }, this.workspace.id); }); @@ -152,13 +150,12 @@ suite('JSO Deserialization', function() { Blockly.Events.setGroup('my group'); Blockly.serialization.workspaces.load(state, this.workspace); assertEventFired( - this.eventsFireStub, - Blockly.Events.VarCreate, - { + this.eventsFireStub, Blockly.Events.VarCreate, { 'varName': 'test', 'varId': 'testId', 'varType': '', 'group': 'my group', + "type": eventUtils.VAR_CREATE, }, this.workspace.id); }); @@ -216,9 +213,12 @@ suite('JSO Deserialization', function() { }, 0); chai.assert.equal(count, 1); assertEventFired( - this.eventsFireStub, - Blockly.Events.VarCreate, - {'varName': 'test', 'varId': 'testId', 'varType': ''}, + this.eventsFireStub, Blockly.Events.VarCreate, { + 'varName': 'test', + 'varId': 'testId', + 'varType': '', + "type": eventUtils.VAR_CREATE, + }, this.workspace.id); }); }); @@ -242,7 +242,7 @@ suite('JSO Deserialization', function() { assertEventFired( this.eventsFireStub, Blockly.Events.BlockCreate, - {'recordUndo': false}, + {'recordUndo': false, "type": eventUtils.BLOCK_CREATE}, this.workspace.id, 'testId'); }); @@ -264,7 +264,7 @@ suite('JSO Deserialization', function() { assertEventFired( this.eventsFireStub, Blockly.Events.BlockCreate, - {'recordUndo': true}, + {'recordUndo': true, "type": eventUtils.BLOCK_CREATE}, this.workspace.id, 'testId'); }); @@ -287,7 +287,7 @@ suite('JSO Deserialization', function() { assertEventFired( this.eventsFireStub, Blockly.Events.BlockCreate, - {'group': 'my group'}, + {'group': 'my group', "type": eventUtils.BLOCK_CREATE}, this.workspace.id, 'testId'); }); @@ -348,7 +348,7 @@ suite('JSO Deserialization', function() { assertEventFired( this.eventsFireStub, Blockly.Events.BlockCreate, - {}, + {type: eventUtils.BLOCK_CREATE}, this.workspace.id, 'id1'); }); @@ -383,7 +383,7 @@ suite('JSO Deserialization', function() { assertEventFired( this.eventsFireStub, Blockly.Events.BlockCreate, - {'recordUndo': true}, + {'recordUndo': true, "type": eventUtils.BLOCK_CREATE}, this.workspace.id, 'testId'); }); @@ -400,7 +400,7 @@ suite('JSO Deserialization', function() { assertEventFired( this.eventsFireStub, Blockly.Events.BlockCreate, - {'group': 'my group'}, + {'group': 'my group', "type": eventUtils.BLOCK_CREATE}, this.workspace.id, 'testId'); }); @@ -662,7 +662,7 @@ suite('JSO Deserialization', function() { Blockly.serialization.workspaces.load( {'first': {}, 'third': {}, 'second': {}}, this.workspace); - + Blockly.serialization.registry.unregister('first'); Blockly.serialization.registry.unregister('second'); Blockly.serialization.registry.unregister('third'); diff --git a/tests/mocha/test_helpers.js b/tests/mocha/test_helpers.js index 9a404e629..4f8ab2eaf 100644 --- a/tests/mocha/test_helpers.js +++ b/tests/mocha/test_helpers.js @@ -401,7 +401,6 @@ exports.assertEventEquals = assertEventEquals; function assertEventFired(spy, instanceType, expectedProperties, expectedWorkspaceId, expectedBlockId) { expectedProperties = Object.assign({ - type: instanceType.prototype.type, workspaceId: expectedWorkspaceId, blockId: expectedBlockId, }, expectedProperties); @@ -423,7 +422,6 @@ exports.assertEventFired = assertEventFired; */ function assertEventNotFired(spy, instanceType, expectedProperties, expectedWorkspaceId, expectedBlockId) { - expectedProperties.type = instanceType.prototype.type; if (expectedWorkspaceId !== undefined) { expectedProperties.workspaceId = expectedWorkspaceId; } diff --git a/tests/mocha/theme_test.js b/tests/mocha/theme_test.js index 5c8d5d24e..fa9480624 100644 --- a/tests/mocha/theme_test.js +++ b/tests/mocha/theme_test.js @@ -6,6 +6,7 @@ goog.module('Blockly.test.theme'); +const eventUtils = goog.require('Blockly.Events.utils'); const {assertEventFired, sharedTestSetup, sharedTestTeardown, workspaceTeardown} = goog.require('Blockly.test.helpers'); @@ -146,7 +147,7 @@ suite('Theme', function() { assertEventFired( this.eventsFireStub, Blockly.Events.ThemeChange, - {themeName: 'themeName'}, workspace.id); + {themeName: 'themeName', type: eventUtils.THEME_CHANGE}, workspace.id); } finally { workspaceTeardown.call(this, workspace); } diff --git a/tests/mocha/trashcan_test.js b/tests/mocha/trashcan_test.js index fc4550b77..d82f60699 100644 --- a/tests/mocha/trashcan_test.js +++ b/tests/mocha/trashcan_test.js @@ -6,8 +6,8 @@ goog.module('Blockly.test.trashcan'); -const {assertEventFired, assertEventNotFired, defineBasicBlockWithField, defineRowBlock, defineStatementBlock, defineStackBlock, defineMutatorBlocks, sharedTestSetup, sharedTestTeardown, simulateClick} = goog.require('Blockly.test.helpers'); const eventUtils = goog.require('Blockly.Events.utils'); +const {assertEventFired, assertEventNotFired, defineBasicBlockWithField, defineRowBlock, defineStatementBlock, defineStackBlock, defineMutatorBlocks, sharedTestSetup, sharedTestTeardown, simulateClick} = goog.require('Blockly.test.helpers'); suite("Trashcan", function() { @@ -77,9 +77,9 @@ suite("Trashcan", function() { simulateClick(this.trashcan.svgGroup_); assertEventNotFired( - this.eventsFireStub, Blockly.Events.TrashcanOpen, {}); + this.eventsFireStub, Blockly.Events.TrashcanOpen, {type: eventUtils.CLICK}); assertEventFired( - this.eventsFireStub, Blockly.Events.Click, {targetType: 'workspace'}, + this.eventsFireStub, Blockly.Events.Click, {targetType: 'workspace', type: eventUtils.CLICK}, this.workspace.id, null); }); test("Click with contents - fires trashcanOpen", function() { @@ -94,9 +94,9 @@ suite("Trashcan", function() { assertEventFired( this.eventsFireStub, Blockly.Events.TrashcanOpen, - {isOpen: true}, this.workspace.id); + {isOpen: true, type: eventUtils.TRASHCAN_OPEN}, this.workspace.id); assertEventNotFired( - this.eventsFireStub, Blockly.Events.Click, {}); + this.eventsFireStub, Blockly.Events.Click, {type: eventUtils.TRASHCAN_OPEN}); }); test("Click outside trashcan - fires trashcanClose", function() { sinon.stub(this.trashcan.flyout, 'isVisible').returns(true); @@ -109,9 +109,9 @@ suite("Trashcan", function() { assertEventFired( this.eventsFireStub, Blockly.Events.TrashcanOpen, - {isOpen: false}, this.workspace.id); + {isOpen: false, type: eventUtils.TRASHCAN_OPEN}, this.workspace.id); assertEventFired( - this.eventsFireStub, Blockly.Events.Click, {targetType: 'workspace'}, + this.eventsFireStub, Blockly.Events.Click, {targetType: 'workspace', type: eventUtils.CLICK}, this.workspace.id, null); }); }); diff --git a/tests/mocha/workspace_svg_test.js b/tests/mocha/workspace_svg_test.js index c6af088ec..6271b2795 100644 --- a/tests/mocha/workspace_svg_test.js +++ b/tests/mocha/workspace_svg_test.js @@ -6,6 +6,7 @@ goog.module('Blockly.test.workspaceSvg'); +const eventUtils = goog.require('Blockly.Events.utils'); const {assertEventFired, assertEventNotFired, assertVariableValues, createFireChangeListenerSpy, defineStackBlock, sharedTestSetup, sharedTestTeardown, workspaceTeardown} = goog.require('Blockly.test.helpers'); const {testAWorkspace} = goog.require('Blockly.test.workspaceHelpers'); @@ -182,6 +183,7 @@ suite('WorkspaceSvg', function() { oldScale: 1, viewTop: metrics.viewTop, viewLeft: metrics.viewLeft, + type: eventUtils.VIEWPORT_CHANGE, }; assertSpyFiredViewportEvent( eventsFireStub, workspace, expectedProperties); @@ -294,9 +296,10 @@ suite('WorkspaceSvg', function() { ''), this.workspace); this.clock.runAll(); assertEventNotFired( - this.eventsFireStub, Blockly.Events.ViewportChange, {}); + this.eventsFireStub, Blockly.Events.ViewportChange, {type: eventUtils.VIEWPORT_CHANGE}); assertEventNotFired( - this.changeListenerSpy, Blockly.Events.ViewportChange, {}); + this.changeListenerSpy, Blockly.Events.ViewportChange, + {type: eventUtils.VIEWPORT_CHANGE}); }); test('domToWorkspace at 0,0 that doesn\'t trigger scroll', function() { // 4 blocks with space in center. @@ -317,9 +320,11 @@ suite('WorkspaceSvg', function() { Blockly.Xml.domToWorkspace(xmlDom, this.workspace); this.clock.runAll(); assertEventNotFired( - this.eventsFireStub, Blockly.Events.ViewportChange, {}); + this.eventsFireStub, Blockly.Events.ViewportChange, + {type: eventUtils.VIEWPORT_CHANGE}); assertEventNotFired( - this.changeListenerSpy, Blockly.Events.ViewportChange, {}); + this.changeListenerSpy, Blockly.Events.ViewportChange, + {type: eventUtils.VIEWPORT_CHANGE}); }); test.skip('domToWorkspace multiple blocks triggers one viewport event', function() { // TODO: Un-skip after adding filtering for consecutive viewport events. diff --git a/tests/mocha/zoom_controls_test.js b/tests/mocha/zoom_controls_test.js index e17bccddb..3d9d1f2d4 100644 --- a/tests/mocha/zoom_controls_test.js +++ b/tests/mocha/zoom_controls_test.js @@ -6,6 +6,7 @@ goog.module('Blockly.test.zoomControls'); +const eventUtils = goog.require('Blockly.Events.utils'); const {assertEventFired, assertEventNotFired, sharedTestSetup, sharedTestTeardown, simulateClick} = goog.require('Blockly.test.helpers'); @@ -31,10 +32,10 @@ suite("Zoom Controls", function() { assertEventFired( this.eventsFireStub, Blockly.Events.Click, - {targetType: 'zoom_controls'}, this.workspace.id, null); + {targetType: 'zoom_controls', type: eventUtils.CLICK}, this.workspace.id, null); assertEventNotFired( this.eventsFireStub, Blockly.Events.Click, - {targetType: 'workspace'}); + {targetType: 'workspace', type: eventUtils.CLICK}); chai.assert.closeTo(this.workspace.getScale(), 1.2, 0.05); }); test("Zoom out", function() { @@ -42,10 +43,10 @@ suite("Zoom Controls", function() { assertEventFired( this.eventsFireStub, Blockly.Events.Click, - {targetType: 'zoom_controls'}, this.workspace.id, null); + {targetType: 'zoom_controls', type: eventUtils.CLICK}, this.workspace.id, null); assertEventNotFired( this.eventsFireStub, Blockly.Events.Click, - {targetType: 'workspace'}); + {targetType: 'workspace', type: eventUtils.CLICK}); chai.assert.closeTo(this.workspace.getScale(), 0.8, 0.05); }); test("Reset zoom", function() { @@ -53,10 +54,10 @@ suite("Zoom Controls", function() { assertEventFired( this.eventsFireStub, Blockly.Events.Click, - {targetType: 'zoom_controls'}, this.workspace.id, null); + {targetType: 'zoom_controls', type: eventUtils.CLICK}, this.workspace.id, null); assertEventNotFired( this.eventsFireStub, Blockly.Events.Click, - {targetType: 'workspace'}); + {targetType: 'workspace', type: eventUtils.CLICK}); chai.assert.equal(this.workspace.getScale(), 1); }); }); From f5caf964aad346866da8e71839fa2d0f0e4b58b9 Mon Sep 17 00:00:00 2001 From: Rachel Fenichel Date: Fri, 14 Jan 2022 12:43:13 -0800 Subject: [PATCH 031/128] refactor: convert renderer classes to es6 classes (#5874) * refactor: convert zelos renderer classes to es6 classes * refactor: convert zelos measurables to es6 classes * refactor: convert thrasos classes to es6 classes * refactor: convert minimalist classes to es6 classes * refactor: update geras classes to es6 classes * chore: rebuild and format * chore: fix indentation in comments --- core/renderers/common/marker_svg.js | 7 + core/renderers/geras/constants.js | 82 +- core/renderers/geras/drawer.js | 333 ++-- core/renderers/geras/highlight_constants.js | 480 ++--- core/renderers/geras/highlighter.js | 449 +++-- core/renderers/geras/info.js | 757 +++---- .../geras/measurables/inline_input.js | 37 +- .../geras/measurables/statement_input.js | 35 +- core/renderers/geras/renderer.js | 196 +- core/renderers/minimalist/constants.js | 17 +- core/renderers/minimalist/drawer.js | 23 +- core/renderers/minimalist/info.js | 38 +- core/renderers/minimalist/renderer.js | 81 +- core/renderers/thrasos/info.js | 527 ++--- core/renderers/thrasos/renderer.js | 40 +- core/renderers/zelos/constants.js | 1747 +++++++++-------- core/renderers/zelos/drawer.js | 362 ++-- core/renderers/zelos/info.js | 1007 +++++----- core/renderers/zelos/marker_svg.js | 248 +-- .../renderers/zelos/measurables/bottom_row.js | 63 +- core/renderers/zelos/measurables/inputs.js | 45 +- .../zelos/measurables/row_elements.js | 29 +- core/renderers/zelos/measurables/top_row.js | 69 +- core/renderers/zelos/path_object.js | 380 ++-- core/renderers/zelos/renderer.js | 199 +- scripts/gulpfiles/chunks.json | 2 +- tests/deps.js | 46 +- 27 files changed, 3711 insertions(+), 3588 deletions(-) diff --git a/core/renderers/common/marker_svg.js b/core/renderers/common/marker_svg.js index 8d19b9191..6878c9e54 100644 --- a/core/renderers/common/marker_svg.js +++ b/core/renderers/common/marker_svg.js @@ -114,6 +114,13 @@ const MarkerSvg = function(workspace, constants, marker) { * @type {string} */ this.colour_ = marker.colour || defaultColour; + + /** + * The root SVG group containing the marker. + * @type {SVGGElement} + * @protected + */ + this.markerSvg_ = null; }; /** diff --git a/core/renderers/geras/constants.js b/core/renderers/geras/constants.js index 9f4f77c8c..26e7f5ebd 100644 --- a/core/renderers/geras/constants.js +++ b/core/renderers/geras/constants.js @@ -17,57 +17,57 @@ */ goog.module('Blockly.geras.ConstantProvider'); -const object = goog.require('Blockly.utils.object'); const {ConstantProvider: BaseConstantProvider} = goog.require('Blockly.blockRendering.ConstantProvider'); /** * An object that provides constants for rendering blocks in Geras mode. - * @constructor - * @package * @extends {BaseConstantProvider} - * @alias Blockly.geras.ConstantProvider */ -const ConstantProvider = function() { - ConstantProvider.superClass_.constructor.call(this); +class ConstantProvider extends BaseConstantProvider { + /** + * @package + * @alias Blockly.geras.ConstantProvider + */ + constructor() { + super(); + + /** + * @override + */ + this.FIELD_TEXT_BASELINE_CENTER = false; + + // The dark/shadow path in classic rendering is the same as the normal block + // path, but translated down one and right one. + this.DARK_PATH_OFFSET = 1; + + /** + * The maximum width of a bottom row that follows a statement input and has + * inputs inline. + * @type {number} + */ + this.MAX_BOTTOM_WIDTH = 30; + + /** + * @override + */ + this.STATEMENT_BOTTOM_SPACER = -this.NOTCH_HEIGHT / 2; + } /** * @override */ - this.FIELD_TEXT_BASELINE_CENTER = false; - - // The dark/shadow path in classic rendering is the same as the normal block - // path, but translated down one and right one. - this.DARK_PATH_OFFSET = 1; - - /** - * The maximum width of a bottom row that follows a statement input and has - * inputs inline. - * @type {number} - */ - this.MAX_BOTTOM_WIDTH = 30; - - /** - * @override - */ - this.STATEMENT_BOTTOM_SPACER = -this.NOTCH_HEIGHT / 2; -}; -object.inherits(ConstantProvider, BaseConstantProvider); - - -/** - * @override - */ -ConstantProvider.prototype.getCSS_ = function(selector) { - return ConstantProvider.superClass_.getCSS_.call(this, selector).concat([ - /* eslint-disable indent */ - // Insertion marker. - selector + ' .blocklyInsertionMarker>.blocklyPathLight,', - selector + ' .blocklyInsertionMarker>.blocklyPathDark {', - 'fill-opacity: ' + this.INSERTION_MARKER_OPACITY + ';', 'stroke: none;', - '}', - /* eslint-enable indent */ - ]); -}; + getCSS_(selector) { + return super.getCSS_(selector).concat([ + /* eslint-disable indent */ + // Insertion marker. + selector + ' .blocklyInsertionMarker>.blocklyPathLight,', + selector + ' .blocklyInsertionMarker>.blocklyPathDark {', + 'fill-opacity: ' + this.INSERTION_MARKER_OPACITY + ';', 'stroke: none;', + '}', + /* eslint-enable indent */ + ]); + } +} exports.ConstantProvider = ConstantProvider; diff --git a/core/renderers/geras/drawer.js b/core/renderers/geras/drawer.js index c56b6e5fe..73186e86a 100644 --- a/core/renderers/geras/drawer.js +++ b/core/renderers/geras/drawer.js @@ -16,13 +16,14 @@ goog.module('Blockly.geras.Drawer'); const debug = goog.require('Blockly.blockRendering.debug'); -const object = goog.require('Blockly.utils.object'); const svgPaths = goog.require('Blockly.utils.svgPaths'); /* eslint-disable-next-line no-unused-vars */ const {BlockSvg} = goog.requireType('Blockly.BlockSvg'); const {Drawer: BaseDrawer} = goog.require('Blockly.blockRendering.Drawer'); const {Highlighter} = goog.require('Blockly.geras.Highlighter'); /* eslint-disable-next-line no-unused-vars */ +const {InlineInput} = goog.require('Blockly.geras.InlineInput'); +/* eslint-disable-next-line no-unused-vars */ const {PathObject} = goog.requireType('Blockly.geras.PathObject'); /* eslint-disable-next-line no-unused-vars */ const {RenderInfo} = goog.requireType('Blockly.geras.RenderInfo'); @@ -30,183 +31,185 @@ const {RenderInfo} = goog.requireType('Blockly.geras.RenderInfo'); /** * An object that draws a block based on the given rendering information. - * @param {!BlockSvg} block The block to render. - * @param {!RenderInfo} info An object containing all - * information needed to render this block. - * @package - * @constructor * @extends {BaseDrawer} - * @alias Blockly.geras.Drawer */ -const Drawer = function(block, info) { - Drawer.superClass_.constructor.call(this, block, info); - // Unlike Thrasos, Geras has highlights and drop shadows. - this.highlighter_ = new Highlighter(info); -}; -object.inherits(Drawer, BaseDrawer); - -/** - * @override - */ -Drawer.prototype.draw = function() { - this.hideHiddenIcons_(); - this.drawOutline_(); - this.drawInternals_(); - - const pathObject = - /** @type {!PathObject} */ (this.block_.pathObject); - pathObject.setPath(this.outlinePath_ + '\n' + this.inlinePath_); - pathObject.setHighlightPath(this.highlighter_.getPath()); - if (this.info_.RTL) { - pathObject.flipRTL(); +class Drawer extends BaseDrawer { + /** + * @param {!BlockSvg} block The block to render. + * @param {!RenderInfo} info An object containing all + * information needed to render this block. + * @package + * @alias Blockly.geras.Drawer + */ + constructor(block, info) { + super(block, info); + // Unlike Thrasos, Geras has highlights and drop shadows. + this.highlighter_ = new Highlighter(info); } - if (debug.isDebuggerEnabled()) { - this.block_.renderingDebugger.drawDebug(this.block_, this.info_); - } - this.recordSizeOnBlock_(); -}; -/** - * @override - */ -Drawer.prototype.drawTop_ = function() { - this.highlighter_.drawTopCorner(this.info_.topRow); - this.highlighter_.drawRightSideRow(this.info_.topRow); + /** + * @override + */ + draw() { + this.hideHiddenIcons_(); + this.drawOutline_(); + this.drawInternals_(); - Drawer.superClass_.drawTop_.call(this); -}; - -/** - * @override - */ -Drawer.prototype.drawJaggedEdge_ = function(row) { - this.highlighter_.drawJaggedEdge_(row); - - Drawer.superClass_.drawJaggedEdge_.call(this, row); -}; - -/** - * @override - */ -Drawer.prototype.drawValueInput_ = function(row) { - this.highlighter_.drawValueInput(row); - - Drawer.superClass_.drawValueInput_.call(this, row); -}; - -/** - * @override - */ -Drawer.prototype.drawStatementInput_ = function(row) { - this.highlighter_.drawStatementInput(row); - - Drawer.superClass_.drawStatementInput_.call(this, row); -}; - -/** - * @override - */ -Drawer.prototype.drawRightSideRow_ = function(row) { - this.highlighter_.drawRightSideRow(row); - - this.outlinePath_ += svgPaths.lineOnAxis('H', row.xPos + row.width) + - svgPaths.lineOnAxis('V', row.yPos + row.height); -}; - -/** - * @override - */ -Drawer.prototype.drawBottom_ = function() { - this.highlighter_.drawBottomRow(this.info_.bottomRow); - - Drawer.superClass_.drawBottom_.call(this); -}; - -/** - * Add steps for the left side of the block, which may include an output - * connection - * @protected - * @override - */ -Drawer.prototype.drawLeft_ = function() { - this.highlighter_.drawLeft(); - - Drawer.superClass_.drawLeft_.call(this); -}; - -/** - * @override - */ -Drawer.prototype.drawInlineInput_ = function(input) { - this.highlighter_.drawInlineInput(input); - - Drawer.superClass_.drawInlineInput_.call(this, input); -}; - -/** - * @override - */ -Drawer.prototype.positionInlineInputConnection_ = function(input) { - const yPos = input.centerline - input.height / 2; - // Move the connection. - if (input.connectionModel) { - // xPos already contains info about startX - let connX = - input.xPos + input.connectionWidth + this.constants_.DARK_PATH_OFFSET; + const pathObject = + /** @type {!PathObject} */ (this.block_.pathObject); + pathObject.setPath(this.outlinePath_ + '\n' + this.inlinePath_); + pathObject.setHighlightPath(this.highlighter_.getPath()); if (this.info_.RTL) { - connX *= -1; + pathObject.flipRTL(); } - input.connectionModel.setOffsetInBlock( - connX, - yPos + input.connectionOffsetY + this.constants_.DARK_PATH_OFFSET); - } -}; - -/** - * @override - */ -Drawer.prototype.positionStatementInputConnection_ = function(row) { - const input = row.getLastInput(); - if (input.connectionModel) { - let connX = row.xPos + row.statementEdge + input.notchOffset; - if (this.info_.RTL) { - connX *= -1; - } else { - connX += this.constants_.DARK_PATH_OFFSET; + if (debug.isDebuggerEnabled()) { + this.block_.renderingDebugger.drawDebug(this.block_, this.info_); } - input.connectionModel.setOffsetInBlock( - connX, row.yPos + this.constants_.DARK_PATH_OFFSET); + this.recordSizeOnBlock_(); } -}; -/** - * @override - */ -Drawer.prototype.positionExternalValueConnection_ = function(row) { - const input = row.getLastInput(); - if (input.connectionModel) { - let connX = row.xPos + row.width + this.constants_.DARK_PATH_OFFSET; - if (this.info_.RTL) { - connX *= -1; + /** + * @override + */ + drawTop_() { + this.highlighter_.drawTopCorner(this.info_.topRow); + this.highlighter_.drawRightSideRow(this.info_.topRow); + + super.drawTop_(); + } + + /** + * @override + */ + drawJaggedEdge_(row) { + this.highlighter_.drawJaggedEdge_(row); + + super.drawJaggedEdge_(row); + } + + /** + * @override + */ + drawValueInput_(row) { + this.highlighter_.drawValueInput(row); + + super.drawValueInput_(row); + } + + /** + * @override + */ + drawStatementInput_(row) { + this.highlighter_.drawStatementInput(row); + + super.drawStatementInput_(row); + } + + /** + * @override + */ + drawRightSideRow_(row) { + this.highlighter_.drawRightSideRow(row); + + this.outlinePath_ += svgPaths.lineOnAxis('H', row.xPos + row.width) + + svgPaths.lineOnAxis('V', row.yPos + row.height); + } + + /** + * @override + */ + drawBottom_() { + this.highlighter_.drawBottomRow(this.info_.bottomRow); + + super.drawBottom_(); + } + + /** + * Add steps for the left side of the block, which may include an output + * connection + * @protected + * @override + */ + drawLeft_() { + this.highlighter_.drawLeft(); + + super.drawLeft_(); + } + + /** + * @override + */ + drawInlineInput_(input) { + this.highlighter_.drawInlineInput(/** @type {!InlineInput} */ (input)); + + super.drawInlineInput_(input); + } + + /** + * @override + */ + positionInlineInputConnection_(input) { + const yPos = input.centerline - input.height / 2; + // Move the connection. + if (input.connectionModel) { + // xPos already contains info about startX + let connX = + input.xPos + input.connectionWidth + this.constants_.DARK_PATH_OFFSET; + if (this.info_.RTL) { + connX *= -1; + } + input.connectionModel.setOffsetInBlock( + connX, + yPos + input.connectionOffsetY + this.constants_.DARK_PATH_OFFSET); } - input.connectionModel.setOffsetInBlock(connX, row.yPos); } -}; -/** - * @override - */ -Drawer.prototype.positionNextConnection_ = function() { - const bottomRow = this.info_.bottomRow; - - if (bottomRow.connection) { - const connInfo = bottomRow.connection; - const x = connInfo.xPos; // Already contains info about startX. - const connX = - (this.info_.RTL ? -x : x) + (this.constants_.DARK_PATH_OFFSET / 2); - connInfo.connectionModel.setOffsetInBlock( - connX, bottomRow.baseline + this.constants_.DARK_PATH_OFFSET); + /** + * @override + */ + positionStatementInputConnection_(row) { + const input = row.getLastInput(); + if (input.connectionModel) { + let connX = row.xPos + row.statementEdge + input.notchOffset; + if (this.info_.RTL) { + connX *= -1; + } else { + connX += this.constants_.DARK_PATH_OFFSET; + } + input.connectionModel.setOffsetInBlock( + connX, row.yPos + this.constants_.DARK_PATH_OFFSET); + } } -}; + + /** + * @override + */ + positionExternalValueConnection_(row) { + const input = row.getLastInput(); + if (input.connectionModel) { + let connX = row.xPos + row.width + this.constants_.DARK_PATH_OFFSET; + if (this.info_.RTL) { + connX *= -1; + } + input.connectionModel.setOffsetInBlock(connX, row.yPos); + } + } + + /** + * @override + */ + positionNextConnection_() { + const bottomRow = this.info_.bottomRow; + + if (bottomRow.connection) { + const connInfo = bottomRow.connection; + const x = connInfo.xPos; // Already contains info about startX. + const connX = + (this.info_.RTL ? -x : x) + (this.constants_.DARK_PATH_OFFSET / 2); + connInfo.connectionModel.setOffsetInBlock( + connX, bottomRow.baseline + this.constants_.DARK_PATH_OFFSET); + } + } +} exports.Drawer = Drawer; diff --git a/core/renderers/geras/highlight_constants.js b/core/renderers/geras/highlight_constants.js index 5627e40c9..23f26d808 100644 --- a/core/renderers/geras/highlight_constants.js +++ b/core/renderers/geras/highlight_constants.js @@ -25,269 +25,275 @@ const {ConstantProvider} = goog.requireType('Blockly.blockRendering.ConstantProv * Some highlights are simple offsets of the parent paths and can be generated * programmatically. Others, especially on curves, are just made out of piles * of constants and are hard to tweak. - * @param {!ConstantProvider} constants The rendering - * constants provider. - * @constructor - * @package - * @alias Blockly.geras.HighlightConstantProvider */ -const HighlightConstantProvider = function(constants) { +class HighlightConstantProvider { /** - * The renderer's constant provider. - * @type {!ConstantProvider} + * @param {!ConstantProvider} constants The rendering + * constants provider. + * @package + * @alias Blockly.geras.HighlightConstantProvider */ - this.constantProvider = constants; + constructor(constants) { + /** + * The renderer's constant provider. + * @type {!ConstantProvider} + */ + this.constantProvider = constants; + + /** + * The offset between the block's main path and highlight path. + * @type {number} + * @package + */ + this.OFFSET = 0.5; + + /** + * The start point, which is offset in both X and Y, as an SVG path chunk. + * @type {string} + */ + this.START_POINT = svgPaths.moveBy(this.OFFSET, this.OFFSET); + } /** - * The offset between the block's main path and highlight path. - * @type {number} + * Initialize shape objects based on the constants set in the constructor. * @package */ - this.OFFSET = 0.5; + init() { + /** + * An object containing sizing and path information about inside corner + * highlights. + * @type {!Object} + */ + this.INSIDE_CORNER = this.makeInsideCorner(); + + /** + * An object containing sizing and path information about outside corner + * highlights. + * @type {!Object} + */ + this.OUTSIDE_CORNER = this.makeOutsideCorner(); + + /** + * An object containing sizing and path information about puzzle tab + * highlights. + * @type {!Object} + */ + this.PUZZLE_TAB = this.makePuzzleTab(); + + /** + * An object containing sizing and path information about notch highlights. + * @type {!Object} + */ + this.NOTCH = this.makeNotch(); + + /** + * An object containing sizing and path information about highlights for + * collapsed block indicators. + * @type {!Object} + */ + this.JAGGED_TEETH = this.makeJaggedTeeth(); + + /** + * An object containing sizing and path information about start hat + * highlights. + * @type {!Object} + */ + this.START_HAT = this.makeStartHat(); + } /** - * The start point, which is offset in both X and Y, as an SVG path chunk. - * @type {string} + * @return {!Object} An object containing sizing and path information about + * inside corner highlights. + * @package */ - this.START_POINT = svgPaths.moveBy(this.OFFSET, this.OFFSET); -}; + makeInsideCorner() { + const radius = this.constantProvider.CORNER_RADIUS; + const offset = this.OFFSET; -/** - * Initialize shape objects based on the constants set in the constructor. - * @package - */ -HighlightConstantProvider.prototype.init = function() { - /** - * An object containing sizing and path information about inside corner - * highlights. - * @type {!Object} - */ - this.INSIDE_CORNER = this.makeInsideCorner(); + /** + * Distance from shape edge to intersect with a curved corner at 45 degrees. + * Applies to highlighting on around the outside of a curve. + * @const + */ + const distance45outside = (1 - Math.SQRT1_2) * (radius + offset) - offset; + + const pathTopRtl = svgPaths.moveBy(distance45outside, distance45outside) + + svgPaths.arc( + 'a', '0 0,0', radius, + svgPaths.point( + -distance45outside - offset, radius - distance45outside)); + + const pathBottomRtl = svgPaths.arc( + 'a', '0 0,0', radius + offset, + svgPaths.point(radius + offset, radius + offset)); + + const pathBottomLtr = + svgPaths.moveBy(distance45outside, -distance45outside) + + svgPaths.arc( + 'a', '0 0,0', radius + offset, + svgPaths.point( + radius - distance45outside, distance45outside + offset)); + + return { + width: radius + offset, + height: radius, + pathTop: function(rtl) { + return rtl ? pathTopRtl : ''; + }, + pathBottom: function(rtl) { + return rtl ? pathBottomRtl : pathBottomLtr; + }, + }; + } /** - * An object containing sizing and path information about outside corner - * highlights. - * @type {!Object} + * @return {!Object} An object containing sizing and path information about + * outside corner highlights. + * @package */ - this.OUTSIDE_CORNER = this.makeOutsideCorner(); + makeOutsideCorner() { + const radius = this.constantProvider.CORNER_RADIUS; + const offset = this.OFFSET; + + /** + * Distance from shape edge to intersect with a curved corner at 45 degrees. + * Applies to highlighting on around the inside of a curve. + * @const + */ + const distance45inside = (1 - Math.SQRT1_2) * (radius - offset) + offset; + + const topLeftStartX = distance45inside; + const topLeftStartY = distance45inside; + const topLeftCornerHighlightRtl = + svgPaths.moveBy(topLeftStartX, topLeftStartY) + + svgPaths.arc( + 'a', '0 0,1', radius - offset, + svgPaths.point(radius - topLeftStartX, -topLeftStartY + offset)); + /** + * SVG path for drawing the highlight on the rounded top-left corner. + * @const + */ + const topLeftCornerHighlightLtr = svgPaths.moveBy(offset, radius) + + svgPaths.arc( + 'a', '0 0,1', radius - offset, + svgPaths.point(radius, -radius + offset)); + + const bottomLeftStartX = distance45inside; + const bottomLeftStartY = -distance45inside; + const bottomLeftPath = svgPaths.moveBy(bottomLeftStartX, bottomLeftStartY) + + svgPaths.arc( + 'a', '0 0,1', radius - offset, + svgPaths.point( + -bottomLeftStartX + offset, -bottomLeftStartY - radius)); + + return { + height: radius, + topLeft: function(rtl) { + return rtl ? topLeftCornerHighlightRtl : topLeftCornerHighlightLtr; + }, + bottomLeft: function() { + return bottomLeftPath; + }, + }; + } /** - * An object containing sizing and path information about puzzle tab - * highlights. - * @type {!Object} + * @return {!Object} An object containing sizing and path information about + * puzzle tab highlights. + * @package */ - this.PUZZLE_TAB = this.makePuzzleTab(); + makePuzzleTab() { + const width = this.constantProvider.TAB_WIDTH; + const height = this.constantProvider.TAB_HEIGHT; + + // This is how much of the vertical block edge is actually drawn by the + // puzzle tab. + const verticalOverlap = 2.5; + + const highlightRtlUp = + svgPaths.moveBy(-2, -height + verticalOverlap + 0.9) + + svgPaths.lineTo(width * -0.45, -2.1); + + const highlightRtlDown = svgPaths.lineOnAxis('v', verticalOverlap) + + svgPaths.moveBy(-width * 0.97, 2.5) + + svgPaths.curve( + 'q', + [ + svgPaths.point(-width * 0.05, 10), + svgPaths.point(width * 0.3, 9.5), + ]) + + svgPaths.moveBy(width * 0.67, -1.9) + + svgPaths.lineOnAxis('v', verticalOverlap); + + const highlightLtrUp = svgPaths.lineOnAxis('v', -1.5) + + svgPaths.moveBy(width * -0.92, -0.5) + + svgPaths.curve( + 'q', + [svgPaths.point(width * -0.19, -5.5), svgPaths.point(0, -11)]) + + svgPaths.moveBy(width * 0.92, 1); + + const highlightLtrDown = + svgPaths.moveBy(-5, height - 0.7) + svgPaths.lineTo(width * 0.46, -2.1); + + return { + width: width, + height: height, + pathUp: function(rtl) { + return rtl ? highlightRtlUp : highlightLtrUp; + }, + pathDown: function(rtl) { + return rtl ? highlightRtlDown : highlightLtrDown; + }, + }; + } /** - * An object containing sizing and path information about notch highlights. - * @type {!Object} + * @return {!Object} An object containing sizing and path information about + * notch highlights. + * @package */ - this.NOTCH = this.makeNotch(); + makeNotch() { + // This is only for the previous connection. + const pathLeft = svgPaths.lineOnAxis('h', this.OFFSET) + + this.constantProvider.NOTCH.pathLeft; + return {pathLeft: pathLeft}; + } /** - * An object containing sizing and path information about highlights for - * collapsed block indicators. - * @type {!Object} + * @return {!Object} An object containing sizing and path information about + * collapsed block edge highlights. + * @package */ - this.JAGGED_TEETH = this.makeJaggedTeeth(); + makeJaggedTeeth() { + const pathLeft = svgPaths.lineTo(5.1, 2.6) + svgPaths.moveBy(-10.2, 6.8) + + svgPaths.lineTo(5.1, 2.6); + return {pathLeft: pathLeft, height: 12, width: 10.2}; + } /** - * An object containing sizing and path information about start hat - * highlights. - * @type {!Object} + * @return {!Object} An object containing sizing and path information about + * start highlights. + * @package */ - this.START_HAT = this.makeStartHat(); -}; + makeStartHat() { + const hatHeight = this.constantProvider.START_HAT.height; + const pathRtl = svgPaths.moveBy(25, -8.7) + svgPaths.curve('c', [ + svgPaths.point(29.7, -6.2), + svgPaths.point(57.2, -0.5), + svgPaths.point(75, 8.7), + ]); -/** - * @return {!Object} An object containing sizing and path information about - * inside corner highlights. - * @package - */ -HighlightConstantProvider.prototype.makeInsideCorner = function() { - const radius = this.constantProvider.CORNER_RADIUS; - const offset = this.OFFSET; - - /** - * Distance from shape edge to intersect with a curved corner at 45 degrees. - * Applies to highlighting on around the outside of a curve. - * @const - */ - const distance45outside = (1 - Math.SQRT1_2) * (radius + offset) - offset; - - const pathTopRtl = svgPaths.moveBy(distance45outside, distance45outside) + - svgPaths.arc( - 'a', '0 0,0', radius, - svgPaths.point( - -distance45outside - offset, radius - distance45outside)); - - const pathBottomRtl = svgPaths.arc( - 'a', '0 0,0', radius + offset, - svgPaths.point(radius + offset, radius + offset)); - - const pathBottomLtr = svgPaths.moveBy(distance45outside, -distance45outside) + - svgPaths.arc( - 'a', '0 0,0', radius + offset, - svgPaths.point( - radius - distance45outside, distance45outside + offset)); - - return { - width: radius + offset, - height: radius, - pathTop: function(rtl) { - return rtl ? pathTopRtl : ''; - }, - pathBottom: function(rtl) { - return rtl ? pathBottomRtl : pathBottomLtr; - }, - }; -}; - -/** - * @return {!Object} An object containing sizing and path information about - * outside corner highlights. - * @package - */ -HighlightConstantProvider.prototype.makeOutsideCorner = function() { - const radius = this.constantProvider.CORNER_RADIUS; - const offset = this.OFFSET; - - /** - * Distance from shape edge to intersect with a curved corner at 45 degrees. - * Applies to highlighting on around the inside of a curve. - * @const - */ - const distance45inside = (1 - Math.SQRT1_2) * (radius - offset) + offset; - - const topLeftStartX = distance45inside; - const topLeftStartY = distance45inside; - const topLeftCornerHighlightRtl = - svgPaths.moveBy(topLeftStartX, topLeftStartY) + - svgPaths.arc( - 'a', '0 0,1', radius - offset, - svgPaths.point(radius - topLeftStartX, -topLeftStartY + offset)); - /** - * SVG path for drawing the highlight on the rounded top-left corner. - * @const - */ - const topLeftCornerHighlightLtr = svgPaths.moveBy(offset, radius) + - svgPaths.arc( - 'a', '0 0,1', radius - offset, - svgPaths.point(radius, -radius + offset)); - - const bottomLeftStartX = distance45inside; - const bottomLeftStartY = -distance45inside; - const bottomLeftPath = svgPaths.moveBy(bottomLeftStartX, bottomLeftStartY) + - svgPaths.arc( - 'a', '0 0,1', radius - offset, - svgPaths.point( - -bottomLeftStartX + offset, -bottomLeftStartY - radius)); - - return { - height: radius, - topLeft: function(rtl) { - return rtl ? topLeftCornerHighlightRtl : topLeftCornerHighlightLtr; - }, - bottomLeft: function() { - return bottomLeftPath; - }, - }; -}; - -/** - * @return {!Object} An object containing sizing and path information about - * puzzle tab highlights. - * @package - */ -HighlightConstantProvider.prototype.makePuzzleTab = function() { - const width = this.constantProvider.TAB_WIDTH; - const height = this.constantProvider.TAB_HEIGHT; - - // This is how much of the vertical block edge is actually drawn by the puzzle - // tab. - const verticalOverlap = 2.5; - - const highlightRtlUp = svgPaths.moveBy(-2, -height + verticalOverlap + 0.9) + - svgPaths.lineTo(width * -0.45, -2.1); - - const highlightRtlDown = svgPaths.lineOnAxis('v', verticalOverlap) + - svgPaths.moveBy(-width * 0.97, 2.5) + - svgPaths.curve( - 'q', - [ - svgPaths.point(-width * 0.05, 10), - svgPaths.point(width * 0.3, 9.5), - ]) + - svgPaths.moveBy(width * 0.67, -1.9) + - svgPaths.lineOnAxis('v', verticalOverlap); - - const highlightLtrUp = svgPaths.lineOnAxis('v', -1.5) + - svgPaths.moveBy(width * -0.92, -0.5) + - svgPaths.curve( - 'q', [svgPaths.point(width * -0.19, -5.5), svgPaths.point(0, -11)]) + - svgPaths.moveBy(width * 0.92, 1); - - const highlightLtrDown = - svgPaths.moveBy(-5, height - 0.7) + svgPaths.lineTo(width * 0.46, -2.1); - - return { - width: width, - height: height, - pathUp: function(rtl) { - return rtl ? highlightRtlUp : highlightLtrUp; - }, - pathDown: function(rtl) { - return rtl ? highlightRtlDown : highlightLtrDown; - }, - }; -}; - -/** - * @return {!Object} An object containing sizing and path information about - * notch highlights. - * @package - */ -HighlightConstantProvider.prototype.makeNotch = function() { - // This is only for the previous connection. - const pathLeft = svgPaths.lineOnAxis('h', this.OFFSET) + - this.constantProvider.NOTCH.pathLeft; - return {pathLeft: pathLeft}; -}; - -/** - * @return {!Object} An object containing sizing and path information about - * collapsed block edge highlights. - * @package - */ -HighlightConstantProvider.prototype.makeJaggedTeeth = function() { - const pathLeft = svgPaths.lineTo(5.1, 2.6) + svgPaths.moveBy(-10.2, 6.8) + - svgPaths.lineTo(5.1, 2.6); - return {pathLeft: pathLeft, height: 12, width: 10.2}; -}; - -/** - * @return {!Object} An object containing sizing and path information about - * start highlights. - * @package - */ -HighlightConstantProvider.prototype.makeStartHat = function() { - const hatHeight = this.constantProvider.START_HAT.height; - const pathRtl = svgPaths.moveBy(25, -8.7) + svgPaths.curve('c', [ - svgPaths.point(29.7, -6.2), - svgPaths.point(57.2, -0.5), - svgPaths.point(75, 8.7), - ]); - - const pathLtr = svgPaths.curve('c', [ - svgPaths.point(17.8, -9.2), - svgPaths.point(45.3, -14.9), - svgPaths.point(75, -8.7), - ]) + svgPaths.moveTo(100.5, hatHeight + 0.5); - return { - path: function(rtl) { - return rtl ? pathRtl : pathLtr; - }, - }; -}; + const pathLtr = svgPaths.curve('c', [ + svgPaths.point(17.8, -9.2), + svgPaths.point(45.3, -14.9), + svgPaths.point(75, -8.7), + ]) + svgPaths.moveTo(100.5, hatHeight + 0.5); + return { + path: function(rtl) { + return rtl ? pathRtl : pathLtr; + }, + }; + } +} exports.HighlightConstantProvider = HighlightConstantProvider; diff --git a/core/renderers/geras/highlighter.js b/core/renderers/geras/highlighter.js index e54d26837..c81beb077 100644 --- a/core/renderers/geras/highlighter.js +++ b/core/renderers/geras/highlighter.js @@ -19,13 +19,21 @@ goog.module('Blockly.geras.Highlighter'); const svgPaths = goog.require('Blockly.utils.svgPaths'); /* eslint-disable-next-line no-unused-vars */ +const {BottomRow} = goog.require('Blockly.blockRendering.BottomRow'); +/* eslint-disable-next-line no-unused-vars */ const {ConstantProvider} = goog.requireType('Blockly.blockRendering.ConstantProvider'); /* eslint-disable-next-line no-unused-vars */ const {HighlightConstantProvider} = goog.requireType('Blockly.geras.HighlightConstantProvider'); /* eslint-disable-next-line no-unused-vars */ +const {InlineInput} = goog.require('Blockly.geras.InlineInput'); +/* eslint-disable-next-line no-unused-vars */ const {RenderInfo} = goog.requireType('Blockly.geras.RenderInfo'); /* eslint-disable-next-line no-unused-vars */ const {Renderer} = goog.requireType('Blockly.geras.Renderer'); +/* eslint-disable-next-line no-unused-vars */ +const {Row} = goog.requireType('Blockly.blockRendering.Row'); +/* eslint-disable-next-line no-unused-vars */ +const {TopRow} = goog.require('Blockly.blockRendering.TopRow'); const {Types} = goog.require('Blockly.blockRendering.Types'); @@ -39,221 +47,264 @@ const {Types} = goog.require('Blockly.blockRendering.Types'); * position of each part of the block. The resulting paths are not continuous * or closed paths. The highlights for tabs and notches are loosely based on * tab and notch shapes, but are not exactly the same. - * - * @param {!RenderInfo} info An object containing all - * information needed to render this block. - * @package - * @constructor - * @alias Blockly.geras.Highlighter */ -const Highlighter = function(info) { - this.info_ = info; - this.steps_ = ''; - this.inlineSteps_ = ''; +class Highlighter { + /** + * @param {!RenderInfo} info An object containing all + * information needed to render this block. + * @package + * @alias Blockly.geras.Highlighter + */ + constructor(info) { + this.info_ = info; + this.steps_ = ''; + this.inlineSteps_ = ''; - this.RTL_ = this.info_.RTL; + this.RTL_ = this.info_.RTL; - const renderer = /** @type {!Renderer} */ (info.getRenderer()); + const renderer = /** @type {!Renderer} */ (info.getRenderer()); + + /** + * The renderer's constant provider. + * @type {!ConstantProvider} + */ + this.constants_ = renderer.getConstants(); + + /** + * @type {!HighlightConstantProvider} + */ + this.highlightConstants_ = renderer.getHighlightConstants(); + /** + * The offset between the block's main path and highlight path. + * @type {number} + * @private + */ + 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; + } /** - * The renderer's constant provider. - * @type {!ConstantProvider} + * Get the steps for the highlight path. + * @return {string} The steps for the highlight path. + * @package */ - this.constants_ = renderer.getConstants(); + getPath() { + return this.steps_ + '\n' + this.inlineSteps_; + } /** - * @type {!HighlightConstantProvider} + * Add a highlight to the top corner of a block. + * @param {!TopRow} row The top row of the block. + * @package */ - this.highlightConstants_ = renderer.getHighlightConstants(); + drawTopCorner(row) { + this.steps_ += svgPaths.moveBy(row.xPos, this.info_.startY); + for (let i = 0, elem; (elem = row.elements[i]); i++) { + if (Types.isLeftSquareCorner(elem)) { + this.steps_ += this.highlightConstants_.START_POINT; + } else if (Types.isLeftRoundedCorner(elem)) { + this.steps_ += this.outsideCornerPaths_.topLeft(this.RTL_); + } else if (Types.isPreviousConnection(elem)) { + this.steps_ += this.notchPaths_.pathLeft; + } else if (Types.isHat(elem)) { + this.steps_ += this.startPaths_.path(this.RTL_); + } else if (Types.isSpacer(elem) && elem.width !== 0) { + // The end point of the spacer needs to be offset by the highlight + // amount. So instead of using the spacer's width for a relative + // horizontal, use its width and position for an absolute horizontal + // move. + this.steps_ += svgPaths.lineOnAxis( + 'H', elem.xPos + elem.width - this.highlightOffset_); + } + } + + const right = row.xPos + row.width - this.highlightOffset_; + this.steps_ += svgPaths.lineOnAxis('H', right); + } + /** - * The offset between the block's main path and highlight path. - * @type {number} - * @private + * Add a highlight on a jagged edge for a collapsed block. + * @param {!Row} row The row to highlight. + * @package */ - 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; -}; - -/** - * Get the steps for the highlight path. - * @return {string} The steps for the highlight path. - * @package - */ -Highlighter.prototype.getPath = function() { - return this.steps_ + '\n' + this.inlineSteps_; -}; - -Highlighter.prototype.drawTopCorner = function(row) { - this.steps_ += svgPaths.moveBy(row.xPos, this.info_.startY); - for (let i = 0, elem; (elem = row.elements[i]); i++) { - if (Types.isLeftSquareCorner(elem)) { - this.steps_ += this.highlightConstants_.START_POINT; - } else if (Types.isLeftRoundedCorner(elem)) { - this.steps_ += this.outsideCornerPaths_.topLeft(this.RTL_); - } else if (Types.isPreviousConnection(elem)) { - this.steps_ += this.notchPaths_.pathLeft; - } else if (Types.isHat(elem)) { - this.steps_ += this.startPaths_.path(this.RTL_); - } else if (Types.isSpacer(elem) && elem.width !== 0) { - // The end point of the spacer needs to be offset by the highlight amount. - // So instead of using the spacer's width for a relative horizontal, use - // its width and position for an absolute horizontal move. - this.steps_ += svgPaths.lineOnAxis( - 'H', elem.xPos + elem.width - this.highlightOffset_); - } - } - - const right = row.xPos + row.width - this.highlightOffset_; - this.steps_ += svgPaths.lineOnAxis('H', right); -}; - -Highlighter.prototype.drawJaggedEdge_ = function(row) { - if (this.info_.RTL) { - const remainder = - row.height - this.jaggedTeethPaths_.height - this.highlightOffset_; - this.steps_ += - this.jaggedTeethPaths_.pathLeft + svgPaths.lineOnAxis('v', remainder); - } -}; - -Highlighter.prototype.drawValueInput = function(row) { - const input = row.getLastInput(); - if (this.RTL_) { - const belowTabHeight = row.height - input.connectionHeight; - - this.steps_ += - svgPaths.moveTo( - input.xPos + input.width - this.highlightOffset_, row.yPos) + - this.puzzleTabPaths_.pathDown(this.RTL_) + - svgPaths.lineOnAxis('v', belowTabHeight); - } else { - this.steps_ += svgPaths.moveTo(input.xPos + input.width, row.yPos) + - this.puzzleTabPaths_.pathDown(this.RTL_); - } -}; - -Highlighter.prototype.drawStatementInput = function(row) { - const input = row.getLastInput(); - if (this.RTL_) { - const innerHeight = row.height - (2 * this.insideCornerPaths_.height); - this.steps_ += svgPaths.moveTo(input.xPos, row.yPos) + - this.insideCornerPaths_.pathTop(this.RTL_) + - svgPaths.lineOnAxis('v', innerHeight) + - this.insideCornerPaths_.pathBottom(this.RTL_) + - svgPaths.lineTo( - row.width - input.xPos - this.insideCornerPaths_.width, 0); - } else { - this.steps_ += svgPaths.moveTo(input.xPos, row.yPos + row.height) + - this.insideCornerPaths_.pathBottom(this.RTL_) + - svgPaths.lineTo( - row.width - input.xPos - this.insideCornerPaths_.width, 0); - } -}; - -Highlighter.prototype.drawRightSideRow = function(row) { - const rightEdge = row.xPos + row.width - this.highlightOffset_; - if (row.followsStatement) { - this.steps_ += svgPaths.lineOnAxis('H', rightEdge); - } - if (this.RTL_) { - this.steps_ += svgPaths.lineOnAxis('H', rightEdge); - if (row.height > this.highlightOffset_) { - this.steps_ += svgPaths.lineOnAxis( - 'V', row.yPos + row.height - this.highlightOffset_); - } - } -}; - -Highlighter.prototype.drawBottomRow = function(row) { - // Highlight the vertical edge of the bottom row on the input side. - // Highlighting is always from the top left, both in LTR and RTL. - if (this.RTL_) { - this.steps_ += - svgPaths.lineOnAxis('V', row.baseline - this.highlightOffset_); - } else { - const cornerElem = this.info_.bottomRow.elements[0]; - if (Types.isLeftSquareCorner(cornerElem)) { - this.steps_ += svgPaths.moveTo( - row.xPos + this.highlightOffset_, - row.baseline - this.highlightOffset_); - } else if (Types.isLeftRoundedCorner(cornerElem)) { - this.steps_ += svgPaths.moveTo(row.xPos, row.baseline); - this.steps_ += this.outsideCornerPaths_.bottomLeft(); - } - } -}; - -Highlighter.prototype.drawLeft = function() { - const outputConnection = this.info_.outputConnection; - if (outputConnection) { - const tabBottom = - outputConnection.connectionOffsetY + outputConnection.height; - // Draw a line up to the bottom of the tab. - if (this.RTL_) { - this.steps_ += svgPaths.moveTo(this.info_.startX, tabBottom); - } else { - const left = this.info_.startX + this.highlightOffset_; - const bottom = this.info_.bottomRow.baseline - this.highlightOffset_; - this.steps_ += svgPaths.moveTo(left, bottom); - this.steps_ += svgPaths.lineOnAxis('V', tabBottom); - } - this.steps_ += this.puzzleTabPaths_.pathUp(this.RTL_); - } - - if (!this.RTL_) { - const topRow = this.info_.topRow; - if (Types.isLeftRoundedCorner(topRow.elements[0])) { - this.steps_ += svgPaths.lineOnAxis('V', this.outsideCornerPaths_.height); - } else { + drawJaggedEdge_(row) { + if (this.info_.RTL) { + const remainder = + row.height - this.jaggedTeethPaths_.height - this.highlightOffset_; this.steps_ += - svgPaths.lineOnAxis('V', topRow.capline + this.highlightOffset_); + this.jaggedTeethPaths_.pathLeft + svgPaths.lineOnAxis('v', remainder); } } -}; -Highlighter.prototype.drawInlineInput = function(input) { - const offset = this.highlightOffset_; + /** + * Add a highlight on a value input. + * @param {!Row} row The row the input belongs to. + * @package + */ + drawValueInput(row) { + const input = row.getLastInput(); + if (this.RTL_) { + const belowTabHeight = row.height - input.connectionHeight; - // Relative to the block's left. - const connectionRight = input.xPos + input.connectionWidth; - const yPos = input.centerline - input.height / 2; - const bottomHighlightWidth = input.width - input.connectionWidth; - const startY = yPos + offset; - - if (this.RTL_) { - const aboveTabHeight = input.connectionOffsetY - offset; - const belowTabHeight = input.height - - (input.connectionOffsetY + input.connectionHeight) + offset; - - const startX = connectionRight - offset; - - this.inlineSteps_ += svgPaths.moveTo(startX, startY) + - // Right edge above tab. - svgPaths.lineOnAxis('v', aboveTabHeight) + - // Back of tab. - this.puzzleTabPaths_.pathDown(this.RTL_) + - // Right edge below tab. - svgPaths.lineOnAxis('v', belowTabHeight) + - // Bottom. - svgPaths.lineOnAxis('h', bottomHighlightWidth); - } else { - this.inlineSteps_ += - // Go to top right corner. - svgPaths.moveTo(input.xPos + input.width + offset, startY) + - // Highlight right edge, bottom. - svgPaths.lineOnAxis('v', input.height) + - svgPaths.lineOnAxis('h', -bottomHighlightWidth) + - // Go to top of tab. - svgPaths.moveTo(connectionRight, yPos + input.connectionOffsetY) + - // Short highlight glint at bottom of tab. - this.puzzleTabPaths_.pathDown(this.RTL_); + this.steps_ += + svgPaths.moveTo( + input.xPos + input.width - this.highlightOffset_, row.yPos) + + this.puzzleTabPaths_.pathDown(this.RTL_) + + svgPaths.lineOnAxis('v', belowTabHeight); + } else { + this.steps_ += svgPaths.moveTo(input.xPos + input.width, row.yPos) + + this.puzzleTabPaths_.pathDown(this.RTL_); + } } -}; + + /** + * Add a highlight on a statement input. + * @param {!Row} row The row to highlight. + * @package + */ + drawStatementInput(row) { + const input = row.getLastInput(); + if (this.RTL_) { + const innerHeight = row.height - (2 * this.insideCornerPaths_.height); + this.steps_ += svgPaths.moveTo(input.xPos, row.yPos) + + this.insideCornerPaths_.pathTop(this.RTL_) + + svgPaths.lineOnAxis('v', innerHeight) + + this.insideCornerPaths_.pathBottom(this.RTL_) + + svgPaths.lineTo( + row.width - input.xPos - this.insideCornerPaths_.width, 0); + } else { + this.steps_ += svgPaths.moveTo(input.xPos, row.yPos + row.height) + + this.insideCornerPaths_.pathBottom(this.RTL_) + + svgPaths.lineTo( + row.width - input.xPos - this.insideCornerPaths_.width, 0); + } + } + + /** + * Add a highlight on the right side of a row. + * @param {!Row} row The row to highlight. + * @package + */ + drawRightSideRow(row) { + const rightEdge = row.xPos + row.width - this.highlightOffset_; + if (row.followsStatement) { + this.steps_ += svgPaths.lineOnAxis('H', rightEdge); + } + if (this.RTL_) { + this.steps_ += svgPaths.lineOnAxis('H', rightEdge); + if (row.height > this.highlightOffset_) { + this.steps_ += svgPaths.lineOnAxis( + 'V', row.yPos + row.height - this.highlightOffset_); + } + } + } + + /** + * Add a highlight to the bottom row. + * @param {!BottomRow} row The row to highlight. + * @package + */ + drawBottomRow(row) { + // Highlight the vertical edge of the bottom row on the input side. + // Highlighting is always from the top left, both in LTR and RTL. + if (this.RTL_) { + this.steps_ += + svgPaths.lineOnAxis('V', row.baseline - this.highlightOffset_); + } else { + const cornerElem = this.info_.bottomRow.elements[0]; + if (Types.isLeftSquareCorner(cornerElem)) { + this.steps_ += svgPaths.moveTo( + row.xPos + this.highlightOffset_, + row.baseline - this.highlightOffset_); + } else if (Types.isLeftRoundedCorner(cornerElem)) { + this.steps_ += svgPaths.moveTo(row.xPos, row.baseline); + this.steps_ += this.outsideCornerPaths_.bottomLeft(); + } + } + } + + /** + * Draw the highlight on the left side of the block. + * @package + */ + drawLeft() { + const outputConnection = this.info_.outputConnection; + if (outputConnection) { + const tabBottom = + outputConnection.connectionOffsetY + outputConnection.height; + // Draw a line up to the bottom of the tab. + if (this.RTL_) { + this.steps_ += svgPaths.moveTo(this.info_.startX, tabBottom); + } else { + const left = this.info_.startX + this.highlightOffset_; + const bottom = this.info_.bottomRow.baseline - this.highlightOffset_; + this.steps_ += svgPaths.moveTo(left, bottom); + this.steps_ += svgPaths.lineOnAxis('V', tabBottom); + } + this.steps_ += this.puzzleTabPaths_.pathUp(this.RTL_); + } + + if (!this.RTL_) { + const topRow = this.info_.topRow; + if (Types.isLeftRoundedCorner(topRow.elements[0])) { + this.steps_ += + svgPaths.lineOnAxis('V', this.outsideCornerPaths_.height); + } else { + this.steps_ += + svgPaths.lineOnAxis('V', topRow.capline + this.highlightOffset_); + } + } + } + + /** + * Add a highlight to an inline input. + * @param {!InlineInput} input The input to highlight. + * @package + */ + drawInlineInput(input) { + const offset = this.highlightOffset_; + + // Relative to the block's left. + const connectionRight = input.xPos + input.connectionWidth; + const yPos = input.centerline - input.height / 2; + const bottomHighlightWidth = input.width - input.connectionWidth; + const startY = yPos + offset; + + if (this.RTL_) { + const aboveTabHeight = input.connectionOffsetY - offset; + const belowTabHeight = input.height - + (input.connectionOffsetY + input.connectionHeight) + offset; + + const startX = connectionRight - offset; + + this.inlineSteps_ += svgPaths.moveTo(startX, startY) + + // Right edge above tab. + svgPaths.lineOnAxis('v', aboveTabHeight) + + // Back of tab. + this.puzzleTabPaths_.pathDown(this.RTL_) + + // Right edge below tab. + svgPaths.lineOnAxis('v', belowTabHeight) + + // Bottom. + svgPaths.lineOnAxis('h', bottomHighlightWidth); + } else { + this.inlineSteps_ += + // Go to top right corner. + svgPaths.moveTo(input.xPos + input.width + offset, startY) + + // Highlight right edge, bottom. + svgPaths.lineOnAxis('v', input.height) + + svgPaths.lineOnAxis('h', -bottomHighlightWidth) + + // Go to top of tab. + svgPaths.moveTo(connectionRight, yPos + input.connectionOffsetY) + + // Short highlight glint at bottom of tab. + this.puzzleTabPaths_.pathDown(this.RTL_); + } + } +} exports.Highlighter = Highlighter; diff --git a/core/renderers/geras/info.js b/core/renderers/geras/info.js index a78ab4ab7..d8e45c271 100644 --- a/core/renderers/geras/info.js +++ b/core/renderers/geras/info.js @@ -17,7 +17,6 @@ */ goog.module('Blockly.geras.RenderInfo'); -const object = goog.require('Blockly.utils.object'); /* eslint-disable-next-line no-unused-vars */ const {BlockSvg} = goog.requireType('Blockly.BlockSvg'); const {ExternalValueInput} = goog.require('Blockly.blockRendering.ExternalValueInput'); @@ -41,425 +40,435 @@ const {inputTypes} = goog.require('Blockly.inputTypes'); * This measure pass does not propagate changes to the block (although fields * may choose to rerender when getSize() is called). However, calling it * repeatedly may be expensive. - * - * @param {!Renderer} renderer The renderer in use. - * @param {!BlockSvg} block The block to measure. - * @constructor - * @package * @extends {BaseRenderInfo} - * @alias Blockly.geras.RenderInfo */ -const RenderInfo = function(renderer, block) { - RenderInfo.superClass_.constructor.call(this, renderer, block); -}; -object.inherits(RenderInfo, BaseRenderInfo); - -/** - * Get the block renderer in use. - * @return {!Renderer} The block renderer in use. - * @package - */ -RenderInfo.prototype.getRenderer = function() { - return /** @type {!Renderer} */ (this.renderer_); -}; - -/** - * @override - */ -RenderInfo.prototype.populateBottomRow_ = function() { - RenderInfo.superClass_.populateBottomRow_.call(this); - - const followsStatement = this.block_.inputList.length && - this.block_.inputList[this.block_.inputList.length - 1].type === - inputTypes.STATEMENT; - - // The minimum height of the bottom row is smaller in Geras than in other - // renderers, because the dark path adds a pixel. - // If one of the row's elements has a greater height this will be overwritten - // in the compute pass. - if (!followsStatement) { - this.bottomRow.minHeight = - this.constants_.MEDIUM_PADDING - this.constants_.DARK_PATH_OFFSET; +class RenderInfo extends BaseRenderInfo { + /** + * @param {!Renderer} renderer The renderer in use. + * @param {!BlockSvg} block The block to measure. + * @package + * @alias Blockly.geras.RenderInfo + */ + constructor(renderer, block) { + super(renderer, block); } -}; -/** - * @override - */ -RenderInfo.prototype.addInput_ = function(input, activeRow) { - // Non-dummy inputs have visual representations onscreen. - if (this.isInline && input.type === inputTypes.VALUE) { - activeRow.elements.push(new InlineInput(this.constants_, input)); - activeRow.hasInlineInput = true; - } else if (input.type === inputTypes.STATEMENT) { - activeRow.elements.push(new StatementInput(this.constants_, input)); - activeRow.hasStatement = true; - } else if (input.type === inputTypes.VALUE) { - activeRow.elements.push(new ExternalValueInput(this.constants_, input)); - activeRow.hasExternalInput = true; - } else if (input.type === inputTypes.DUMMY) { - // Dummy inputs have no visual representation, but the information is still - // important. - activeRow.minHeight = - Math.max(activeRow.minHeight, this.constants_.DUMMY_INPUT_MIN_HEIGHT); - activeRow.hasDummyInput = true; + /** + * Get the block renderer in use. + * @return {!Renderer} The block renderer in use. + * @package + */ + getRenderer() { + return /** @type {!Renderer} */ (this.renderer_); } - // Ignore row alignment if inline. - if (!this.isInline && activeRow.align === null) { - activeRow.align = input.align; - } -}; -/** - * @override - */ -RenderInfo.prototype.addElemSpacing_ = function() { - let hasExternalInputs = false; - for (let i = 0, row; (row = this.rows[i]); i++) { - if (row.hasExternalInput) { - hasExternalInputs = true; + /** + * @override + */ + populateBottomRow_() { + super.populateBottomRow_(); + + const followsStatement = this.block_.inputList.length && + this.block_.inputList[this.block_.inputList.length - 1].type === + inputTypes.STATEMENT; + + // The minimum height of the bottom row is smaller in Geras than in other + // renderers, because the dark path adds a pixel. + // If one of the row's elements has a greater height this will be + // overwritten in the compute pass. + if (!followsStatement) { + this.bottomRow.minHeight = + this.constants_.MEDIUM_PADDING - this.constants_.DARK_PATH_OFFSET; } } - for (let i = 0, row; (row = this.rows[i]); i++) { - const oldElems = row.elements; - row.elements = []; - // No spacing needed before the corner on the top row or the bottom row. - if (row.startsWithElemSpacer()) { - // There's a spacer before the first element in the row. - row.elements.push(new InRowSpacer( - this.constants_, this.getInRowSpacing_(null, oldElems[0]))); + + /** + * @override + */ + addInput_(input, activeRow) { + // Non-dummy inputs have visual representations onscreen. + if (this.isInline && input.type === inputTypes.VALUE) { + activeRow.elements.push(new InlineInput(this.constants_, input)); + activeRow.hasInlineInput = true; + } else if (input.type === inputTypes.STATEMENT) { + activeRow.elements.push(new StatementInput(this.constants_, input)); + activeRow.hasStatement = true; + } else if (input.type === inputTypes.VALUE) { + activeRow.elements.push(new ExternalValueInput(this.constants_, input)); + activeRow.hasExternalInput = true; + } else if (input.type === inputTypes.DUMMY) { + // Dummy inputs have no visual representation, but the information is + // still important. + activeRow.minHeight = + Math.max(activeRow.minHeight, this.constants_.DUMMY_INPUT_MIN_HEIGHT); + activeRow.hasDummyInput = true; } - if (!oldElems.length) { - continue; + // Ignore row alignment if inline. + if (!this.isInline && activeRow.align === null) { + activeRow.align = input.align; } - for (let e = 0; e < oldElems.length - 1; e++) { - row.elements.push(oldElems[e]); - const spacing = this.getInRowSpacing_(oldElems[e], oldElems[e + 1]); - row.elements.push(new InRowSpacer(this.constants_, spacing)); - } - row.elements.push(oldElems[oldElems.length - 1]); - if (row.endsWithElemSpacer()) { - let spacing = this.getInRowSpacing_(oldElems[oldElems.length - 1], null); - if (hasExternalInputs && row.hasDummyInput) { - spacing += this.constants_.TAB_WIDTH; + } + + /** + * @override + */ + addElemSpacing_() { + let hasExternalInputs = false; + for (let i = 0, row; (row = this.rows[i]); i++) { + if (row.hasExternalInput) { + hasExternalInputs = true; + } + } + for (let i = 0, row; (row = this.rows[i]); i++) { + const oldElems = row.elements; + row.elements = []; + // No spacing needed before the corner on the top row or the bottom row. + if (row.startsWithElemSpacer()) { + // There's a spacer before the first element in the row. + row.elements.push(new InRowSpacer( + this.constants_, this.getInRowSpacing_(null, oldElems[0]))); + } + if (!oldElems.length) { + continue; + } + for (let e = 0; e < oldElems.length - 1; e++) { + row.elements.push(oldElems[e]); + const spacing = this.getInRowSpacing_(oldElems[e], oldElems[e + 1]); + row.elements.push(new InRowSpacer(this.constants_, spacing)); + } + row.elements.push(oldElems[oldElems.length - 1]); + if (row.endsWithElemSpacer()) { + let spacing = + this.getInRowSpacing_(oldElems[oldElems.length - 1], null); + if (hasExternalInputs && row.hasDummyInput) { + spacing += this.constants_.TAB_WIDTH; + } + // There's a spacer after the last element in the row. + row.elements.push(new InRowSpacer(this.constants_, spacing)); } - // There's a spacer after the last element in the row. - row.elements.push(new InRowSpacer(this.constants_, spacing)); } } -}; -/** - * @override - */ -RenderInfo.prototype.getInRowSpacing_ = function(prev, next) { - if (!prev) { - // Between an editable field and the beginning of the row. - if (next && Types.isField(next) && - (/** @type {Field} */ (next)).isEditable) { - return this.constants_.MEDIUM_PADDING; - } - // Inline input at the beginning of the row. - if (next && Types.isInlineInput(next)) { - return this.constants_.MEDIUM_LARGE_PADDING; - } - if (next && Types.isStatementInput(next)) { - return this.constants_.STATEMENT_INPUT_PADDING_LEFT; - } - // Anything else at the beginning of the row. - return this.constants_.LARGE_PADDING; - } - - // Spacing between a non-input and the end of the row or a statement input. - if (!Types.isInput(prev) && (!next || Types.isStatementInput(next))) { - // Between an editable field and the end of the row. - if (Types.isField(prev) && (/** @type {Field} */ (prev)).isEditable) { - return this.constants_.MEDIUM_PADDING; - } - // Padding at the end of an icon-only row to make the block shape clearer. - if (Types.isIcon(prev)) { - return (this.constants_.LARGE_PADDING * 2) + 1; - } - if (Types.isHat(prev)) { - return this.constants_.NO_PADDING; - } - // Establish a minimum width for a block with a previous or next connection. - if (Types.isPreviousOrNextConnection(prev)) { + /** + * @override + */ + getInRowSpacing_(prev, next) { + if (!prev) { + // Between an editable field and the beginning of the row. + if (next && Types.isField(next) && + (/** @type {Field} */ (next)).isEditable) { + return this.constants_.MEDIUM_PADDING; + } + // Inline input at the beginning of the row. + if (next && Types.isInlineInput(next)) { + return this.constants_.MEDIUM_LARGE_PADDING; + } + if (next && Types.isStatementInput(next)) { + return this.constants_.STATEMENT_INPUT_PADDING_LEFT; + } + // Anything else at the beginning of the row. return this.constants_.LARGE_PADDING; } - // Between rounded corner and the end of the row. - if (Types.isLeftRoundedCorner(prev)) { - return this.constants_.MIN_BLOCK_WIDTH; - } - // Between a jagged edge and the end of the row. - if (Types.isJaggedEdge(prev)) { - return this.constants_.NO_PADDING; - } - // Between noneditable fields and icons and the end of the row. - return this.constants_.LARGE_PADDING; - } - // Between inputs and the end of the row. - if (Types.isInput(prev) && !next) { - if (Types.isExternalInput(prev)) { - return this.constants_.NO_PADDING; - } else if (Types.isInlineInput(prev)) { - return this.constants_.LARGE_PADDING; - } else if (Types.isStatementInput(prev)) { - return this.constants_.NO_PADDING; - } - } - - // Spacing between a non-input and an input. - if (!Types.isInput(prev) && next && Types.isInput(next)) { - // Between an editable field and an input. - if (Types.isField(prev) && (/** @type {Field} */ (prev)).isEditable) { - if (Types.isInlineInput(next)) { - return this.constants_.SMALL_PADDING; - } else if (Types.isExternalInput(next)) { - return this.constants_.SMALL_PADDING; + // Spacing between a non-input and the end of the row or a statement input. + if (!Types.isInput(prev) && (!next || Types.isStatementInput(next))) { + // Between an editable field and the end of the row. + if (Types.isField(prev) && (/** @type {Field} */ (prev)).isEditable) { + return this.constants_.MEDIUM_PADDING; } - } else { - if (Types.isInlineInput(next)) { - return this.constants_.MEDIUM_LARGE_PADDING; - } else if (Types.isExternalInput(next)) { - return this.constants_.MEDIUM_LARGE_PADDING; - } else if (Types.isStatementInput(next)) { + // Padding at the end of an icon-only row to make the block shape clearer. + if (Types.isIcon(prev)) { + return (this.constants_.LARGE_PADDING * 2) + 1; + } + if (Types.isHat(prev)) { + return this.constants_.NO_PADDING; + } + // Establish a minimum width for a block with a previous or next + // connection. + if (Types.isPreviousOrNextConnection(prev)) { + return this.constants_.LARGE_PADDING; + } + // Between rounded corner and the end of the row. + if (Types.isLeftRoundedCorner(prev)) { + return this.constants_.MIN_BLOCK_WIDTH; + } + // Between a jagged edge and the end of the row. + if (Types.isJaggedEdge(prev)) { + return this.constants_.NO_PADDING; + } + // Between noneditable fields and icons and the end of the row. + return this.constants_.LARGE_PADDING; + } + + // Between inputs and the end of the row. + if (Types.isInput(prev) && !next) { + if (Types.isExternalInput(prev)) { + return this.constants_.NO_PADDING; + } else if (Types.isInlineInput(prev)) { + return this.constants_.LARGE_PADDING; + } else if (Types.isStatementInput(prev)) { + return this.constants_.NO_PADDING; + } + } + + // Spacing between a non-input and an input. + if (!Types.isInput(prev) && next && Types.isInput(next)) { + // Between an editable field and an input. + if (Types.isField(prev) && (/** @type {Field} */ (prev)).isEditable) { + if (Types.isInlineInput(next)) { + return this.constants_.SMALL_PADDING; + } else if (Types.isExternalInput(next)) { + return this.constants_.SMALL_PADDING; + } + } else { + if (Types.isInlineInput(next)) { + return this.constants_.MEDIUM_LARGE_PADDING; + } else if (Types.isExternalInput(next)) { + return this.constants_.MEDIUM_LARGE_PADDING; + } else if (Types.isStatementInput(next)) { + return this.constants_.LARGE_PADDING; + } + } + return this.constants_.LARGE_PADDING - 1; + } + + // Spacing between an icon and an icon or field. + if (Types.isIcon(prev) && next && !Types.isInput(next)) { + return this.constants_.LARGE_PADDING; + } + + // Spacing between an inline input and a field. + if (Types.isInlineInput(prev) && next && Types.isField(next)) { + // Editable field after inline input. + if ((/** @type {Field} */ (next)).isEditable) { + return this.constants_.MEDIUM_PADDING; + } else { + // Noneditable field after inline input. return this.constants_.LARGE_PADDING; } } - return this.constants_.LARGE_PADDING - 1; - } - // Spacing between an icon and an icon or field. - if (Types.isIcon(prev) && next && !Types.isInput(next)) { - return this.constants_.LARGE_PADDING; - } + if (Types.isLeftSquareCorner(prev) && next) { + // Spacing between a hat and a corner + if (Types.isHat(next)) { + return this.constants_.NO_PADDING; + } + // Spacing between a square corner and a previous or next connection + if (Types.isPreviousConnection(next)) { + return next.notchOffset; + } else if (Types.isNextConnection(next)) { + // Next connections are shifted slightly to the left (in both LTR and + // RTL) to make the dark path under the previous connection show + // through. + const offset = + (this.RTL ? 1 : -1) * this.constants_.DARK_PATH_OFFSET / 2; + return next.notchOffset + offset; + } + } - // Spacing between an inline input and a field. - if (Types.isInlineInput(prev) && next && Types.isField(next)) { - // Editable field after inline input. - if ((/** @type {Field} */ (next)).isEditable) { - return this.constants_.MEDIUM_PADDING; - } else { - // Noneditable field after inline input. + // Spacing between a rounded corner and a previous or next connection. + if (Types.isLeftRoundedCorner(prev) && next) { + if (Types.isPreviousConnection(next)) { + return next.notchOffset - this.constants_.CORNER_RADIUS; + } else if (Types.isNextConnection(next)) { + // Next connections are shifted slightly to the left (in both LTR and + // RTL) to make the dark path under the previous connection show + // through. + const offset = + (this.RTL ? 1 : -1) * this.constants_.DARK_PATH_OFFSET / 2; + return next.notchOffset - this.constants_.CORNER_RADIUS + offset; + } + } + + // Spacing between two fields of the same editability. + if (Types.isField(prev) && next && Types.isField(next) && + ((/** @type {Field} */ (prev)).isEditable === + (/** @type {Field} */ (next)).isEditable)) { return this.constants_.LARGE_PADDING; } + + // Spacing between anything and a jagged edge. + if (next && Types.isJaggedEdge(next)) { + return this.constants_.LARGE_PADDING; + } + + return this.constants_.MEDIUM_PADDING; } - if (Types.isLeftSquareCorner(prev) && next) { - // Spacing between a hat and a corner - if (Types.isHat(next)) { + /** + * @override + */ + getSpacerRowHeight_(prev, next) { + // If we have an empty block add a spacer to increase the height. + if (Types.isTopRow(prev) && Types.isBottomRow(next)) { + return this.constants_.EMPTY_BLOCK_SPACER_HEIGHT; + } + // Top and bottom rows act as a spacer so we don't need any extra padding. + if (Types.isTopRow(prev) || Types.isBottomRow(next)) { return this.constants_.NO_PADDING; } - // Spacing between a square corner and a previous or next connection - if (Types.isPreviousConnection(next)) { - return next.notchOffset; - } else if (Types.isNextConnection(next)) { - // Next connections are shifted slightly to the left (in both LTR and RTL) - // to make the dark path under the previous connection show through. - const offset = (this.RTL ? 1 : -1) * this.constants_.DARK_PATH_OFFSET / 2; - return next.notchOffset + offset; + if (prev.hasExternalInput && next.hasExternalInput) { + return this.constants_.LARGE_PADDING; } - } - - // Spacing between a rounded corner and a previous or next connection. - if (Types.isLeftRoundedCorner(prev) && next) { - if (Types.isPreviousConnection(next)) { - return next.notchOffset - this.constants_.CORNER_RADIUS; - } else if (Types.isNextConnection(next)) { - // Next connections are shifted slightly to the left (in both LTR and RTL) - // to make the dark path under the previous connection show through. - const offset = (this.RTL ? 1 : -1) * this.constants_.DARK_PATH_OFFSET / 2; - return next.notchOffset - this.constants_.CORNER_RADIUS + offset; + if (!prev.hasStatement && next.hasStatement) { + return this.constants_.BETWEEN_STATEMENT_PADDING_Y; } - } - - // Spacing between two fields of the same editability. - if (Types.isField(prev) && next && Types.isField(next) && - ((/** @type {Field} */ (prev)).isEditable === - (/** @type {Field} */ (next)).isEditable)) { - return this.constants_.LARGE_PADDING; - } - - // Spacing between anything and a jagged edge. - if (next && Types.isJaggedEdge(next)) { - return this.constants_.LARGE_PADDING; - } - - return this.constants_.MEDIUM_PADDING; -}; - -/** - * @override - */ -RenderInfo.prototype.getSpacerRowHeight_ = function(prev, next) { - // If we have an empty block add a spacer to increase the height. - if (Types.isTopRow(prev) && Types.isBottomRow(next)) { - return this.constants_.EMPTY_BLOCK_SPACER_HEIGHT; - } - // Top and bottom rows act as a spacer so we don't need any extra padding. - if (Types.isTopRow(prev) || Types.isBottomRow(next)) { - return this.constants_.NO_PADDING; - } - if (prev.hasExternalInput && next.hasExternalInput) { - return this.constants_.LARGE_PADDING; - } - if (!prev.hasStatement && next.hasStatement) { - return this.constants_.BETWEEN_STATEMENT_PADDING_Y; - } - if (prev.hasStatement && next.hasStatement) { - return this.constants_.LARGE_PADDING; - } - if (!prev.hasStatement && next.hasDummyInput) { - return this.constants_.LARGE_PADDING; - } - if (prev.hasDummyInput) { - return this.constants_.LARGE_PADDING; - } - return this.constants_.MEDIUM_PADDING; -}; - -/** - * @override - */ -RenderInfo.prototype.getElemCenterline_ = function(row, elem) { - if (Types.isSpacer(elem)) { - return row.yPos + elem.height / 2; - } - if (Types.isBottomRow(row)) { - const baseline = row.yPos + row.height - row.descenderHeight; - if (Types.isNextConnection(elem)) { - return baseline + elem.height / 2; + if (prev.hasStatement && next.hasStatement) { + return this.constants_.LARGE_PADDING; } - return baseline - elem.height / 2; - } - if (Types.isTopRow(row)) { - if (Types.isHat(elem)) { - return row.capline - elem.height / 2; + if (!prev.hasStatement && next.hasDummyInput) { + return this.constants_.LARGE_PADDING; } - return row.capline + elem.height / 2; - } - - let result = row.yPos; - if (Types.isField(elem) || Types.isIcon(elem)) { - result += (elem.height / 2); - if ((row.hasInlineInput || row.hasStatement) && - elem.height + this.constants_.TALL_INPUT_FIELD_OFFSET_Y <= row.height) { - result += this.constants_.TALL_INPUT_FIELD_OFFSET_Y; + if (prev.hasDummyInput) { + return this.constants_.LARGE_PADDING; } - } else if (Types.isInlineInput(elem)) { - result += elem.height / 2; - } else { - result += (row.height / 2); - } - return result; -}; - -/** - * @override - */ -RenderInfo.prototype.alignRowElements_ = function() { - if (!this.isInline) { - RenderInfo.superClass_.alignRowElements_.call(this); - return; + return this.constants_.MEDIUM_PADDING; } - // Walk backgrounds through rows on the block, keeping track of the right - // input edge. - let nextRightEdge = 0; - let prevInput = null; - for (let i = this.rows.length - 1, row; (row = this.rows[i]); i--) { - row.nextRightEdge = nextRightEdge; - if (Types.isInputRow(row)) { - if (row.hasStatement) { - this.alignStatementRow_( - /** @type {!InputRow} */ (row)); + /** + * @override + */ + getElemCenterline_(row, elem) { + if (Types.isSpacer(elem)) { + return row.yPos + elem.height / 2; + } + if (Types.isBottomRow(row)) { + const baseline = row.yPos + row.height - row.descenderHeight; + if (Types.isNextConnection(elem)) { + return baseline + elem.height / 2; } - if (prevInput && prevInput.hasStatement && row.width < prevInput.width) { - row.nextRightEdge = prevInput.width; - } else { - nextRightEdge = row.width; - } - prevInput = row; + return baseline - elem.height / 2; } - } - // Walk down each row from the top, comparing the prev and next right input - // edges and setting the desired width to the max of the two. - let prevRightEdge = 0; - for (let i = 0, row; (row = this.rows[i]); i++) { - if (row.hasStatement) { - prevRightEdge = this.getDesiredRowWidth_(row); - } else if (Types.isSpacer(row)) { - // Set the spacer row to the max of the prev or next input width. - row.width = Math.max(prevRightEdge, row.nextRightEdge); + if (Types.isTopRow(row)) { + if (Types.isHat(elem)) { + return row.capline - elem.height / 2; + } + return row.capline + elem.height / 2; + } + + let result = row.yPos; + if (Types.isField(elem) || Types.isIcon(elem)) { + result += (elem.height / 2); + if ((row.hasInlineInput || row.hasStatement) && + elem.height + this.constants_.TALL_INPUT_FIELD_OFFSET_Y <= + row.height) { + result += this.constants_.TALL_INPUT_FIELD_OFFSET_Y; + } + } else if (Types.isInlineInput(elem)) { + result += elem.height / 2; } else { - const currentWidth = row.width; - const desiredWidth = Math.max(prevRightEdge, row.nextRightEdge); - const missingSpace = desiredWidth - currentWidth; - if (missingSpace > 0) { - this.addAlignmentPadding_(row, missingSpace); + result += (row.height / 2); + } + return result; + } + + /** + * @override + */ + alignRowElements_() { + if (!this.isInline) { + super.alignRowElements_(); + return; + } + + // Walk backgrounds through rows on the block, keeping track of the right + // input edge. + let nextRightEdge = 0; + let prevInput = null; + for (let i = this.rows.length - 1, row; (row = this.rows[i]); i--) { + row.nextRightEdge = nextRightEdge; + if (Types.isInputRow(row)) { + if (row.hasStatement) { + this.alignStatementRow_( + /** @type {!InputRow} */ (row)); + } + if (prevInput && prevInput.hasStatement && + row.width < prevInput.width) { + row.nextRightEdge = prevInput.width; + } else { + nextRightEdge = row.width; + } + prevInput = row; + } + } + // Walk down each row from the top, comparing the prev and next right input + // edges and setting the desired width to the max of the two. + let prevRightEdge = 0; + for (let i = 0, row; (row = this.rows[i]); i++) { + if (row.hasStatement) { + prevRightEdge = this.getDesiredRowWidth_(row); + } else if (Types.isSpacer(row)) { + // Set the spacer row to the max of the prev or next input width. + row.width = Math.max(prevRightEdge, row.nextRightEdge); + } else { + const currentWidth = row.width; + const desiredWidth = Math.max(prevRightEdge, row.nextRightEdge); + const missingSpace = desiredWidth - currentWidth; + if (missingSpace > 0) { + this.addAlignmentPadding_(row, missingSpace); + } + prevRightEdge = row.width; } - prevRightEdge = row.width; } } -}; -/** - * @override - */ -RenderInfo.prototype.getDesiredRowWidth_ = function(row) { - // Limit the width of a statement row when a block is inline. - if (this.isInline && row.hasStatement) { - return this.statementEdge + this.constants_.MAX_BOTTOM_WIDTH + this.startX; - } - return RenderInfo.superClass_.getDesiredRowWidth_.call(this, row); -}; - -/** - * @override - */ -RenderInfo.prototype.finalize_ = function() { - // Performance note: this could be combined with the draw pass, if the time - // that this takes is excessive. But it shouldn't be, because it only - // accesses and sets properties that already exist on the objects. - let widestRowWithConnectedBlocks = 0; - let yCursor = 0; - for (let i = 0, row; (row = this.rows[i]); i++) { - row.yPos = yCursor; - row.xPos = this.startX; - yCursor += row.height; - - widestRowWithConnectedBlocks = - Math.max(widestRowWithConnectedBlocks, row.widthWithConnectedBlocks); - // Add padding to the bottom row if block height is less than minimum - const heightWithoutHat = yCursor - this.topRow.ascenderHeight; - if (row === this.bottomRow && - heightWithoutHat < this.constants_.MIN_BLOCK_HEIGHT) { - // But the hat height shouldn't be part of this. - const diff = this.constants_.MIN_BLOCK_HEIGHT - heightWithoutHat; - this.bottomRow.height += diff; - yCursor += diff; + /** + * @override + */ + getDesiredRowWidth_(row) { + // Limit the width of a statement row when a block is inline. + if (this.isInline && row.hasStatement) { + return this.statementEdge + this.constants_.MAX_BOTTOM_WIDTH + + this.startX; } - this.recordElemPositions_(row); - } - if (this.outputConnection && this.block_.nextConnection && - this.block_.nextConnection.isConnected()) { - // Include width of connected block in value to stack width measurement. - widestRowWithConnectedBlocks = Math.max( - widestRowWithConnectedBlocks, - this.block_.nextConnection.targetBlock().getHeightWidth().width - - this.constants_.DARK_PATH_OFFSET); + return super.getDesiredRowWidth_(row); } - this.bottomRow.baseline = yCursor - this.bottomRow.descenderHeight; + /** + * @override + */ + finalize_() { + // Performance note: this could be combined with the draw pass, if the time + // that this takes is excessive. But it shouldn't be, because it only + // accesses and sets properties that already exist on the objects. + let widestRowWithConnectedBlocks = 0; + let yCursor = 0; + for (let i = 0, row; (row = this.rows[i]); i++) { + row.yPos = yCursor; + row.xPos = this.startX; + yCursor += row.height; - // The dark (lowlight) adds to the size of the block in both x and y. - this.widthWithChildren = widestRowWithConnectedBlocks + this.startX + - this.constants_.DARK_PATH_OFFSET; - this.width += this.constants_.DARK_PATH_OFFSET; - this.height = yCursor + this.constants_.DARK_PATH_OFFSET; - this.startY = this.topRow.capline; -}; + widestRowWithConnectedBlocks = + Math.max(widestRowWithConnectedBlocks, row.widthWithConnectedBlocks); + // Add padding to the bottom row if block height is less than minimum + const heightWithoutHat = yCursor - this.topRow.ascenderHeight; + if (row === this.bottomRow && + heightWithoutHat < this.constants_.MIN_BLOCK_HEIGHT) { + // But the hat height shouldn't be part of this. + const diff = this.constants_.MIN_BLOCK_HEIGHT - heightWithoutHat; + this.bottomRow.height += diff; + yCursor += diff; + } + this.recordElemPositions_(row); + } + if (this.outputConnection && this.block_.nextConnection && + this.block_.nextConnection.isConnected()) { + // Include width of connected block in value to stack width measurement. + widestRowWithConnectedBlocks = Math.max( + widestRowWithConnectedBlocks, + this.block_.nextConnection.targetBlock().getHeightWidth().width - + this.constants_.DARK_PATH_OFFSET); + } + + this.bottomRow.baseline = yCursor - this.bottomRow.descenderHeight; + + // The dark (lowlight) adds to the size of the block in both x and y. + this.widthWithChildren = widestRowWithConnectedBlocks + this.startX + + this.constants_.DARK_PATH_OFFSET; + this.width += this.constants_.DARK_PATH_OFFSET; + this.height = yCursor + this.constants_.DARK_PATH_OFFSET; + this.startY = this.topRow.capline; + } +} exports.RenderInfo = RenderInfo; diff --git a/core/renderers/geras/measurables/inline_input.js b/core/renderers/geras/measurables/inline_input.js index 5df435181..a759be624 100644 --- a/core/renderers/geras/measurables/inline_input.js +++ b/core/renderers/geras/measurables/inline_input.js @@ -17,7 +17,6 @@ */ goog.module('Blockly.geras.InlineInput'); -const object = goog.require('Blockly.utils.object'); /* eslint-disable-next-line no-unused-vars */ const {ConstantProvider} = goog.requireType('Blockly.blockRendering.ConstantProvider'); const {InlineInput: BaseInlineInput} = goog.require('Blockly.blockRendering.InlineInput'); @@ -27,26 +26,28 @@ const {Input} = goog.requireType('Blockly.Input'); /** * An object containing information about the space an inline input takes up - * during rendering - * @param {!ConstantProvider} constants The rendering - * constants provider. - * @param {!Input} input The inline input to measure and store - * information for. - * @package - * @constructor + * during rendering. * @extends {BaseInlineInput} - * @alias Blockly.geras.InlineInput */ -const InlineInput = function(constants, input) { - InlineInput.superClass_.constructor.call(this, constants, input); +class InlineInput extends BaseInlineInput { + /** + * @param {!ConstantProvider} constants The rendering + * constants provider. + * @param {!Input} input The inline input to measure and store + * information for. + * @package + * @alias Blockly.geras.InlineInput + */ + constructor(constants, input) { + super(constants, input); - if (this.connectedBlock) { - // We allow the dark path to show on the parent block so that the child - // block looks embossed. This takes up an extra pixel in both x and y. - this.width += this.constants_.DARK_PATH_OFFSET; - this.height += this.constants_.DARK_PATH_OFFSET; + if (this.connectedBlock) { + // We allow the dark path to show on the parent block so that the child + // block looks embossed. This takes up an extra pixel in both x and y. + this.width += this.constants_.DARK_PATH_OFFSET; + this.height += this.constants_.DARK_PATH_OFFSET; + } } -}; -object.inherits(InlineInput, BaseInlineInput); +} exports.InlineInput = InlineInput; diff --git a/core/renderers/geras/measurables/statement_input.js b/core/renderers/geras/measurables/statement_input.js index d4636af3c..ce696b201 100644 --- a/core/renderers/geras/measurables/statement_input.js +++ b/core/renderers/geras/measurables/statement_input.js @@ -17,7 +17,6 @@ */ goog.module('Blockly.geras.StatementInput'); -const object = goog.require('Blockly.utils.object'); /* eslint-disable-next-line no-unused-vars */ const {ConstantProvider} = goog.requireType('Blockly.blockRendering.ConstantProvider'); /* eslint-disable-next-line no-unused-vars */ @@ -27,25 +26,27 @@ const {StatementInput: BaseStatementInput} = goog.require('Blockly.blockRenderin /** * An object containing information about the space a statement input takes up - * during rendering - * @param {!ConstantProvider} constants The rendering - * constants provider. - * @param {!Input} input The statement input to measure and store - * information for. - * @package - * @constructor + * during rendering. * @extends {BaseStatementInput} - * @alias Blockly.geras.StatementInput */ -const StatementInput = function(constants, input) { - StatementInput.superClass_.constructor.call(this, constants, input); +class StatementInput extends BaseStatementInput { + /** + * @param {!ConstantProvider} constants The rendering + * constants provider. + * @param {!Input} input The statement input to measure and store + * information for. + * @package + * @alias Blockly.geras.StatementInput + */ + constructor(constants, input) { + super(constants, input); - if (this.connectedBlock) { - // We allow the dark path to show on the parent block so that the child - // block looks embossed. This takes up an extra pixel in both x and y. - this.height += this.constants_.DARK_PATH_OFFSET; + if (this.connectedBlock) { + // We allow the dark path to show on the parent block so that the child + // block looks embossed. This takes up an extra pixel in both x and y. + this.height += this.constants_.DARK_PATH_OFFSET; + } } -}; -object.inherits(StatementInput, BaseStatementInput); +} exports.StatementInput = StatementInput; diff --git a/core/renderers/geras/renderer.js b/core/renderers/geras/renderer.js index 25629843c..e71789c01 100644 --- a/core/renderers/geras/renderer.js +++ b/core/renderers/geras/renderer.js @@ -16,7 +16,6 @@ goog.module('Blockly.geras.Renderer'); const blockRendering = goog.require('Blockly.blockRendering'); -const object = goog.require('Blockly.utils.object'); /* eslint-disable-next-line no-unused-vars */ const {BlockSvg} = goog.requireType('Blockly.BlockSvg'); /* eslint-disable-next-line no-unused-vars */ @@ -35,116 +34,115 @@ const {Theme} = goog.requireType('Blockly.Theme'); /** * The geras renderer. - * @param {string} name The renderer name. - * @package - * @constructor * @extends {BaseRenderer} - * @alias Blockly.geras.Renderer */ -const Renderer = function(name) { - Renderer.superClass_.constructor.call(this, name); +class Renderer extends BaseRenderer { + /** + * @param {string} name The renderer name. + * @package + * @alias Blockly.geras.Renderer + */ + constructor(name) { + super(name); + + /** + * The renderer's highlight constant provider. + * @type {HighlightConstantProvider} + * @private + */ + this.highlightConstants_ = null; + } /** - * The renderer's highlight constant provider. - * @type {HighlightConstantProvider} - * @private + * Initialize the renderer. Geras has a highlight provider in addition to + * the normal constant provider. + * @package + * @override */ - this.highlightConstants_ = null; -}; -object.inherits(Renderer, BaseRenderer); + init(theme, opt_rendererOverrides) { + super.init(theme, opt_rendererOverrides); + this.highlightConstants_ = this.makeHighlightConstants_(); + this.highlightConstants_.init(); + } -/** - * Initialize the renderer. Geras has a highlight provider in addition to - * the normal constant provider. - * @package - * @override - */ -Renderer.prototype.init = function(theme, opt_rendererOverrides) { - Renderer.superClass_.init.call(this, theme, opt_rendererOverrides); - this.highlightConstants_ = this.makeHighlightConstants_(); - this.highlightConstants_.init(); -}; + /** + * @override + */ + refreshDom(svg, theme) { + super.refreshDom(svg, theme); + this.getHighlightConstants().init(); + } -/** - * @override - */ -Renderer.prototype.refreshDom = function(svg, theme) { - Renderer.superClass_.refreshDom.call(this, svg, theme); - this.getHighlightConstants().init(); -}; + /** + * @override + */ + makeConstants_() { + return new ConstantProvider(); + } -/** - * @override - */ -Renderer.prototype.makeConstants_ = function() { - return new ConstantProvider(); -}; + /** + * Create a new instance of the renderer's render info object. + * @param {!BlockSvg} block The block to measure. + * @return {!RenderInfo} The render info object. + * @protected + * @override + */ + makeRenderInfo_(block) { + return new RenderInfo(this, block); + } -/** - * Create a new instance of the renderer's render info object. - * @param {!BlockSvg} block The block to measure. - * @return {!RenderInfo} The render info object. - * @protected - * @override - */ -Renderer.prototype.makeRenderInfo_ = function(block) { - return new RenderInfo(this, block); -}; + /** + * Create a new instance of the renderer's drawer. + * @param {!BlockSvg} block The block to render. + * @param {!BaseRenderInfo} info An object containing all information needed + * to render this block. + * @return {!Drawer} The drawer. + * @protected + * @override + */ + makeDrawer_(block, info) { + return new Drawer( + block, + /** @type {!RenderInfo} */ (info)); + } -/** - * Create a new instance of the renderer's drawer. - * @param {!BlockSvg} block The block to render. - * @param {!BaseRenderInfo} info An object containing all - * information needed to render this block. - * @return {!Drawer} The drawer. - * @protected - * @override - */ -Renderer.prototype.makeDrawer_ = function(block, info) { - return new Drawer( - block, - /** @type {!RenderInfo} */ (info)); -}; + /** + * Create a new instance of a renderer path object. + * @param {!SVGElement} root The root SVG element. + * @param {!Theme.BlockStyle} style The style object to use for colouring. + * @return {!PathObject} The renderer path object. + * @package + * @override + */ + makePathObject(root, style) { + return new PathObject( + root, style, + /** @type {!ConstantProvider} */ (this.getConstants())); + } -/** - * Create a new instance of a renderer path object. - * @param {!SVGElement} root The root SVG element. - * @param {!Theme.BlockStyle} style The style object to use for - * colouring. - * @return {!PathObject} The renderer path object. - * @package - * @override - */ -Renderer.prototype.makePathObject = function(root, style) { - return new PathObject( - root, style, - /** @type {!ConstantProvider} */ (this.getConstants())); -}; + /** + * Create a new instance of the renderer's highlight constant provider. + * @return {!HighlightConstantProvider} The highlight constant provider. + * @protected + */ + makeHighlightConstants_() { + return new HighlightConstantProvider( + /** @type {!BaseConstantProvider} */ + (this.getConstants())); + } -/** - * Create a new instance of the renderer's highlight constant provider. - * @return {!HighlightConstantProvider} The highlight constant - * provider. - * @protected - */ -Renderer.prototype.makeHighlightConstants_ = function() { - return new HighlightConstantProvider( - /** @type {!BaseConstantProvider} */ - (this.getConstants())); -}; - -/** - * Get the renderer's highlight constant provider. We assume that when this is - * called, the renderer has already been initialized. - * @return {!HighlightConstantProvider} The highlight constant - * provider. - * @package - */ -Renderer.prototype.getHighlightConstants = function() { - return ( - /** @type {!HighlightConstantProvider} */ - (this.highlightConstants_)); -}; + /** + * Get the renderer's highlight constant provider. We assume that when this + * is called, the renderer has already been initialized. + * @return {!HighlightConstantProvider} The highlight constant provider. + * @package + */ + getHighlightConstants() { + return ( + /** @type {!HighlightConstantProvider} */ + (this.highlightConstants_)); + } +} blockRendering.register('geras', Renderer); diff --git a/core/renderers/minimalist/constants.js b/core/renderers/minimalist/constants.js index eb89ea2ad..488178629 100644 --- a/core/renderers/minimalist/constants.js +++ b/core/renderers/minimalist/constants.js @@ -17,20 +17,21 @@ */ goog.module('Blockly.minimalist.ConstantProvider'); -const object = goog.require('Blockly.utils.object'); const {ConstantProvider: BaseConstantProvider} = goog.require('Blockly.blockRendering.ConstantProvider'); /** * An object that provides constants for rendering blocks in the sample. - * @constructor - * @package * @extends {BaseConstantProvider} - * @alias Blockly.minimalist.ConstantProvider */ -const ConstantProvider = function() { - ConstantProvider.superClass_.constructor.call(this); -}; -object.inherits(ConstantProvider, BaseConstantProvider); +class ConstantProvider extends BaseConstantProvider { + /** + * @package + * @alias Blockly.minimalist.ConstantProvider + */ + constructor() { + super(); + } +} exports.ConstantProvider = ConstantProvider; diff --git a/core/renderers/minimalist/drawer.js b/core/renderers/minimalist/drawer.js index 13eb682a1..829e24b4a 100644 --- a/core/renderers/minimalist/drawer.js +++ b/core/renderers/minimalist/drawer.js @@ -15,7 +15,6 @@ */ goog.module('Blockly.minimalist.Drawer'); -const object = goog.require('Blockly.utils.object'); /* eslint-disable-next-line no-unused-vars */ const {BlockSvg} = goog.requireType('Blockly.BlockSvg'); const {Drawer: BaseDrawer} = goog.require('Blockly.blockRendering.Drawer'); @@ -25,17 +24,19 @@ const {RenderInfo} = goog.requireType('Blockly.minimalist.RenderInfo'); /** * An object that draws a block based on the given rendering information. - * @param {!BlockSvg} block The block to render. - * @param {!RenderInfo} info An object containing all - * information needed to render this block. - * @package - * @constructor * @extends {BaseDrawer} - * @alias Blockly.minimalist.Drawer */ -const Drawer = function(block, info) { - Drawer.superClass_.constructor.call(this, block, info); -}; -object.inherits(Drawer, BaseDrawer); +class Drawer extends BaseDrawer { + /** + * @param {!BlockSvg} block The block to render. + * @param {!RenderInfo} info An object containing all + * information needed to render this block. + * @package + * @alias Blockly.minimalist.Drawer + */ + constructor(block, info) { + super(block, info); + } +} exports.Drawer = Drawer; diff --git a/core/renderers/minimalist/info.js b/core/renderers/minimalist/info.js index 36e66f9e5..1f2172b37 100644 --- a/core/renderers/minimalist/info.js +++ b/core/renderers/minimalist/info.js @@ -15,7 +15,6 @@ */ goog.module('Blockly.minimalist.RenderInfo'); -const object = goog.require('Blockly.utils.object'); /* eslint-disable-next-line no-unused-vars */ const {BlockSvg} = goog.requireType('Blockly.BlockSvg'); const {RenderInfo: BaseRenderInfo} = goog.require('Blockly.blockRendering.RenderInfo'); @@ -29,26 +28,27 @@ const {Renderer} = goog.requireType('Blockly.minimalist.Renderer'); * This measure pass does not propagate changes to the block (although fields * may choose to rerender when getSize() is called). However, calling it * repeatedly may be expensive. - * - * @param {!Renderer} renderer The renderer in use. - * @param {!BlockSvg} block The block to measure. - * @constructor - * @package * @extends {BaseRenderInfo} - * @alias Blockly.minimalist.RenderInfo */ -const RenderInfo = function(renderer, block) { - RenderInfo.superClass_.constructor.call(this, renderer, block); -}; -object.inherits(RenderInfo, BaseRenderInfo); +class RenderInfo extends BaseRenderInfo { + /** + * @param {!Renderer} renderer The renderer in use. + * @param {!BlockSvg} block The block to measure. + * @package + * @alias Blockly.minimalist.RenderInfo + */ + constructor(renderer, block) { + super(renderer, block); + } -/** - * Get the block renderer in use. - * @return {!Renderer} The block renderer in use. - * @package - */ -RenderInfo.prototype.getRenderer = function() { - return /** @type {!Renderer} */ (this.renderer_); -}; + /** + * Get the block renderer in use. + * @return {!Renderer} The block renderer in use. + * @package + */ + getRenderer() { + return /** @type {!Renderer} */ (this.renderer_); + } +} exports.RenderInfo = RenderInfo; diff --git a/core/renderers/minimalist/renderer.js b/core/renderers/minimalist/renderer.js index 6cc7c9e2f..46522172d 100644 --- a/core/renderers/minimalist/renderer.js +++ b/core/renderers/minimalist/renderer.js @@ -16,7 +16,6 @@ goog.module('Blockly.minimalist.Renderer'); const blockRendering = goog.require('Blockly.blockRendering'); -const object = goog.require('Blockly.utils.object'); /* eslint-disable-next-line no-unused-vars */ const {BlockSvg} = goog.requireType('Blockly.BlockSvg'); const {ConstantProvider} = goog.require('Blockly.minimalist.ConstantProvider'); @@ -29,50 +28,52 @@ const {Renderer: BaseRenderer} = goog.require('Blockly.blockRendering.Renderer') /** * The minimalist renderer. - * @param {string} name The renderer name. - * @package - * @constructor * @extends {BaseRenderer} - * @alias Blockly.minimalist.Renderer */ -const Renderer = function(name) { - Renderer.superClass_.constructor.call(this, name); -}; -object.inherits(Renderer, BaseRenderer); +class Renderer extends BaseRenderer { + /** + * @param {string} name The renderer name. + * @package + * @alias Blockly.minimalist.Renderer + */ + constructor(name) { + super(name); + } -/** - * Create a new instance of the renderer's constant provider. - * @return {!ConstantProvider} The constant provider. - * @protected - * @override - */ -Renderer.prototype.makeConstants_ = function() { - return new ConstantProvider(); -}; + /** + * Create a new instance of the renderer's constant provider. + * @return {!ConstantProvider} The constant provider. + * @protected + * @override + */ + makeConstants_() { + return new ConstantProvider(); + } -/** - * Create a new instance of the renderer's render info object. - * @param {!BlockSvg} block The block to measure. - * @return {!RenderInfo} The render info object. - * @protected - * @override - */ -Renderer.prototype.makeRenderInfo_ = function(block) { - return new RenderInfo(this, block); -}; + /** + * Create a new instance of the renderer's render info object. + * @param {!BlockSvg} block The block to measure. + * @return {!RenderInfo} The render info object. + * @protected + * @override + */ + makeRenderInfo_(block) { + return new RenderInfo(this, block); + } -/** - * Create a new instance of the renderer's drawer. - * @param {!BlockSvg} block The block to render. - * @param {!BaseRenderInfo} info An object containing all - * information needed to render this block. - * @return {!Drawer} The drawer. - * @protected - * @override - */ -Renderer.prototype.makeDrawer_ = function(block, info) { - return new Drawer(block, /** @type {!RenderInfo} */ (info)); -}; + /** + * Create a new instance of the renderer's drawer. + * @param {!BlockSvg} block The block to render. + * @param {!BaseRenderInfo} info An object containing all + * information needed to render this block. + * @return {!Drawer} The drawer. + * @protected + * @override + */ + makeDrawer_(block, info) { + return new Drawer(block, /** @type {!RenderInfo} */ (info)); + } +} blockRendering.register('minimalist', Renderer); diff --git a/core/renderers/thrasos/info.js b/core/renderers/thrasos/info.js index a8cb2bfed..cf894842e 100644 --- a/core/renderers/thrasos/info.js +++ b/core/renderers/thrasos/info.js @@ -17,7 +17,6 @@ */ goog.module('Blockly.thrasos.RenderInfo'); -const object = goog.require('Blockly.utils.object'); /* eslint-disable-next-line no-unused-vars */ const {BlockSvg} = goog.requireType('Blockly.BlockSvg'); /* eslint-disable-next-line no-unused-vars */ @@ -35,295 +34,299 @@ const {Types} = goog.require('Blockly.blockRendering.Types'); * This measure pass does not propagate changes to the block (although fields * may choose to rerender when getSize() is called). However, calling it * repeatedly may be expensive. - * - * @param {!Renderer} renderer The renderer in use. - * @param {!BlockSvg} block The block to measure. - * @constructor - * @package * @extends {BaseRenderInfo} - * @alias Blockly.thrasos.RenderInfo */ -const RenderInfo = function(renderer, block) { - RenderInfo.superClass_.constructor.call(this, renderer, block); -}; -object.inherits(RenderInfo, BaseRenderInfo); - -/** - * Get the block renderer in use. - * @return {!Renderer} The block renderer in use. - * @package - */ -RenderInfo.prototype.getRenderer = function() { - return /** @type {!Renderer} */ (this.renderer_); -}; - -/** - * @override - */ -RenderInfo.prototype.addElemSpacing_ = function() { - let hasExternalInputs = false; - for (let i = 0; i < this.rows.length; i++) { - const row = this.rows[i]; - if (row.hasExternalInput) { - hasExternalInputs = true; - break; - } +class RenderInfo extends BaseRenderInfo { + /** + * @param {!Renderer} renderer The renderer in use. + * @param {!BlockSvg} block The block to measure. + * @package + * @alias Blockly.thrasos.RenderInfo + */ + constructor(renderer, block) { + super(renderer, block); } - for (let i = 0; i < this.rows.length; i++) { - const row = this.rows[i]; - const oldElems = row.elements; - row.elements = []; - // No spacing needed before the corner on the top row or the bottom row. - if (row.startsWithElemSpacer()) { - // There's a spacer before the first element in the row. - row.elements.push(new InRowSpacer( - this.constants_, this.getInRowSpacing_(null, oldElems[0]))); - } - for (let e = 0; e < oldElems.length - 1; e++) { - row.elements.push(oldElems[e]); - const spacing = this.getInRowSpacing_(oldElems[e], oldElems[e + 1]); - row.elements.push(new InRowSpacer(this.constants_, spacing)); - } - row.elements.push(oldElems[oldElems.length - 1]); - if (row.endsWithElemSpacer()) { - let spacing = this.getInRowSpacing_(oldElems[oldElems.length - 1], null); - if (hasExternalInputs && row.hasDummyInput) { - spacing += this.constants_.TAB_WIDTH; + + /** + * Get the block renderer in use. + * @return {!Renderer} The block renderer in use. + * @package + */ + getRenderer() { + return /** @type {!Renderer} */ (this.renderer_); + } + + /** + * @override + */ + addElemSpacing_() { + let hasExternalInputs = false; + for (let i = 0; i < this.rows.length; i++) { + const row = this.rows[i]; + if (row.hasExternalInput) { + hasExternalInputs = true; + break; + } + } + for (let i = 0; i < this.rows.length; i++) { + const row = this.rows[i]; + const oldElems = row.elements; + row.elements = []; + // No spacing needed before the corner on the top row or the bottom row. + if (row.startsWithElemSpacer()) { + // There's a spacer before the first element in the row. + row.elements.push(new InRowSpacer( + this.constants_, this.getInRowSpacing_(null, oldElems[0]))); + } + for (let e = 0; e < oldElems.length - 1; e++) { + row.elements.push(oldElems[e]); + const spacing = this.getInRowSpacing_(oldElems[e], oldElems[e + 1]); + row.elements.push(new InRowSpacer(this.constants_, spacing)); + } + row.elements.push(oldElems[oldElems.length - 1]); + if (row.endsWithElemSpacer()) { + let spacing = + this.getInRowSpacing_(oldElems[oldElems.length - 1], null); + if (hasExternalInputs && row.hasDummyInput) { + spacing += this.constants_.TAB_WIDTH; + } + // There's a spacer after the last element in the row. + row.elements.push(new InRowSpacer(this.constants_, spacing)); } - // There's a spacer after the last element in the row. - row.elements.push(new InRowSpacer(this.constants_, spacing)); } } -}; -/** - * @override - */ -RenderInfo.prototype.getInRowSpacing_ = function(prev, next) { - if (!prev) { - // Between an editable field and the beginning of the row. - if (next && Types.isField(next) && - (/** @type {Field} */ (next)).isEditable) { - return this.constants_.MEDIUM_PADDING; - } - // Inline input at the beginning of the row. - if (next && Types.isInlineInput(next)) { - return this.constants_.MEDIUM_LARGE_PADDING; - } - if (next && Types.isStatementInput(next)) { - return this.constants_.STATEMENT_INPUT_PADDING_LEFT; - } - // Anything else at the beginning of the row. - return this.constants_.LARGE_PADDING; - } - - // Spacing between a non-input and the end of the row. - if (!Types.isInput(prev) && !next) { - // Between an editable field and the end of the row. - if (Types.isField(prev) && (/** @type {Field} */ (prev)).isEditable) { - return this.constants_.MEDIUM_PADDING; - } - // Padding at the end of an icon-only row to make the block shape clearer. - if (Types.isIcon(prev)) { - return (this.constants_.LARGE_PADDING * 2) + 1; - } - if (Types.isHat(prev)) { - return this.constants_.NO_PADDING; - } - // Establish a minimum width for a block with a previous or next connection. - if (Types.isPreviousOrNextConnection(prev)) { + /** + * @override + */ + getInRowSpacing_(prev, next) { + if (!prev) { + // Between an editable field and the beginning of the row. + if (next && Types.isField(next) && + (/** @type {Field} */ (next)).isEditable) { + return this.constants_.MEDIUM_PADDING; + } + // Inline input at the beginning of the row. + if (next && Types.isInlineInput(next)) { + return this.constants_.MEDIUM_LARGE_PADDING; + } + if (next && Types.isStatementInput(next)) { + return this.constants_.STATEMENT_INPUT_PADDING_LEFT; + } + // Anything else at the beginning of the row. return this.constants_.LARGE_PADDING; } - // Between rounded corner and the end of the row. - if (Types.isLeftRoundedCorner(prev)) { - return this.constants_.MIN_BLOCK_WIDTH; - } - // Between a jagged edge and the end of the row. - if (Types.isJaggedEdge(prev)) { - return this.constants_.NO_PADDING; - } - // Between noneditable fields and icons and the end of the row. - return this.constants_.LARGE_PADDING; - } - // Between inputs and the end of the row. - if (Types.isInput(prev) && !next) { - if (Types.isExternalInput(prev)) { - return this.constants_.NO_PADDING; - } else if (Types.isInlineInput(prev)) { - return this.constants_.LARGE_PADDING; - } else if (Types.isStatementInput(prev)) { - return this.constants_.NO_PADDING; - } - } - - // Spacing between a non-input and an input. - if (!Types.isInput(prev) && next && Types.isInput(next)) { - // Between an editable field and an input. - if (Types.isField(prev) && (/** @type {Field} */ (prev)).isEditable) { - if (Types.isInlineInput(next)) { - return this.constants_.SMALL_PADDING; - } else if (Types.isExternalInput(next)) { - return this.constants_.SMALL_PADDING; + // Spacing between a non-input and the end of the row. + if (!Types.isInput(prev) && !next) { + // Between an editable field and the end of the row. + if (Types.isField(prev) && (/** @type {Field} */ (prev)).isEditable) { + return this.constants_.MEDIUM_PADDING; } - } else { - if (Types.isInlineInput(next)) { - return this.constants_.MEDIUM_LARGE_PADDING; - } else if (Types.isExternalInput(next)) { - return this.constants_.MEDIUM_LARGE_PADDING; - } else if (Types.isStatementInput(next)) { + // Padding at the end of an icon-only row to make the block shape clearer. + if (Types.isIcon(prev)) { + return (this.constants_.LARGE_PADDING * 2) + 1; + } + if (Types.isHat(prev)) { + return this.constants_.NO_PADDING; + } + // Establish a minimum width for a block with a previous or next + // connection. + if (Types.isPreviousOrNextConnection(prev)) { + return this.constants_.LARGE_PADDING; + } + // Between rounded corner and the end of the row. + if (Types.isLeftRoundedCorner(prev)) { + return this.constants_.MIN_BLOCK_WIDTH; + } + // Between a jagged edge and the end of the row. + if (Types.isJaggedEdge(prev)) { + return this.constants_.NO_PADDING; + } + // Between noneditable fields and icons and the end of the row. + return this.constants_.LARGE_PADDING; + } + + // Between inputs and the end of the row. + if (Types.isInput(prev) && !next) { + if (Types.isExternalInput(prev)) { + return this.constants_.NO_PADDING; + } else if (Types.isInlineInput(prev)) { + return this.constants_.LARGE_PADDING; + } else if (Types.isStatementInput(prev)) { + return this.constants_.NO_PADDING; + } + } + + // Spacing between a non-input and an input. + if (!Types.isInput(prev) && next && Types.isInput(next)) { + // Between an editable field and an input. + if (Types.isField(prev) && (/** @type {Field} */ (prev)).isEditable) { + if (Types.isInlineInput(next)) { + return this.constants_.SMALL_PADDING; + } else if (Types.isExternalInput(next)) { + return this.constants_.SMALL_PADDING; + } + } else { + if (Types.isInlineInput(next)) { + return this.constants_.MEDIUM_LARGE_PADDING; + } else if (Types.isExternalInput(next)) { + return this.constants_.MEDIUM_LARGE_PADDING; + } else if (Types.isStatementInput(next)) { + return this.constants_.LARGE_PADDING; + } + } + return this.constants_.LARGE_PADDING - 1; + } + + // Spacing between an icon and an icon or field. + if (Types.isIcon(prev) && next && !Types.isInput(next)) { + return this.constants_.LARGE_PADDING; + } + + // Spacing between an inline input and a field. + if (Types.isInlineInput(prev) && next && Types.isField(next)) { + // Editable field after inline input. + if ((/** @type {Field} */ (next)).isEditable) { + return this.constants_.MEDIUM_PADDING; + } else { + // Noneditable field after inline input. return this.constants_.LARGE_PADDING; } } - return this.constants_.LARGE_PADDING - 1; - } - // Spacing between an icon and an icon or field. - if (Types.isIcon(prev) && next && !Types.isInput(next)) { - return this.constants_.LARGE_PADDING; - } + if (Types.isLeftSquareCorner(prev) && next) { + // Spacing between a hat and a corner + if (Types.isHat(next)) { + return this.constants_.NO_PADDING; + } + // Spacing between a square corner and a previous or next connection + if (Types.isPreviousConnection(next) || Types.isNextConnection(next)) { + return next.notchOffset; + } + } - // Spacing between an inline input and a field. - if (Types.isInlineInput(prev) && next && Types.isField(next)) { - // Editable field after inline input. - if ((/** @type {Field} */ (next)).isEditable) { - return this.constants_.MEDIUM_PADDING; - } else { - // Noneditable field after inline input. + // Spacing between a rounded corner and a previous or next connection. + if (Types.isLeftRoundedCorner(prev) && next) { + return next.notchOffset - this.constants_.CORNER_RADIUS; + } + + // Spacing between two fields of the same editability. + if (Types.isField(prev) && next && Types.isField(next) && + ((/** @type {Field} */ (prev)).isEditable === + (/** @type {Field} */ (next)).isEditable)) { return this.constants_.LARGE_PADDING; } + + // Spacing between anything and a jagged edge. + if (next && Types.isJaggedEdge(next)) { + return this.constants_.LARGE_PADDING; + } + + return this.constants_.MEDIUM_PADDING; } - if (Types.isLeftSquareCorner(prev) && next) { - // Spacing between a hat and a corner - if (Types.isHat(next)) { + /** + * @override + */ + getSpacerRowHeight_(prev, next) { + // If we have an empty block add a spacer to increase the height. + if (Types.isTopRow(prev) && Types.isBottomRow(next)) { + return this.constants_.EMPTY_BLOCK_SPACER_HEIGHT; + } + // Top and bottom rows act as a spacer so we don't need any extra padding. + if (Types.isTopRow(prev) || Types.isBottomRow(next)) { return this.constants_.NO_PADDING; } - // Spacing between a square corner and a previous or next connection - if (Types.isPreviousConnection(next) || Types.isNextConnection(next)) { - return next.notchOffset; + if (prev.hasExternalInput && next.hasExternalInput) { + return this.constants_.LARGE_PADDING; } - } - - // Spacing between a rounded corner and a previous or next connection. - if (Types.isLeftRoundedCorner(prev) && next) { - return next.notchOffset - this.constants_.CORNER_RADIUS; - } - - // Spacing between two fields of the same editability. - if (Types.isField(prev) && next && Types.isField(next) && - ((/** @type {Field} */ (prev)).isEditable === - (/** @type {Field} */ (next)).isEditable)) { - return this.constants_.LARGE_PADDING; - } - - // Spacing between anything and a jagged edge. - if (next && Types.isJaggedEdge(next)) { - return this.constants_.LARGE_PADDING; - } - - return this.constants_.MEDIUM_PADDING; -}; - -/** - * @override - */ -RenderInfo.prototype.getSpacerRowHeight_ = function(prev, next) { - // If we have an empty block add a spacer to increase the height. - if (Types.isTopRow(prev) && Types.isBottomRow(next)) { - return this.constants_.EMPTY_BLOCK_SPACER_HEIGHT; - } - // Top and bottom rows act as a spacer so we don't need any extra padding. - if (Types.isTopRow(prev) || Types.isBottomRow(next)) { - return this.constants_.NO_PADDING; - } - if (prev.hasExternalInput && next.hasExternalInput) { - return this.constants_.LARGE_PADDING; - } - if (!prev.hasStatement && next.hasStatement) { - return this.constants_.BETWEEN_STATEMENT_PADDING_Y; - } - if (prev.hasStatement && next.hasStatement) { - return this.constants_.LARGE_PADDING; - } - if (prev.hasDummyInput || next.hasDummyInput) { - return this.constants_.LARGE_PADDING; - } - return this.constants_.MEDIUM_PADDING; -}; - -/** - * @override - */ -RenderInfo.prototype.getElemCenterline_ = function(row, elem) { - if (Types.isSpacer(elem)) { - return row.yPos + elem.height / 2; - } - if (Types.isBottomRow(row)) { - const baseline = row.yPos + row.height - row.descenderHeight; - if (Types.isNextConnection(elem)) { - return baseline + elem.height / 2; + if (!prev.hasStatement && next.hasStatement) { + return this.constants_.BETWEEN_STATEMENT_PADDING_Y; } - return baseline - elem.height / 2; - } - if (Types.isTopRow(row)) { - if (Types.isHat(elem)) { - return row.capline - elem.height / 2; + if (prev.hasStatement && next.hasStatement) { + return this.constants_.LARGE_PADDING; } - return row.capline + elem.height / 2; - } - - let result = row.yPos; - if (Types.isField(elem) && row.hasStatement) { - const offset = this.constants_.TALL_INPUT_FIELD_OFFSET_Y + elem.height / 2; - result += offset; - } else { - result += (row.height / 2); - } - return result; -}; - -/** - * @override - */ -RenderInfo.prototype.finalize_ = function() { - // Performance note: this could be combined with the draw pass, if the time - // that this takes is excessive. But it shouldn't be, because it only - // accesses and sets properties that already exist on the objects. - let widestRowWithConnectedBlocks = 0; - let yCursor = 0; - for (let i = 0; i < this.rows.length; i++) { - const row = this.rows[i]; - row.yPos = yCursor; - row.xPos = this.startX; - yCursor += row.height; - - widestRowWithConnectedBlocks = - Math.max(widestRowWithConnectedBlocks, row.widthWithConnectedBlocks); - // Add padding to the bottom row if block height is less than minimum - const heightWithoutHat = yCursor - this.topRow.ascenderHeight; - if (row === this.bottomRow && - heightWithoutHat < this.constants_.MIN_BLOCK_HEIGHT) { - // But the hat height shouldn't be part of this. - const diff = this.constants_.MIN_BLOCK_HEIGHT - heightWithoutHat; - this.bottomRow.height += diff; - yCursor += diff; + if (prev.hasDummyInput || next.hasDummyInput) { + return this.constants_.LARGE_PADDING; } - this.recordElemPositions_(row); - } - if (this.outputConnection && this.block_.nextConnection && - this.block_.nextConnection.isConnected()) { - // Include width of connected block in value to stack width measurement. - widestRowWithConnectedBlocks = Math.max( - widestRowWithConnectedBlocks, - this.block_.nextConnection.targetBlock().getHeightWidth().width); + return this.constants_.MEDIUM_PADDING; } - this.bottomRow.baseline = yCursor - this.bottomRow.descenderHeight; - this.widthWithChildren = widestRowWithConnectedBlocks + this.startX; + /** + * @override + */ + getElemCenterline_(row, elem) { + if (Types.isSpacer(elem)) { + return row.yPos + elem.height / 2; + } + if (Types.isBottomRow(row)) { + const baseline = row.yPos + row.height - row.descenderHeight; + if (Types.isNextConnection(elem)) { + return baseline + elem.height / 2; + } + return baseline - elem.height / 2; + } + if (Types.isTopRow(row)) { + if (Types.isHat(elem)) { + return row.capline - elem.height / 2; + } + return row.capline + elem.height / 2; + } - this.height = yCursor; - this.startY = this.topRow.capline; -}; + let result = row.yPos; + if (Types.isField(elem) && row.hasStatement) { + const offset = + this.constants_.TALL_INPUT_FIELD_OFFSET_Y + elem.height / 2; + result += offset; + } else { + result += (row.height / 2); + } + return result; + } + + /** + * @override + */ + finalize_() { + // Performance note: this could be combined with the draw pass, if the time + // that this takes is excessive. But it shouldn't be, because it only + // accesses and sets properties that already exist on the objects. + let widestRowWithConnectedBlocks = 0; + let yCursor = 0; + for (let i = 0; i < this.rows.length; i++) { + const row = this.rows[i]; + row.yPos = yCursor; + row.xPos = this.startX; + yCursor += row.height; + + widestRowWithConnectedBlocks = + Math.max(widestRowWithConnectedBlocks, row.widthWithConnectedBlocks); + // Add padding to the bottom row if block height is less than minimum + const heightWithoutHat = yCursor - this.topRow.ascenderHeight; + if (row === this.bottomRow && + heightWithoutHat < this.constants_.MIN_BLOCK_HEIGHT) { + // But the hat height shouldn't be part of this. + const diff = this.constants_.MIN_BLOCK_HEIGHT - heightWithoutHat; + this.bottomRow.height += diff; + yCursor += diff; + } + this.recordElemPositions_(row); + } + if (this.outputConnection && this.block_.nextConnection && + this.block_.nextConnection.isConnected()) { + // Include width of connected block in value to stack width measurement. + widestRowWithConnectedBlocks = Math.max( + widestRowWithConnectedBlocks, + this.block_.nextConnection.targetBlock().getHeightWidth().width); + } + + this.bottomRow.baseline = yCursor - this.bottomRow.descenderHeight; + this.widthWithChildren = widestRowWithConnectedBlocks + this.startX; + + this.height = yCursor; + this.startY = this.topRow.capline; + } +} exports.RenderInfo = RenderInfo; diff --git a/core/renderers/thrasos/renderer.js b/core/renderers/thrasos/renderer.js index b192c3145..0c19240ba 100644 --- a/core/renderers/thrasos/renderer.js +++ b/core/renderers/thrasos/renderer.js @@ -16,7 +16,6 @@ goog.module('Blockly.thrasos.Renderer'); const blockRendering = goog.require('Blockly.blockRendering'); -const object = goog.require('Blockly.utils.object'); /* eslint-disable-next-line no-unused-vars */ const {BlockSvg} = goog.requireType('Blockly.BlockSvg'); const {RenderInfo} = goog.require('Blockly.thrasos.RenderInfo'); @@ -25,28 +24,29 @@ const {Renderer: BaseRenderer} = goog.require('Blockly.blockRendering.Renderer') /** * The thrasos renderer. - * @param {string} name The renderer name. - * @package - * @constructor * @extends {BaseRenderer} - * @alias Blockly.thrasos.Renderer */ -const Renderer = function(name) { - Renderer.superClass_.constructor.call(this, name); -}; -object.inherits(Renderer, BaseRenderer); - -/** - * Create a new instance of the renderer's render info object. - * @param {!BlockSvg} block The block to measure. - * @return {!RenderInfo} The render info object. - * @protected - * @override - */ -Renderer.prototype.makeRenderInfo_ = function(block) { - return new RenderInfo(this, block); -}; +class Renderer extends BaseRenderer { + /** + * @param {string} name The renderer name. + * @package + * @alias Blockly.thrasos.Renderer + */ + constructor(name) { + super(name); + } + /** + * Create a new instance of the renderer's render info object. + * @param {!BlockSvg} block The block to measure. + * @return {!RenderInfo} The render info object. + * @protected + * @override + */ + makeRenderInfo_(block) { + return new RenderInfo(this, block); + } +} blockRendering.register('thrasos', Renderer); diff --git a/core/renderers/zelos/constants.js b/core/renderers/zelos/constants.js index 582f0a4fa..7eb47068d 100644 --- a/core/renderers/zelos/constants.js +++ b/core/renderers/zelos/constants.js @@ -18,7 +18,6 @@ goog.module('Blockly.zelos.ConstantProvider'); const dom = goog.require('Blockly.utils.dom'); -const object = goog.require('Blockly.utils.object'); const svgPaths = goog.require('Blockly.utils.svgPaths'); const utilsColour = goog.require('Blockly.utils.colour'); const {ConnectionType} = goog.require('Blockly.ConnectionType'); @@ -28,953 +27,979 @@ const {Svg} = goog.require('Blockly.utils.Svg'); /** * An object that provides constants for rendering blocks in Zelos mode. - * @constructor - * @package * @extends {BaseConstantProvider} - * @alias Blockly.zelos.ConstantProvider */ -const ConstantProvider = function() { - ConstantProvider.superClass_.constructor.call(this); - - this.GRID_UNIT = 4; - +class ConstantProvider extends BaseConstantProvider { /** - * @override - */ - this.SMALL_PADDING = this.GRID_UNIT; - - /** - * @override - */ - this.MEDIUM_PADDING = 2 * this.GRID_UNIT; - - /** - * @override - */ - this.MEDIUM_LARGE_PADDING = 3 * this.GRID_UNIT; - - /** - * @override - */ - this.LARGE_PADDING = 4 * this.GRID_UNIT; - - /** - * @override - */ - this.CORNER_RADIUS = 1 * this.GRID_UNIT; - - /** - * @override - */ - this.NOTCH_WIDTH = 9 * this.GRID_UNIT; - - /** - * @override - */ - this.NOTCH_HEIGHT = 2 * this.GRID_UNIT; - - /** - * @override - */ - this.NOTCH_OFFSET_LEFT = 3 * this.GRID_UNIT; - - /** - * @override - */ - this.STATEMENT_INPUT_NOTCH_OFFSET = this.NOTCH_OFFSET_LEFT; - - /** - * @override - */ - this.MIN_BLOCK_WIDTH = 2 * this.GRID_UNIT; - - /** - * @override - */ - this.MIN_BLOCK_HEIGHT = 12 * this.GRID_UNIT; - - /** - * @override - */ - this.EMPTY_STATEMENT_INPUT_HEIGHT = 6 * this.GRID_UNIT; - - /** - * @override - */ - this.TAB_OFFSET_FROM_TOP = 0; - - /** - * @override - */ - this.TOP_ROW_MIN_HEIGHT = this.CORNER_RADIUS; - - /** - * @override - */ - this.TOP_ROW_PRECEDES_STATEMENT_MIN_HEIGHT = this.LARGE_PADDING; - - /** - * @override - */ - this.BOTTOM_ROW_MIN_HEIGHT = this.CORNER_RADIUS; - - /** - * @override - */ - this.BOTTOM_ROW_AFTER_STATEMENT_MIN_HEIGHT = 6 * this.GRID_UNIT; - - /** - * @override - */ - this.STATEMENT_BOTTOM_SPACER = -this.NOTCH_HEIGHT; - - /** - * Minimum statement input spacer width. - * @type {number} - */ - this.STATEMENT_INPUT_SPACER_MIN_WIDTH = 40 * this.GRID_UNIT; - - /** - * @override - */ - this.STATEMENT_INPUT_PADDING_LEFT = 4 * this.GRID_UNIT; - - /** - * @override - */ - this.EMPTY_INLINE_INPUT_PADDING = 4 * this.GRID_UNIT; - - /** - * @override - */ - this.EMPTY_INLINE_INPUT_HEIGHT = 8 * this.GRID_UNIT; - - /** - * @override - */ - this.DUMMY_INPUT_MIN_HEIGHT = 8 * this.GRID_UNIT; - - /** - * @override - */ - this.DUMMY_INPUT_SHADOW_MIN_HEIGHT = 6 * this.GRID_UNIT; - - /** - * @override - */ - this.CURSOR_WS_WIDTH = 20 * this.GRID_UNIT; - - /** - * @override - */ - this.CURSOR_COLOUR = '#ffa200'; - - /** - * Radius of the cursor for input and output connections. - * @type {number} * @package + * @alias Blockly.zelos.ConstantProvider */ - this.CURSOR_RADIUS = 5; + constructor() { + super(); - /** - * @override - */ - this.JAGGED_TEETH_HEIGHT = 0; + this.GRID_UNIT = 4; - /** - * @override - */ - this.JAGGED_TEETH_WIDTH = 0; + /** + * @override + */ + this.SMALL_PADDING = this.GRID_UNIT; - /** - * @override - */ - this.START_HAT_HEIGHT = 22; + /** + * @override + */ + this.MEDIUM_PADDING = 2 * this.GRID_UNIT; - /** - * @override - */ - this.START_HAT_WIDTH = 96; + /** + * @override + */ + this.MEDIUM_LARGE_PADDING = 3 * this.GRID_UNIT; - /** - * @enum {number} - * @override - */ - this.SHAPES = {HEXAGONAL: 1, ROUND: 2, SQUARE: 3, PUZZLE: 4, NOTCH: 5}; + /** + * @override + */ + this.LARGE_PADDING = 4 * this.GRID_UNIT; - /** - * Map of output/input shapes and the amount they should cause a block to be - * padded. Outer key is the outer shape, inner key is the inner shape. - * When a block with the outer shape contains an input block with the inner - * shape on its left or right edge, the block elements are aligned such that - * the padding specified is reached. - * @package - */ - this.SHAPE_IN_SHAPE_PADDING = { - 1: { - // Outer shape: hexagon. - 0: 5 * this.GRID_UNIT, // Field in hexagon. - 1: 2 * this.GRID_UNIT, // Hexagon in hexagon. - 2: 5 * this.GRID_UNIT, // Round in hexagon. - 3: 5 * this.GRID_UNIT, // Square in hexagon. - }, - 2: { - // Outer shape: round. - 0: 3 * this.GRID_UNIT, // Field in round. - 1: 3 * this.GRID_UNIT, // Hexagon in round. - 2: 1 * this.GRID_UNIT, // Round in round. - 3: 2 * this.GRID_UNIT, // Square in round. - }, - 3: { - // Outer shape: square. - 0: 2 * this.GRID_UNIT, // Field in square. - 1: 2 * this.GRID_UNIT, // Hexagon in square. - 2: 2 * this.GRID_UNIT, // Round in square. - 3: 2 * this.GRID_UNIT, // Square in square. - }, - }; + /** + * @override + */ + this.CORNER_RADIUS = 1 * this.GRID_UNIT; - /** - * @override - */ - this.FULL_BLOCK_FIELDS = true; + /** + * @override + */ + this.NOTCH_WIDTH = 9 * this.GRID_UNIT; - /** - * @override - */ - this.FIELD_TEXT_FONTSIZE = 3 * this.GRID_UNIT; + /** + * @override + */ + this.NOTCH_HEIGHT = 2 * this.GRID_UNIT; - /** - * @override - */ - this.FIELD_TEXT_FONTWEIGHT = 'bold'; + /** + * @override + */ + this.NOTCH_OFFSET_LEFT = 3 * this.GRID_UNIT; - /** - * @override - */ - this.FIELD_TEXT_FONTFAMILY = - '"Helvetica Neue", "Segoe UI", Helvetica, sans-serif'; + /** + * @override + */ + this.STATEMENT_INPUT_NOTCH_OFFSET = this.NOTCH_OFFSET_LEFT; - /** - * @override - */ - this.FIELD_BORDER_RECT_RADIUS = this.CORNER_RADIUS; + /** + * @override + */ + this.MIN_BLOCK_WIDTH = 2 * this.GRID_UNIT; - /** - * @override - */ - this.FIELD_BORDER_RECT_X_PADDING = 2 * this.GRID_UNIT; + /** + * @override + */ + this.MIN_BLOCK_HEIGHT = 12 * this.GRID_UNIT; - /** - * @override - */ - this.FIELD_BORDER_RECT_Y_PADDING = 1.625 * this.GRID_UNIT; + /** + * @override + */ + this.EMPTY_STATEMENT_INPUT_HEIGHT = 6 * this.GRID_UNIT; - /** - * @override - */ - this.FIELD_BORDER_RECT_HEIGHT = 8 * this.GRID_UNIT; + /** + * @override + */ + this.TAB_OFFSET_FROM_TOP = 0; - /** - * @override - */ - this.FIELD_DROPDOWN_BORDER_RECT_HEIGHT = 8 * this.GRID_UNIT; + /** + * @override + */ + this.TOP_ROW_MIN_HEIGHT = this.CORNER_RADIUS; - /** - * @override - */ - this.FIELD_DROPDOWN_NO_BORDER_RECT_SHADOW = true; + /** + * @override + */ + this.TOP_ROW_PRECEDES_STATEMENT_MIN_HEIGHT = this.LARGE_PADDING; - /** - * @override - */ - this.FIELD_DROPDOWN_COLOURED_DIV = true; + /** + * @override + */ + this.BOTTOM_ROW_MIN_HEIGHT = this.CORNER_RADIUS; - /** - * @override - */ - this.FIELD_DROPDOWN_SVG_ARROW = true; + /** + * @override + */ + this.BOTTOM_ROW_AFTER_STATEMENT_MIN_HEIGHT = 6 * this.GRID_UNIT; - /** - * @override - */ - this.FIELD_DROPDOWN_SVG_ARROW_PADDING = this.FIELD_BORDER_RECT_X_PADDING; + /** + * @override + */ + this.STATEMENT_BOTTOM_SPACER = -this.NOTCH_HEIGHT; - /** - * @override - */ - this.FIELD_TEXTINPUT_BOX_SHADOW = true; + /** + * Minimum statement input spacer width. + * @type {number} + */ + this.STATEMENT_INPUT_SPACER_MIN_WIDTH = 40 * this.GRID_UNIT; - /** - * @override - */ - this.FIELD_COLOUR_FULL_BLOCK = true; + /** + * @override + */ + this.STATEMENT_INPUT_PADDING_LEFT = 4 * this.GRID_UNIT; - /** - * @override - */ - this.FIELD_COLOUR_DEFAULT_WIDTH = 2 * this.GRID_UNIT; + /** + * @override + */ + this.EMPTY_INLINE_INPUT_PADDING = 4 * this.GRID_UNIT; - /** - * @override - */ - this.FIELD_COLOUR_DEFAULT_HEIGHT = 4 * this.GRID_UNIT; + /** + * @override + */ + this.EMPTY_INLINE_INPUT_HEIGHT = 8 * this.GRID_UNIT; - /** - * @override - */ - this.FIELD_CHECKBOX_X_OFFSET = 1 * this.GRID_UNIT; + /** + * @override + */ + this.DUMMY_INPUT_MIN_HEIGHT = 8 * this.GRID_UNIT; - /** - * The maximum width of a dynamic connection shape. - * @type {number} - */ - this.MAX_DYNAMIC_CONNECTION_SHAPE_WIDTH = 12 * this.GRID_UNIT; + /** + * @override + */ + this.DUMMY_INPUT_SHADOW_MIN_HEIGHT = 6 * this.GRID_UNIT; - /** - * The selected glow colour. - * @type {string} - */ - this.SELECTED_GLOW_COLOUR = '#fff200'; + /** + * @override + */ + this.CURSOR_WS_WIDTH = 20 * this.GRID_UNIT; - /** - * The size of the selected glow. - * @type {number} - */ - this.SELECTED_GLOW_SIZE = 0.5; + /** + * @override + */ + this.CURSOR_COLOUR = '#ffa200'; - /** - * The replacement glow colour. - * @type {string} - */ - this.REPLACEMENT_GLOW_COLOUR = '#fff200'; + /** + * Radius of the cursor for input and output connections. + * @type {number} + * @package + */ + this.CURSOR_RADIUS = 5; - /** - * The size of the selected glow. - * @type {number} - */ - this.REPLACEMENT_GLOW_SIZE = 2; + /** + * @override + */ + this.JAGGED_TEETH_HEIGHT = 0; - /** - * The ID of the selected glow filter, or the empty string if no filter is - * set. - * @type {string} - * @package - */ - this.selectedGlowFilterId = ''; + /** + * @override + */ + this.JAGGED_TEETH_WIDTH = 0; - /** - * The element to use for a selected glow, or null if not set. - * @type {SVGElement} - * @private - */ - this.selectedGlowFilter_ = null; + /** + * @override + */ + this.START_HAT_HEIGHT = 22; - /** - * The ID of the replacement glow filter, or the empty string if no filter is - * set. - * @type {string} - * @package - */ - this.replacementGlowFilterId = ''; + /** + * @override + */ + this.START_HAT_WIDTH = 96; - /** - * The element to use for a replacement glow, or null if not set. - * @type {SVGElement} - * @private - */ - this.replacementGlowFilter_ = null; -}; -object.inherits(ConstantProvider, BaseConstantProvider); + /** + * @enum {number} + * @override + */ + this.SHAPES = {HEXAGONAL: 1, ROUND: 2, SQUARE: 3, PUZZLE: 4, NOTCH: 5}; -/** - * @override - */ -ConstantProvider.prototype.setFontConstants_ = function(theme) { - ConstantProvider.superClass_.setFontConstants_.call(this, theme); + /** + * Map of output/input shapes and the amount they should cause a block to be + * padded. Outer key is the outer shape, inner key is the inner shape. + * When a block with the outer shape contains an input block with the inner + * shape on its left or right edge, the block elements are aligned such that + * the padding specified is reached. + * @package + */ + this.SHAPE_IN_SHAPE_PADDING = { + 1: { + // Outer shape: hexagon. + 0: 5 * this.GRID_UNIT, // Field in hexagon. + 1: 2 * this.GRID_UNIT, // Hexagon in hexagon. + 2: 5 * this.GRID_UNIT, // Round in hexagon. + 3: 5 * this.GRID_UNIT, // Square in hexagon. + }, + 2: { + // Outer shape: round. + 0: 3 * this.GRID_UNIT, // Field in round. + 1: 3 * this.GRID_UNIT, // Hexagon in round. + 2: 1 * this.GRID_UNIT, // Round in round. + 3: 2 * this.GRID_UNIT, // Square in round. + }, + 3: { + // Outer shape: square. + 0: 2 * this.GRID_UNIT, // Field in square. + 1: 2 * this.GRID_UNIT, // Hexagon in square. + 2: 2 * this.GRID_UNIT, // Round in square. + 3: 2 * this.GRID_UNIT, // Square in square. + }, + }; - this.FIELD_BORDER_RECT_HEIGHT = - this.FIELD_TEXT_HEIGHT + this.FIELD_BORDER_RECT_Y_PADDING * 2; - this.FIELD_DROPDOWN_BORDER_RECT_HEIGHT = this.FIELD_BORDER_RECT_HEIGHT; -}; + /** + * @override + */ + this.FULL_BLOCK_FIELDS = true; -/** - * @override - */ -ConstantProvider.prototype.init = function() { - ConstantProvider.superClass_.init.call(this); - this.HEXAGONAL = this.makeHexagonal(); - this.ROUNDED = this.makeRounded(); - this.SQUARED = this.makeSquared(); + /** + * @override + */ + this.FIELD_TEXT_FONTSIZE = 3 * this.GRID_UNIT; - this.STATEMENT_INPUT_NOTCH_OFFSET = - this.NOTCH_OFFSET_LEFT + this.INSIDE_CORNERS.rightWidth; -}; + /** + * @override + */ + this.FIELD_TEXT_FONTWEIGHT = 'bold'; -/** - * @override - */ -ConstantProvider.prototype.setDynamicProperties_ = function(theme) { - ConstantProvider.superClass_.setDynamicProperties_.call(this, theme); + /** + * @override + */ + this.FIELD_TEXT_FONTFAMILY = + '"Helvetica Neue", "Segoe UI", Helvetica, sans-serif'; - this.SELECTED_GLOW_COLOUR = theme.getComponentStyle('selectedGlowColour') || - this.SELECTED_GLOW_COLOUR; - const selectedGlowSize = Number(theme.getComponentStyle('selectedGlowSize')); - this.SELECTED_GLOW_SIZE = selectedGlowSize && !isNaN(selectedGlowSize) ? - selectedGlowSize : - this.SELECTED_GLOW_SIZE; - this.REPLACEMENT_GLOW_COLOUR = - theme.getComponentStyle('replacementGlowColour') || - this.REPLACEMENT_GLOW_COLOUR; - const replacementGlowSize = - Number(theme.getComponentStyle('replacementGlowSize')); - this.REPLACEMENT_GLOW_SIZE = - replacementGlowSize && !isNaN(replacementGlowSize) ? - replacementGlowSize : - this.REPLACEMENT_GLOW_SIZE; -}; + /** + * @override + */ + this.FIELD_BORDER_RECT_RADIUS = this.CORNER_RADIUS; -/** - * @override - */ -ConstantProvider.prototype.dispose = function() { - ConstantProvider.superClass_.dispose.call(this); - if (this.selectedGlowFilter_) { - dom.removeNode(this.selectedGlowFilter_); - } - if (this.replacementGlowFilter_) { - dom.removeNode(this.replacementGlowFilter_); - } -}; + /** + * @override + */ + this.FIELD_BORDER_RECT_X_PADDING = 2 * this.GRID_UNIT; -/** - * @override - */ -ConstantProvider.prototype.makeStartHat = function() { - const height = this.START_HAT_HEIGHT; - const width = this.START_HAT_WIDTH; + /** + * @override + */ + this.FIELD_BORDER_RECT_Y_PADDING = 1.625 * this.GRID_UNIT; - const mainPath = svgPaths.curve('c', [ - svgPaths.point(25, -height), - svgPaths.point(71, -height), - svgPaths.point(width, 0), - ]); - return {height: height, width: width, path: mainPath}; -}; + /** + * @override + */ + this.FIELD_BORDER_RECT_HEIGHT = 8 * this.GRID_UNIT; -/** - * Create sizing and path information about a hexagonal shape. - * @return {!Object} An object containing sizing and path information about - * a hexagonal shape for connections. - * @package - */ -ConstantProvider.prototype.makeHexagonal = function() { - const maxWidth = this.MAX_DYNAMIC_CONNECTION_SHAPE_WIDTH; + /** + * @override + */ + this.FIELD_DROPDOWN_BORDER_RECT_HEIGHT = 8 * this.GRID_UNIT; - /** - * Make the main path for the hexagonal connection shape out of two lines. - * The lines are defined with relative positions and require the block height. - * The 'up' and 'down' versions of the paths are the same, but the Y sign - * flips. The 'left' and 'right' versions of the path are also the same, but - * the X sign flips. - * @param {number} height The height of the block the connection is on. - * @param {boolean} up True if the path should be drawn from bottom to top, - * false otherwise. - * @param {boolean} right True if the path is for the right side of the - * block. - * @return {string} A path fragment describing a rounded connection. - */ - function makeMainPath(height, up, right) { - const halfHeight = height / 2; - const width = halfHeight > maxWidth ? maxWidth : halfHeight; - const forward = up ? -1 : 1; - const direction = right ? -1 : 1; - const dy = forward * height / 2; - return svgPaths.lineTo(-direction * width, dy) + - svgPaths.lineTo(direction * width, dy); + /** + * @override + */ + this.FIELD_DROPDOWN_NO_BORDER_RECT_SHADOW = true; + + /** + * @override + */ + this.FIELD_DROPDOWN_COLOURED_DIV = true; + + /** + * @override + */ + this.FIELD_DROPDOWN_SVG_ARROW = true; + + /** + * @override + */ + this.FIELD_DROPDOWN_SVG_ARROW_PADDING = this.FIELD_BORDER_RECT_X_PADDING; + + /** + * @override + */ + this.FIELD_TEXTINPUT_BOX_SHADOW = true; + + /** + * @override + */ + this.FIELD_COLOUR_FULL_BLOCK = true; + + /** + * @override + */ + this.FIELD_COLOUR_DEFAULT_WIDTH = 2 * this.GRID_UNIT; + + /** + * @override + */ + this.FIELD_COLOUR_DEFAULT_HEIGHT = 4 * this.GRID_UNIT; + + /** + * @override + */ + this.FIELD_CHECKBOX_X_OFFSET = 1 * this.GRID_UNIT; + + /** + * The maximum width of a dynamic connection shape. + * @type {number} + */ + this.MAX_DYNAMIC_CONNECTION_SHAPE_WIDTH = 12 * this.GRID_UNIT; + + /** + * The selected glow colour. + * @type {string} + */ + this.SELECTED_GLOW_COLOUR = '#fff200'; + + /** + * The size of the selected glow. + * @type {number} + */ + this.SELECTED_GLOW_SIZE = 0.5; + + /** + * The replacement glow colour. + * @type {string} + */ + this.REPLACEMENT_GLOW_COLOUR = '#fff200'; + + /** + * The size of the selected glow. + * @type {number} + */ + this.REPLACEMENT_GLOW_SIZE = 2; + + /** + * The ID of the selected glow filter, or the empty string if no filter is + * set. + * @type {string} + * @package + */ + this.selectedGlowFilterId = ''; + + /** + * The element to use for a selected glow, or null if not set. + * @type {SVGElement} + * @private + */ + this.selectedGlowFilter_ = null; + + /** + * The ID of the replacement glow filter, or the empty string if no filter + * is set. + * @type {string} + * @package + */ + this.replacementGlowFilterId = ''; + + /** + * The element to use for a replacement glow, or null if not set. + * @type {SVGElement} + * @private + */ + this.replacementGlowFilter_ = null; + + /** + * The object containing information about the hexagon used for a boolean + * reporter block. Null before init is called. + * @type {Object} + */ + this.HEXAGONAL = null; + + /** + * The object containing information about the hexagon used for a number or + * string reporter block. Null before init is called. + * @type {Object} + */ + this.ROUNDED = null; + + /** + * The object containing information about the hexagon used for a + * rectangular reporter block. Null before init is called. + * @type {Object} + */ + this.SQUARED = null; } - return { - type: this.SHAPES.HEXAGONAL, - isDynamic: true, - width: function(height) { + /** + * @override + */ + setFontConstants_(theme) { + super.setFontConstants_(theme); + + this.FIELD_BORDER_RECT_HEIGHT = + this.FIELD_TEXT_HEIGHT + this.FIELD_BORDER_RECT_Y_PADDING * 2; + this.FIELD_DROPDOWN_BORDER_RECT_HEIGHT = this.FIELD_BORDER_RECT_HEIGHT; + } + + /** + * @override + */ + init() { + super.init(); + 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; + } + + /** + * @override + */ + setDynamicProperties_(theme) { + super.setDynamicProperties_(theme); + + this.SELECTED_GLOW_COLOUR = theme.getComponentStyle('selectedGlowColour') || + this.SELECTED_GLOW_COLOUR; + const selectedGlowSize = + Number(theme.getComponentStyle('selectedGlowSize')); + this.SELECTED_GLOW_SIZE = selectedGlowSize && !isNaN(selectedGlowSize) ? + selectedGlowSize : + this.SELECTED_GLOW_SIZE; + this.REPLACEMENT_GLOW_COLOUR = + theme.getComponentStyle('replacementGlowColour') || + this.REPLACEMENT_GLOW_COLOUR; + const replacementGlowSize = + Number(theme.getComponentStyle('replacementGlowSize')); + this.REPLACEMENT_GLOW_SIZE = + replacementGlowSize && !isNaN(replacementGlowSize) ? + replacementGlowSize : + this.REPLACEMENT_GLOW_SIZE; + } + + /** + * @override + */ + dispose() { + super.dispose(); + if (this.selectedGlowFilter_) { + dom.removeNode(this.selectedGlowFilter_); + } + if (this.replacementGlowFilter_) { + dom.removeNode(this.replacementGlowFilter_); + } + } + + /** + * @override + */ + makeStartHat() { + const height = this.START_HAT_HEIGHT; + const width = this.START_HAT_WIDTH; + + const mainPath = svgPaths.curve('c', [ + svgPaths.point(25, -height), + svgPaths.point(71, -height), + svgPaths.point(width, 0), + ]); + return {height: height, width: width, path: mainPath}; + } + + /** + * Create sizing and path information about a hexagonal shape. + * @return {!Object} An object containing sizing and path information about + * a hexagonal shape for connections. + * @package + */ + makeHexagonal() { + const maxWidth = this.MAX_DYNAMIC_CONNECTION_SHAPE_WIDTH; + + /** + * Make the main path for the hexagonal connection shape out of two lines. + * The lines are defined with relative positions and require the block + * height. The 'up' and 'down' versions of the paths are the same, but the Y + * sign flips. The 'left' and 'right' versions of the path are also the + * same, but the X sign flips. + * @param {number} height The height of the block the connection is on. + * @param {boolean} up True if the path should be drawn from bottom to top, + * false otherwise. + * @param {boolean} right True if the path is for the right side of the + * block. + * @return {string} A path fragment describing a rounded connection. + */ + function makeMainPath(height, up, right) { const halfHeight = height / 2; - return halfHeight > maxWidth ? maxWidth : halfHeight; - }, - height: function(height) { - return height; - }, - connectionOffsetY: function(connectionHeight) { - return connectionHeight / 2; - }, - connectionOffsetX: function(connectionWidth) { - return -connectionWidth; - }, - pathDown: function(height) { - return makeMainPath(height, false, false); - }, - pathUp: function(height) { - return makeMainPath(height, true, false); - }, - pathRightDown: function(height) { - return makeMainPath(height, false, true); - }, - pathRightUp: function(height) { - return makeMainPath(height, false, true); - }, - }; -}; + const width = halfHeight > maxWidth ? maxWidth : halfHeight; + const forward = up ? -1 : 1; + const direction = right ? -1 : 1; + const dy = forward * height / 2; + return svgPaths.lineTo(-direction * width, dy) + + svgPaths.lineTo(direction * width, dy); + } -/** - * Create sizing and path information about a rounded shape. - * @return {!Object} An object containing sizing and path information about - * a rounded shape for connections. - * @package - */ -ConstantProvider.prototype.makeRounded = function() { - const maxWidth = this.MAX_DYNAMIC_CONNECTION_SHAPE_WIDTH; - const maxHeight = maxWidth * 2; + return { + type: this.SHAPES.HEXAGONAL, + isDynamic: true, + width: function(height) { + const halfHeight = height / 2; + return halfHeight > maxWidth ? maxWidth : halfHeight; + }, + height: function(height) { + return height; + }, + connectionOffsetY: function(connectionHeight) { + return connectionHeight / 2; + }, + connectionOffsetX: function(connectionWidth) { + return -connectionWidth; + }, + pathDown: function(height) { + return makeMainPath(height, false, false); + }, + pathUp: function(height) { + return makeMainPath(height, true, false); + }, + pathRightDown: function(height) { + return makeMainPath(height, false, true); + }, + pathRightUp: function(height) { + return makeMainPath(height, false, true); + }, + }; + } /** - * Make the main path for the rounded connection shape out of two arcs and - * a line that joins them. The arcs are defined with relative positions. - * Usually, the height of the block is split between the two arcs. In the case - * where the height of the block exceeds the maximum height, a line is drawn - * in between the two arcs. - * The 'up' and 'down' versions of the paths are the same, but the Y sign - * flips. The 'up' and 'right' versions of the path flip the sweep-flag - * which moves the arc at negative angles. - * @param {number} blockHeight The height of the block the connection is on. - * @param {boolean} up True if the path should be drawn from bottom to top, - * false otherwise. - * @param {boolean} right True if the path is for the right side of the - * block. - * @return {string} A path fragment describing a rounded connection. + * Create sizing and path information about a rounded shape. + * @return {!Object} An object containing sizing and path information about + * a rounded shape for connections. + * @package */ - function makeMainPath(blockHeight, up, right) { - const remainingHeight = - blockHeight > maxHeight ? blockHeight - maxHeight : 0; - const height = blockHeight > maxHeight ? maxHeight : blockHeight; - const radius = height / 2; - return svgPaths.arc( - 'a', '0 0,1', radius, - svgPaths.point((up ? -1 : 1) * radius, (up ? -1 : 1) * radius)) + - svgPaths.lineOnAxis('v', (right ? 1 : -1) * remainingHeight) + - svgPaths.arc( - 'a', '0 0,1', radius, - svgPaths.point((up ? 1 : -1) * radius, (up ? -1 : 1) * radius)); + makeRounded() { + const maxWidth = this.MAX_DYNAMIC_CONNECTION_SHAPE_WIDTH; + const maxHeight = maxWidth * 2; + + /** + * Make the main path for the rounded connection shape out of two arcs and + * a line that joins them. The arcs are defined with relative positions. + * Usually, the height of the block is split between the two arcs. In the + * case where the height of the block exceeds the maximum height, a line is + * drawn in between the two arcs. The 'up' and 'down' versions of the paths + * are the same, but the Y sign flips. The 'up' and 'right' versions of the + * path flip the sweep-flag which moves the arc at negative angles. + * @param {number} blockHeight The height of the block the connection is on. + * @param {boolean} up True if the path should be drawn from bottom to top, + * false otherwise. + * @param {boolean} right True if the path is for the right side of the + * block. + * @return {string} A path fragment describing a rounded connection. + */ + function makeMainPath(blockHeight, up, right) { + const remainingHeight = + blockHeight > maxHeight ? blockHeight - maxHeight : 0; + const height = blockHeight > maxHeight ? maxHeight : blockHeight; + const radius = height / 2; + return svgPaths.arc( + 'a', '0 0,1', radius, + svgPaths.point( + (up ? -1 : 1) * radius, (up ? -1 : 1) * radius)) + + svgPaths.lineOnAxis('v', (right ? 1 : -1) * remainingHeight) + + svgPaths.arc( + 'a', '0 0,1', radius, + svgPaths.point((up ? 1 : -1) * radius, (up ? -1 : 1) * radius)); + } + + return { + type: this.SHAPES.ROUND, + isDynamic: true, + width: function(height) { + const halfHeight = height / 2; + return halfHeight > maxWidth ? maxWidth : halfHeight; + }, + height: function(height) { + return height; + }, + connectionOffsetY: function(connectionHeight) { + return connectionHeight / 2; + }, + connectionOffsetX: function(connectionWidth) { + return -connectionWidth; + }, + pathDown: function(height) { + return makeMainPath(height, false, false); + }, + pathUp: function(height) { + return makeMainPath(height, true, false); + }, + pathRightDown: function(height) { + return makeMainPath(height, false, true); + }, + pathRightUp: function(height) { + return makeMainPath(height, false, true); + }, + }; } - return { - type: this.SHAPES.ROUND, - isDynamic: true, - width: function(height) { - const halfHeight = height / 2; - return halfHeight > maxWidth ? maxWidth : halfHeight; - }, - height: function(height) { - return height; - }, - connectionOffsetY: function(connectionHeight) { - return connectionHeight / 2; - }, - connectionOffsetX: function(connectionWidth) { - return -connectionWidth; - }, - pathDown: function(height) { - return makeMainPath(height, false, false); - }, - pathUp: function(height) { - return makeMainPath(height, true, false); - }, - pathRightDown: function(height) { - return makeMainPath(height, false, true); - }, - pathRightUp: function(height) { - return makeMainPath(height, false, true); - }, - }; -}; - -/** - * Create sizing and path information about a squared shape. - * @return {!Object} An object containing sizing and path information about - * a squared shape for connections. - * @package - */ -ConstantProvider.prototype.makeSquared = function() { - const radius = this.CORNER_RADIUS; - /** - * Make the main path for the squared connection shape out of two corners - * and a single line in-between (a and v). These are defined in relative - * positions and require the height of the block. - * The 'left' and 'right' versions of the paths are the same, but the Y sign - * flips. The 'up' and 'down' versions of the path determine where the corner - * point is placed and in turn the direction of the corners. - * @param {number} height The height of the block the connection is on. - * @param {boolean} up True if the path should be drawn from bottom to top, - * false otherwise. - * @param {boolean} right True if the path is for the right side of the - * block. - * @return {string} A path fragment describing a squared connection. + * Create sizing and path information about a squared shape. + * @return {!Object} An object containing sizing and path information about + * a squared shape for connections. + * @package */ - function makeMainPath(height, up, right) { - const innerHeight = height - radius * 2; - return svgPaths.arc( - 'a', '0 0,1', radius, - svgPaths.point((up ? -1 : 1) * radius, (up ? -1 : 1) * radius)) + - svgPaths.lineOnAxis('v', (right ? 1 : -1) * innerHeight) + - svgPaths.arc( - 'a', '0 0,1', radius, - svgPaths.point((up ? 1 : -1) * radius, (up ? -1 : 1) * radius)); + makeSquared() { + const radius = this.CORNER_RADIUS; + + /** + * Make the main path for the squared connection shape out of two corners + * and a single line in-between (a and v). These are defined in relative + * positions and require the height of the block. + * The 'left' and 'right' versions of the paths are the same, but the Y sign + * flips. The 'up' and 'down' versions of the path determine where the + * corner point is placed and in turn the direction of the corners. + * @param {number} height The height of the block the connection is on. + * @param {boolean} up True if the path should be drawn from bottom to top, + * false otherwise. + * @param {boolean} right True if the path is for the right side of the + * block. + * @return {string} A path fragment describing a squared connection. + */ + function makeMainPath(height, up, right) { + const innerHeight = height - radius * 2; + return svgPaths.arc( + 'a', '0 0,1', radius, + svgPaths.point( + (up ? -1 : 1) * radius, (up ? -1 : 1) * radius)) + + svgPaths.lineOnAxis('v', (right ? 1 : -1) * innerHeight) + + svgPaths.arc( + 'a', '0 0,1', radius, + svgPaths.point((up ? 1 : -1) * radius, (up ? -1 : 1) * radius)); + } + + return { + type: this.SHAPES.SQUARE, + isDynamic: true, + width: function(_height) { + return radius; + }, + height: function(height) { + return height; + }, + connectionOffsetY: function(connectionHeight) { + return connectionHeight / 2; + }, + connectionOffsetX: function(connectionWidth) { + return -connectionWidth; + }, + pathDown: function(height) { + return makeMainPath(height, false, false); + }, + pathUp: function(height) { + return makeMainPath(height, true, false); + }, + pathRightDown: function(height) { + return makeMainPath(height, false, true); + }, + pathRightUp: function(height) { + return makeMainPath(height, false, true); + }, + }; } - return { - type: this.SHAPES.SQUARE, - isDynamic: true, - width: function(_height) { - return radius; - }, - height: function(height) { - return height; - }, - connectionOffsetY: function(connectionHeight) { - return connectionHeight / 2; - }, - connectionOffsetX: function(connectionWidth) { - return -connectionWidth; - }, - pathDown: function(height) { - return makeMainPath(height, false, false); - }, - pathUp: function(height) { - return makeMainPath(height, true, false); - }, - pathRightDown: function(height) { - return makeMainPath(height, false, true); - }, - pathRightUp: function(height) { - return makeMainPath(height, false, true); - }, - }; -}; - -/** - * @override - */ -ConstantProvider.prototype.shapeFor = function(connection) { - let checks = connection.getCheck(); - if (!checks && connection.targetConnection) { - checks = connection.targetConnection.getCheck(); - } - let outputShape; - switch (connection.type) { - case ConnectionType.INPUT_VALUE: - case ConnectionType.OUTPUT_VALUE: - outputShape = connection.getSourceBlock().getOutputShape(); - // If the block has an output shape set, use that instead. - if (outputShape !== null) { - switch (outputShape) { - case this.SHAPES.HEXAGONAL: - return this.HEXAGONAL; - case this.SHAPES.ROUND: - return this.ROUNDED; - case this.SHAPES.SQUARE: - return this.SQUARED; + /** + * @override + */ + shapeFor(connection) { + let checks = connection.getCheck(); + if (!checks && connection.targetConnection) { + checks = connection.targetConnection.getCheck(); + } + let outputShape; + switch (connection.type) { + case ConnectionType.INPUT_VALUE: + case ConnectionType.OUTPUT_VALUE: + outputShape = connection.getSourceBlock().getOutputShape(); + // If the block has an output shape set, use that instead. + if (outputShape !== null) { + switch (outputShape) { + case this.SHAPES.HEXAGONAL: + return /** @type {!Object} */ (this.HEXAGONAL); + case this.SHAPES.ROUND: + return /** @type {!Object} */ (this.ROUNDED); + case this.SHAPES.SQUARE: + return /** @type {!Object} */ (this.SQUARED); + } } - } - // Includes doesn't work in IE. - if (checks && checks.indexOf('Boolean') !== -1) { - return this.HEXAGONAL; - } - if (checks && checks.indexOf('Number') !== -1) { - return this.ROUNDED; - } - if (checks && checks.indexOf('String') !== -1) { - return this.ROUNDED; - } - return this.ROUNDED; - case ConnectionType.PREVIOUS_STATEMENT: - case ConnectionType.NEXT_STATEMENT: - return this.NOTCH; - default: - throw Error('Unknown type'); + // Includes doesn't work in IE. + if (checks && checks.indexOf('Boolean') !== -1) { + return /** @type {!Object} */ (this.HEXAGONAL); + } + if (checks && checks.indexOf('Number') !== -1) { + return /** @type {!Object} */ (this.ROUNDED); + } + if (checks && checks.indexOf('String') !== -1) { + return /** @type {!Object} */ (this.ROUNDED); + } + return /** @type {!Object} */ (this.ROUNDED); + case ConnectionType.PREVIOUS_STATEMENT: + case ConnectionType.NEXT_STATEMENT: + return this.NOTCH; + default: + throw Error('Unknown type'); + } } -}; - -/** - * @override - */ -ConstantProvider.prototype.makeNotch = function() { - const width = this.NOTCH_WIDTH; - const height = this.NOTCH_HEIGHT; - - const innerWidth = width / 3; - const curveWidth = innerWidth / 3; - - const halfHeight = height / 2; - const quarterHeight = halfHeight / 2; /** - * Make the main path for the notch. - * @param {number} dir Direction multiplier to apply to horizontal offsets - * along the path. Either 1 or -1. - * @return {string} A path fragment describing a notch. + * @override */ - function makeMainPath(dir) { - return ( - svgPaths.curve( - 'c', - [ - svgPaths.point(dir * curveWidth / 2, 0), - svgPaths.point(dir * curveWidth * 3 / 4, quarterHeight / 2), - svgPaths.point(dir * curveWidth, quarterHeight), - ]) + - svgPaths.line([svgPaths.point(dir * curveWidth, halfHeight)]) + - svgPaths.curve( - 'c', - [ - svgPaths.point(dir * curveWidth / 4, quarterHeight / 2), - svgPaths.point(dir * curveWidth / 2, quarterHeight), - svgPaths.point(dir * curveWidth, quarterHeight), - ]) + - svgPaths.lineOnAxis('h', dir * innerWidth) + - svgPaths.curve( - 'c', - [ - svgPaths.point(dir * curveWidth / 2, 0), - svgPaths.point(dir * curveWidth * 3 / 4, -(quarterHeight / 2)), - svgPaths.point(dir * curveWidth, -quarterHeight), - ]) + - svgPaths.line([svgPaths.point(dir * curveWidth, -halfHeight)]) + - svgPaths.curve('c', [ - svgPaths.point(dir * curveWidth / 4, -(quarterHeight / 2)), - svgPaths.point(dir * curveWidth / 2, -quarterHeight), - svgPaths.point(dir * curveWidth, -quarterHeight), - ])); + makeNotch() { + const width = this.NOTCH_WIDTH; + const height = this.NOTCH_HEIGHT; + + const innerWidth = width / 3; + const curveWidth = innerWidth / 3; + + const halfHeight = height / 2; + const quarterHeight = halfHeight / 2; + + /** + * Make the main path for the notch. + * @param {number} dir Direction multiplier to apply to horizontal offsets + * along the path. Either 1 or -1. + * @return {string} A path fragment describing a notch. + */ + function makeMainPath(dir) { + return ( + svgPaths.curve( + 'c', + [ + svgPaths.point(dir * curveWidth / 2, 0), + svgPaths.point(dir * curveWidth * 3 / 4, quarterHeight / 2), + svgPaths.point(dir * curveWidth, quarterHeight), + ]) + + svgPaths.line([svgPaths.point(dir * curveWidth, halfHeight)]) + + svgPaths.curve( + 'c', + [ + svgPaths.point(dir * curveWidth / 4, quarterHeight / 2), + svgPaths.point(dir * curveWidth / 2, quarterHeight), + svgPaths.point(dir * curveWidth, quarterHeight), + ]) + + svgPaths.lineOnAxis('h', dir * innerWidth) + + svgPaths.curve( + 'c', + [ + svgPaths.point(dir * curveWidth / 2, 0), + svgPaths.point(dir * curveWidth * 3 / 4, -(quarterHeight / 2)), + svgPaths.point(dir * curveWidth, -quarterHeight), + ]) + + svgPaths.line([svgPaths.point(dir * curveWidth, -halfHeight)]) + + svgPaths.curve('c', [ + svgPaths.point(dir * curveWidth / 4, -(quarterHeight / 2)), + svgPaths.point(dir * curveWidth / 2, -quarterHeight), + svgPaths.point(dir * curveWidth, -quarterHeight), + ])); + } + + const pathLeft = makeMainPath(1); + const pathRight = makeMainPath(-1); + + return { + type: this.SHAPES.NOTCH, + width: width, + height: height, + pathLeft: pathLeft, + pathRight: pathRight, + }; } - const pathLeft = makeMainPath(1); - const pathRight = makeMainPath(-1); + /** + * @override + */ + makeInsideCorners() { + const radius = this.CORNER_RADIUS; - return { - type: this.SHAPES.NOTCH, - width: width, - height: height, - pathLeft: pathLeft, - pathRight: pathRight, - }; -}; + const innerTopLeftCorner = + svgPaths.arc('a', '0 0,0', radius, svgPaths.point(-radius, radius)); -/** - * @override - */ -ConstantProvider.prototype.makeInsideCorners = function() { - const radius = this.CORNER_RADIUS; + const innerTopRightCorner = + svgPaths.arc('a', '0 0,1', radius, svgPaths.point(-radius, radius)); - const innerTopLeftCorner = - svgPaths.arc('a', '0 0,0', radius, svgPaths.point(-radius, radius)); + const innerBottomLeftCorner = + svgPaths.arc('a', '0 0,0', radius, svgPaths.point(radius, radius)); - const innerTopRightCorner = - svgPaths.arc('a', '0 0,1', radius, svgPaths.point(-radius, radius)); + const innerBottomRightCorner = + svgPaths.arc('a', '0 0,1', radius, svgPaths.point(radius, radius)); - const innerBottomLeftCorner = - svgPaths.arc('a', '0 0,0', radius, svgPaths.point(radius, radius)); + return { + width: radius, + height: radius, + pathTop: innerTopLeftCorner, + pathBottom: innerBottomLeftCorner, + rightWidth: radius, + rightHeight: radius, + pathTopRight: innerTopRightCorner, + pathBottomRight: innerBottomRightCorner, + }; + } - const innerBottomRightCorner = - svgPaths.arc('a', '0 0,1', radius, svgPaths.point(radius, radius)); + /** + * @override + */ + generateSecondaryColour_(colour) { + return utilsColour.blend('#000', colour, 0.15) || colour; + } - return { - width: radius, - height: radius, - pathTop: innerTopLeftCorner, - pathBottom: innerBottomLeftCorner, - rightWidth: radius, - rightHeight: radius, - pathTopRight: innerTopRightCorner, - pathBottomRight: innerBottomRightCorner, - }; -}; + /** + * @override + */ + generateTertiaryColour_(colour) { + return utilsColour.blend('#000', colour, 0.25) || colour; + } -/** - * @override - */ -ConstantProvider.prototype.generateSecondaryColour_ = function(colour) { - return utilsColour.blend('#000', colour, 0.15) || colour; -}; + /** + * @override + */ + createDom(svg, tagName, selector) { + super.createDom(svg, tagName, selector); + /* + + ... filters go here ... + + */ + const defs = dom.createSvgElement(Svg.DEFS, {}, svg); + // Using a dilate distorts the block shape. + // Instead use a gaussian blur, and then set all alpha to 1 with a transfer. + const selectedGlowFilter = dom.createSvgElement( + Svg.FILTER, { + 'id': 'blocklySelectedGlowFilter' + this.randomIdentifier, + 'height': '160%', + 'width': '180%', + 'y': '-30%', + 'x': '-40%', + }, + defs); + dom.createSvgElement( + Svg.FEGAUSSIANBLUR, + {'in': 'SourceGraphic', 'stdDeviation': this.SELECTED_GLOW_SIZE}, + selectedGlowFilter); + // Set all gaussian blur pixels to 1 opacity before applying flood + const selectedComponentTransfer = dom.createSvgElement( + Svg.FECOMPONENTTRANSFER, {'result': 'outBlur'}, selectedGlowFilter); + dom.createSvgElement( + Svg.FEFUNCA, + {'type': 'table', 'tableValues': '0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1'}, + selectedComponentTransfer); + // Color the highlight + dom.createSvgElement( + Svg.FEFLOOD, { + 'flood-color': this.SELECTED_GLOW_COLOUR, + 'flood-opacity': 1, + 'result': 'outColor', + }, + selectedGlowFilter); + dom.createSvgElement( + Svg.FECOMPOSITE, { + 'in': 'outColor', + 'in2': 'outBlur', + 'operator': 'in', + 'result': 'outGlow', + }, + selectedGlowFilter); + this.selectedGlowFilterId = selectedGlowFilter.id; + this.selectedGlowFilter_ = selectedGlowFilter; -/** - * @override - */ -ConstantProvider.prototype.generateTertiaryColour_ = function(colour) { - return utilsColour.blend('#000', colour, 0.25) || colour; -}; + // Using a dilate distorts the block shape. + // Instead use a gaussian blur, and then set all alpha to 1 with a transfer. + const replacementGlowFilter = dom.createSvgElement( + Svg.FILTER, { + 'id': 'blocklyReplacementGlowFilter' + this.randomIdentifier, + 'height': '160%', + 'width': '180%', + 'y': '-30%', + 'x': '-40%', + }, + defs); + dom.createSvgElement( + Svg.FEGAUSSIANBLUR, + {'in': 'SourceGraphic', 'stdDeviation': this.REPLACEMENT_GLOW_SIZE}, + replacementGlowFilter); + // Set all gaussian blur pixels to 1 opacity before applying flood + const replacementComponentTransfer = dom.createSvgElement( + Svg.FECOMPONENTTRANSFER, {'result': 'outBlur'}, replacementGlowFilter); + dom.createSvgElement( + Svg.FEFUNCA, + {'type': 'table', 'tableValues': '0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1'}, + replacementComponentTransfer); + // Color the highlight + dom.createSvgElement( + Svg.FEFLOOD, { + 'flood-color': this.REPLACEMENT_GLOW_COLOUR, + 'flood-opacity': 1, + 'result': 'outColor', + }, + replacementGlowFilter); + dom.createSvgElement( + Svg.FECOMPOSITE, { + 'in': 'outColor', + 'in2': 'outBlur', + 'operator': 'in', + 'result': 'outGlow', + }, + replacementGlowFilter); + dom.createSvgElement( + Svg.FECOMPOSITE, { + 'in': 'SourceGraphic', + 'in2': 'outGlow', + 'operator': 'over', + }, + replacementGlowFilter); + this.replacementGlowFilterId = replacementGlowFilter.id; + this.replacementGlowFilter_ = replacementGlowFilter; + } -/** - * @override - */ -ConstantProvider.prototype.createDom = function(svg, tagName, selector) { - ConstantProvider.superClass_.createDom.call(this, svg, tagName, selector); - /* - - ... filters go here ... - - */ - const defs = dom.createSvgElement(Svg.DEFS, {}, svg); - // Using a dilate distorts the block shape. - // Instead use a gaussian blur, and then set all alpha to 1 with a transfer. - const selectedGlowFilter = dom.createSvgElement( - Svg.FILTER, { - 'id': 'blocklySelectedGlowFilter' + this.randomIdentifier, - 'height': '160%', - 'width': '180%', - 'y': '-30%', - 'x': '-40%', - }, - defs); - dom.createSvgElement( - Svg.FEGAUSSIANBLUR, - {'in': 'SourceGraphic', 'stdDeviation': this.SELECTED_GLOW_SIZE}, - selectedGlowFilter); - // Set all gaussian blur pixels to 1 opacity before applying flood - const selectedComponentTransfer = dom.createSvgElement( - Svg.FECOMPONENTTRANSFER, {'result': 'outBlur'}, selectedGlowFilter); - dom.createSvgElement( - Svg.FEFUNCA, - {'type': 'table', 'tableValues': '0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1'}, - selectedComponentTransfer); - // Color the highlight - dom.createSvgElement( - Svg.FEFLOOD, { - 'flood-color': this.SELECTED_GLOW_COLOUR, - 'flood-opacity': 1, - 'result': 'outColor', - }, - selectedGlowFilter); - dom.createSvgElement( - Svg.FECOMPOSITE, { - 'in': 'outColor', - 'in2': 'outBlur', - 'operator': 'in', - 'result': 'outGlow', - }, - selectedGlowFilter); - this.selectedGlowFilterId = selectedGlowFilter.id; - this.selectedGlowFilter_ = selectedGlowFilter; + /** + * @override + */ + getCSS_(selector) { + return [ + /* eslint-disable indent */ + // Text. + selector + ' .blocklyText,', selector + ' .blocklyFlyoutLabelText {', + 'font: ' + this.FIELD_TEXT_FONTWEIGHT + ' ' + this.FIELD_TEXT_FONTSIZE + + 'pt ' + this.FIELD_TEXT_FONTFAMILY + ';', + '}', - // Using a dilate distorts the block shape. - // Instead use a gaussian blur, and then set all alpha to 1 with a transfer. - const replacementGlowFilter = dom.createSvgElement( - Svg.FILTER, { - 'id': 'blocklyReplacementGlowFilter' + this.randomIdentifier, - 'height': '160%', - 'width': '180%', - 'y': '-30%', - 'x': '-40%', - }, - defs); - dom.createSvgElement( - Svg.FEGAUSSIANBLUR, - {'in': 'SourceGraphic', 'stdDeviation': this.REPLACEMENT_GLOW_SIZE}, - replacementGlowFilter); - // Set all gaussian blur pixels to 1 opacity before applying flood - const replacementComponentTransfer = dom.createSvgElement( - Svg.FECOMPONENTTRANSFER, {'result': 'outBlur'}, replacementGlowFilter); - dom.createSvgElement( - Svg.FEFUNCA, - {'type': 'table', 'tableValues': '0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1'}, - replacementComponentTransfer); - // Color the highlight - dom.createSvgElement( - Svg.FEFLOOD, { - 'flood-color': this.REPLACEMENT_GLOW_COLOUR, - 'flood-opacity': 1, - 'result': 'outColor', - }, - replacementGlowFilter); - dom.createSvgElement( - Svg.FECOMPOSITE, { - 'in': 'outColor', - 'in2': 'outBlur', - 'operator': 'in', - 'result': 'outGlow', - }, - replacementGlowFilter); - dom.createSvgElement( - Svg.FECOMPOSITE, { - 'in': 'SourceGraphic', - 'in2': 'outGlow', - 'operator': 'over', - }, - replacementGlowFilter); - this.replacementGlowFilterId = replacementGlowFilter.id; - this.replacementGlowFilter_ = replacementGlowFilter; -}; + // Fields. + selector + ' .blocklyText {', 'fill: #fff;', '}', + selector + ' .blocklyNonEditableText>rect:not(.blocklyDropdownRect),', + selector + ' .blocklyEditableText>rect:not(.blocklyDropdownRect) {', + 'fill: ' + this.FIELD_BORDER_RECT_COLOUR + ';', '}', + selector + ' .blocklyNonEditableText>text,', + selector + ' .blocklyEditableText>text,', + selector + ' .blocklyNonEditableText>g>text,', + selector + ' .blocklyEditableText>g>text {', 'fill: #575E75;', '}', -/** - * @override - */ -ConstantProvider.prototype.getCSS_ = function(selector) { - return [ - /* eslint-disable indent */ - // Text. - selector + ' .blocklyText,', selector + ' .blocklyFlyoutLabelText {', - 'font: ' + this.FIELD_TEXT_FONTWEIGHT + ' ' + this.FIELD_TEXT_FONTSIZE + - 'pt ' + this.FIELD_TEXT_FONTFAMILY + ';', - '}', + // Flyout labels. + selector + ' .blocklyFlyoutLabelText {', 'fill: #575E75;', '}', - // Fields. - selector + ' .blocklyText {', 'fill: #fff;', '}', - selector + ' .blocklyNonEditableText>rect:not(.blocklyDropdownRect),', - selector + ' .blocklyEditableText>rect:not(.blocklyDropdownRect) {', - 'fill: ' + this.FIELD_BORDER_RECT_COLOUR + ';', '}', - selector + ' .blocklyNonEditableText>text,', - selector + ' .blocklyEditableText>text,', - selector + ' .blocklyNonEditableText>g>text,', - selector + ' .blocklyEditableText>g>text {', 'fill: #575E75;', '}', + // Bubbles. + selector + ' .blocklyText.blocklyBubbleText {', 'fill: #575E75;', '}', - // Flyout labels. - selector + ' .blocklyFlyoutLabelText {', 'fill: #575E75;', '}', + // Editable field hover. + selector + ' .blocklyDraggable:not(.blocklyDisabled)', + ' .blocklyEditableText:not(.editing):hover>rect,', + selector + ' .blocklyDraggable:not(.blocklyDisabled)', + ' .blocklyEditableText:not(.editing):hover>.blocklyPath {', + 'stroke: #fff;', 'stroke-width: 2;', '}', - // Bubbles. - selector + ' .blocklyText.blocklyBubbleText {', 'fill: #575E75;', '}', + // Text field input. + selector + ' .blocklyHtmlInput {', + 'font-family: ' + this.FIELD_TEXT_FONTFAMILY + ';', + 'font-weight: ' + this.FIELD_TEXT_FONTWEIGHT + ';', 'color: #575E75;', + '}', - // Editable field hover. - selector + ' .blocklyDraggable:not(.blocklyDisabled)', - ' .blocklyEditableText:not(.editing):hover>rect,', - selector + ' .blocklyDraggable:not(.blocklyDisabled)', - ' .blocklyEditableText:not(.editing):hover>.blocklyPath {', 'stroke: #fff;', - 'stroke-width: 2;', '}', + // Dropdown field. + selector + ' .blocklyDropdownText {', 'fill: #fff !important;', '}', + // Widget and Dropdown Div + selector + '.blocklyWidgetDiv .goog-menuitem,', + selector + '.blocklyDropDownDiv .goog-menuitem {', + 'font-family: ' + this.FIELD_TEXT_FONTFAMILY + ';', '}', + selector + '.blocklyDropDownDiv .goog-menuitem-content {', 'color: #fff;', + '}', - // Text field input. - selector + ' .blocklyHtmlInput {', - 'font-family: ' + this.FIELD_TEXT_FONTFAMILY + ';', - 'font-weight: ' + this.FIELD_TEXT_FONTWEIGHT + ';', 'color: #575E75;', '}', + // Connection highlight. + selector + ' .blocklyHighlightedConnectionPath {', + 'stroke: ' + this.SELECTED_GLOW_COLOUR + ';', '}', - // Dropdown field. - selector + ' .blocklyDropdownText {', 'fill: #fff !important;', '}', - // Widget and Dropdown Div - selector + '.blocklyWidgetDiv .goog-menuitem,', - selector + '.blocklyDropDownDiv .goog-menuitem {', - 'font-family: ' + this.FIELD_TEXT_FONTFAMILY + ';', '}', - selector + '.blocklyDropDownDiv .goog-menuitem-content {', 'color: #fff;', - '}', + // Disabled outline paths. + selector + ' .blocklyDisabled > .blocklyOutlinePath {', + 'fill: url(#blocklyDisabledPattern' + this.randomIdentifier + ')', '}', - // Connection highlight. - selector + ' .blocklyHighlightedConnectionPath {', - 'stroke: ' + this.SELECTED_GLOW_COLOUR + ';', '}', - - // Disabled outline paths. - selector + ' .blocklyDisabled > .blocklyOutlinePath {', - 'fill: url(#blocklyDisabledPattern' + this.randomIdentifier + ')', '}', - - // Insertion marker. - selector + ' .blocklyInsertionMarker>.blocklyPath {', - 'fill-opacity: ' + this.INSERTION_MARKER_OPACITY + ';', 'stroke: none;', - '}', - /* eslint-enable indent */ - ]; -}; + // Insertion marker. + selector + ' .blocklyInsertionMarker>.blocklyPath {', + 'fill-opacity: ' + this.INSERTION_MARKER_OPACITY + ';', 'stroke: none;', + '}', + /* eslint-enable indent */ + ]; + } +} exports.ConstantProvider = ConstantProvider; diff --git a/core/renderers/zelos/drawer.js b/core/renderers/zelos/drawer.js index fc3dfbbaf..9c9f7917e 100644 --- a/core/renderers/zelos/drawer.js +++ b/core/renderers/zelos/drawer.js @@ -16,7 +16,6 @@ goog.module('Blockly.zelos.Drawer'); const debug = goog.require('Blockly.blockRendering.debug'); -const object = goog.require('Blockly.utils.object'); const svgPaths = goog.require('Blockly.utils.svgPaths'); /* eslint-disable-next-line no-unused-vars */ const {BlockSvg} = goog.requireType('Blockly.BlockSvg'); @@ -31,203 +30,206 @@ const {Row} = goog.requireType('Blockly.blockRendering.Row'); /** * An object that draws a block based on the given rendering information. - * @param {!BlockSvg} block The block to render. - * @param {!RenderInfo} info An object containing all - * information needed to render this block. - * @package - * @constructor * @extends {BaseDrawer} - * @alias Blockly.zelos.Drawer */ -const Drawer = function(block, info) { - Drawer.superClass_.constructor.call(this, block, info); -}; -object.inherits(Drawer, BaseDrawer); - - -/** - * @override - */ -Drawer.prototype.draw = function() { - const pathObject = - /** @type {!PathObject} */ (this.block_.pathObject); - pathObject.beginDrawing(); - this.hideHiddenIcons_(); - this.drawOutline_(); - this.drawInternals_(); - - pathObject.setPath(this.outlinePath_ + '\n' + this.inlinePath_); - if (this.info_.RTL) { - pathObject.flipRTL(); +class Drawer extends BaseDrawer { + /** + * @param {!BlockSvg} block The block to render. + * @param {!RenderInfo} info An object containing all + * information needed to render this block. + * @package + * @alias Blockly.zelos.Drawer + */ + constructor(block, info) { + super(block, info); } - if (debug.isDebuggerEnabled()) { - this.block_.renderingDebugger.drawDebug(this.block_, this.info_); - } - this.recordSizeOnBlock_(); - if (this.info_.outputConnection) { - // Store the output connection shape type for parent blocks to use during - // rendering. - pathObject.outputShapeType = this.info_.outputConnection.shape.type; - } - pathObject.endDrawing(); -}; -/** - * @override - */ -Drawer.prototype.drawOutline_ = function() { - if (this.info_.outputConnection && - this.info_.outputConnection.isDynamicShape && - !this.info_.hasStatementInput && - !this.info_.bottomRow.hasNextConnection) { - this.drawFlatTop_(); - this.drawRightDynamicConnection_(); - this.drawFlatBottom_(); - this.drawLeftDynamicConnection_(); - } else { - Drawer.superClass_.drawOutline_.call(this); - } -}; + /** + * @override + */ + draw() { + const pathObject = + /** @type {!PathObject} */ (this.block_.pathObject); + pathObject.beginDrawing(); + this.hideHiddenIcons_(); + this.drawOutline_(); + this.drawInternals_(); -/** - * @override - */ -Drawer.prototype.drawLeft_ = function() { - if (this.info_.outputConnection && - this.info_.outputConnection.isDynamicShape) { - this.drawLeftDynamicConnection_(); - } else { - Drawer.superClass_.drawLeft_.call(this); + pathObject.setPath(this.outlinePath_ + '\n' + this.inlinePath_); + if (this.info_.RTL) { + pathObject.flipRTL(); + } + if (debug.isDebuggerEnabled()) { + this.block_.renderingDebugger.drawDebug(this.block_, this.info_); + } + this.recordSizeOnBlock_(); + if (this.info_.outputConnection) { + // Store the output connection shape type for parent blocks to use during + // rendering. + pathObject.outputShapeType = this.info_.outputConnection.shape.type; + } + pathObject.endDrawing(); } -}; -/** - * Add steps for the right side of a row that does not have value or - * statement input connections. - * @param {!Row} row The row to draw the - * side of. - * @protected - */ -Drawer.prototype.drawRightSideRow_ = function(row) { - if (row.height <= 0) { - return; + /** + * @override + */ + drawOutline_() { + if (this.info_.outputConnection && + this.info_.outputConnection.isDynamicShape && + !this.info_.hasStatementInput && + !this.info_.bottomRow.hasNextConnection) { + this.drawFlatTop_(); + this.drawRightDynamicConnection_(); + this.drawFlatBottom_(); + this.drawLeftDynamicConnection_(); + } else { + super.drawOutline_(); + } } - if (row.precedesStatement || row.followsStatement) { - const cornerHeight = this.constants_.INSIDE_CORNERS.rightHeight; - const remainingHeight = - row.height - (row.precedesStatement ? cornerHeight : 0); - this.outlinePath_ += - (row.followsStatement ? this.constants_.INSIDE_CORNERS.pathBottomRight : + + /** + * @override + */ + drawLeft_() { + if (this.info_.outputConnection && + this.info_.outputConnection.isDynamicShape) { + this.drawLeftDynamicConnection_(); + } else { + super.drawLeft_(); + } + } + + /** + * Add steps for the right side of a row that does not have value or + * statement input connections. + * @param {!Row} row The row to draw the + * side of. + * @protected + */ + drawRightSideRow_(row) { + if (row.height <= 0) { + return; + } + if (row.precedesStatement || row.followsStatement) { + const cornerHeight = this.constants_.INSIDE_CORNERS.rightHeight; + const remainingHeight = + row.height - (row.precedesStatement ? cornerHeight : 0); + this.outlinePath_ += (row.followsStatement ? + this.constants_.INSIDE_CORNERS.pathBottomRight : '') + - (remainingHeight > 0 ? - svgPaths.lineOnAxis('V', row.yPos + remainingHeight) : - '') + - (row.precedesStatement ? this.constants_.INSIDE_CORNERS.pathTopRight : - ''); - } else { - this.outlinePath_ += svgPaths.lineOnAxis('V', row.yPos + row.height); - } -}; - -/** - * Add steps to draw the right side of an output with a dynamic connection. - * @protected - */ -Drawer.prototype.drawRightDynamicConnection_ = function() { - this.outlinePath_ += this.info_.outputConnection.shape.pathRightDown( - this.info_.outputConnection.height); -}; - -/** - * Add steps to draw the left side of an output with a dynamic connection. - * @protected - */ -Drawer.prototype.drawLeftDynamicConnection_ = function() { - this.positionOutputConnection_(); - - this.outlinePath_ += this.info_.outputConnection.shape.pathUp( - this.info_.outputConnection.height); - - // Close off the path. This draws a vertical line up to the start of the - // block's path, which may be either a rounded or a sharp corner. - this.outlinePath_ += 'z'; -}; - -/** - * Add steps to draw a flat top row. - * @protected - */ -Drawer.prototype.drawFlatTop_ = function() { - const topRow = this.info_.topRow; - this.positionPreviousConnection_(); - - this.outlinePath_ += svgPaths.moveBy(topRow.xPos, this.info_.startY); - - this.outlinePath_ += svgPaths.lineOnAxis('h', topRow.width); -}; - -/** - * Add steps to draw a flat bottom row. - * @protected - */ -Drawer.prototype.drawFlatBottom_ = function() { - const bottomRow = this.info_.bottomRow; - this.positionNextConnection_(); - - this.outlinePath_ += svgPaths.lineOnAxis('V', bottomRow.baseline); - - this.outlinePath_ += svgPaths.lineOnAxis('h', -bottomRow.width); -}; - -/** - * @override - */ -Drawer.prototype.drawInlineInput_ = function(input) { - this.positionInlineInputConnection_(input); - - const inputName = input.input.name; - if (input.connectedBlock || this.info_.isInsertionMarker) { - return; + (remainingHeight > 0 ? + svgPaths.lineOnAxis('V', row.yPos + remainingHeight) : + '') + + (row.precedesStatement ? this.constants_.INSIDE_CORNERS.pathTopRight : + ''); + } else { + this.outlinePath_ += svgPaths.lineOnAxis('V', row.yPos + row.height); + } } - const width = input.width - (input.connectionWidth * 2); - const height = input.height; - const yPos = input.centerline - height / 2; + /** + * Add steps to draw the right side of an output with a dynamic connection. + * @protected + */ + drawRightDynamicConnection_() { + this.outlinePath_ += this.info_.outputConnection.shape.pathRightDown( + this.info_.outputConnection.height); + } - const connectionRight = input.xPos + input.connectionWidth; + /** + * Add steps to draw the left side of an output with a dynamic connection. + * @protected + */ + drawLeftDynamicConnection_() { + this.positionOutputConnection_(); - const outlinePath = svgPaths.moveTo(connectionRight, yPos) + - svgPaths.lineOnAxis('h', width) + - input.shape.pathRightDown(input.height) + - svgPaths.lineOnAxis('h', -width) + input.shape.pathUp(input.height) + 'z'; - this.block_.pathObject.setOutlinePath(inputName, outlinePath); -}; + this.outlinePath_ += this.info_.outputConnection.shape.pathUp( + this.info_.outputConnection.height); -/** - * @override - */ -Drawer.prototype.drawStatementInput_ = function(row) { - const input = row.getLastInput(); - // Where to start drawing the notch, which is on the right side in LTR. - const x = input.xPos + input.notchOffset + input.shape.width; + // Close off the path. This draws a vertical line up to the start of the + // block's path, which may be either a rounded or a sharp corner. + this.outlinePath_ += 'z'; + } - const innerTopLeftCorner = input.shape.pathRight + - svgPaths.lineOnAxis( - 'h', -(input.notchOffset - this.constants_.INSIDE_CORNERS.width)) + - this.constants_.INSIDE_CORNERS.pathTop; + /** + * Add steps to draw a flat top row. + * @protected + */ + drawFlatTop_() { + const topRow = this.info_.topRow; + this.positionPreviousConnection_(); - const innerHeight = row.height - (2 * this.constants_.INSIDE_CORNERS.height); + this.outlinePath_ += svgPaths.moveBy(topRow.xPos, this.info_.startY); - const innerBottomLeftCorner = this.constants_.INSIDE_CORNERS.pathBottom + - svgPaths.lineOnAxis( - 'h', (input.notchOffset - this.constants_.INSIDE_CORNERS.width)) + - (input.connectedBottomNextConnection ? '' : input.shape.pathLeft); + this.outlinePath_ += svgPaths.lineOnAxis('h', topRow.width); + } - this.outlinePath_ += svgPaths.lineOnAxis('H', x) + innerTopLeftCorner + - svgPaths.lineOnAxis('v', innerHeight) + innerBottomLeftCorner + - svgPaths.lineOnAxis('H', row.xPos + row.width); + /** + * Add steps to draw a flat bottom row. + * @protected + */ + drawFlatBottom_() { + const bottomRow = this.info_.bottomRow; + this.positionNextConnection_(); - this.positionStatementInputConnection_(row); -}; + this.outlinePath_ += svgPaths.lineOnAxis('V', bottomRow.baseline); + + this.outlinePath_ += svgPaths.lineOnAxis('h', -bottomRow.width); + } + + /** + * @override + */ + drawInlineInput_(input) { + this.positionInlineInputConnection_(input); + + const inputName = input.input.name; + if (input.connectedBlock || this.info_.isInsertionMarker) { + return; + } + + const width = input.width - (input.connectionWidth * 2); + const height = input.height; + const yPos = input.centerline - height / 2; + + const connectionRight = input.xPos + input.connectionWidth; + + const outlinePath = svgPaths.moveTo(connectionRight, yPos) + + svgPaths.lineOnAxis('h', width) + + input.shape.pathRightDown(input.height) + + svgPaths.lineOnAxis('h', -width) + input.shape.pathUp(input.height) + + 'z'; + this.block_.pathObject.setOutlinePath(inputName, outlinePath); + } + + /** + * @override + */ + drawStatementInput_(row) { + const input = row.getLastInput(); + // Where to start drawing the notch, which is on the right side in LTR. + const x = input.xPos + input.notchOffset + input.shape.width; + + const innerTopLeftCorner = input.shape.pathRight + + svgPaths.lineOnAxis( + 'h', -(input.notchOffset - this.constants_.INSIDE_CORNERS.width)) + + this.constants_.INSIDE_CORNERS.pathTop; + + const innerHeight = + row.height - (2 * this.constants_.INSIDE_CORNERS.height); + + const innerBottomLeftCorner = this.constants_.INSIDE_CORNERS.pathBottom + + svgPaths.lineOnAxis( + 'h', (input.notchOffset - this.constants_.INSIDE_CORNERS.width)) + + (input.connectedBottomNextConnection ? '' : input.shape.pathLeft); + + this.outlinePath_ += svgPaths.lineOnAxis('H', x) + innerTopLeftCorner + + svgPaths.lineOnAxis('v', innerHeight) + innerBottomLeftCorner + + svgPaths.lineOnAxis('H', row.xPos + row.width); + + this.positionStatementInputConnection_(row); + } +} exports.Drawer = Drawer; diff --git a/core/renderers/zelos/info.js b/core/renderers/zelos/info.js index 46b315295..58802a909 100644 --- a/core/renderers/zelos/info.js +++ b/core/renderers/zelos/info.js @@ -17,7 +17,6 @@ goog.module('Blockly.zelos.RenderInfo'); const {Align} = goog.require('Blockly.Input'); -const object = goog.require('Blockly.utils.object'); /* eslint-disable-next-line no-unused-vars */ const {BlockSvg} = goog.requireType('Blockly.BlockSvg'); const {BottomRow} = goog.require('Blockly.zelos.BottomRow'); @@ -45,557 +44,559 @@ const {inputTypes} = goog.require('Blockly.inputTypes'); * This measure pass does not propagate changes to the block (although fields * may choose to rerender when getSize() is called). However, calling it * repeatedly may be expensive. - * - * @param {!Renderer} renderer The renderer in use. - * @param {!BlockSvg} block The block to measure. - * @constructor - * @package * @extends {BaseRenderInfo} - * @alias Blockly.zelos.RenderInfo */ -const RenderInfo = function(renderer, block) { - RenderInfo.superClass_.constructor.call(this, renderer, block); +class RenderInfo extends BaseRenderInfo { + /** + * @param {!Renderer} renderer The renderer in use. + * @param {!BlockSvg} block The block to measure. + * @package + * @alias Blockly.zelos.RenderInfo + */ + constructor(renderer, block) { + super(renderer, block); + + /** + * An object with rendering information about the top row of the block. + * @type {!TopRow} + * @override + */ + this.topRow = new TopRow(this.constants_); + + /** + * An object with rendering information about the bottom row of the block. + * @type {!BottomRow} + * @override + */ + this.bottomRow = new BottomRow(this.constants_); + + /** + * @override + */ + this.isInline = true; + + /** + * Whether the block should be rendered as a multi-line block, either + * because it's not inline or because it has been collapsed. + * @type {boolean} + */ + this.isMultiRow = !block.getInputsInline() || block.isCollapsed(); + + /** + * Whether or not the block has a statement input in one of its rows. + * @type {boolean} + */ + this.hasStatementInput = block.statementInputCount > 0; + + /** + * An object with rendering information about the right connection shape. + * @type {RightConnectionShape} + */ + this.rightSide = this.outputConnection ? + new RightConnectionShape(this.constants_) : + null; + } /** - * An object with rendering information about the top row of the block. - * @type {!TopRow} - * @override + * Get the block renderer in use. + * @return {!Renderer} The block renderer in use. + * @package */ - this.topRow = new TopRow(this.constants_); - - /** - * An object with rendering information about the bottom row of the block. - * @type {!BottomRow} - * @override - */ - this.bottomRow = new BottomRow(this.constants_); + getRenderer() { + return /** @type {!Renderer} */ (this.renderer_); + } /** * @override */ - this.isInline = true; + measure() { + // Modifying parent measure method to add `adjustXPosition_`. + this.createRows_(); + this.addElemSpacing_(); + this.addRowSpacing_(); + this.adjustXPosition_(); + this.computeBounds_(); + this.alignRowElements_(); + this.finalize_(); + } /** - * Whether the block should be rendered as a multi-line block, either because - * it's not inline or because it has been collapsed. - * @type {boolean} + * @override */ - this.isMultiRow = !block.getInputsInline() || block.isCollapsed(); - - /** - * Whether or not the block has a statement input in one of its rows. - * @type {boolean} - */ - this.hasStatementInput = block.statementInputCount > 0; - - /** - * An object with rendering information about the right connection shape. - * @type {RightConnectionShape} - */ - this.rightSide = - this.outputConnection ? new RightConnectionShape(this.constants_) : null; -}; -object.inherits(RenderInfo, BaseRenderInfo); - -/** - * Get the block renderer in use. - * @return {!Renderer} The block renderer in use. - * @package - */ -RenderInfo.prototype.getRenderer = function() { - return /** @type {!Renderer} */ (this.renderer_); -}; - -/** - * @override - */ -RenderInfo.prototype.measure = function() { - // Modifying parent measure method to add `adjustXPosition_`. - this.createRows_(); - this.addElemSpacing_(); - this.addRowSpacing_(); - this.adjustXPosition_(); - this.computeBounds_(); - this.alignRowElements_(); - this.finalize_(); -}; - -/** - * @override - */ -RenderInfo.prototype.shouldStartNewRow_ = function(input, lastInput) { - // If this is the first input, just add to the existing row. - // That row is either empty or has some icons in it. - if (!lastInput) { + shouldStartNewRow_(input, lastInput) { + // If this is the first input, just add to the existing row. + // That row is either empty or has some icons in it. + if (!lastInput) { + return false; + } + // A statement input or an input following one always gets a new row. + if (input.type === inputTypes.STATEMENT || + lastInput.type === inputTypes.STATEMENT) { + return true; + } + // Value and dummy inputs get new row if inputs are not inlined. + if (input.type === inputTypes.VALUE || input.type === inputTypes.DUMMY) { + return !this.isInline || this.isMultiRow; + } return false; } - // A statement input or an input following one always gets a new row. - if (input.type === inputTypes.STATEMENT || - lastInput.type === inputTypes.STATEMENT) { - return true; - } - // Value and dummy inputs get new row if inputs are not inlined. - if (input.type === inputTypes.VALUE || input.type === inputTypes.DUMMY) { - return !this.isInline || this.isMultiRow; - } - return false; -}; - -/** - * @override - */ -RenderInfo.prototype.getDesiredRowWidth_ = function(row) { - if (row.hasStatement) { - const rightCornerWidth = this.constants_.INSIDE_CORNERS.rightWidth || 0; - return this.width - this.startX - rightCornerWidth; + /** + * @override + */ + getDesiredRowWidth_(row) { + if (row.hasStatement) { + const rightCornerWidth = this.constants_.INSIDE_CORNERS.rightWidth || 0; + return this.width - this.startX - rightCornerWidth; + } + return super.getDesiredRowWidth_(row); } - return RenderInfo.superClass_.getDesiredRowWidth_.call(this, row); -}; -/** - * @override - */ -RenderInfo.prototype.getInRowSpacing_ = function(prev, next) { - if (!prev || !next) { - // No need for padding at the beginning or end of the row if the - // output shape is dynamic. - if (this.outputConnection && this.outputConnection.isDynamicShape && - !this.hasStatementInput && !this.bottomRow.hasNextConnection) { + /** + * @override + */ + getInRowSpacing_(prev, next) { + if (!prev || !next) { + // No need for padding at the beginning or end of the row if the + // output shape is dynamic. + if (this.outputConnection && this.outputConnection.isDynamicShape && + !this.hasStatementInput && !this.bottomRow.hasNextConnection) { + return this.constants_.NO_PADDING; + } + } + if (!prev) { + // Statement input padding. + if (next && Types.isStatementInput(next)) { + return this.constants_.STATEMENT_INPUT_PADDING_LEFT; + } + } + // Spacing between a rounded corner and a previous or next connection. + if (prev && Types.isLeftRoundedCorner(prev) && next) { + if (Types.isPreviousConnection(next) || Types.isNextConnection(next)) { + return next.notchOffset - this.constants_.CORNER_RADIUS; + } + } + // Spacing between a square corner and a hat. + if (prev && Types.isLeftSquareCorner(prev) && next && Types.isHat(next)) { return this.constants_.NO_PADDING; } + return this.constants_.MEDIUM_PADDING; } - if (!prev) { - // Statement input padding. - if (next && Types.isStatementInput(next)) { - return this.constants_.STATEMENT_INPUT_PADDING_LEFT; - } - } - // Spacing between a rounded corner and a previous or next connection. - if (prev && Types.isLeftRoundedCorner(prev) && next) { - if (Types.isPreviousConnection(next) || Types.isNextConnection(next)) { - return next.notchOffset - this.constants_.CORNER_RADIUS; - } - } - // Spacing between a square corner and a hat. - if (prev && Types.isLeftSquareCorner(prev) && next && Types.isHat(next)) { - return this.constants_.NO_PADDING; - } - return this.constants_.MEDIUM_PADDING; -}; -/** - * @override - */ -RenderInfo.prototype.getSpacerRowHeight_ = function(prev, next) { - // If we have an empty block add a spacer to increase the height. - if (Types.isTopRow(prev) && Types.isBottomRow(next)) { - return this.constants_.EMPTY_BLOCK_SPACER_HEIGHT; - } - const followsStatement = Types.isInputRow(prev) && prev.hasStatement; - const precedesStatement = Types.isInputRow(next) && next.hasStatement; - if (precedesStatement || followsStatement) { - const cornerHeight = this.constants_.INSIDE_CORNERS.rightHeight || 0; - const height = Math.max(this.constants_.NOTCH_HEIGHT, cornerHeight); - return precedesStatement && followsStatement ? - Math.max(height, this.constants_.DUMMY_INPUT_MIN_HEIGHT) : - height; - } - // Top and bottom rows act as a spacer so we don't need any extra padding. - if (Types.isTopRow(prev)) { - if (!prev.hasPreviousConnection && - (!this.outputConnection || this.hasStatementInput)) { - return Math.abs( - this.constants_.NOTCH_HEIGHT - this.constants_.CORNER_RADIUS); + /** + * @override + */ + getSpacerRowHeight_(prev, next) { + // If we have an empty block add a spacer to increase the height. + if (Types.isTopRow(prev) && Types.isBottomRow(next)) { + return this.constants_.EMPTY_BLOCK_SPACER_HEIGHT; } - return this.constants_.NO_PADDING; - } - if (Types.isBottomRow(next)) { - if (!this.outputConnection) { - const topHeight = Math.max( - this.topRow.minHeight, - Math.max( - this.constants_.NOTCH_HEIGHT, - this.constants_.CORNER_RADIUS)) - - this.constants_.CORNER_RADIUS; - return topHeight; - } else if (!next.hasNextConnection && this.hasStatementInput) { - return Math.abs( - this.constants_.NOTCH_HEIGHT - this.constants_.CORNER_RADIUS); + const followsStatement = Types.isInputRow(prev) && prev.hasStatement; + const precedesStatement = Types.isInputRow(next) && next.hasStatement; + if (precedesStatement || followsStatement) { + const cornerHeight = this.constants_.INSIDE_CORNERS.rightHeight || 0; + const height = Math.max(this.constants_.NOTCH_HEIGHT, cornerHeight); + return precedesStatement && followsStatement ? + Math.max(height, this.constants_.DUMMY_INPUT_MIN_HEIGHT) : + height; } - return this.constants_.NO_PADDING; - } - return this.constants_.MEDIUM_PADDING; -}; - -/** - * @override - */ -RenderInfo.prototype.getSpacerRowWidth_ = function(prev, next) { - const width = this.width - this.startX; - if ((Types.isInputRow(prev) && prev.hasStatement) || - (Types.isInputRow(next) && next.hasStatement)) { - return Math.max(width, this.constants_.STATEMENT_INPUT_SPACER_MIN_WIDTH); - } - return width; -}; - -/** - * @override - */ -RenderInfo.prototype.getElemCenterline_ = function(row, elem) { - if (row.hasStatement && !Types.isSpacer(elem) && - !Types.isStatementInput(elem)) { - return row.yPos + this.constants_.EMPTY_STATEMENT_INPUT_HEIGHT / 2; - } - if (Types.isInlineInput(elem)) { - const connectedBlock = elem.connectedBlock; - if (connectedBlock && connectedBlock.outputConnection && - connectedBlock.nextConnection) { - return row.yPos + connectedBlock.height / 2; - } - } - return RenderInfo.superClass_.getElemCenterline_.call(this, row, elem); -}; - -/** - * @override - */ -RenderInfo.prototype.addInput_ = function(input, activeRow) { - // If we have two dummy inputs on the same row, one aligned left and the other - // right, keep track of the right aligned dummy input so we can add padding - // later. - if (input.type === inputTypes.DUMMY && activeRow.hasDummyInput && - activeRow.align === Align.LEFT && input.align === Align.RIGHT) { - activeRow.rightAlignedDummyInput = input; - } else if (input.type === inputTypes.STATEMENT) { - // Handle statements without next connections correctly. - activeRow.elements.push(new StatementInput(this.constants_, input)); - activeRow.hasStatement = true; - - if (activeRow.align === null) { - activeRow.align = input.align; - } - return; - } - RenderInfo.superClass_.addInput_.call(this, input, activeRow); -}; - -/** - * @override - */ -RenderInfo.prototype.addAlignmentPadding_ = function(row, missingSpace) { - if (row.rightAlignedDummyInput) { - let alignmentDivider; - for (let i = 0; i < row.elements.length; i++) { - const elem = row.elements[i]; - if (Types.isSpacer(elem)) { - alignmentDivider = elem; + // Top and bottom rows act as a spacer so we don't need any extra padding. + if (Types.isTopRow(prev)) { + if (!prev.hasPreviousConnection && + (!this.outputConnection || this.hasStatementInput)) { + return Math.abs( + this.constants_.NOTCH_HEIGHT - this.constants_.CORNER_RADIUS); } - if (Types.isField(elem) && - elem.parentInput === row.rightAlignedDummyInput) { - break; + return this.constants_.NO_PADDING; + } + if (Types.isBottomRow(next)) { + if (!this.outputConnection) { + const topHeight = Math.max( + this.topRow.minHeight, + Math.max( + this.constants_.NOTCH_HEIGHT, + this.constants_.CORNER_RADIUS)) - + this.constants_.CORNER_RADIUS; + return topHeight; + } else if (!next.hasNextConnection && this.hasStatementInput) { + return Math.abs( + this.constants_.NOTCH_HEIGHT - this.constants_.CORNER_RADIUS); + } + return this.constants_.NO_PADDING; + } + return this.constants_.MEDIUM_PADDING; + } + + /** + * @override + */ + getSpacerRowWidth_(prev, next) { + const width = this.width - this.startX; + if ((Types.isInputRow(prev) && prev.hasStatement) || + (Types.isInputRow(next) && next.hasStatement)) { + return Math.max(width, this.constants_.STATEMENT_INPUT_SPACER_MIN_WIDTH); + } + return width; + } + + /** + * @override + */ + getElemCenterline_(row, elem) { + if (row.hasStatement && !Types.isSpacer(elem) && + !Types.isStatementInput(elem)) { + return row.yPos + this.constants_.EMPTY_STATEMENT_INPUT_HEIGHT / 2; + } + if (Types.isInlineInput(elem)) { + const connectedBlock = elem.connectedBlock; + if (connectedBlock && connectedBlock.outputConnection && + connectedBlock.nextConnection) { + return row.yPos + connectedBlock.height / 2; } } - if (alignmentDivider) { - alignmentDivider.width += missingSpace; - row.width += missingSpace; + return super.getElemCenterline_(row, elem); + } + + /** + * @override + */ + addInput_(input, activeRow) { + // If we have two dummy inputs on the same row, one aligned left and the + // other right, keep track of the right aligned dummy input so we can add + // padding later. + if (input.type === inputTypes.DUMMY && activeRow.hasDummyInput && + activeRow.align === Align.LEFT && input.align === Align.RIGHT) { + activeRow.rightAlignedDummyInput = input; + } else if (input.type === inputTypes.STATEMENT) { + // Handle statements without next connections correctly. + activeRow.elements.push(new StatementInput(this.constants_, input)); + activeRow.hasStatement = true; + + if (activeRow.align === null) { + activeRow.align = input.align; + } return; } + super.addInput_(input, activeRow); } - RenderInfo.superClass_.addAlignmentPadding_.call(this, row, missingSpace); -}; -/** - * Adjust the x position of fields to bump all non-label fields in the first row - * past the notch position. This must be called before ``computeBounds`` is - * called. - * @protected - */ -RenderInfo.prototype.adjustXPosition_ = function() { - const notchTotalWidth = - this.constants_.NOTCH_OFFSET_LEFT + this.constants_.NOTCH_WIDTH; - let minXPos = notchTotalWidth; - // Run through every input row on the block and only apply bump logic to the - // first input row (if the block has prev connection) and every input row that - // has a prev and next notch. - for (let i = 2; i < this.rows.length - 1; i += 2) { - const prevSpacer = this.rows[i - 1]; - const row = this.rows[i]; - const nextSpacer = this.rows[i + 1]; - - const hasPrevNotch = i === 2 ? !!this.topRow.hasPreviousConnection : - !!prevSpacer.followsStatement; - const hasNextNotch = i + 2 >= this.rows.length - 1 ? - !!this.bottomRow.hasNextConnection : - !!nextSpacer.precedesStatement; - - if (Types.isInputRow(row) && row.hasStatement) { - row.measure(); - minXPos = row.width - row.getLastInput().width + notchTotalWidth; - } else if ( - hasPrevNotch && (i === 2 || hasNextNotch) && Types.isInputRow(row) && - !row.hasStatement) { - let xCursor = row.xPos; - let prevInRowSpacer = null; - for (let j = 0; j < row.elements.length; j++) { - const elem = row.elements[j]; + /** + * @override + */ + addAlignmentPadding_(row, missingSpace) { + if (row.rightAlignedDummyInput) { + let alignmentDivider; + for (let i = 0; i < row.elements.length; i++) { + const elem = row.elements[i]; if (Types.isSpacer(elem)) { - prevInRowSpacer = elem; + alignmentDivider = elem; } - if (prevInRowSpacer && (Types.isField(elem) || Types.isInput(elem))) { - if (xCursor < minXPos && - !(Types.isField(elem) && - (elem.field instanceof FieldLabel || - elem.field instanceof FieldImage))) { - const difference = minXPos - xCursor; - prevInRowSpacer.width += difference; - } + if (Types.isField(elem) && + elem.parentInput === row.rightAlignedDummyInput) { + break; } - xCursor += elem.width; + } + if (alignmentDivider) { + alignmentDivider.width += missingSpace; + row.width += missingSpace; + return; } } + super.addAlignmentPadding_(row, missingSpace); } -}; -/** - * Finalize the output connection info. In particular, set the height of the - * output connection to match that of the block. For the right side, add a - * right connection shape element and have it match the dimensions of the - * output connection. - * @protected - */ -RenderInfo.prototype.finalizeOutputConnection_ = function() { - // Dynamic output connections depend on the height of the block. - if (!this.outputConnection || !this.outputConnection.isDynamicShape) { - return; - } - let yCursor = 0; - // Determine the block height. - for (let i = 0; i < this.rows.length; i++) { - const row = this.rows[i]; - row.yPos = yCursor; - yCursor += row.height; - } - this.height = yCursor; - - // Adjust the height of the output connection. - const blockHeight = this.bottomRow.hasNextConnection ? - this.height - this.bottomRow.descenderHeight : - this.height; - const connectionHeight = this.outputConnection.shape.height(blockHeight); - const connectionWidth = this.outputConnection.shape.width(blockHeight); - - this.outputConnection.height = connectionHeight; - this.outputConnection.width = connectionWidth; - this.outputConnection.startX = connectionWidth; - this.outputConnection.connectionOffsetY = - this.outputConnection.shape.connectionOffsetY(connectionHeight); - this.outputConnection.connectionOffsetX = - this.outputConnection.shape.connectionOffsetX(connectionWidth); - - // Add the right connection measurable. - // Don't add it if we have a value-to-statement or a value-to-stack block. - let rightConnectionWidth = 0; - if (!this.hasStatementInput && !this.bottomRow.hasNextConnection) { - rightConnectionWidth = connectionWidth; - this.rightSide.height = connectionHeight; - this.rightSide.width = rightConnectionWidth; - this.rightSide.centerline = connectionHeight / 2; - this.rightSide.xPos = this.width + rightConnectionWidth; - } - this.startX = connectionWidth; - this.width += connectionWidth + rightConnectionWidth; - this.widthWithChildren += connectionWidth + rightConnectionWidth; -}; - -/** - * Finalize horizontal alignment of elements on the block. In particular, - * reduce the implicit spacing created by the left and right output connection - * shapes by adding setting negative spacing onto the leftmost and rightmost - * spacers. - * @protected - */ -RenderInfo.prototype.finalizeHorizontalAlignment_ = function() { - if (!this.outputConnection || this.hasStatementInput || - this.bottomRow.hasNextConnection) { - return; - } - let totalNegativeSpacing = 0; - for (let i = 0; i < this.rows.length; i++) { - const row = this.rows[i]; - if (!Types.isInputRow(row)) { - continue; - } - const firstElem = row.elements[1]; - const lastElem = row.elements[row.elements.length - 2]; - let leftNegPadding = this.getNegativeSpacing_(firstElem); - let rightNegPadding = this.getNegativeSpacing_(lastElem); - totalNegativeSpacing = leftNegPadding + rightNegPadding; - const minBlockWidth = - this.constants_.MIN_BLOCK_WIDTH + this.outputConnection.width * 2; - if (this.width - totalNegativeSpacing < minBlockWidth) { - // Maintain a minimum block width, split negative spacing between left - // and right edge. - totalNegativeSpacing = this.width - minBlockWidth; - leftNegPadding = totalNegativeSpacing / 2; - rightNegPadding = totalNegativeSpacing / 2; - } - // Add a negative spacer on the start and end of the block. - row.elements.unshift(new InRowSpacer(this.constants_, -leftNegPadding)); - row.elements.push(new InRowSpacer(this.constants_, -rightNegPadding)); - } - if (totalNegativeSpacing) { - this.width -= totalNegativeSpacing; - this.widthWithChildren -= totalNegativeSpacing; - this.rightSide.xPos -= totalNegativeSpacing; - for (let i = 0; i < this.rows.length; i++) { + /** + * Adjust the x position of fields to bump all non-label fields in the first + * row past the notch position. This must be called before ``computeBounds`` + * is called. + * @protected + */ + adjustXPosition_() { + const notchTotalWidth = + this.constants_.NOTCH_OFFSET_LEFT + this.constants_.NOTCH_WIDTH; + let minXPos = notchTotalWidth; + // Run through every input row on the block and only apply bump logic to the + // first input row (if the block has prev connection) and every input row + // that has a prev and next notch. + for (let i = 2; i < this.rows.length - 1; i += 2) { + const prevSpacer = this.rows[i - 1]; const row = this.rows[i]; - if (Types.isTopOrBottomRow(row)) { - row.elements[1].width -= totalNegativeSpacing; - row.elements[1].widthWithConnectedBlocks -= totalNegativeSpacing; - } - row.width -= totalNegativeSpacing; - row.widthWithConnectedBlocks -= totalNegativeSpacing; - } - } -}; + const nextSpacer = this.rows[i + 1]; -/** - * Calculate the spacing to reduce the left and right edges by based on the - * outer and inner connection shape. - * @param {Measurable} elem The first or last element on - * a block. - * @return {number} The amount of spacing to reduce the first or last spacer. - * @protected - */ -RenderInfo.prototype.getNegativeSpacing_ = function(elem) { - if (!elem) { - return 0; - } - const connectionWidth = this.outputConnection.width; - const outerShape = this.outputConnection.shape.type; - const constants = - /** @type {!ConstantProvider} */ (this.constants_); - if (this.isMultiRow && this.inputRows.length > 1) { - switch (outerShape) { - case constants.SHAPES.ROUND: { - // Special case for multi-row round reporter blocks. - const maxWidth = this.constants_.MAX_DYNAMIC_CONNECTION_SHAPE_WIDTH; - const width = this.height / 2 > maxWidth ? maxWidth : this.height / 2; - const topPadding = this.constants_.SMALL_PADDING; - const roundPadding = - width * (1 - Math.sin(Math.acos((width - topPadding) / width))); - return connectionWidth - roundPadding; - } - default: - return 0; - } - } - if (Types.isInlineInput(elem)) { - const connectedBlock = elem.connectedBlock; - const innerShape = connectedBlock ? - connectedBlock.pathObject.outputShapeType : - elem.shape.type; - // Special case for value to stack / value to statement blocks. - if (connectedBlock && connectedBlock.outputConnection && - (connectedBlock.statementInputCount || connectedBlock.nextConnection)) { - return 0; - } - // Special case for hexagonal output. - if (outerShape === constants.SHAPES.HEXAGONAL && - outerShape !== innerShape) { - return 0; - } - return connectionWidth - - this.constants_.SHAPE_IN_SHAPE_PADDING[outerShape][innerShape]; - } else if (Types.isField(elem)) { - // Special case for text inputs. - if (outerShape === constants.SHAPES.ROUND && - elem.field instanceof FieldTextInput) { - return connectionWidth - (2.75 * constants.GRID_UNIT); - } - return connectionWidth - - this.constants_.SHAPE_IN_SHAPE_PADDING[outerShape][0]; - } else if (Types.isIcon(elem)) { - return this.constants_.SMALL_PADDING; - } - return 0; -}; + const hasPrevNotch = i === 2 ? !!this.topRow.hasPreviousConnection : + !!prevSpacer.followsStatement; + const hasNextNotch = i + 2 >= this.rows.length - 1 ? + !!this.bottomRow.hasNextConnection : + !!nextSpacer.precedesStatement; -/** - * Finalize vertical alignment of rows on a block. In particular, reduce the - * implicit spacing when a non-shadow block is connected to any of an input - * row's inline inputs. - * @protected - */ -RenderInfo.prototype.finalizeVerticalAlignment_ = function() { - if (this.outputConnection) { - return; - } - // Run through every input row on the block and only apply tight nesting logic - // to input rows that have a prev and next notch. - for (let i = 2; i < this.rows.length - 1; i += 2) { - const prevSpacer = this.rows[i - 1]; - const row = this.rows[i]; - const nextSpacer = this.rows[i + 1]; - - const firstRow = i === 2; - const hasPrevNotch = firstRow ? !!this.topRow.hasPreviousConnection : - !!prevSpacer.followsStatement; - const hasNextNotch = i + 2 >= this.rows.length - 1 ? - !!this.bottomRow.hasNextConnection : - !!nextSpacer.precedesStatement; - - if (hasPrevNotch) { - const hasSingleTextOrImageField = row.elements.length === 3 && - (row.elements[1].field instanceof FieldLabel || - row.elements[1].field instanceof FieldImage); - if (!firstRow && hasSingleTextOrImageField) { - // Remove some padding if we have a single image or text field. - prevSpacer.height -= this.constants_.SMALL_PADDING; - nextSpacer.height -= this.constants_.SMALL_PADDING; - row.height -= this.constants_.MEDIUM_PADDING; - } else if (!firstRow && !hasNextNotch) { - // Add a small padding so the notch doesn't clash with inputs/fields. - prevSpacer.height += this.constants_.SMALL_PADDING; - } else if (hasNextNotch) { - // Determine if the input row has non-shadow connected blocks. - let hasNonShadowConnectedBlocks = false; - const minVerticalTightNestingHeight = 40; + if (Types.isInputRow(row) && row.hasStatement) { + row.measure(); + minXPos = row.width - row.getLastInput().width + notchTotalWidth; + } else if ( + hasPrevNotch && (i === 2 || hasNextNotch) && Types.isInputRow(row) && + !row.hasStatement) { + let xCursor = row.xPos; + let prevInRowSpacer = null; for (let j = 0; j < row.elements.length; j++) { const elem = row.elements[j]; - if (Types.isInlineInput(elem) && elem.connectedBlock && - !elem.connectedBlock.isShadow() && - elem.connectedBlock.getHeightWidth().height >= - minVerticalTightNestingHeight) { - hasNonShadowConnectedBlocks = true; - break; + if (Types.isSpacer(elem)) { + prevInRowSpacer = elem; } - } - // Apply tight-nesting if we have both a prev and next notch and the - // block has non-shadow connected blocks. - if (hasNonShadowConnectedBlocks) { - prevSpacer.height -= this.constants_.SMALL_PADDING; - nextSpacer.height -= this.constants_.SMALL_PADDING; + if (prevInRowSpacer && (Types.isField(elem) || Types.isInput(elem))) { + if (xCursor < minXPos && + !(Types.isField(elem) && + (elem.field instanceof FieldLabel || + elem.field instanceof FieldImage))) { + const difference = minXPos - xCursor; + prevInRowSpacer.width += difference; + } + } + xCursor += elem.width; } } } } -}; -/** - * @override - */ -RenderInfo.prototype.finalize_ = function() { - this.finalizeOutputConnection_(); - this.finalizeHorizontalAlignment_(); - this.finalizeVerticalAlignment_(); - RenderInfo.superClass_.finalize_.call(this); + /** + * Finalize the output connection info. In particular, set the height of the + * output connection to match that of the block. For the right side, add a + * right connection shape element and have it match the dimensions of the + * output connection. + * @protected + */ + finalizeOutputConnection_() { + // Dynamic output connections depend on the height of the block. + if (!this.outputConnection || !this.outputConnection.isDynamicShape) { + return; + } + let yCursor = 0; + // Determine the block height. + for (let i = 0; i < this.rows.length; i++) { + const row = this.rows[i]; + row.yPos = yCursor; + yCursor += row.height; + } + this.height = yCursor; - if (this.rightSide) { - this.widthWithChildren += this.rightSide.width; + // Adjust the height of the output connection. + const blockHeight = this.bottomRow.hasNextConnection ? + this.height - this.bottomRow.descenderHeight : + this.height; + const connectionHeight = this.outputConnection.shape.height(blockHeight); + const connectionWidth = this.outputConnection.shape.width(blockHeight); + + this.outputConnection.height = connectionHeight; + this.outputConnection.width = connectionWidth; + this.outputConnection.startX = connectionWidth; + this.outputConnection.connectionOffsetY = + this.outputConnection.shape.connectionOffsetY(connectionHeight); + this.outputConnection.connectionOffsetX = + this.outputConnection.shape.connectionOffsetX(connectionWidth); + + // Add the right connection measurable. + // Don't add it if we have a value-to-statement or a value-to-stack block. + let rightConnectionWidth = 0; + if (!this.hasStatementInput && !this.bottomRow.hasNextConnection) { + rightConnectionWidth = connectionWidth; + this.rightSide.height = connectionHeight; + this.rightSide.width = rightConnectionWidth; + this.rightSide.centerline = connectionHeight / 2; + this.rightSide.xPos = this.width + rightConnectionWidth; + } + this.startX = connectionWidth; + this.width += connectionWidth + rightConnectionWidth; + this.widthWithChildren += connectionWidth + rightConnectionWidth; } -}; + + /** + * Finalize horizontal alignment of elements on the block. In particular, + * reduce the implicit spacing created by the left and right output connection + * shapes by adding setting negative spacing onto the leftmost and rightmost + * spacers. + * @protected + */ + finalizeHorizontalAlignment_() { + if (!this.outputConnection || this.hasStatementInput || + this.bottomRow.hasNextConnection) { + return; + } + let totalNegativeSpacing = 0; + for (let i = 0; i < this.rows.length; i++) { + const row = this.rows[i]; + if (!Types.isInputRow(row)) { + continue; + } + const firstElem = row.elements[1]; + const lastElem = row.elements[row.elements.length - 2]; + let leftNegPadding = this.getNegativeSpacing_(firstElem); + let rightNegPadding = this.getNegativeSpacing_(lastElem); + totalNegativeSpacing = leftNegPadding + rightNegPadding; + const minBlockWidth = + this.constants_.MIN_BLOCK_WIDTH + this.outputConnection.width * 2; + if (this.width - totalNegativeSpacing < minBlockWidth) { + // Maintain a minimum block width, split negative spacing between left + // and right edge. + totalNegativeSpacing = this.width - minBlockWidth; + leftNegPadding = totalNegativeSpacing / 2; + rightNegPadding = totalNegativeSpacing / 2; + } + // Add a negative spacer on the start and end of the block. + row.elements.unshift(new InRowSpacer(this.constants_, -leftNegPadding)); + row.elements.push(new InRowSpacer(this.constants_, -rightNegPadding)); + } + if (totalNegativeSpacing) { + this.width -= totalNegativeSpacing; + this.widthWithChildren -= totalNegativeSpacing; + this.rightSide.xPos -= totalNegativeSpacing; + for (let i = 0; i < this.rows.length; i++) { + const row = this.rows[i]; + if (Types.isTopOrBottomRow(row)) { + row.elements[1].width -= totalNegativeSpacing; + row.elements[1].widthWithConnectedBlocks -= totalNegativeSpacing; + } + row.width -= totalNegativeSpacing; + row.widthWithConnectedBlocks -= totalNegativeSpacing; + } + } + } + + /** + * Calculate the spacing to reduce the left and right edges by based on the + * outer and inner connection shape. + * @param {Measurable} elem The first or last element on + * a block. + * @return {number} The amount of spacing to reduce the first or last spacer. + * @protected + */ + getNegativeSpacing_(elem) { + if (!elem) { + return 0; + } + const connectionWidth = this.outputConnection.width; + const outerShape = this.outputConnection.shape.type; + const constants = + /** @type {!ConstantProvider} */ (this.constants_); + if (this.isMultiRow && this.inputRows.length > 1) { + switch (outerShape) { + case constants.SHAPES.ROUND: { + // Special case for multi-row round reporter blocks. + const maxWidth = this.constants_.MAX_DYNAMIC_CONNECTION_SHAPE_WIDTH; + const width = this.height / 2 > maxWidth ? maxWidth : this.height / 2; + const topPadding = this.constants_.SMALL_PADDING; + const roundPadding = + width * (1 - Math.sin(Math.acos((width - topPadding) / width))); + return connectionWidth - roundPadding; + } + default: + return 0; + } + } + if (Types.isInlineInput(elem)) { + const connectedBlock = elem.connectedBlock; + const innerShape = connectedBlock ? + connectedBlock.pathObject.outputShapeType : + elem.shape.type; + // Special case for value to stack / value to statement blocks. + if (connectedBlock && connectedBlock.outputConnection && + (connectedBlock.statementInputCount || + connectedBlock.nextConnection)) { + return 0; + } + // Special case for hexagonal output. + if (outerShape === constants.SHAPES.HEXAGONAL && + outerShape !== innerShape) { + return 0; + } + return connectionWidth - + this.constants_.SHAPE_IN_SHAPE_PADDING[outerShape][innerShape]; + } else if (Types.isField(elem)) { + // Special case for text inputs. + if (outerShape === constants.SHAPES.ROUND && + elem.field instanceof FieldTextInput) { + return connectionWidth - (2.75 * constants.GRID_UNIT); + } + return connectionWidth - + this.constants_.SHAPE_IN_SHAPE_PADDING[outerShape][0]; + } else if (Types.isIcon(elem)) { + return this.constants_.SMALL_PADDING; + } + return 0; + } + + /** + * Finalize vertical alignment of rows on a block. In particular, reduce the + * implicit spacing when a non-shadow block is connected to any of an input + * row's inline inputs. + * @protected + */ + finalizeVerticalAlignment_() { + if (this.outputConnection) { + return; + } + // Run through every input row on the block and only apply tight nesting + // logic to input rows that have a prev and next notch. + for (let i = 2; i < this.rows.length - 1; i += 2) { + const prevSpacer = this.rows[i - 1]; + const row = this.rows[i]; + const nextSpacer = this.rows[i + 1]; + + const firstRow = i === 2; + const hasPrevNotch = firstRow ? !!this.topRow.hasPreviousConnection : + !!prevSpacer.followsStatement; + const hasNextNotch = i + 2 >= this.rows.length - 1 ? + !!this.bottomRow.hasNextConnection : + !!nextSpacer.precedesStatement; + + if (hasPrevNotch) { + const hasSingleTextOrImageField = row.elements.length === 3 && + (row.elements[1].field instanceof FieldLabel || + row.elements[1].field instanceof FieldImage); + if (!firstRow && hasSingleTextOrImageField) { + // Remove some padding if we have a single image or text field. + prevSpacer.height -= this.constants_.SMALL_PADDING; + nextSpacer.height -= this.constants_.SMALL_PADDING; + row.height -= this.constants_.MEDIUM_PADDING; + } else if (!firstRow && !hasNextNotch) { + // Add a small padding so the notch doesn't clash with inputs/fields. + prevSpacer.height += this.constants_.SMALL_PADDING; + } else if (hasNextNotch) { + // Determine if the input row has non-shadow connected blocks. + let hasNonShadowConnectedBlocks = false; + const minVerticalTightNestingHeight = 40; + for (let j = 0; j < row.elements.length; j++) { + const elem = row.elements[j]; + if (Types.isInlineInput(elem) && elem.connectedBlock && + !elem.connectedBlock.isShadow() && + elem.connectedBlock.getHeightWidth().height >= + minVerticalTightNestingHeight) { + hasNonShadowConnectedBlocks = true; + break; + } + } + // Apply tight-nesting if we have both a prev and next notch and the + // block has non-shadow connected blocks. + if (hasNonShadowConnectedBlocks) { + prevSpacer.height -= this.constants_.SMALL_PADDING; + nextSpacer.height -= this.constants_.SMALL_PADDING; + } + } + } + } + } + + /** + * @override + */ + finalize_() { + this.finalizeOutputConnection_(); + this.finalizeHorizontalAlignment_(); + this.finalizeVerticalAlignment_(); + super.finalize_(); + + if (this.rightSide) { + this.widthWithChildren += this.rightSide.width; + } + } +} exports.RenderInfo = RenderInfo; diff --git a/core/renderers/zelos/marker_svg.js b/core/renderers/zelos/marker_svg.js index 0fc1a7132..30019063c 100644 --- a/core/renderers/zelos/marker_svg.js +++ b/core/renderers/zelos/marker_svg.js @@ -16,7 +16,6 @@ goog.module('Blockly.zelos.MarkerSvg'); const dom = goog.require('Blockly.utils.dom'); -const object = goog.require('Blockly.utils.object'); /* eslint-disable-next-line no-unused-vars */ const {ASTNode} = goog.requireType('Blockly.ASTNode'); /* eslint-disable-next-line no-unused-vars */ @@ -35,131 +34,140 @@ const {WorkspaceSvg} = goog.requireType('Blockly.WorkspaceSvg'); /** * Class to draw a marker. - * @param {!WorkspaceSvg} workspace The workspace the marker belongs to. - * @param {!ConstantProvider} constants The constants for - * the renderer. - * @param {!Marker} marker The marker to draw. - * @constructor * @extends {BaseMarkerSvg} - * @alias Blockly.zelos.MarkerSvg */ -const MarkerSvg = function(workspace, constants, marker) { - MarkerSvg.superClass_.constructor.call(this, workspace, constants, marker); -}; -object.inherits(MarkerSvg, BaseMarkerSvg); +class MarkerSvg extends BaseMarkerSvg { + /** + * @param {!WorkspaceSvg} workspace The workspace the marker belongs to. + * @param {!ConstantProvider} constants The constants for + * the renderer. + * @param {!Marker} marker The marker to draw. + * @alias Blockly.zelos.MarkerSvg + */ + constructor(workspace, constants, marker) { + super(workspace, constants, marker); -/** - * Position and display the marker for an input or an output connection. - * @param {!ASTNode} curNode The node to draw the marker for. - * @private - */ -MarkerSvg.prototype.showWithInputOutput_ = function(curNode) { - const block = /** @type {!BlockSvg} */ (curNode.getSourceBlock()); - const connection = /** @type {!Connection} */ (curNode.getLocation()); - const offsetInBlock = connection.getOffsetInBlock(); - - this.positionCircle_(offsetInBlock.x, offsetInBlock.y); - this.setParent_(block); - this.showCurrent_(); -}; - -/** - * @override - */ -MarkerSvg.prototype.showWithOutput_ = function(curNode) { - this.showWithInputOutput_(curNode); -}; - -/** - * @override - */ -MarkerSvg.prototype.showWithInput_ = function(curNode) { - this.showWithInputOutput_(curNode); -}; - -/** - * Draw a rectangle around the block. - * @param {!ASTNode} curNode The current node of the marker. - */ -MarkerSvg.prototype.showWithBlock_ = function(curNode) { - const block = /** @type {!BlockSvg} */ (curNode.getLocation()); - - // Gets the height and width of entire stack. - const heightWidth = block.getHeightWidth(); - - // Add padding so that being on a stack looks different than being on a block. - this.positionRect_(0, 0, heightWidth.width, heightWidth.height); - this.setParent_(block); - this.showCurrent_(); -}; - -/** - * Position the circle we use for input and output connections. - * @param {number} x The x position of the circle. - * @param {number} y The y position of the circle. - * @private - */ -MarkerSvg.prototype.positionCircle_ = function(x, y) { - this.markerCircle_.setAttribute('cx', x); - this.markerCircle_.setAttribute('cy', y); - this.currentMarkerSvg = this.markerCircle_; -}; - -/** - * @override - */ -MarkerSvg.prototype.hide = function() { - MarkerSvg.superClass_.hide.call(this); - this.markerCircle_.style.display = 'none'; -}; - -/** - * @override - */ -MarkerSvg.prototype.createDomInternal_ = function() { - /* clang-format off */ - /* This markup will be generated and added to the .svgGroup_: - - - - - - */ - /* clang-format on */ - - MarkerSvg.superClass_.createDomInternal_.call(this); - - this.markerCircle_ = dom.createSvgElement( - Svg.CIRCLE, { - 'r': this.constants_.CURSOR_RADIUS, - 'style': 'display: none', - 'stroke-width': this.constants_.CURSOR_STROKE_WIDTH, - }, - this.markerSvg_); - - // Markers and stack cursors don't blink. - if (this.isCursor()) { - const blinkProperties = this.getBlinkProperties_(); - dom.createSvgElement(Svg.ANIMATE, blinkProperties, this.markerCircle_); + /** + * @type {SVGCircleElement} + * @private + */ + this.markerCircle_ = null; } - return this.markerSvg_; -}; + /** + * Position and display the marker for an input or an output connection. + * @param {!ASTNode} curNode The node to draw the marker for. + * @private + */ + showWithInputOutput_(curNode) { + const block = /** @type {!BlockSvg} */ (curNode.getSourceBlock()); + const connection = /** @type {!Connection} */ (curNode.getLocation()); + const offsetInBlock = connection.getOffsetInBlock(); -/** - * @override - */ -MarkerSvg.prototype.applyColour_ = function(curNode) { - MarkerSvg.superClass_.applyColour_.call(this, curNode); - - this.markerCircle_.setAttribute('fill', this.colour_); - this.markerCircle_.setAttribute('stroke', this.colour_); - - if (this.isCursor()) { - const values = this.colour_ + ';transparent;transparent;'; - this.markerCircle_.firstChild.setAttribute('values', values); + this.positionCircle_(offsetInBlock.x, offsetInBlock.y); + this.setParent_(block); + this.showCurrent_(); } -}; + + /** + * @override + */ + showWithOutput_(curNode) { + this.showWithInputOutput_(curNode); + } + + /** + * @override + */ + showWithInput_(curNode) { + this.showWithInputOutput_(curNode); + } + + /** + * Draw a rectangle around the block. + * @param {!ASTNode} curNode The current node of the marker. + */ + showWithBlock_(curNode) { + const block = /** @type {!BlockSvg} */ (curNode.getLocation()); + + // Gets the height and width of entire stack. + const heightWidth = block.getHeightWidth(); + + // Add padding so that being on a stack looks different than being on a + // block. + this.positionRect_(0, 0, heightWidth.width, heightWidth.height); + this.setParent_(block); + this.showCurrent_(); + } + + /** + * Position the circle we use for input and output connections. + * @param {number} x The x position of the circle. + * @param {number} y The y position of the circle. + * @private + */ + positionCircle_(x, y) { + this.markerCircle_.setAttribute('cx', x); + this.markerCircle_.setAttribute('cy', y); + this.currentMarkerSvg = this.markerCircle_; + } + + /** + * @override + */ + hide() { + super.hide(); + this.markerCircle_.style.display = 'none'; + } + + /** + * @override + */ + createDomInternal_() { + /* clang-format off */ + /* This markup will be generated and added to the .svgGroup_: + + + + + + */ + /* clang-format on */ + + super.createDomInternal_(); + + this.markerCircle_ = dom.createSvgElement( + Svg.CIRCLE, { + 'r': this.constants_.CURSOR_RADIUS, + 'style': 'display: none', + 'stroke-width': this.constants_.CURSOR_STROKE_WIDTH, + }, + this.markerSvg_); + + // Markers and stack cursors don't blink. + if (this.isCursor()) { + const blinkProperties = this.getBlinkProperties_(); + dom.createSvgElement(Svg.ANIMATE, blinkProperties, this.markerCircle_); + } + + return this.markerSvg_; + } + + /** + * @override + */ + applyColour_(curNode) { + super.applyColour_(curNode); + + this.markerCircle_.setAttribute('fill', this.colour_); + this.markerCircle_.setAttribute('stroke', this.colour_); + + if (this.isCursor()) { + const values = this.colour_ + ';transparent;transparent;'; + this.markerCircle_.firstChild.setAttribute('values', values); + } + } +} exports.MarkerSvg = MarkerSvg; diff --git a/core/renderers/zelos/measurables/bottom_row.js b/core/renderers/zelos/measurables/bottom_row.js index 2a6045f64..4d3180938 100644 --- a/core/renderers/zelos/measurables/bottom_row.js +++ b/core/renderers/zelos/measurables/bottom_row.js @@ -15,7 +15,6 @@ */ goog.module('Blockly.zelos.BottomRow'); -const object = goog.require('Blockly.utils.object'); const {BottomRow: BaseBottomRow} = goog.require('Blockly.blockRendering.BottomRow'); /* eslint-disable-next-line no-unused-vars */ const {ConstantProvider} = goog.requireType('Blockly.blockRendering.ConstantProvider'); @@ -26,40 +25,42 @@ const {ConstantProvider} = goog.requireType('Blockly.blockRendering.ConstantProv * a block as well as spacing information for the top row. * Elements in a bottom row can consist of corners, spacers and next * connections. - * @param {!ConstantProvider} constants The rendering - * constants provider. - * @package - * @constructor * @extends {BaseBottomRow} - * @alias Blockly.zelos.BottomRow */ -const BottomRow = function(constants) { - BottomRow.superClass_.constructor.call(this, constants); -}; -object.inherits(BottomRow, BaseBottomRow); +class BottomRow extends BaseBottomRow { + /** + * @param {!ConstantProvider} constants The rendering + * constants provider. + * @package + * @alias Blockly.zelos.BottomRow + */ + constructor(constants) { + super(constants); + } -/** - * @override - */ -BottomRow.prototype.endsWithElemSpacer = function() { - return false; -}; + /** + * @override + */ + endsWithElemSpacer() { + return false; + } -/** - * Render a round corner unless the block has an output connection. - * @override - */ -BottomRow.prototype.hasLeftSquareCorner = function(block) { - return !!block.outputConnection; -}; + /** + * Render a round corner unless the block has an output connection. + * @override + */ + hasLeftSquareCorner(block) { + return !!block.outputConnection; + } -/** - * Render a round corner unless the block has an output connection. - * @override - */ -BottomRow.prototype.hasRightSquareCorner = function(block) { - return !!block.outputConnection && !block.statementInputCount && - !block.nextConnection; -}; + /** + * Render a round corner unless the block has an output connection. + * @override + */ + hasRightSquareCorner(block) { + return !!block.outputConnection && !block.statementInputCount && + !block.nextConnection; + } +} exports.BottomRow = BottomRow; diff --git a/core/renderers/zelos/measurables/inputs.js b/core/renderers/zelos/measurables/inputs.js index ada8cdea3..11c517a77 100644 --- a/core/renderers/zelos/measurables/inputs.js +++ b/core/renderers/zelos/measurables/inputs.js @@ -16,7 +16,6 @@ */ goog.module('Blockly.zelos.StatementInput'); -const object = goog.require('Blockly.utils.object'); /* eslint-disable-next-line no-unused-vars */ const {ConstantProvider} = goog.requireType('Blockly.blockRendering.ConstantProvider'); /* eslint-disable-next-line no-unused-vars */ @@ -26,31 +25,33 @@ const {StatementInput: BaseStatementInput} = goog.require('Blockly.blockRenderin /** * An object containing information about the space a statement input takes up - * during rendering - * @param {!ConstantProvider} constants The rendering constants provider. - * @param {!Input} input The statement input to measure and store information - * for. - * @package - * @constructor + * during rendering. * @extends {BaseStatementInput} - * @alias Blockly.zelos.StatementInput */ -const StatementInput = function(constants, input) { - StatementInput.superClass_.constructor.call(this, constants, input); +class StatementInput extends BaseStatementInput { + /** + * @param {!ConstantProvider} constants The rendering constants provider. + * @param {!Input} input The statement input to measure and store information + * for. + * @package + * @alias Blockly.zelos.StatementInput + */ + constructor(constants, input) { + super(constants, input); - if (this.connectedBlock) { - // Find the bottom-most connected block in the stack. - let block = this.connectedBlock; - let nextBlock; - while ((nextBlock = block.getNextBlock())) { - block = nextBlock; - } - if (!block.nextConnection) { - this.height = this.connectedBlockHeight; - this.connectedBottomNextConnection = true; + if (this.connectedBlock) { + // Find the bottom-most connected block in the stack. + let block = this.connectedBlock; + let nextBlock; + while ((nextBlock = block.getNextBlock())) { + block = nextBlock; + } + if (!block.nextConnection) { + this.height = this.connectedBlockHeight; + this.connectedBottomNextConnection = true; + } } } -}; -object.inherits(StatementInput, BaseStatementInput); +} exports.StatementInput = StatementInput; diff --git a/core/renderers/zelos/measurables/row_elements.js b/core/renderers/zelos/measurables/row_elements.js index d0634f3dd..5a7d73b87 100644 --- a/core/renderers/zelos/measurables/row_elements.js +++ b/core/renderers/zelos/measurables/row_elements.js @@ -16,7 +16,6 @@ */ goog.module('Blockly.zelos.RightConnectionShape'); -const object = goog.require('Blockly.utils.object'); /* eslint-disable-next-line no-unused-vars */ const {ConstantProvider} = goog.requireType('Blockly.blockRendering.ConstantProvider'); const {Measurable} = goog.require('Blockly.blockRendering.Measurable'); @@ -26,20 +25,22 @@ const {Types} = goog.require('Blockly.blockRendering.Types'); /** * An object containing information about the space a right connection shape * takes up during rendering. - * @param {!ConstantProvider} constants The rendering - * constants provider. - * @package - * @constructor * @extends {Measurable} - * @alias Blockly.zelos.RightConnectionShape */ -const RightConnectionShape = function(constants) { - RightConnectionShape.superClass_.constructor.call(this, constants); - this.type |= Types.getType('RIGHT_CONNECTION'); - // Size is dynamic - this.height = 0; - this.width = 0; -}; -object.inherits(RightConnectionShape, Measurable); +class RightConnectionShape extends Measurable { + /** + * @param {!ConstantProvider} constants The rendering + * constants provider. + * @package + * @alias Blockly.zelos.RightConnectionShape + */ + constructor(constants) { + super(constants); + this.type |= Types.getType('RIGHT_CONNECTION'); + // Size is dynamic + this.height = 0; + this.width = 0; + } +} exports.RightConnectionShape = RightConnectionShape; diff --git a/core/renderers/zelos/measurables/top_row.js b/core/renderers/zelos/measurables/top_row.js index 50df37d96..049ae0f91 100644 --- a/core/renderers/zelos/measurables/top_row.js +++ b/core/renderers/zelos/measurables/top_row.js @@ -15,7 +15,6 @@ */ goog.module('Blockly.zelos.TopRow'); -const object = goog.require('Blockly.utils.object'); /* eslint-disable-next-line no-unused-vars */ const {ConstantProvider} = goog.requireType('Blockly.blockRendering.ConstantProvider'); const {TopRow: BaseTopRow} = goog.require('Blockly.blockRendering.TopRow'); @@ -28,43 +27,45 @@ const {TopRow: BaseTopRow} = goog.require('Blockly.blockRendering.TopRow'); * connections. * After this constructor is called, the row will contain all non-spacer * elements it needs. - * @param {!ConstantProvider} constants The rendering - * constants provider. - * @package - * @constructor * @extends {BaseTopRow} - * @alias Blockly.zelos.TopRow */ -const TopRow = function(constants) { - TopRow.superClass_.constructor.call(this, constants); -}; -object.inherits(TopRow, BaseTopRow); +class TopRow extends BaseTopRow { + /** + * @param {!ConstantProvider} constants The rendering + * constants provider. + * @package + * @alias Blockly.zelos.TopRow + */ + constructor(constants) { + super(constants); + } -/** - * @override - */ -TopRow.prototype.endsWithElemSpacer = function() { - return false; -}; + /** + * @override + */ + endsWithElemSpacer() { + return false; + } -/** - * Render a round corner unless the block has an output connection. - * @override - */ -TopRow.prototype.hasLeftSquareCorner = function(block) { - const hasHat = - (block.hat ? block.hat === 'cap' : this.constants_.ADD_START_HATS) && - !block.outputConnection && !block.previousConnection; - return !!block.outputConnection || hasHat; -}; + /** + * Render a round corner unless the block has an output connection. + * @override + */ + hasLeftSquareCorner(block) { + const hasHat = + (block.hat ? block.hat === 'cap' : this.constants_.ADD_START_HATS) && + !block.outputConnection && !block.previousConnection; + return !!block.outputConnection || hasHat; + } -/** - * Render a round corner unless the block has an output connection. - * @override - */ -TopRow.prototype.hasRightSquareCorner = function(block) { - return !!block.outputConnection && !block.statementInputCount && - !block.nextConnection; -}; + /** + * Render a round corner unless the block has an output connection. + * @override + */ + hasRightSquareCorner(block) { + return !!block.outputConnection && !block.statementInputCount && + !block.nextConnection; + } +} exports.TopRow = TopRow; diff --git a/core/renderers/zelos/path_object.js b/core/renderers/zelos/path_object.js index a4697c09d..84131e166 100644 --- a/core/renderers/zelos/path_object.js +++ b/core/renderers/zelos/path_object.js @@ -17,7 +17,6 @@ goog.module('Blockly.zelos.PathObject'); const dom = goog.require('Blockly.utils.dom'); -const object = goog.require('Blockly.utils.object'); /* eslint-disable-next-line no-unused-vars */ const {ConstantProvider} = goog.requireType('Blockly.zelos.ConstantProvider'); const {PathObject: BasePathObject} = goog.require('Blockly.blockRendering.PathObject'); @@ -29,218 +28,221 @@ const {Theme} = goog.requireType('Blockly.Theme'); /** * An object that handles creating and setting each of the SVG elements * used by the renderer. - * @param {!SVGElement} root The root SVG element. - * @param {!Theme.BlockStyle} style The style object to use for - * colouring. - * @param {!ConstantProvider} constants The renderer's constants. - * @constructor * @extends {BasePathObject} - * @package - * @alias Blockly.zelos.PathObject */ -const PathObject = function(root, style, constants) { - PathObject.superClass_.constructor.call(this, root, style, constants); - +class PathObject extends BasePathObject { /** - * The renderer's constant provider. - * @type {!ConstantProvider} + * @param {!SVGElement} root The root SVG element. + * @param {!Theme.BlockStyle} style The style object to use for + * colouring. + * @param {!ConstantProvider} constants The renderer's constants. + * @package + * @alias Blockly.zelos.PathObject */ - this.constants = constants; + constructor(root, style, constants) { + super(root, style, constants); + + /** + * The renderer's constant provider. + * @type {!ConstantProvider} + */ + this.constants = constants; + + /** + * The selected path of the block. + * @type {?SVGElement} + * @private + */ + this.svgPathSelected_ = null; + + /** + * The outline paths on the block. + * @type {!Object} + * @private + */ + this.outlines_ = Object.create(null); + + /** + * A set used to determine which outlines were used during a draw pass. The + * set is initialized with a reference to all the outlines in + * `this.outlines_`. Every time we use an outline during the draw pass, the + * reference is removed from this set. + * @type {Object} + * @private + */ + this.remainingOutlines_ = null; + + /** + * The type of block's output connection shape. This is set when a block + * with an output connection is drawn. + * @package + */ + this.outputShapeType = null; + } /** - * The selected path of the block. - * @type {?SVGElement} - * @private + * @override */ - this.svgPathSelected_ = null; + setPath(pathString) { + super.setPath(pathString); + if (this.svgPathSelected_) { + this.svgPathSelected_.setAttribute('d', pathString); + } + } /** - * The outline paths on the block. - * @type {!Object} - * @private + * @override */ - this.outlines_ = Object.create(null); + applyColour(block) { + super.applyColour(block); + // Set shadow stroke colour. + if (block.isShadow() && block.getParent()) { + this.svgPath.setAttribute( + 'stroke', block.getParent().style.colourTertiary); + } + + // Apply colour to outlines. + for (const key in this.outlines_) { + this.outlines_[key].setAttribute('fill', this.style.colourTertiary); + } + } /** - * A set used to determine which outlines were used during a draw pass. The - * set is initialized with a reference to all the outlines in - * `this.outlines_`. Every time we use an outline during the draw pass, the - * reference is removed from this set. - * @type {Object} - * @private + * @override */ - this.remainingOutlines_ = null; + flipRTL() { + super.flipRTL(); + // Mirror each input outline path. + for (const key in this.outlines_) { + this.outlines_[key].setAttribute('transform', 'scale(-1 1)'); + } + } /** - * The type of block's output connection shape. This is set when a block with - * an output connection is drawn. + * @override + */ + updateSelected(enable) { + this.setClass_('blocklySelected', enable); + if (enable) { + if (!this.svgPathSelected_) { + this.svgPathSelected_ = + /** @type {!SVGElement} */ (this.svgPath.cloneNode(true)); + this.svgPathSelected_.setAttribute('fill', 'none'); + this.svgPathSelected_.setAttribute( + 'filter', 'url(#' + this.constants.selectedGlowFilterId + ')'); + this.svgRoot.appendChild(this.svgPathSelected_); + } + } else { + if (this.svgPathSelected_) { + this.svgRoot.removeChild(this.svgPathSelected_); + this.svgPathSelected_ = null; + } + } + } + + /** + * @override + */ + updateReplacementFade(enable) { + this.setClass_('blocklyReplaceable', enable); + if (enable) { + this.svgPath.setAttribute( + 'filter', 'url(#' + this.constants.replacementGlowFilterId + ')'); + } else { + this.svgPath.removeAttribute('filter'); + } + } + + /** + * @override + */ + updateShapeForInputHighlight(conn, enable) { + const name = conn.getParentInput().name; + const outlinePath = this.getOutlinePath_(name); + if (!outlinePath) { + return; + } + if (enable) { + outlinePath.setAttribute( + 'filter', 'url(#' + this.constants.replacementGlowFilterId + ')'); + } else { + outlinePath.removeAttribute('filter'); + } + } + + /** + * Method that's called when the drawer is about to draw the block. * @package */ - this.outputShapeType = null; -}; -object.inherits(PathObject, BasePathObject); - -/** - * @override - */ -PathObject.prototype.setPath = function(pathString) { - PathObject.superClass_.setPath.call(this, pathString); - if (this.svgPathSelected_) { - this.svgPathSelected_.setAttribute('d', pathString); - } -}; - -/** - * @override - */ -PathObject.prototype.applyColour = function(block) { - PathObject.superClass_.applyColour.call(this, block); - // Set shadow stroke colour. - if (block.isShadow() && block.getParent()) { - this.svgPath.setAttribute('stroke', block.getParent().style.colourTertiary); - } - - // Apply colour to outlines. - for (const key in this.outlines_) { - this.outlines_[key].setAttribute('fill', this.style.colourTertiary); - } -}; - -/** - * @override - */ -PathObject.prototype.flipRTL = function() { - PathObject.superClass_.flipRTL.call(this); - // Mirror each input outline path. - for (const key in this.outlines_) { - this.outlines_[key].setAttribute('transform', 'scale(-1 1)'); - } -}; - -/** - * @override - */ -PathObject.prototype.updateSelected = function(enable) { - this.setClass_('blocklySelected', enable); - if (enable) { - if (!this.svgPathSelected_) { - this.svgPathSelected_ = - /** @type {!SVGElement} */ (this.svgPath.cloneNode(true)); - this.svgPathSelected_.setAttribute('fill', 'none'); - this.svgPathSelected_.setAttribute( - 'filter', 'url(#' + this.constants.selectedGlowFilterId + ')'); - this.svgRoot.appendChild(this.svgPathSelected_); - } - } else { - if (this.svgPathSelected_) { - this.svgRoot.removeChild(this.svgPathSelected_); - this.svgPathSelected_ = null; + beginDrawing() { + this.remainingOutlines_ = Object.create(null); + for (const key in this.outlines_) { + // The value set here isn't used anywhere, we are just using the + // object as a Set data structure. + this.remainingOutlines_[key] = 1; } } -}; -/** - * @override - */ -PathObject.prototype.updateReplacementFade = function(enable) { - this.setClass_('blocklyReplaceable', enable); - if (enable) { - this.svgPath.setAttribute( - 'filter', 'url(#' + this.constants.replacementGlowFilterId + ')'); - } else { - this.svgPath.removeAttribute('filter'); - } -}; - -/** - * @override - */ -PathObject.prototype.updateShapeForInputHighlight = function(conn, enable) { - const name = conn.getParentInput().name; - const outlinePath = this.getOutlinePath_(name); - if (!outlinePath) { - return; - } - if (enable) { - outlinePath.setAttribute( - 'filter', 'url(#' + this.constants.replacementGlowFilterId + ')'); - } else { - outlinePath.removeAttribute('filter'); - } -}; - -/** - * Method that's called when the drawer is about to draw the block. - * @package - */ -PathObject.prototype.beginDrawing = function() { - this.remainingOutlines_ = Object.create(null); - for (const key in this.outlines_) { - // The value set here isn't used anywhere, we are just using the - // object as a Set data structure. - this.remainingOutlines_[key] = 1; - } -}; - -/** - * Method that's called when the drawer is done drawing. - * @package - */ -PathObject.prototype.endDrawing = function() { - // Go through all remaining outlines that were not used this draw pass, and - // remove them. - if (this.remainingOutlines_) { - for (const key in this.remainingOutlines_) { - this.removeOutlinePath_(key); + /** + * Method that's called when the drawer is done drawing. + * @package + */ + endDrawing() { + // Go through all remaining outlines that were not used this draw pass, and + // remove them. + if (this.remainingOutlines_) { + for (const key in this.remainingOutlines_) { + this.removeOutlinePath_(key); + } } + this.remainingOutlines_ = null; } - this.remainingOutlines_ = null; -}; -/** - * Set the path generated by the renderer for an outline path on the respective - * outline path SVG element. - * @param {string} name The input name. - * @param {string} pathString The path. - * @package - */ -PathObject.prototype.setOutlinePath = function(name, pathString) { - const outline = this.getOutlinePath_(name); - outline.setAttribute('d', pathString); - outline.setAttribute('fill', this.style.colourTertiary); -}; - -/** - * Create's an outline path for the specified input. - * @param {string} name The input name. - * @return {!SVGElement} The SVG outline path. - * @private - */ -PathObject.prototype.getOutlinePath_ = function(name) { - if (!this.outlines_[name]) { - this.outlines_[name] = dom.createSvgElement( - Svg.PATH, { - 'class': 'blocklyOutlinePath', - // IE doesn't like paths without the data definition, set empty - // default - 'd': '', - }, - this.svgRoot); + /** + * Set the path generated by the renderer for an outline path on the + * respective outline path SVG element. + * @param {string} name The input name. + * @param {string} pathString The path. + * @package + */ + setOutlinePath(name, pathString) { + const outline = this.getOutlinePath_(name); + outline.setAttribute('d', pathString); + outline.setAttribute('fill', this.style.colourTertiary); } - if (this.remainingOutlines_) { - delete this.remainingOutlines_[name]; - } - return this.outlines_[name]; -}; -/** - * Remove an outline path that is associated with the specified input. - * @param {string} name The input name. - * @private - */ -PathObject.prototype.removeOutlinePath_ = function(name) { - this.outlines_[name].parentNode.removeChild(this.outlines_[name]); - delete this.outlines_[name]; -}; + /** + * Create's an outline path for the specified input. + * @param {string} name The input name. + * @return {!SVGElement} The SVG outline path. + * @private + */ + getOutlinePath_(name) { + if (!this.outlines_[name]) { + this.outlines_[name] = dom.createSvgElement( + Svg.PATH, { + 'class': 'blocklyOutlinePath', + // IE doesn't like paths without the data definition, set empty + // default + 'd': '', + }, + this.svgRoot); + } + if (this.remainingOutlines_) { + delete this.remainingOutlines_[name]; + } + return this.outlines_[name]; + } + + /** + * Remove an outline path that is associated with the specified input. + * @param {string} name The input name. + * @private + */ + removeOutlinePath_(name) { + this.outlines_[name].parentNode.removeChild(this.outlines_[name]); + delete this.outlines_[name]; + } +} exports.PathObject = PathObject; diff --git a/core/renderers/zelos/renderer.js b/core/renderers/zelos/renderer.js index 62d7a27f2..d18962bb8 100644 --- a/core/renderers/zelos/renderer.js +++ b/core/renderers/zelos/renderer.js @@ -16,7 +16,6 @@ goog.module('Blockly.zelos.Renderer'); const blockRendering = goog.require('Blockly.blockRendering'); -const object = goog.require('Blockly.utils.object'); /* eslint-disable-next-line no-unused-vars */ const {BlockSvg} = goog.requireType('Blockly.BlockSvg'); const {ConnectionType} = goog.require('Blockly.ConnectionType'); @@ -39,109 +38,109 @@ const {WorkspaceSvg} = goog.requireType('Blockly.WorkspaceSvg'); /** * The zelos renderer. - * @param {string} name The renderer name. - * @package - * @constructor * @extends {BaseRenderer} - * @alias Blockly.zelos.Renderer */ -const Renderer = function(name) { - Renderer.superClass_.constructor.call(this, name); -}; -object.inherits(Renderer, BaseRenderer); - -/** - * Create a new instance of the renderer's constant provider. - * @return {!ConstantProvider} The constant provider. - * @protected - * @override - */ -Renderer.prototype.makeConstants_ = function() { - return new ConstantProvider(); -}; - -/** - * Create a new instance of the renderer's render info object. - * @param {!BlockSvg} block The block to measure. - * @return {!RenderInfo} The render info object. - * @protected - * @override - */ -Renderer.prototype.makeRenderInfo_ = function(block) { - return new RenderInfo(this, block); -}; - -/** - * Create a new instance of the renderer's drawer. - * @param {!BlockSvg} block The block to render. - * @param {!BaseRenderInfo} info An object containing all - * information needed to render this block. - * @return {!Drawer} The drawer. - * @protected - * @override - */ -Renderer.prototype.makeDrawer_ = function(block, info) { - return new Drawer( - block, - /** @type {!RenderInfo} */ (info)); -}; - -/** - * Create a new instance of the renderer's cursor drawer. - * @param {!WorkspaceSvg} workspace The workspace the cursor belongs to. - * @param {!Marker} marker The marker. - * @return {!MarkerSvg} The object in charge of drawing - * the marker. - * @package - * @override - */ -Renderer.prototype.makeMarkerDrawer = function(workspace, marker) { - return new MarkerSvg(workspace, this.getConstants(), marker); -}; - -/** - * Create a new instance of a renderer path object. - * @param {!SVGElement} root The root SVG element. - * @param {!Theme.BlockStyle} style The style object to use for - * colouring. - * @return {!PathObject} The renderer path object. - * @package - * @override - */ -Renderer.prototype.makePathObject = function(root, style) { - return new PathObject( - root, style, - /** @type {!ConstantProvider} */ (this.getConstants())); -}; - -/** - * @override - */ -Renderer.prototype.shouldHighlightConnection = function(conn) { - return conn.type !== ConnectionType.INPUT_VALUE && - conn.type !== ConnectionType.OUTPUT_VALUE; -}; - -/** - * @override - */ -Renderer.prototype.getConnectionPreviewMethod = function( - closest, local, topBlock) { - if (local.type === ConnectionType.OUTPUT_VALUE) { - if (!closest.isConnected()) { - return InsertionMarkerManager.PREVIEW_TYPE.INPUT_OUTLINE; - } - // TODO: Returning this is a total hack, because we don't want to show - // a replacement fade, we want to show an outline affect. - // Sadly zelos does not support showing an outline around filled - // inputs, so we have to pretend like the connected block is getting - // replaced. - return InsertionMarkerManager.PREVIEW_TYPE.REPLACEMENT_FADE; +class Renderer extends BaseRenderer { + /** + * @param {string} name The renderer name. + * @package + * @alias Blockly.zelos.Renderer + */ + constructor(name) { + super(name); } - return Renderer.superClass_.getConnectionPreviewMethod( - closest, local, topBlock); -}; + /** + * Create a new instance of the renderer's constant provider. + * @return {!ConstantProvider} The constant provider. + * @protected + * @override + */ + makeConstants_() { + return new ConstantProvider(); + } + + /** + * Create a new instance of the renderer's render info object. + * @param {!BlockSvg} block The block to measure. + * @return {!RenderInfo} The render info object. + * @protected + * @override + */ + makeRenderInfo_(block) { + return new RenderInfo(this, block); + } + + /** + * Create a new instance of the renderer's drawer. + * @param {!BlockSvg} block The block to render. + * @param {!BaseRenderInfo} info An object containing all + * information needed to render this block. + * @return {!Drawer} The drawer. + * @protected + * @override + */ + makeDrawer_(block, info) { + return new Drawer( + block, + /** @type {!RenderInfo} */ (info)); + } + + /** + * Create a new instance of the renderer's cursor drawer. + * @param {!WorkspaceSvg} workspace The workspace the cursor belongs to. + * @param {!Marker} marker The marker. + * @return {!MarkerSvg} The object in charge of drawing + * the marker. + * @package + * @override + */ + makeMarkerDrawer(workspace, marker) { + return new MarkerSvg(workspace, this.getConstants(), marker); + } + + /** + * Create a new instance of a renderer path object. + * @param {!SVGElement} root The root SVG element. + * @param {!Theme.BlockStyle} style The style object to use for + * colouring. + * @return {!PathObject} The renderer path object. + * @package + * @override + */ + makePathObject(root, style) { + return new PathObject( + root, style, + /** @type {!ConstantProvider} */ (this.getConstants())); + } + + /** + * @override + */ + shouldHighlightConnection(conn) { + return conn.type !== ConnectionType.INPUT_VALUE && + conn.type !== ConnectionType.OUTPUT_VALUE; + } + + /** + * @override + */ + getConnectionPreviewMethod(closest, local, topBlock) { + if (local.type === ConnectionType.OUTPUT_VALUE) { + if (!closest.isConnected()) { + return InsertionMarkerManager.PREVIEW_TYPE.INPUT_OUTLINE; + } + // TODO: Returning this is a total hack, because we don't want to show + // a replacement fade, we want to show an outline affect. + // Sadly zelos does not support showing an outline around filled + // inputs, so we have to pretend like the connected block is getting + // replaced. + return InsertionMarkerManager.PREVIEW_TYPE.REPLACEMENT_FADE; + } + + return super.getConnectionPreviewMethod(closest, local, topBlock); + } +} blockRendering.register('zelos', Renderer); diff --git a/scripts/gulpfiles/chunks.json b/scripts/gulpfiles/chunks.json index a7fcc3cbf..c3df5c612 100644 --- a/scripts/gulpfiles/chunks.json +++ b/scripts/gulpfiles/chunks.json @@ -52,8 +52,8 @@ "./core/renderers/geras/measurables/statement_input.js", "./core/renderers/geras/path_object.js", "./core/renderers/geras/renderer.js", - "./core/renderers/geras/measurables/inline_input.js", "./core/renderers/geras/info.js", + "./core/renderers/geras/measurables/inline_input.js", "./core/renderers/geras/highlight_constants.js", "./core/renderers/geras/highlighter.js", "./core/renderers/geras/drawer.js", diff --git a/tests/deps.js b/tests/deps.js index ab5c32064..d244eaf47 100644 --- a/tests/deps.js +++ b/tests/deps.js @@ -150,16 +150,16 @@ goog.addDependency('../../core/renderers/common/info.js', ['Blockly.blockRenderi goog.addDependency('../../core/renderers/common/marker_svg.js', ['Blockly.blockRendering.MarkerSvg'], ['Blockly.ASTNode', 'Blockly.ConnectionType', 'Blockly.Events.MarkerMove', 'Blockly.Events.utils', 'Blockly.utils.Svg', 'Blockly.utils.dom', 'Blockly.utils.svgPaths'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/renderers/common/path_object.js', ['Blockly.blockRendering.PathObject'], ['Blockly.blockRendering.IPathObject', 'Blockly.utils.Svg', 'Blockly.utils.dom'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/renderers/common/renderer.js', ['Blockly.blockRendering.Renderer'], ['Blockly.Connection', 'Blockly.ConnectionType', 'Blockly.IRegistrable', 'Blockly.InsertionMarkerManager', 'Blockly.blockRendering.ConstantProvider', 'Blockly.blockRendering.Drawer', 'Blockly.blockRendering.MarkerSvg', 'Blockly.blockRendering.PathObject', 'Blockly.blockRendering.RenderInfo', 'Blockly.blockRendering.debug', 'Blockly.utils.object'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/renderers/geras/constants.js', ['Blockly.geras.ConstantProvider'], ['Blockly.blockRendering.ConstantProvider', 'Blockly.utils.object'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/renderers/geras/drawer.js', ['Blockly.geras.Drawer'], ['Blockly.blockRendering.Drawer', 'Blockly.blockRendering.debug', 'Blockly.geras.Highlighter', 'Blockly.utils.object', 'Blockly.utils.svgPaths'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/renderers/geras/constants.js', ['Blockly.geras.ConstantProvider'], ['Blockly.blockRendering.ConstantProvider'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/renderers/geras/drawer.js', ['Blockly.geras.Drawer'], ['Blockly.blockRendering.Drawer', 'Blockly.blockRendering.debug', 'Blockly.geras.Highlighter', 'Blockly.geras.InlineInput', 'Blockly.utils.svgPaths'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/renderers/geras/geras.js', ['Blockly.geras'], ['Blockly.geras.ConstantProvider', 'Blockly.geras.Drawer', 'Blockly.geras.HighlightConstantProvider', 'Blockly.geras.Highlighter', 'Blockly.geras.InlineInput', 'Blockly.geras.PathObject', 'Blockly.geras.RenderInfo', 'Blockly.geras.Renderer', 'Blockly.geras.StatementInput'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/renderers/geras/highlight_constants.js', ['Blockly.geras.HighlightConstantProvider'], ['Blockly.utils.svgPaths'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/renderers/geras/highlighter.js', ['Blockly.geras.Highlighter'], ['Blockly.blockRendering.Types', 'Blockly.utils.svgPaths'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/renderers/geras/info.js', ['Blockly.geras.RenderInfo'], ['Blockly.blockRendering.ExternalValueInput', 'Blockly.blockRendering.InRowSpacer', 'Blockly.blockRendering.RenderInfo', 'Blockly.blockRendering.Types', 'Blockly.geras.InlineInput', 'Blockly.geras.StatementInput', 'Blockly.inputTypes', 'Blockly.utils.object'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/renderers/geras/measurables/inline_input.js', ['Blockly.geras.InlineInput'], ['Blockly.blockRendering.InlineInput', 'Blockly.utils.object'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/renderers/geras/measurables/statement_input.js', ['Blockly.geras.StatementInput'], ['Blockly.blockRendering.StatementInput', 'Blockly.utils.object'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/renderers/geras/highlighter.js', ['Blockly.geras.Highlighter'], ['Blockly.blockRendering.BottomRow', 'Blockly.blockRendering.TopRow', 'Blockly.blockRendering.Types', 'Blockly.geras.InlineInput', 'Blockly.utils.svgPaths'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/renderers/geras/info.js', ['Blockly.geras.RenderInfo'], ['Blockly.blockRendering.ExternalValueInput', 'Blockly.blockRendering.InRowSpacer', 'Blockly.blockRendering.RenderInfo', 'Blockly.blockRendering.Types', 'Blockly.geras.InlineInput', 'Blockly.geras.StatementInput', 'Blockly.inputTypes'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/renderers/geras/measurables/inline_input.js', ['Blockly.geras.InlineInput'], ['Blockly.blockRendering.InlineInput'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/renderers/geras/measurables/statement_input.js', ['Blockly.geras.StatementInput'], ['Blockly.blockRendering.StatementInput'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/renderers/geras/path_object.js', ['Blockly.geras.PathObject'], ['Blockly.blockRendering.PathObject', 'Blockly.utils.Svg', 'Blockly.utils.colour', 'Blockly.utils.dom', 'Blockly.utils.object'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/renderers/geras/renderer.js', ['Blockly.geras.Renderer'], ['Blockly.blockRendering', 'Blockly.blockRendering.Renderer', 'Blockly.geras.ConstantProvider', 'Blockly.geras.Drawer', 'Blockly.geras.HighlightConstantProvider', 'Blockly.geras.PathObject', 'Blockly.geras.RenderInfo', 'Blockly.utils.object'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/renderers/geras/renderer.js', ['Blockly.geras.Renderer'], ['Blockly.blockRendering', 'Blockly.blockRendering.Renderer', 'Blockly.geras.ConstantProvider', 'Blockly.geras.Drawer', 'Blockly.geras.HighlightConstantProvider', 'Blockly.geras.PathObject', 'Blockly.geras.RenderInfo'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/renderers/measurables/base.js', ['Blockly.blockRendering.Measurable'], ['Blockly.blockRendering.Types'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/renderers/measurables/bottom_row.js', ['Blockly.blockRendering.BottomRow'], ['Blockly.blockRendering.Row', 'Blockly.blockRendering.Types', 'Blockly.utils.object'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/renderers/measurables/connection.js', ['Blockly.blockRendering.Connection'], ['Blockly.blockRendering.Measurable', 'Blockly.blockRendering.Types', 'Blockly.utils.object'], {'lang': 'es6', 'module': 'goog'}); @@ -182,24 +182,24 @@ goog.addDependency('../../core/renderers/measurables/square_corner.js', ['Blockl goog.addDependency('../../core/renderers/measurables/statement_input.js', ['Blockly.blockRendering.StatementInput'], ['Blockly.blockRendering.InputConnection', 'Blockly.blockRendering.Types', 'Blockly.utils.object'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/renderers/measurables/top_row.js', ['Blockly.blockRendering.TopRow'], ['Blockly.blockRendering.Row', 'Blockly.blockRendering.Types', 'Blockly.utils.object'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/renderers/measurables/types.js', ['Blockly.blockRendering.Types'], [], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/renderers/minimalist/constants.js', ['Blockly.minimalist.ConstantProvider'], ['Blockly.blockRendering.ConstantProvider', 'Blockly.utils.object'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/renderers/minimalist/drawer.js', ['Blockly.minimalist.Drawer'], ['Blockly.blockRendering.Drawer', 'Blockly.utils.object'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/renderers/minimalist/info.js', ['Blockly.minimalist.RenderInfo'], ['Blockly.blockRendering.RenderInfo', 'Blockly.utils.object'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/renderers/minimalist/constants.js', ['Blockly.minimalist.ConstantProvider'], ['Blockly.blockRendering.ConstantProvider'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/renderers/minimalist/drawer.js', ['Blockly.minimalist.Drawer'], ['Blockly.blockRendering.Drawer'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/renderers/minimalist/info.js', ['Blockly.minimalist.RenderInfo'], ['Blockly.blockRendering.RenderInfo'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/renderers/minimalist/minimalist.js', ['Blockly.minimalist'], ['Blockly.minimalist.ConstantProvider', 'Blockly.minimalist.Drawer', 'Blockly.minimalist.RenderInfo', 'Blockly.minimalist.Renderer'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/renderers/minimalist/renderer.js', ['Blockly.minimalist.Renderer'], ['Blockly.blockRendering', 'Blockly.blockRendering.Renderer', 'Blockly.minimalist.ConstantProvider', 'Blockly.minimalist.Drawer', 'Blockly.minimalist.RenderInfo', 'Blockly.utils.object'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/renderers/thrasos/info.js', ['Blockly.thrasos.RenderInfo'], ['Blockly.blockRendering.InRowSpacer', 'Blockly.blockRendering.RenderInfo', 'Blockly.blockRendering.Types', 'Blockly.utils.object'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/renderers/thrasos/renderer.js', ['Blockly.thrasos.Renderer'], ['Blockly.blockRendering', 'Blockly.blockRendering.Renderer', 'Blockly.thrasos.RenderInfo', 'Blockly.utils.object'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/renderers/minimalist/renderer.js', ['Blockly.minimalist.Renderer'], ['Blockly.blockRendering', 'Blockly.blockRendering.Renderer', 'Blockly.minimalist.ConstantProvider', 'Blockly.minimalist.Drawer', 'Blockly.minimalist.RenderInfo'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/renderers/thrasos/info.js', ['Blockly.thrasos.RenderInfo'], ['Blockly.blockRendering.InRowSpacer', 'Blockly.blockRendering.RenderInfo', 'Blockly.blockRendering.Types'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/renderers/thrasos/renderer.js', ['Blockly.thrasos.Renderer'], ['Blockly.blockRendering', 'Blockly.blockRendering.Renderer', 'Blockly.thrasos.RenderInfo'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/renderers/thrasos/thrasos.js', ['Blockly.thrasos'], ['Blockly.thrasos.RenderInfo', 'Blockly.thrasos.Renderer'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/renderers/zelos/constants.js', ['Blockly.zelos.ConstantProvider'], ['Blockly.ConnectionType', 'Blockly.blockRendering.ConstantProvider', 'Blockly.utils.Svg', 'Blockly.utils.colour', 'Blockly.utils.dom', 'Blockly.utils.object', 'Blockly.utils.svgPaths'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/renderers/zelos/drawer.js', ['Blockly.zelos.Drawer'], ['Blockly.blockRendering.Drawer', 'Blockly.blockRendering.debug', 'Blockly.utils.object', 'Blockly.utils.svgPaths'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/renderers/zelos/info.js', ['Blockly.zelos.RenderInfo'], ['Blockly.FieldImage', 'Blockly.FieldLabel', 'Blockly.FieldTextInput', 'Blockly.Input', 'Blockly.blockRendering.InRowSpacer', 'Blockly.blockRendering.RenderInfo', 'Blockly.blockRendering.Types', 'Blockly.inputTypes', 'Blockly.utils.object', 'Blockly.zelos.BottomRow', 'Blockly.zelos.RightConnectionShape', 'Blockly.zelos.StatementInput', 'Blockly.zelos.TopRow'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/renderers/zelos/marker_svg.js', ['Blockly.zelos.MarkerSvg'], ['Blockly.blockRendering.MarkerSvg', 'Blockly.utils.Svg', 'Blockly.utils.dom', 'Blockly.utils.object'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/renderers/zelos/measurables/bottom_row.js', ['Blockly.zelos.BottomRow'], ['Blockly.blockRendering.BottomRow', 'Blockly.utils.object'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/renderers/zelos/measurables/inputs.js', ['Blockly.zelos.StatementInput'], ['Blockly.blockRendering.StatementInput', 'Blockly.utils.object'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/renderers/zelos/measurables/row_elements.js', ['Blockly.zelos.RightConnectionShape'], ['Blockly.blockRendering.Measurable', 'Blockly.blockRendering.Types', 'Blockly.utils.object'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/renderers/zelos/measurables/top_row.js', ['Blockly.zelos.TopRow'], ['Blockly.blockRendering.TopRow', 'Blockly.utils.object'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/renderers/zelos/path_object.js', ['Blockly.zelos.PathObject'], ['Blockly.blockRendering.PathObject', 'Blockly.utils.Svg', 'Blockly.utils.dom', 'Blockly.utils.object'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/renderers/zelos/renderer.js', ['Blockly.zelos.Renderer'], ['Blockly.ConnectionType', 'Blockly.InsertionMarkerManager', 'Blockly.blockRendering', 'Blockly.blockRendering.Renderer', 'Blockly.utils.object', 'Blockly.zelos.ConstantProvider', 'Blockly.zelos.Drawer', 'Blockly.zelos.MarkerSvg', 'Blockly.zelos.PathObject', 'Blockly.zelos.RenderInfo'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/renderers/zelos/constants.js', ['Blockly.zelos.ConstantProvider'], ['Blockly.ConnectionType', 'Blockly.blockRendering.ConstantProvider', 'Blockly.utils.Svg', 'Blockly.utils.colour', 'Blockly.utils.dom', 'Blockly.utils.svgPaths'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/renderers/zelos/drawer.js', ['Blockly.zelos.Drawer'], ['Blockly.blockRendering.Drawer', 'Blockly.blockRendering.debug', 'Blockly.utils.svgPaths'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/renderers/zelos/info.js', ['Blockly.zelos.RenderInfo'], ['Blockly.FieldImage', 'Blockly.FieldLabel', 'Blockly.FieldTextInput', 'Blockly.Input', 'Blockly.blockRendering.InRowSpacer', 'Blockly.blockRendering.RenderInfo', 'Blockly.blockRendering.Types', 'Blockly.inputTypes', 'Blockly.zelos.BottomRow', 'Blockly.zelos.RightConnectionShape', 'Blockly.zelos.StatementInput', 'Blockly.zelos.TopRow'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/renderers/zelos/marker_svg.js', ['Blockly.zelos.MarkerSvg'], ['Blockly.blockRendering.MarkerSvg', 'Blockly.utils.Svg', 'Blockly.utils.dom'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/renderers/zelos/measurables/bottom_row.js', ['Blockly.zelos.BottomRow'], ['Blockly.blockRendering.BottomRow'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/renderers/zelos/measurables/inputs.js', ['Blockly.zelos.StatementInput'], ['Blockly.blockRendering.StatementInput'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/renderers/zelos/measurables/row_elements.js', ['Blockly.zelos.RightConnectionShape'], ['Blockly.blockRendering.Measurable', 'Blockly.blockRendering.Types'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/renderers/zelos/measurables/top_row.js', ['Blockly.zelos.TopRow'], ['Blockly.blockRendering.TopRow'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/renderers/zelos/path_object.js', ['Blockly.zelos.PathObject'], ['Blockly.blockRendering.PathObject', 'Blockly.utils.Svg', 'Blockly.utils.dom'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/renderers/zelos/renderer.js', ['Blockly.zelos.Renderer'], ['Blockly.ConnectionType', 'Blockly.InsertionMarkerManager', 'Blockly.blockRendering', 'Blockly.blockRendering.Renderer', 'Blockly.zelos.ConstantProvider', 'Blockly.zelos.Drawer', 'Blockly.zelos.MarkerSvg', 'Blockly.zelos.PathObject', 'Blockly.zelos.RenderInfo'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/renderers/zelos/zelos.js', ['Blockly.zelos'], ['Blockly.zelos.BottomRow', 'Blockly.zelos.ConstantProvider', 'Blockly.zelos.Drawer', 'Blockly.zelos.MarkerSvg', 'Blockly.zelos.PathObject', 'Blockly.zelos.RenderInfo', 'Blockly.zelos.Renderer', 'Blockly.zelos.RightConnectionShape', 'Blockly.zelos.StatementInput', 'Blockly.zelos.TopRow'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/scrollbar.js', ['Blockly.Scrollbar'], ['Blockly.Touch', 'Blockly.browserEvents', 'Blockly.utils.Coordinate', 'Blockly.utils.Svg', 'Blockly.utils.dom', 'Blockly.utils.svgMath'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/scrollbar_pair.js', ['Blockly.ScrollbarPair'], ['Blockly.Events.utils', 'Blockly.Scrollbar', 'Blockly.utils.Svg', 'Blockly.utils.dom'], {'lang': 'es6', 'module': 'goog'}); From 23a19f87f421744351e4b5ffb2e3c21631f64f12 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 18 Jan 2022 13:18:16 -0800 Subject: [PATCH 032/128] chore(deps): bump @blockly/dev-tools from 3.0.1 to 3.0.3 (#5877) Bumps [@blockly/dev-tools](https://github.com/google/blockly-samples/tree/HEAD/plugins/dev-tools) from 3.0.1 to 3.0.3. - [Release notes](https://github.com/google/blockly-samples/releases) - [Commits](https://github.com/google/blockly-samples/commits/@blockly/dev-tools@3.0.3/plugins/dev-tools) --- updated-dependencies: - dependency-name: "@blockly/dev-tools" dependency-type: direct:development update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- package-lock.json | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/package-lock.json b/package-lock.json index c4616b0c0..137617e77 100644 --- a/package-lock.json +++ b/package-lock.json @@ -164,9 +164,9 @@ } }, "node_modules/@blockly/dev-tools": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/@blockly/dev-tools/-/dev-tools-3.0.1.tgz", - "integrity": "sha512-afFCokPWHKeFrZRSoHa0oBBUWIwqI02/svYPRTjviEsxGcU89nG/bYBpfG9Fosm8hEKROvZf7/bIMn0x1KlCBA==", + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/@blockly/dev-tools/-/dev-tools-3.0.3.tgz", + "integrity": "sha512-eg3j1vWapDgmsQY1DbEzWHJoEE5sK4IGyTOd+YKNwumtTR/GqjlCzM6ajcBAuAYwL9pBqD6rb6al/MfuwlbTtg==", "dev": true, "dependencies": { "@blockly/block-test": "^2.0.1", @@ -1749,9 +1749,9 @@ } }, "node_modules/blockly": { - "version": "6.20210701.0", - "resolved": "https://registry.npmjs.org/blockly/-/blockly-6.20210701.0.tgz", - "integrity": "sha512-cNrwFOAxXE5Pbs1FJAyLTlSRzpNW/C+0gPT2rGQDOJVVKcyF3vhFC1StgnxvQNsv//ueuksKWIXxDuSWh1VI4w==", + "version": "7.20211209.2", + "resolved": "https://registry.npmjs.org/blockly/-/blockly-7.20211209.2.tgz", + "integrity": "sha512-74HTPbnDOwVGKx6qRE/ZVVQwf+J9s/WkgDKv0vuXw/DtBLvLrew7Nf5jaZP0+DXRVJpP1u5sfu+qtHaom0i6Ug==", "dev": true, "peer": true, "dependencies": { @@ -12473,9 +12473,9 @@ "requires": {} }, "@blockly/dev-tools": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/@blockly/dev-tools/-/dev-tools-3.0.1.tgz", - "integrity": "sha512-afFCokPWHKeFrZRSoHa0oBBUWIwqI02/svYPRTjviEsxGcU89nG/bYBpfG9Fosm8hEKROvZf7/bIMn0x1KlCBA==", + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/@blockly/dev-tools/-/dev-tools-3.0.3.tgz", + "integrity": "sha512-eg3j1vWapDgmsQY1DbEzWHJoEE5sK4IGyTOd+YKNwumtTR/GqjlCzM6ajcBAuAYwL9pBqD6rb6al/MfuwlbTtg==", "dev": true, "requires": { "@blockly/block-test": "^2.0.1", @@ -13746,9 +13746,9 @@ } }, "blockly": { - "version": "6.20210701.0", - "resolved": "https://registry.npmjs.org/blockly/-/blockly-6.20210701.0.tgz", - "integrity": "sha512-cNrwFOAxXE5Pbs1FJAyLTlSRzpNW/C+0gPT2rGQDOJVVKcyF3vhFC1StgnxvQNsv//ueuksKWIXxDuSWh1VI4w==", + "version": "7.20211209.2", + "resolved": "https://registry.npmjs.org/blockly/-/blockly-7.20211209.2.tgz", + "integrity": "sha512-74HTPbnDOwVGKx6qRE/ZVVQwf+J9s/WkgDKv0vuXw/DtBLvLrew7Nf5jaZP0+DXRVJpP1u5sfu+qtHaom0i6Ug==", "dev": true, "peer": true, "requires": { From 1bac2ef78b8816a6aff10d58bf88d2dd5b5c0e42 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 18 Jan 2022 21:40:46 +0000 Subject: [PATCH 033/128] chore(deps): bump google-closure-compiler (#5865) Bumps [google-closure-compiler](https://github.com/google/closure-compiler-npm) from 20211201.0.0 to 20220104.0.0. - [Release notes](https://github.com/google/closure-compiler-npm/releases) - [Commits](https://github.com/google/closure-compiler-npm/compare/v20211201.0.0...v20220104.0.0) --- updated-dependencies: - dependency-name: google-closure-compiler dependency-type: direct:development update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- package-lock.json | 78 +++++++++++++++++++++++------------------------ package.json | 2 +- 2 files changed, 40 insertions(+), 40 deletions(-) diff --git a/package-lock.json b/package-lock.json index 137617e77..22275cf93 100644 --- a/package-lock.json +++ b/package-lock.json @@ -21,7 +21,7 @@ "concurrently": "^7.0.0", "eslint": "^8.4.1", "eslint-config-google": "^0.14.0", - "google-closure-compiler": "^20211201.0.0", + "google-closure-compiler": "^20220104.0.0", "google-closure-deps": "^20211201.0.0", "gulp": "^4.0.2", "gulp-clang-format": "^1.0.27", @@ -4975,13 +4975,13 @@ } }, "node_modules/google-closure-compiler": { - "version": "20211201.0.0", - "resolved": "https://registry.npmjs.org/google-closure-compiler/-/google-closure-compiler-20211201.0.0.tgz", - "integrity": "sha512-QPNp6uHR94EKbi17XCsdISHAqIgk1Ep7LpB+rmPDY7VoNAX4784WT/0bz6HyVK4QYRVLlNAy2X+1+VlFhS0FzQ==", + "version": "20220104.0.0", + "resolved": "https://registry.npmjs.org/google-closure-compiler/-/google-closure-compiler-20220104.0.0.tgz", + "integrity": "sha512-8JQs1cWpJYjvqnAskMis1sQ/nm2wHYIt/Rd3HYyMOgfEzjNdqLkIiuzCXbz2flktHXS63mvdxU4+ZlJR72Kz8g==", "dev": true, "dependencies": { "chalk": "2.x", - "google-closure-compiler-java": "^20211201.0.0", + "google-closure-compiler-java": "^20220104.0.0", "minimist": "1.x", "vinyl": "2.x", "vinyl-sourcemaps-apply": "^0.2.0" @@ -4993,21 +4993,21 @@ "node": ">=10" }, "optionalDependencies": { - "google-closure-compiler-linux": "^20211201.0.0", - "google-closure-compiler-osx": "^20211201.0.0", - "google-closure-compiler-windows": "^20211201.0.0" + "google-closure-compiler-linux": "^20220104.0.0", + "google-closure-compiler-osx": "^20220104.0.0", + "google-closure-compiler-windows": "^20220104.0.0" } }, "node_modules/google-closure-compiler-java": { - "version": "20211201.0.0", - "resolved": "https://registry.npmjs.org/google-closure-compiler-java/-/google-closure-compiler-java-20211201.0.0.tgz", - "integrity": "sha512-TQop4dF0k/mb9sPu0aZsvW8OVfuZG4+t4ITZeA/u43deiAA4AFScZQQUMUmoVmXzR8Jz0eeucKoZPTwKAwcSmQ==", + "version": "20220104.0.0", + "resolved": "https://registry.npmjs.org/google-closure-compiler-java/-/google-closure-compiler-java-20220104.0.0.tgz", + "integrity": "sha512-cnxEfms548+whhdtIT5MLNVfHcXasYmsUGpyrdLDX+0xR4t+oJBT7RI/O7qOusoqXdW6lwAIT2jbFI8Irk6eVQ==", "dev": true }, "node_modules/google-closure-compiler-linux": { - "version": "20211201.0.0", - "resolved": "https://registry.npmjs.org/google-closure-compiler-linux/-/google-closure-compiler-linux-20211201.0.0.tgz", - "integrity": "sha512-7nMgBFZYYQTvDLcO+LqqwtibgZJu8qaFJbK84T12xneY1Yy1fUSn56NXaZ9cgdS7p30Hqy6tYcw9ZSuxK7fuEA==", + "version": "20220104.0.0", + "resolved": "https://registry.npmjs.org/google-closure-compiler-linux/-/google-closure-compiler-linux-20220104.0.0.tgz", + "integrity": "sha512-3la7sjrcKHlQc8piP+nzsZmFQFYV/4DtxFcpjq+Re81+vYmE9NWUZ21xgp6OZ7ygZhVLEWQqGlZqJls45HS0rA==", "cpu": [ "x64", "x86" @@ -5019,9 +5019,9 @@ ] }, "node_modules/google-closure-compiler-osx": { - "version": "20211201.0.0", - "resolved": "https://registry.npmjs.org/google-closure-compiler-osx/-/google-closure-compiler-osx-20211201.0.0.tgz", - "integrity": "sha512-eJKmvYm5C82BAcfK64/7nR3RbR4bwIXO2Dmhmb5AR6FXxD/J1svaG3BMINlS+U/GT7NeV4Z7bKb2TcPIAfGO9A==", + "version": "20220104.0.0", + "resolved": "https://registry.npmjs.org/google-closure-compiler-osx/-/google-closure-compiler-osx-20220104.0.0.tgz", + "integrity": "sha512-D6WPBKS6H416kY4OH9WBhviY7e+b1+RXT8jWhBGXMHoSlUiIUALOi67RvBuibiX39ljG0D1JSZbfYXNCDYLMmw==", "cpu": [ "x64", "x86", @@ -5034,9 +5034,9 @@ ] }, "node_modules/google-closure-compiler-windows": { - "version": "20211201.0.0", - "resolved": "https://registry.npmjs.org/google-closure-compiler-windows/-/google-closure-compiler-windows-20211201.0.0.tgz", - "integrity": "sha512-OPZYA0+tJSjutt1EYrECmXChNsY5USoMbQkBEmwI29riVvNnK5Ot+/SE66/NPHwm3qI/p3O7TnOTKhVpXKed5Q==", + "version": "20220104.0.0", + "resolved": "https://registry.npmjs.org/google-closure-compiler-windows/-/google-closure-compiler-windows-20220104.0.0.tgz", + "integrity": "sha512-VNBUBSBLn2ZeK4EKsoY/rl6qjXYoph+DWmiicNeFrEvqyUB9Vh9MhhP4F+PPOg1iYdPw4XtNsmfSnIV96kQHyA==", "cpu": [ "x64" ], @@ -16320,16 +16320,16 @@ } }, "google-closure-compiler": { - "version": "20211201.0.0", - "resolved": "https://registry.npmjs.org/google-closure-compiler/-/google-closure-compiler-20211201.0.0.tgz", - "integrity": "sha512-QPNp6uHR94EKbi17XCsdISHAqIgk1Ep7LpB+rmPDY7VoNAX4784WT/0bz6HyVK4QYRVLlNAy2X+1+VlFhS0FzQ==", + "version": "20220104.0.0", + "resolved": "https://registry.npmjs.org/google-closure-compiler/-/google-closure-compiler-20220104.0.0.tgz", + "integrity": "sha512-8JQs1cWpJYjvqnAskMis1sQ/nm2wHYIt/Rd3HYyMOgfEzjNdqLkIiuzCXbz2flktHXS63mvdxU4+ZlJR72Kz8g==", "dev": true, "requires": { "chalk": "2.x", - "google-closure-compiler-java": "^20211201.0.0", - "google-closure-compiler-linux": "^20211201.0.0", - "google-closure-compiler-osx": "^20211201.0.0", - "google-closure-compiler-windows": "^20211201.0.0", + "google-closure-compiler-java": "^20220104.0.0", + "google-closure-compiler-linux": "^20220104.0.0", + "google-closure-compiler-osx": "^20220104.0.0", + "google-closure-compiler-windows": "^20220104.0.0", "minimist": "1.x", "vinyl": "2.x", "vinyl-sourcemaps-apply": "^0.2.0" @@ -16394,29 +16394,29 @@ } }, "google-closure-compiler-java": { - "version": "20211201.0.0", - "resolved": "https://registry.npmjs.org/google-closure-compiler-java/-/google-closure-compiler-java-20211201.0.0.tgz", - "integrity": "sha512-TQop4dF0k/mb9sPu0aZsvW8OVfuZG4+t4ITZeA/u43deiAA4AFScZQQUMUmoVmXzR8Jz0eeucKoZPTwKAwcSmQ==", + "version": "20220104.0.0", + "resolved": "https://registry.npmjs.org/google-closure-compiler-java/-/google-closure-compiler-java-20220104.0.0.tgz", + "integrity": "sha512-cnxEfms548+whhdtIT5MLNVfHcXasYmsUGpyrdLDX+0xR4t+oJBT7RI/O7qOusoqXdW6lwAIT2jbFI8Irk6eVQ==", "dev": true }, "google-closure-compiler-linux": { - "version": "20211201.0.0", - "resolved": "https://registry.npmjs.org/google-closure-compiler-linux/-/google-closure-compiler-linux-20211201.0.0.tgz", - "integrity": "sha512-7nMgBFZYYQTvDLcO+LqqwtibgZJu8qaFJbK84T12xneY1Yy1fUSn56NXaZ9cgdS7p30Hqy6tYcw9ZSuxK7fuEA==", + "version": "20220104.0.0", + "resolved": "https://registry.npmjs.org/google-closure-compiler-linux/-/google-closure-compiler-linux-20220104.0.0.tgz", + "integrity": "sha512-3la7sjrcKHlQc8piP+nzsZmFQFYV/4DtxFcpjq+Re81+vYmE9NWUZ21xgp6OZ7ygZhVLEWQqGlZqJls45HS0rA==", "dev": true, "optional": true }, "google-closure-compiler-osx": { - "version": "20211201.0.0", - "resolved": "https://registry.npmjs.org/google-closure-compiler-osx/-/google-closure-compiler-osx-20211201.0.0.tgz", - "integrity": "sha512-eJKmvYm5C82BAcfK64/7nR3RbR4bwIXO2Dmhmb5AR6FXxD/J1svaG3BMINlS+U/GT7NeV4Z7bKb2TcPIAfGO9A==", + "version": "20220104.0.0", + "resolved": "https://registry.npmjs.org/google-closure-compiler-osx/-/google-closure-compiler-osx-20220104.0.0.tgz", + "integrity": "sha512-D6WPBKS6H416kY4OH9WBhviY7e+b1+RXT8jWhBGXMHoSlUiIUALOi67RvBuibiX39ljG0D1JSZbfYXNCDYLMmw==", "dev": true, "optional": true }, "google-closure-compiler-windows": { - "version": "20211201.0.0", - "resolved": "https://registry.npmjs.org/google-closure-compiler-windows/-/google-closure-compiler-windows-20211201.0.0.tgz", - "integrity": "sha512-OPZYA0+tJSjutt1EYrECmXChNsY5USoMbQkBEmwI29riVvNnK5Ot+/SE66/NPHwm3qI/p3O7TnOTKhVpXKed5Q==", + "version": "20220104.0.0", + "resolved": "https://registry.npmjs.org/google-closure-compiler-windows/-/google-closure-compiler-windows-20220104.0.0.tgz", + "integrity": "sha512-VNBUBSBLn2ZeK4EKsoY/rl6qjXYoph+DWmiicNeFrEvqyUB9Vh9MhhP4F+PPOg1iYdPw4XtNsmfSnIV96kQHyA==", "dev": true, "optional": true }, diff --git a/package.json b/package.json index 59ba7e6f5..42fee0197 100644 --- a/package.json +++ b/package.json @@ -75,7 +75,7 @@ "concurrently": "^7.0.0", "eslint": "^8.4.1", "eslint-config-google": "^0.14.0", - "google-closure-compiler": "^20211201.0.0", + "google-closure-compiler": "^20220104.0.0", "google-closure-deps": "^20211201.0.0", "gulp": "^4.0.2", "gulp-clang-format": "^1.0.27", From 1572fe885b0ead55c4cbbe7a6e15be7b60bc12fb Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 18 Jan 2022 21:43:19 +0000 Subject: [PATCH 034/128] chore(deps): bump yargs from 17.3.0 to 17.3.1 (#5851) Bumps [yargs](https://github.com/yargs/yargs) from 17.3.0 to 17.3.1. - [Release notes](https://github.com/yargs/yargs/releases) - [Changelog](https://github.com/yargs/yargs/blob/main/CHANGELOG.md) - [Commits](https://github.com/yargs/yargs/compare/v17.3.0...v17.3.1) --- updated-dependencies: - dependency-name: yargs dependency-type: direct:development update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- package-lock.json | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/package-lock.json b/package-lock.json index 22275cf93..a5a56ac61 100644 --- a/package-lock.json +++ b/package-lock.json @@ -12134,9 +12134,9 @@ "dev": true }, "node_modules/yargs": { - "version": "17.3.0", - "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.3.0.tgz", - "integrity": "sha512-GQl1pWyDoGptFPJx9b9L6kmR33TGusZvXIZUT+BOz9f7X2L94oeAskFYLEg/FkhV06zZPBYLvLZRWeYId29lew==", + "version": "17.3.1", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.3.1.tgz", + "integrity": "sha512-WUANQeVgjLbNsEmGk20f+nlHgOqzRFpiGWVaBrYGYIGANIIu3lWjoyi0fNlFmJkvfhCZ6BXINe7/W2O2bV4iaA==", "dev": true, "dependencies": { "cliui": "^7.0.2", @@ -22122,9 +22122,9 @@ "dev": true }, "yargs": { - "version": "17.3.0", - "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.3.0.tgz", - "integrity": "sha512-GQl1pWyDoGptFPJx9b9L6kmR33TGusZvXIZUT+BOz9f7X2L94oeAskFYLEg/FkhV06zZPBYLvLZRWeYId29lew==", + "version": "17.3.1", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.3.1.tgz", + "integrity": "sha512-WUANQeVgjLbNsEmGk20f+nlHgOqzRFpiGWVaBrYGYIGANIIu3lWjoyi0fNlFmJkvfhCZ6BXINe7/W2O2bV4iaA==", "dev": true, "requires": { "cliui": "^7.0.2", From 05636800c15080c71a352ddb167d73b221720105 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 18 Jan 2022 22:32:11 +0000 Subject: [PATCH 035/128] chore(deps): bump mocha from 9.1.3 to 9.1.4 (#5882) Bumps [mocha](https://github.com/mochajs/mocha) from 9.1.3 to 9.1.4. - [Release notes](https://github.com/mochajs/mocha/releases) - [Changelog](https://github.com/mochajs/mocha/blob/master/CHANGELOG.md) - [Commits](https://github.com/mochajs/mocha/compare/v9.1.3...v9.1.4) --- updated-dependencies: - dependency-name: mocha dependency-type: direct:development update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- package-lock.json | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/package-lock.json b/package-lock.json index a5a56ac61..0e9c85dff 100644 --- a/package-lock.json +++ b/package-lock.json @@ -7876,9 +7876,9 @@ "dev": true }, "node_modules/mocha": { - "version": "9.1.3", - "resolved": "https://registry.npmjs.org/mocha/-/mocha-9.1.3.tgz", - "integrity": "sha512-Xcpl9FqXOAYqI3j79pEtHBBnQgVXIhpULjGQa7DVb0Po+VzmSIK9kanAiWLHoRR/dbZ2qpdPshuXr8l1VaHCzw==", + "version": "9.1.4", + "resolved": "https://registry.npmjs.org/mocha/-/mocha-9.1.4.tgz", + "integrity": "sha512-+q2aV5VlJZuLgCWoBvGI5zEwPF9eEI0kr/sAA9Jm4xMND7RfIEyF8JE7C0JIg8WXRG+P1sdIAb5ccoHPlXLzcw==", "dev": true, "dependencies": { "@ungap/promise-all-settled": "1.1.2", @@ -18679,9 +18679,9 @@ "dev": true }, "mocha": { - "version": "9.1.3", - "resolved": "https://registry.npmjs.org/mocha/-/mocha-9.1.3.tgz", - "integrity": "sha512-Xcpl9FqXOAYqI3j79pEtHBBnQgVXIhpULjGQa7DVb0Po+VzmSIK9kanAiWLHoRR/dbZ2qpdPshuXr8l1VaHCzw==", + "version": "9.1.4", + "resolved": "https://registry.npmjs.org/mocha/-/mocha-9.1.4.tgz", + "integrity": "sha512-+q2aV5VlJZuLgCWoBvGI5zEwPF9eEI0kr/sAA9Jm4xMND7RfIEyF8JE7C0JIg8WXRG+P1sdIAb5ccoHPlXLzcw==", "dev": true, "requires": { "@ungap/promise-all-settled": "1.1.2", From 789c7f7ab725e03c43edeb4b53c35fdce055a72f Mon Sep 17 00:00:00 2001 From: Christopher Allen Date: Tue, 18 Jan 2022 22:50:17 +0000 Subject: [PATCH 036/128] chores(deps): Update follow-redirects to 1.14.7 to fix CVE-2022-0155. (#5879) --- package-lock.json | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/package-lock.json b/package-lock.json index 0e9c85dff..e879e7422 100644 --- a/package-lock.json +++ b/package-lock.json @@ -5,6 +5,7 @@ "requires": true, "packages": { "": { + "name": "blockly", "version": "7.20211209.0", "license": "Apache-2.0", "dependencies": { @@ -4363,9 +4364,9 @@ } }, "node_modules/follow-redirects": { - "version": "1.14.6", - "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.14.6.tgz", - "integrity": "sha512-fhUl5EwSJbbl8AR+uYL2KQDxLkdSjZGR36xy46AO7cOMTrCMON6Sa28FmAnC2tRTDbd/Uuzz3aJBv7EBN7JH8A==", + "version": "1.14.7", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.14.7.tgz", + "integrity": "sha512-+hbxoLbFMbRKDwohX8GkTataGqO6Jb7jGwpAlwgy2bIz25XtRm7KEzJM76R1WiNT5SwZkX4Y75SwBolkpmE7iQ==", "dev": true, "funding": [ { @@ -15846,9 +15847,9 @@ } }, "follow-redirects": { - "version": "1.14.6", - "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.14.6.tgz", - "integrity": "sha512-fhUl5EwSJbbl8AR+uYL2KQDxLkdSjZGR36xy46AO7cOMTrCMON6Sa28FmAnC2tRTDbd/Uuzz3aJBv7EBN7JH8A==", + "version": "1.14.7", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.14.7.tgz", + "integrity": "sha512-+hbxoLbFMbRKDwohX8GkTataGqO6Jb7jGwpAlwgy2bIz25XtRm7KEzJM76R1WiNT5SwZkX4Y75SwBolkpmE7iQ==", "dev": true }, "for-in": { From 7b645363e5c87b81dc4ef0862c17fccf392fd5ee Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 18 Jan 2022 16:39:50 -0800 Subject: [PATCH 037/128] chore(deps): bump http-server from 14.0.0 to 14.1.0 (#5881) Bumps [http-server](https://github.com/http-party/http-server) from 14.0.0 to 14.1.0. - [Release notes](https://github.com/http-party/http-server/releases) - [Commits](https://github.com/http-party/http-server/compare/v14.0.0...v14.1.0) --- updated-dependencies: - dependency-name: http-server dependency-type: direct:development update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- package-lock.json | 31 ++++++++----------------------- 1 file changed, 8 insertions(+), 23 deletions(-) diff --git a/package-lock.json b/package-lock.json index e879e7422..62e54c6a5 100644 --- a/package-lock.json +++ b/package-lock.json @@ -2580,15 +2580,6 @@ "color-support": "bin.js" } }, - "node_modules/colors": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/colors/-/colors-1.4.0.tgz", - "integrity": "sha512-a+UqTh4kgZg/SlGvfbzDHpgRu7AAQOmmqRHJnxhRZICKFUT91brVhNNt58CMWU9PsBbv3PDCZUHbVxuDiH2mtA==", - "dev": true, - "engines": { - "node": ">=0.1.90" - } - }, "node_modules/combined-stream": { "version": "1.0.8", "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", @@ -6089,13 +6080,13 @@ } }, "node_modules/http-server": { - "version": "14.0.0", - "resolved": "https://registry.npmjs.org/http-server/-/http-server-14.0.0.tgz", - "integrity": "sha512-XTePIXAo5x72bI8SlKFSqsg7UuSHwsOa4+RJIe56YeMUvfTvGDy7TxFkTEhfIRmM/Dnf6x29ut541ythSBZdkQ==", + "version": "14.1.0", + "resolved": "https://registry.npmjs.org/http-server/-/http-server-14.1.0.tgz", + "integrity": "sha512-5lYsIcZtf6pdR8tCtzAHTWrAveo4liUlJdWc7YafwK/maPgYHs+VNP6KpCClmUnSorJrARVMXqtT055zBv11Yg==", "dev": true, "dependencies": { "basic-auth": "^2.0.1", - "colors": "^1.4.0", + "chalk": "^4.1.2", "corser": "^2.0.1", "he": "^1.2.0", "html-encoding-sniffer": "^3.0.0", @@ -14400,12 +14391,6 @@ "integrity": "sha512-qiBjkpbMLO/HL68y+lh4q0/O1MZFj2RX6X/KmMa3+gJD3z+WwI1ZzDHysvqHGS3mP6mznPckpXmw1nI9cJjyRg==", "dev": true }, - "colors": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/colors/-/colors-1.4.0.tgz", - "integrity": "sha512-a+UqTh4kgZg/SlGvfbzDHpgRu7AAQOmmqRHJnxhRZICKFUT91brVhNNt58CMWU9PsBbv3PDCZUHbVxuDiH2mtA==", - "dev": true - }, "combined-stream": { "version": "1.0.8", "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", @@ -17242,13 +17227,13 @@ } }, "http-server": { - "version": "14.0.0", - "resolved": "https://registry.npmjs.org/http-server/-/http-server-14.0.0.tgz", - "integrity": "sha512-XTePIXAo5x72bI8SlKFSqsg7UuSHwsOa4+RJIe56YeMUvfTvGDy7TxFkTEhfIRmM/Dnf6x29ut541ythSBZdkQ==", + "version": "14.1.0", + "resolved": "https://registry.npmjs.org/http-server/-/http-server-14.1.0.tgz", + "integrity": "sha512-5lYsIcZtf6pdR8tCtzAHTWrAveo4liUlJdWc7YafwK/maPgYHs+VNP6KpCClmUnSorJrARVMXqtT055zBv11Yg==", "dev": true, "requires": { "basic-auth": "^2.0.1", - "colors": "^1.4.0", + "chalk": "^4.1.2", "corser": "^2.0.1", "he": "^1.2.0", "html-encoding-sniffer": "^3.0.0", From 050c89d8ebfbd4884a6e782e2576a93730cf8f3d Mon Sep 17 00:00:00 2001 From: Rachel Fenichel Date: Tue, 18 Jan 2022 17:34:27 -0800 Subject: [PATCH 038/128] chore: configure release-please as a bot, not an action (#5886) --- .github/release-please.yml | 6 ++++++ .github/workflows/release-please.yml | 15 --------------- .release-please-manifest.json | 2 +- 3 files changed, 7 insertions(+), 16 deletions(-) create mode 100644 .github/release-please.yml delete mode 100644 .github/workflows/release-please.yml diff --git a/.github/release-please.yml b/.github/release-please.yml new file mode 100644 index 000000000..0115689b2 --- /dev/null +++ b/.github/release-please.yml @@ -0,0 +1,6 @@ +primaryBranch: develop +releaseType: node +packageName: blockly +manifest: true +manifestConfig: release-please-config.json +manifestFile: .release-please-manifest.json diff --git a/.github/workflows/release-please.yml b/.github/workflows/release-please.yml deleted file mode 100644 index 6fc36aff0..000000000 --- a/.github/workflows/release-please.yml +++ /dev/null @@ -1,15 +0,0 @@ -on: - push: - branches: - - develop -name: release-please -jobs: - release-please: - runs-on: ubuntu-latest - steps: - - uses: GoogleCloudPlatform/release-please-action@v3.0.0 - with: - token: ${{ secrets.GITHUB_TOKEN }} - release-type: node - package-name: blockly - command: manifest diff --git a/.release-please-manifest.json b/.release-please-manifest.json index f3df3ba67..c6f67ad42 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - "package.json": "7.20211209.0" + ".": "7.20211209.0" } From 3ec70fd2b86107330e6c70b1f211e5045a25d3ad Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 18 Jan 2022 17:39:55 -0800 Subject: [PATCH 039/128] chore(deps): bump @wdio/selenium-standalone-service (#5878) Bumps [@wdio/selenium-standalone-service](https://github.com/webdriverio/webdriverio) from 7.16.6 to 7.16.13. - [Release notes](https://github.com/webdriverio/webdriverio/releases) - [Changelog](https://github.com/webdriverio/webdriverio/blob/main/CHANGELOG.md) - [Commits](https://github.com/webdriverio/webdriverio/compare/v7.16.6...v7.16.13) --- updated-dependencies: - dependency-name: "@wdio/selenium-standalone-service" dependency-type: direct:development update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- package-lock.json | 92 ++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 80 insertions(+), 12 deletions(-) diff --git a/package-lock.json b/package-lock.json index 62e54c6a5..75fbbeb1d 100644 --- a/package-lock.json +++ b/package-lock.json @@ -899,6 +899,7 @@ "resolved": "https://registry.npmjs.org/@wdio/config/-/config-7.16.3.tgz", "integrity": "sha512-YbpeZAeEncyJrsKxfAwjhNbDUf/ZrMB2Io3PYnH3RQjEEo5lYlO15aUt9uJx09W5h8hBPcrj7CfUC5yNkFZJhw==", "dev": true, + "peer": true, "dependencies": { "@wdio/logger": "7.16.0", "@wdio/types": "7.16.3", @@ -973,17 +974,17 @@ } }, "node_modules/@wdio/selenium-standalone-service": { - "version": "7.16.6", - "resolved": "https://registry.npmjs.org/@wdio/selenium-standalone-service/-/selenium-standalone-service-7.16.6.tgz", - "integrity": "sha512-KWoVzoOkOSnXlCNQj13yniaSJLbVPQJkytXam/MKy6CKsnQqeLt+6E3DvcdUhP+fRfvh5AzZrMNLer8Rv4hXhg==", + "version": "7.16.13", + "resolved": "https://registry.npmjs.org/@wdio/selenium-standalone-service/-/selenium-standalone-service-7.16.13.tgz", + "integrity": "sha512-xGKP0c1XrUXRzFtNIBOPVQlSLpfWQ7uxfXTLezrjmv3LfqGRnAo0iH0rpyn9qeEbOX1mURkbC+Jngc3jAx/cgw==", "dev": true, "dependencies": { "@types/fs-extra": "^9.0.1", - "@types/node": "^16.11.1", + "@types/node": "^17.0.4", "@types/selenium-standalone": "^7.0.0", - "@wdio/config": "7.16.3", + "@wdio/config": "7.16.13", "@wdio/logger": "7.16.0", - "@wdio/types": "7.16.3", + "@wdio/types": "7.16.13", "fs-extra": "^10.0.0", "selenium-standalone": "^8.0.3" }, @@ -994,11 +995,46 @@ "@wdio/cli": "^7.0.0" } }, + "node_modules/@wdio/selenium-standalone-service/node_modules/@types/node": { + "version": "17.0.8", + "resolved": "https://registry.npmjs.org/@types/node/-/node-17.0.8.tgz", + "integrity": "sha512-YofkM6fGv4gDJq78g4j0mMuGMkZVxZDgtU0JRdx6FgiJDG+0fY0GKVolOV8WqVmEhLCXkQRjwDdKyPxJp/uucg==", + "dev": true + }, + "node_modules/@wdio/selenium-standalone-service/node_modules/@wdio/config": { + "version": "7.16.13", + "resolved": "https://registry.npmjs.org/@wdio/config/-/config-7.16.13.tgz", + "integrity": "sha512-LSGoa83tWQIBppB+LeHjY40B9tuuvmDV1qdBLVXR1ROcOUWWz/oQP3NFLtLm3266LXoJUbwebzGcRIK1EcNk3Q==", + "dev": true, + "dependencies": { + "@wdio/logger": "7.16.0", + "@wdio/types": "7.16.13", + "deepmerge": "^4.0.0", + "glob": "^7.1.2" + }, + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/@wdio/selenium-standalone-service/node_modules/@wdio/types": { + "version": "7.16.13", + "resolved": "https://registry.npmjs.org/@wdio/types/-/types-7.16.13.tgz", + "integrity": "sha512-HIeXKCL+mUjyJxvnHSoaIo3NRgZLbeekyRIwo6USfd9qGlQ8dQ6fyCR3ZU9VqNz9j4+JIn+LRQ7imbz5SdnGbw==", + "dev": true, + "dependencies": { + "@types/node": "^17.0.4", + "got": "^11.8.1" + }, + "engines": { + "node": ">=12.0.0" + } + }, "node_modules/@wdio/types": { "version": "7.16.3", "resolved": "https://registry.npmjs.org/@wdio/types/-/types-7.16.3.tgz", "integrity": "sha512-iJLtJrOJZSJrXR1zseCkVWUFs477FngjWz2HTMfGHR69LzfmxC0RNagemjZuLTfhTqWp/FBbqaA/F+7xJdNKag==", "dev": true, + "peer": true, "dependencies": { "@types/node": "^16.11.1", "got": "^11.8.1" @@ -13094,6 +13130,7 @@ "resolved": "https://registry.npmjs.org/@wdio/config/-/config-7.16.3.tgz", "integrity": "sha512-YbpeZAeEncyJrsKxfAwjhNbDUf/ZrMB2Io3PYnH3RQjEEo5lYlO15aUt9uJx09W5h8hBPcrj7CfUC5yNkFZJhw==", "dev": true, + "peer": true, "requires": { "@wdio/logger": "7.16.0", "@wdio/types": "7.16.3", @@ -13152,19 +13189,49 @@ } }, "@wdio/selenium-standalone-service": { - "version": "7.16.6", - "resolved": "https://registry.npmjs.org/@wdio/selenium-standalone-service/-/selenium-standalone-service-7.16.6.tgz", - "integrity": "sha512-KWoVzoOkOSnXlCNQj13yniaSJLbVPQJkytXam/MKy6CKsnQqeLt+6E3DvcdUhP+fRfvh5AzZrMNLer8Rv4hXhg==", + "version": "7.16.13", + "resolved": "https://registry.npmjs.org/@wdio/selenium-standalone-service/-/selenium-standalone-service-7.16.13.tgz", + "integrity": "sha512-xGKP0c1XrUXRzFtNIBOPVQlSLpfWQ7uxfXTLezrjmv3LfqGRnAo0iH0rpyn9qeEbOX1mURkbC+Jngc3jAx/cgw==", "dev": true, "requires": { "@types/fs-extra": "^9.0.1", - "@types/node": "^16.11.1", + "@types/node": "^17.0.4", "@types/selenium-standalone": "^7.0.0", - "@wdio/config": "7.16.3", + "@wdio/config": "7.16.13", "@wdio/logger": "7.16.0", - "@wdio/types": "7.16.3", + "@wdio/types": "7.16.13", "fs-extra": "^10.0.0", "selenium-standalone": "^8.0.3" + }, + "dependencies": { + "@types/node": { + "version": "17.0.8", + "resolved": "https://registry.npmjs.org/@types/node/-/node-17.0.8.tgz", + "integrity": "sha512-YofkM6fGv4gDJq78g4j0mMuGMkZVxZDgtU0JRdx6FgiJDG+0fY0GKVolOV8WqVmEhLCXkQRjwDdKyPxJp/uucg==", + "dev": true + }, + "@wdio/config": { + "version": "7.16.13", + "resolved": "https://registry.npmjs.org/@wdio/config/-/config-7.16.13.tgz", + "integrity": "sha512-LSGoa83tWQIBppB+LeHjY40B9tuuvmDV1qdBLVXR1ROcOUWWz/oQP3NFLtLm3266LXoJUbwebzGcRIK1EcNk3Q==", + "dev": true, + "requires": { + "@wdio/logger": "7.16.0", + "@wdio/types": "7.16.13", + "deepmerge": "^4.0.0", + "glob": "^7.1.2" + } + }, + "@wdio/types": { + "version": "7.16.13", + "resolved": "https://registry.npmjs.org/@wdio/types/-/types-7.16.13.tgz", + "integrity": "sha512-HIeXKCL+mUjyJxvnHSoaIo3NRgZLbeekyRIwo6USfd9qGlQ8dQ6fyCR3ZU9VqNz9j4+JIn+LRQ7imbz5SdnGbw==", + "dev": true, + "requires": { + "@types/node": "^17.0.4", + "got": "^11.8.1" + } + } } }, "@wdio/types": { @@ -13172,6 +13239,7 @@ "resolved": "https://registry.npmjs.org/@wdio/types/-/types-7.16.3.tgz", "integrity": "sha512-iJLtJrOJZSJrXR1zseCkVWUFs477FngjWz2HTMfGHR69LzfmxC0RNagemjZuLTfhTqWp/FBbqaA/F+7xJdNKag==", "dev": true, + "peer": true, "requires": { "@types/node": "^16.11.1", "got": "^11.8.1" From bf0f4d94de87e631435f124c4565864d0220d932 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 18 Jan 2022 17:55:50 -0800 Subject: [PATCH 040/128] chore(deps): bump eslint from 8.6.0 to 8.7.0 (#5884) Bumps [eslint](https://github.com/eslint/eslint) from 8.6.0 to 8.7.0. - [Release notes](https://github.com/eslint/eslint/releases) - [Changelog](https://github.com/eslint/eslint/blob/main/CHANGELOG.md) - [Commits](https://github.com/eslint/eslint/compare/v8.6.0...v8.7.0) --- updated-dependencies: - dependency-name: eslint dependency-type: direct:development update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- package-lock.json | 74 ++++++++++++++++++++--------------------------- 1 file changed, 31 insertions(+), 43 deletions(-) diff --git a/package-lock.json b/package-lock.json index 75fbbeb1d..c9af2684a 100644 --- a/package-lock.json +++ b/package-lock.json @@ -3477,18 +3477,6 @@ "once": "^1.4.0" } }, - "node_modules/enquirer": { - "version": "2.3.6", - "resolved": "https://registry.npmjs.org/enquirer/-/enquirer-2.3.6.tgz", - "integrity": "sha512-yjNnPr315/FjS4zIsUxYguYUPP2e1NK4d7E7ZOLiyYCcbFBiTMyID+2wvm2w6+pZ/odMA7cRkjhsPbltwBOrLg==", - "dev": true, - "dependencies": { - "ansi-colors": "^4.1.1" - }, - "engines": { - "node": ">=8.6" - } - }, "node_modules/error-ex": { "version": "1.3.2", "resolved": "https://registry.npmjs.org/error-ex/-/error-ex-1.3.2.tgz", @@ -3641,9 +3629,9 @@ } }, "node_modules/eslint": { - "version": "8.6.0", - "resolved": "https://registry.npmjs.org/eslint/-/eslint-8.6.0.tgz", - "integrity": "sha512-UvxdOJ7mXFlw7iuHZA4jmzPaUqIw54mZrv+XPYKNbKdLR0et4rf60lIZUU9kiNtnzzMzGWxMV+tQ7uG7JG8DPw==", + "version": "8.7.0", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-8.7.0.tgz", + "integrity": "sha512-ifHYzkBGrzS2iDU7KjhCAVMGCvF6M3Xfs8X8b37cgrUlDt6bWRTpRh6T/gtSXv1HJ/BUGgmjvNvOEGu85Iif7w==", "dev": true, "dependencies": { "@eslint/eslintrc": "^1.0.5", @@ -3653,11 +3641,10 @@ "cross-spawn": "^7.0.2", "debug": "^4.3.2", "doctrine": "^3.0.0", - "enquirer": "^2.3.5", "escape-string-regexp": "^4.0.0", "eslint-scope": "^7.1.0", "eslint-utils": "^3.0.0", - "eslint-visitor-keys": "^3.1.0", + "eslint-visitor-keys": "^3.2.0", "espree": "^9.3.0", "esquery": "^1.4.0", "esutils": "^2.0.2", @@ -3666,7 +3653,7 @@ "functional-red-black-tree": "^1.0.1", "glob-parent": "^6.0.1", "globals": "^13.6.0", - "ignore": "^4.0.6", + "ignore": "^5.2.0", "import-fresh": "^3.0.0", "imurmurhash": "^0.1.4", "is-glob": "^4.0.0", @@ -3677,9 +3664,7 @@ "minimatch": "^3.0.4", "natural-compare": "^1.4.0", "optionator": "^0.9.1", - "progress": "^2.0.0", "regexpp": "^3.2.0", - "semver": "^7.2.1", "strip-ansi": "^6.0.1", "strip-json-comments": "^3.1.0", "text-table": "^0.2.0", @@ -3757,9 +3742,9 @@ } }, "node_modules/eslint-visitor-keys": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.1.0.tgz", - "integrity": "sha512-yWJFpu4DtjsWKkt5GeNBBuZMlNcYVs6vRCLoCVEJrTjaSB6LC98gFipNK/erM2Heg/E8mIK+hXG/pJMLK+eRZA==", + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.2.0.tgz", + "integrity": "sha512-IOzT0X126zn7ALX0dwFiUQEdsfzrm4+ISsQS8nukaJXwEyYKRSnEIIDULYg1mCtGp7UUXgfGl7BIolXREQK+XQ==", "dev": true, "engines": { "node": "^12.22.0 || ^14.17.0 || >=16.0.0" @@ -3777,6 +3762,15 @@ "node": ">=10.13.0" } }, + "node_modules/eslint/node_modules/ignore": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.2.0.tgz", + "integrity": "sha512-CmxgYGiEPCLhfLnpPp1MoRmifwEIOgjcHXxOBjv7mY96c+eWScsOP9c112ZyLdWHi0FxHjI+4uVhKYp/gcdRmQ==", + "dev": true, + "engines": { + "node": ">= 4" + } + }, "node_modules/espree": { "version": "9.3.0", "resolved": "https://registry.npmjs.org/espree/-/espree-9.3.0.tgz", @@ -15169,15 +15163,6 @@ "once": "^1.4.0" } }, - "enquirer": { - "version": "2.3.6", - "resolved": "https://registry.npmjs.org/enquirer/-/enquirer-2.3.6.tgz", - "integrity": "sha512-yjNnPr315/FjS4zIsUxYguYUPP2e1NK4d7E7ZOLiyYCcbFBiTMyID+2wvm2w6+pZ/odMA7cRkjhsPbltwBOrLg==", - "dev": true, - "requires": { - "ansi-colors": "^4.1.1" - } - }, "error-ex": { "version": "1.3.2", "resolved": "https://registry.npmjs.org/error-ex/-/error-ex-1.3.2.tgz", @@ -15299,9 +15284,9 @@ } }, "eslint": { - "version": "8.6.0", - "resolved": "https://registry.npmjs.org/eslint/-/eslint-8.6.0.tgz", - "integrity": "sha512-UvxdOJ7mXFlw7iuHZA4jmzPaUqIw54mZrv+XPYKNbKdLR0et4rf60lIZUU9kiNtnzzMzGWxMV+tQ7uG7JG8DPw==", + "version": "8.7.0", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-8.7.0.tgz", + "integrity": "sha512-ifHYzkBGrzS2iDU7KjhCAVMGCvF6M3Xfs8X8b37cgrUlDt6bWRTpRh6T/gtSXv1HJ/BUGgmjvNvOEGu85Iif7w==", "dev": true, "requires": { "@eslint/eslintrc": "^1.0.5", @@ -15311,11 +15296,10 @@ "cross-spawn": "^7.0.2", "debug": "^4.3.2", "doctrine": "^3.0.0", - "enquirer": "^2.3.5", "escape-string-regexp": "^4.0.0", "eslint-scope": "^7.1.0", "eslint-utils": "^3.0.0", - "eslint-visitor-keys": "^3.1.0", + "eslint-visitor-keys": "^3.2.0", "espree": "^9.3.0", "esquery": "^1.4.0", "esutils": "^2.0.2", @@ -15324,7 +15308,7 @@ "functional-red-black-tree": "^1.0.1", "glob-parent": "^6.0.1", "globals": "^13.6.0", - "ignore": "^4.0.6", + "ignore": "^5.2.0", "import-fresh": "^3.0.0", "imurmurhash": "^0.1.4", "is-glob": "^4.0.0", @@ -15335,9 +15319,7 @@ "minimatch": "^3.0.4", "natural-compare": "^1.4.0", "optionator": "^0.9.1", - "progress": "^2.0.0", "regexpp": "^3.2.0", - "semver": "^7.2.1", "strip-ansi": "^6.0.1", "strip-json-comments": "^3.1.0", "text-table": "^0.2.0", @@ -15352,6 +15334,12 @@ "requires": { "is-glob": "^4.0.3" } + }, + "ignore": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.2.0.tgz", + "integrity": "sha512-CmxgYGiEPCLhfLnpPp1MoRmifwEIOgjcHXxOBjv7mY96c+eWScsOP9c112ZyLdWHi0FxHjI+4uVhKYp/gcdRmQ==", + "dev": true } } }, @@ -15398,9 +15386,9 @@ } }, "eslint-visitor-keys": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.1.0.tgz", - "integrity": "sha512-yWJFpu4DtjsWKkt5GeNBBuZMlNcYVs6vRCLoCVEJrTjaSB6LC98gFipNK/erM2Heg/E8mIK+hXG/pJMLK+eRZA==", + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.2.0.tgz", + "integrity": "sha512-IOzT0X126zn7ALX0dwFiUQEdsfzrm4+ISsQS8nukaJXwEyYKRSnEIIDULYg1mCtGp7UUXgfGl7BIolXREQK+XQ==", "dev": true }, "espree": { From f0b10776eb0657a5446adcfc62ad13f419c14271 Mon Sep 17 00:00:00 2001 From: alschmiedt Date: Fri, 21 Jan 2022 14:57:32 -0800 Subject: [PATCH 041/128] refactor!: remove unused constants from internalConstants (#5889) --- core/blockly.js | 5 ----- core/browser_events.js | 27 +++++++++++++++++++++----- core/internal_constants.js | 38 ------------------------------------- core/rendered_connection.js | 12 +++++++++--- core/touch.js | 9 +++++++-- core/workspace_audio.js | 12 +++++++++--- tests/deps.js | 4 ++-- 7 files changed, 49 insertions(+), 58 deletions(-) diff --git a/core/blockly.js b/core/blockly.js index b916abd6e..4ea66fdbf 100644 --- a/core/blockly.js +++ b/core/blockly.js @@ -655,8 +655,6 @@ const bindEventWithChecks_ = function( exports.bindEventWithChecks_ = bindEventWithChecks_; // Aliases to allow external code to access these values for legacy reasons. -exports.LINE_MODE_MULTIPLIER = internalConstants.LINE_MODE_MULTIPLIER; -exports.PAGE_MODE_MULTIPLIER = internalConstants.PAGE_MODE_MULTIPLIER; exports.DRAG_RADIUS = internalConstants.DRAG_RADIUS; exports.FLYOUT_DRAG_RADIUS = internalConstants.FLYOUT_DRAG_RADIUS; exports.SNAP_RADIUS = internalConstants.SNAP_RADIUS; @@ -664,10 +662,7 @@ exports.CONNECTING_SNAP_RADIUS = internalConstants.CONNECTING_SNAP_RADIUS; exports.CURRENT_CONNECTION_PREFERENCE = internalConstants.CURRENT_CONNECTION_PREFERENCE; exports.BUMP_DELAY = internalConstants.BUMP_DELAY; -exports.BUMP_RANDOMNESS = internalConstants.BUMP_RANDOMNESS; exports.COLLAPSE_CHARS = internalConstants.COLLAPSE_CHARS; -exports.LONGPRESS = internalConstants.LONGPRESS; -exports.SOUND_LIMIT = internalConstants.SOUND_LIMIT; exports.DRAG_STACK = internalConstants.DRAG_STACK; exports.SPRITE = internalConstants.SPRITE; exports.DRAG_NONE = internalConstants.DRAG_NONE; diff --git a/core/browser_events.js b/core/browser_events.js index c4f16a4df..3a33cbbcc 100644 --- a/core/browser_events.js +++ b/core/browser_events.js @@ -16,7 +16,6 @@ goog.module('Blockly.browserEvents'); const Touch = goog.require('Blockly.Touch'); -const internalConstants = goog.require('Blockly.internalConstants'); const userAgent = goog.require('Blockly.utils.userAgent'); const {globalThis} = goog.require('Blockly.utils.global'); @@ -30,6 +29,24 @@ const {globalThis} = goog.require('Blockly.utils.global'); let Data; exports.Data = Data; +/** + * The multiplier for scroll wheel deltas using the line delta mode. + * See https://developer.mozilla.org/en-US/docs/Web/API/WheelEvent/deltaMode + * for more information on deltaMode. + * @type {number} + * @const + */ +const LINE_MODE_MULTIPLIER = 40; + +/** + * The multiplier for scroll wheel deltas using the page delta mode. + * See https://developer.mozilla.org/en-US/docs/Web/API/WheelEvent/deltaMode + * for more information on deltaMode. + * @type {number} + * @const + */ +const PAGE_MODE_MULTIPLIER = 125; + /** * Bind an event handler that can be ignored if it is not part of the active * touch stream. @@ -254,13 +271,13 @@ const getScrollDeltaPixels = function(e) { return {x: e.deltaX, y: e.deltaY}; case 0x01: // Line mode. return { - x: e.deltaX * internalConstants.LINE_MODE_MULTIPLIER, - y: e.deltaY * internalConstants.LINE_MODE_MULTIPLIER, + x: e.deltaX * LINE_MODE_MULTIPLIER, + y: e.deltaY * LINE_MODE_MULTIPLIER, }; case 0x02: // Page mode. return { - x: e.deltaX * internalConstants.PAGE_MODE_MULTIPLIER, - y: e.deltaY * internalConstants.PAGE_MODE_MULTIPLIER, + x: e.deltaX * PAGE_MODE_MULTIPLIER, + y: e.deltaY * PAGE_MODE_MULTIPLIER, }; } }; diff --git a/core/internal_constants.js b/core/internal_constants.js index d5952eb05..e7d0d97a6 100644 --- a/core/internal_constants.js +++ b/core/internal_constants.js @@ -21,22 +21,6 @@ goog.module('Blockly.internalConstants'); const {ConnectionType} = goog.require('Blockly.ConnectionType'); -/** - * The multiplier for scroll wheel deltas using the line delta mode. - * @type {number} - * @alias Blockly.internalConstants.LINE_MODE_MULTIPLIER - */ -const LINE_MODE_MULTIPLIER = 40; -exports.LINE_MODE_MULTIPLIER = LINE_MODE_MULTIPLIER; - -/** - * The multiplier for scroll wheel deltas using the page delta mode. - * @type {number} - * @alias Blockly.internalConstants.PAGE_MODE_MULTIPLIER - */ -const PAGE_MODE_MULTIPLIER = 125; -exports.PAGE_MODE_MULTIPLIER = PAGE_MODE_MULTIPLIER; - /** * Number of pixels the mouse must move before a drag starts. * @alias Blockly.internalConstants.DRAG_RADIUS @@ -84,13 +68,6 @@ exports.CURRENT_CONNECTION_PREFERENCE = CURRENT_CONNECTION_PREFERENCE; const BUMP_DELAY = 250; exports.BUMP_DELAY = BUMP_DELAY; -/** - * Maximum randomness in workspace units for bumping a block. - * @alias Blockly.internalConstants.BUMP_RANDOMNESS - */ -const BUMP_RANDOMNESS = 10; -exports.BUMP_RANDOMNESS = BUMP_RANDOMNESS; - /** * Number of characters to truncate a collapsed block to. * @alias Blockly.internalConstants.COLLAPSE_CHARS @@ -98,21 +75,6 @@ exports.BUMP_RANDOMNESS = BUMP_RANDOMNESS; const COLLAPSE_CHARS = 30; exports.COLLAPSE_CHARS = COLLAPSE_CHARS; -/** - * Length in ms for a touch to become a long press. - * @alias Blockly.internalConstants.LONGPRESS - */ -const LONGPRESS = 750; -exports.LONGPRESS = LONGPRESS; - -/** - * Prevent a sound from playing if another sound preceded it within this many - * milliseconds. - * @alias Blockly.internalConstants.SOUND_LIMIT - */ -const SOUND_LIMIT = 100; -exports.SOUND_LIMIT = SOUND_LIMIT; - /** * When dragging a block out of a stack, split the stack in two (true), or drag * out the block healing the stack (false). diff --git a/core/rendered_connection.js b/core/rendered_connection.js index 5f52a54e1..08d6529ec 100644 --- a/core/rendered_connection.js +++ b/core/rendered_connection.js @@ -101,6 +101,12 @@ RenderedConnection.TrackedState = { TRACKED: 1, }; +/** + * Maximum randomness in workspace units for bumping a block. + * @const + */ +const BUMP_RANDOMNESS = 10; + /** * Dispose of this connection. Remove it from the database (if it is * tracked) and call the super-function to deal with connected blocks. @@ -181,10 +187,10 @@ RenderedConnection.prototype.bumpAwayFrom = function(staticConnection) { const selected = common.getSelected() == rootBlock; selected || rootBlock.addSelect(); let dx = (staticConnection.x + internalConstants.SNAP_RADIUS + - Math.floor(Math.random() * internalConstants.BUMP_RANDOMNESS)) - + Math.floor(Math.random() * BUMP_RANDOMNESS)) - this.x; let dy = (staticConnection.y + internalConstants.SNAP_RADIUS + - Math.floor(Math.random() * internalConstants.BUMP_RANDOMNESS)) - + Math.floor(Math.random() * BUMP_RANDOMNESS)) - this.y; if (reverse) { // When reversing a bump due to an uneditable block, bump up. @@ -192,7 +198,7 @@ RenderedConnection.prototype.bumpAwayFrom = function(staticConnection) { } if (rootBlock.RTL) { dx = (staticConnection.x - internalConstants.SNAP_RADIUS - - Math.floor(Math.random() * internalConstants.BUMP_RANDOMNESS)) - + Math.floor(Math.random() * BUMP_RANDOMNESS)) - this.x; } rootBlock.moveBy(dx, dy); diff --git a/core/touch.js b/core/touch.js index b977d05af..b0eb0b347 100644 --- a/core/touch.js +++ b/core/touch.js @@ -15,13 +15,18 @@ */ goog.module('Blockly.Touch'); -const internalConstants = goog.require('Blockly.internalConstants'); const utilsString = goog.require('Blockly.utils.string'); /* eslint-disable-next-line no-unused-vars */ const {Gesture} = goog.requireType('Blockly.Gesture'); const {globalThis} = goog.require('Blockly.utils.global'); +/** + * Length in ms for a touch to become a long press. + * @const + */ +const LONGPRESS = 750; + /** * Whether touch is enabled in the browser. * Copied from Closure's goog.events.BrowserFeature.TOUCH_ENABLED @@ -107,7 +112,7 @@ const longStart = function(e, gesture) { if (gesture) { gesture.handleRightClick(e); } - }, internalConstants.LONGPRESS); + }, LONGPRESS); }; exports.longStart = longStart; diff --git a/core/workspace_audio.js b/core/workspace_audio.js index 1be8bb5b7..4b06ee8cd 100644 --- a/core/workspace_audio.js +++ b/core/workspace_audio.js @@ -17,13 +17,19 @@ */ goog.module('Blockly.WorkspaceAudio'); -const internalConstants = goog.require('Blockly.internalConstants'); const userAgent = goog.require('Blockly.utils.userAgent'); /* eslint-disable-next-line no-unused-vars */ const {WorkspaceSvg} = goog.requireType('Blockly.WorkspaceSvg'); const {globalThis} = goog.require('Blockly.utils.global'); +/** + * Prevent a sound from playing if another sound preceded it within this many + * milliseconds. + * @const + */ +const SOUND_LIMIT = 100; + /** * Class for loading, storing, and playing audio for a workspace. * @alias Blockly.WorkspaceAudio @@ -55,6 +61,7 @@ class WorkspaceAudio { */ this.lastSound_ = null; } + /** * Dispose of this audio manager. * @package @@ -137,8 +144,7 @@ class WorkspaceAudio { if (sound) { // Don't play one sound on top of another. const now = new Date; - if (this.lastSound_ !== null && - now - this.lastSound_ < internalConstants.SOUND_LIMIT) { + if (this.lastSound_ !== null && now - this.lastSound_ < SOUND_LIMIT) { return; } this.lastSound_ = now; diff --git a/tests/deps.js b/tests/deps.js index d244eaf47..4d422f483 100644 --- a/tests/deps.js +++ b/tests/deps.js @@ -222,7 +222,7 @@ goog.addDependency('../../core/toolbox/separator.js', ['Blockly.ToolboxSeparator goog.addDependency('../../core/toolbox/toolbox.js', ['Blockly.Toolbox'], ['Blockly.BlockSvg', 'Blockly.CollapsibleToolboxCategory', 'Blockly.ComponentManager', 'Blockly.Css', 'Blockly.DeleteArea', 'Blockly.Events.ToolboxItemSelect', 'Blockly.Events.utils', 'Blockly.IAutoHideable', 'Blockly.IKeyboardAccessible', 'Blockly.IStyleable', 'Blockly.IToolbox', 'Blockly.Options', 'Blockly.Touch', 'Blockly.browserEvents', 'Blockly.common', 'Blockly.registry', 'Blockly.utils.KeyCodes', 'Blockly.utils.Rect', 'Blockly.utils.aria', 'Blockly.utils.dom', 'Blockly.utils.object', 'Blockly.utils.toolbox'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/toolbox/toolbox_item.js', ['Blockly.ToolboxItem'], ['Blockly.IToolboxItem', 'Blockly.utils.idGenerator'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/tooltip.js', ['Blockly.Tooltip'], ['Blockly.browserEvents', 'Blockly.common', 'Blockly.utils.deprecation', 'Blockly.utils.string'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/touch.js', ['Blockly.Touch'], ['Blockly.internalConstants', 'Blockly.utils.global', 'Blockly.utils.string'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/touch.js', ['Blockly.Touch'], ['Blockly.utils.global', 'Blockly.utils.string'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/touch_gesture.js', ['Blockly.TouchGesture'], ['Blockly.Gesture', 'Blockly.Touch', 'Blockly.browserEvents', 'Blockly.utils.Coordinate', 'Blockly.utils.object'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/trashcan.js', ['Blockly.Trashcan'], ['Blockly.ComponentManager', 'Blockly.DeleteArea', 'Blockly.Events.TrashcanOpen', 'Blockly.Events.utils', 'Blockly.IAutoHideable', 'Blockly.IPositionable', 'Blockly.Options', 'Blockly.browserEvents', 'Blockly.internalConstants', 'Blockly.registry', 'Blockly.uiPosition', 'Blockly.utils.Rect', 'Blockly.utils.Size', 'Blockly.utils.Svg', 'Blockly.utils.dom', 'Blockly.utils.object', 'Blockly.utils.toolbox'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/utils.js', ['Blockly.utils'], ['Blockly.Extensions', 'Blockly.browserEvents', 'Blockly.common', 'Blockly.utils.Coordinate', 'Blockly.utils.KeyCodes', 'Blockly.utils.Metrics', 'Blockly.utils.Rect', 'Blockly.utils.Size', 'Blockly.utils.Svg', 'Blockly.utils.aria', 'Blockly.utils.array', 'Blockly.utils.colour', 'Blockly.utils.deprecation', 'Blockly.utils.dom', 'Blockly.utils.global', 'Blockly.utils.idGenerator', 'Blockly.utils.math', 'Blockly.utils.object', 'Blockly.utils.parsing', 'Blockly.utils.string', 'Blockly.utils.style', 'Blockly.utils.svgMath', 'Blockly.utils.svgPaths', 'Blockly.utils.toolbox', 'Blockly.utils.userAgent', 'Blockly.utils.xml'], {'lang': 'es6', 'module': 'goog'}); @@ -256,7 +256,7 @@ goog.addDependency('../../core/variables_dynamic.js', ['Blockly.VariablesDynamic goog.addDependency('../../core/warning.js', ['Blockly.Warning'], ['Blockly.Bubble', 'Blockly.Events.BubbleOpen', 'Blockly.Events.utils', 'Blockly.Icon', 'Blockly.utils.Svg', 'Blockly.utils.dom', 'Blockly.utils.object'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/widgetdiv.js', ['Blockly.WidgetDiv'], ['Blockly.common', 'Blockly.utils.deprecation', 'Blockly.utils.dom'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/workspace.js', ['Blockly.Workspace'], ['Blockly.ConnectionChecker', 'Blockly.Events.utils', 'Blockly.IASTNodeLocation', 'Blockly.Options', 'Blockly.VariableMap', 'Blockly.registry', 'Blockly.utils.array', 'Blockly.utils.idGenerator', 'Blockly.utils.math'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/workspace_audio.js', ['Blockly.WorkspaceAudio'], ['Blockly.internalConstants', 'Blockly.utils.global', 'Blockly.utils.userAgent'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/workspace_audio.js', ['Blockly.WorkspaceAudio'], ['Blockly.utils.global', 'Blockly.utils.userAgent'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/workspace_comment.js', ['Blockly.WorkspaceComment'], ['Blockly.Events.CommentChange', 'Blockly.Events.CommentCreate', 'Blockly.Events.CommentDelete', 'Blockly.Events.CommentMove', 'Blockly.Events.utils', 'Blockly.utils.Coordinate', 'Blockly.utils.idGenerator', 'Blockly.utils.xml'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/workspace_comment_svg.js', ['Blockly.WorkspaceCommentSvg'], ['Blockly.ContextMenu', 'Blockly.Css', 'Blockly.Events.CommentCreate', 'Blockly.Events.CommentDelete', 'Blockly.Events.CommentMove', 'Blockly.Events.Selected', 'Blockly.Events.utils', 'Blockly.IBoundedElement', 'Blockly.IBubble', 'Blockly.ICopyable', 'Blockly.Touch', 'Blockly.WorkspaceComment', 'Blockly.browserEvents', 'Blockly.common', 'Blockly.utils.Coordinate', 'Blockly.utils.Rect', 'Blockly.utils.Svg', 'Blockly.utils.dom', 'Blockly.utils.object', 'Blockly.utils.svgMath'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/workspace_drag_surface_svg.js', ['Blockly.WorkspaceDragSurfaceSvg'], ['Blockly.utils.Svg', 'Blockly.utils.dom', 'Blockly.utils.svgMath'], {'lang': 'es6', 'module': 'goog'}); From 004d12e48728c8ff3d225ff14df6c490d63e1a1c Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 24 Jan 2022 09:08:10 -0800 Subject: [PATCH 042/128] chore(deps): bump typescript from 4.5.4 to 4.5.5 (#5895) Bumps [typescript](https://github.com/Microsoft/TypeScript) from 4.5.4 to 4.5.5. - [Release notes](https://github.com/Microsoft/TypeScript/releases) - [Commits](https://github.com/Microsoft/TypeScript/compare/v4.5.4...v4.5.5) --- updated-dependencies: - dependency-name: typescript dependency-type: direct:development update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- package-lock.json | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/package-lock.json b/package-lock.json index c9af2684a..8c6ca928a 100644 --- a/package-lock.json +++ b/package-lock.json @@ -11405,9 +11405,9 @@ "dev": true }, "node_modules/typescript": { - "version": "4.5.4", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-4.5.4.tgz", - "integrity": "sha512-VgYs2A2QIRuGphtzFV7aQJduJ2gyfTljngLzjpfW9FoYZF6xuw1W0vW9ghCKLfcWrCFxK81CSGRAvS1pn4fIUg==", + "version": "4.5.5", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-4.5.5.tgz", + "integrity": "sha512-TCTIul70LyWe6IJWT8QSYeA54WQe8EjQFU4wY52Fasj5UKx88LNYKCgBEHcOMOrFF1rKGbD8v/xcNWVUq9SymA==", "dev": true, "bin": { "tsc": "bin/tsc", @@ -21548,9 +21548,9 @@ "dev": true }, "typescript": { - "version": "4.5.4", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-4.5.4.tgz", - "integrity": "sha512-VgYs2A2QIRuGphtzFV7aQJduJ2gyfTljngLzjpfW9FoYZF6xuw1W0vW9ghCKLfcWrCFxK81CSGRAvS1pn4fIUg==", + "version": "4.5.5", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-4.5.5.tgz", + "integrity": "sha512-TCTIul70LyWe6IJWT8QSYeA54WQe8EjQFU4wY52Fasj5UKx88LNYKCgBEHcOMOrFF1rKGbD8v/xcNWVUq9SymA==", "dev": true }, "ua-parser-js": { From e3207ff3bbe7e5342e89d75440e8375da614b01d Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 24 Jan 2022 09:09:03 -0800 Subject: [PATCH 043/128] chore(deps): bump webdriverio from 7.16.12 to 7.16.13 (#5883) Bumps [webdriverio](https://github.com/webdriverio/webdriverio) from 7.16.12 to 7.16.13. - [Release notes](https://github.com/webdriverio/webdriverio/releases) - [Changelog](https://github.com/webdriverio/webdriverio/blob/main/CHANGELOG.md) - [Commits](https://github.com/webdriverio/webdriverio/compare/v7.16.12...v7.16.13) --- updated-dependencies: - dependency-name: webdriverio dependency-type: direct:development update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- package-lock.json | 380 ++++++++++++++++++++++++++-------------------- 1 file changed, 214 insertions(+), 166 deletions(-) diff --git a/package-lock.json b/package-lock.json index 8c6ca928a..2eaedc7ee 100644 --- a/package-lock.json +++ b/package-lock.json @@ -935,24 +935,30 @@ } }, "node_modules/@wdio/repl": { - "version": "7.16.11", - "resolved": "https://registry.npmjs.org/@wdio/repl/-/repl-7.16.11.tgz", - "integrity": "sha512-wcKkb8L4VmotiE00wxn+RybG5FIUu4Ll7VvLM+DRd9TqEs1IEYwqKLaZKEP1lo/O2nKdcYFHtiAYZ9hon9947Q==", + "version": "7.16.13", + "resolved": "https://registry.npmjs.org/@wdio/repl/-/repl-7.16.13.tgz", + "integrity": "sha512-XWh3dzp6U8LLL4cNGWFra+quVyXZ25Ym38zpsBVtV0/z5NCHJmjRS4ytyvvkzbQ8SyqQ7Y3G8MjfGNi2sBNkIQ==", "dev": true, "dependencies": { - "@wdio/utils": "7.16.11" + "@wdio/utils": "7.16.13" }, "engines": { "node": ">=12.0.0" } }, + "node_modules/@wdio/repl/node_modules/@types/node": { + "version": "17.0.10", + "resolved": "https://registry.npmjs.org/@types/node/-/node-17.0.10.tgz", + "integrity": "sha512-S/3xB4KzyFxYGCppyDt68yzBU9ysL88lSdIah4D6cptdcltc4NCPCAMc0+PCpg/lLIyC7IPvj2Z52OJWeIUkog==", + "dev": true + }, "node_modules/@wdio/repl/node_modules/@wdio/types": { - "version": "7.16.11", - "resolved": "https://registry.npmjs.org/@wdio/types/-/types-7.16.11.tgz", - "integrity": "sha512-OFVTFEB6qdG84Y+cOWIacV0loGMgq2SF/rGGlGxai89V3UQxzCFTYVoAx6odAuSNZ37wmfWCykyAR/lAlMItoQ==", + "version": "7.16.13", + "resolved": "https://registry.npmjs.org/@wdio/types/-/types-7.16.13.tgz", + "integrity": "sha512-HIeXKCL+mUjyJxvnHSoaIo3NRgZLbeekyRIwo6USfd9qGlQ8dQ6fyCR3ZU9VqNz9j4+JIn+LRQ7imbz5SdnGbw==", "dev": true, "dependencies": { - "@types/node": "^16.11.1", + "@types/node": "^17.0.4", "got": "^11.8.1" }, "engines": { @@ -960,13 +966,13 @@ } }, "node_modules/@wdio/repl/node_modules/@wdio/utils": { - "version": "7.16.11", - "resolved": "https://registry.npmjs.org/@wdio/utils/-/utils-7.16.11.tgz", - "integrity": "sha512-qeXHREZJ7mz3C2cWGOmFG6MS6njp1js4f8zca3iqxaorWshwkrlNsps3B1iTHfkvK6oWnmc2Q0o5CrtLZl0LkA==", + "version": "7.16.13", + "resolved": "https://registry.npmjs.org/@wdio/utils/-/utils-7.16.13.tgz", + "integrity": "sha512-O6D89Ghtm5XtTv4DPKvCBKZOZYNONIcBM5/hmdr3V9mzVrTFq8Q3uE8pmmq303Oh91KcoN8Em5zoAG7Zpc5tRg==", "dev": true, "dependencies": { "@wdio/logger": "7.16.0", - "@wdio/types": "7.16.11", + "@wdio/types": "7.16.13", "p-iteration": "^1.1.8" }, "engines": { @@ -3239,18 +3245,18 @@ } }, "node_modules/devtools": { - "version": "7.16.12", - "resolved": "https://registry.npmjs.org/devtools/-/devtools-7.16.12.tgz", - "integrity": "sha512-gKe2DV1VkcZ4omTEss3cTeVg/ZmAUkJArAQp22ceDEbeE6AYYDeCpFDlZmbVgsjMxh+gY2mU5IWQlRIY/7Vyrg==", + "version": "7.16.13", + "resolved": "https://registry.npmjs.org/devtools/-/devtools-7.16.13.tgz", + "integrity": "sha512-jm/DL5tlOUUMe0pUgahDqixw3z+NANLN6DYDeZPFv7z0CBtmnaTyOe2zbT0apLxCBpi800VeXaISVZwmKE2NiQ==", "dev": true, "dependencies": { - "@types/node": "^16.11.1", + "@types/node": "^17.0.4", "@types/ua-parser-js": "^0.7.33", - "@wdio/config": "7.16.11", + "@wdio/config": "7.16.13", "@wdio/logger": "7.16.0", "@wdio/protocols": "7.16.7", - "@wdio/types": "7.16.11", - "@wdio/utils": "7.16.11", + "@wdio/types": "7.16.13", + "@wdio/utils": "7.16.13", "chrome-launcher": "^0.15.0", "edge-paths": "^2.1.0", "puppeteer-core": "^13.0.0", @@ -3263,19 +3269,25 @@ } }, "node_modules/devtools-protocol": { - "version": "0.0.948846", - "resolved": "https://registry.npmjs.org/devtools-protocol/-/devtools-protocol-0.0.948846.tgz", - "integrity": "sha512-5fGyt9xmMqUl2VI7+rnUkKCiAQIpLns8sfQtTENy5L70ktbNw0Z3TFJ1JoFNYdx/jffz4YXU45VF75wKZD7sZQ==", + "version": "0.0.953906", + "resolved": "https://registry.npmjs.org/devtools-protocol/-/devtools-protocol-0.0.953906.tgz", + "integrity": "sha512-Z2vAafCNnl0Iw/u7TUjqOXW1sOhAMDOviflmUoUIxfq2rgfsoCO3qruB/LUJCdqF9aTJ32DUjXyMsX3+if6kDQ==", + "dev": true + }, + "node_modules/devtools/node_modules/@types/node": { + "version": "17.0.10", + "resolved": "https://registry.npmjs.org/@types/node/-/node-17.0.10.tgz", + "integrity": "sha512-S/3xB4KzyFxYGCppyDt68yzBU9ysL88lSdIah4D6cptdcltc4NCPCAMc0+PCpg/lLIyC7IPvj2Z52OJWeIUkog==", "dev": true }, "node_modules/devtools/node_modules/@wdio/config": { - "version": "7.16.11", - "resolved": "https://registry.npmjs.org/@wdio/config/-/config-7.16.11.tgz", - "integrity": "sha512-sIk9FINQfXohuDONb8RA1uv+29XvUw6OBHfaaU7/c9gfKiOWiRczdfiLqfySZRwYgEgNhzCw5vHIogTry1h+xQ==", + "version": "7.16.13", + "resolved": "https://registry.npmjs.org/@wdio/config/-/config-7.16.13.tgz", + "integrity": "sha512-LSGoa83tWQIBppB+LeHjY40B9tuuvmDV1qdBLVXR1ROcOUWWz/oQP3NFLtLm3266LXoJUbwebzGcRIK1EcNk3Q==", "dev": true, "dependencies": { "@wdio/logger": "7.16.0", - "@wdio/types": "7.16.11", + "@wdio/types": "7.16.13", "deepmerge": "^4.0.0", "glob": "^7.1.2" }, @@ -3284,12 +3296,12 @@ } }, "node_modules/devtools/node_modules/@wdio/types": { - "version": "7.16.11", - "resolved": "https://registry.npmjs.org/@wdio/types/-/types-7.16.11.tgz", - "integrity": "sha512-OFVTFEB6qdG84Y+cOWIacV0loGMgq2SF/rGGlGxai89V3UQxzCFTYVoAx6odAuSNZ37wmfWCykyAR/lAlMItoQ==", + "version": "7.16.13", + "resolved": "https://registry.npmjs.org/@wdio/types/-/types-7.16.13.tgz", + "integrity": "sha512-HIeXKCL+mUjyJxvnHSoaIo3NRgZLbeekyRIwo6USfd9qGlQ8dQ6fyCR3ZU9VqNz9j4+JIn+LRQ7imbz5SdnGbw==", "dev": true, "dependencies": { - "@types/node": "^16.11.1", + "@types/node": "^17.0.4", "got": "^11.8.1" }, "engines": { @@ -3297,13 +3309,13 @@ } }, "node_modules/devtools/node_modules/@wdio/utils": { - "version": "7.16.11", - "resolved": "https://registry.npmjs.org/@wdio/utils/-/utils-7.16.11.tgz", - "integrity": "sha512-qeXHREZJ7mz3C2cWGOmFG6MS6njp1js4f8zca3iqxaorWshwkrlNsps3B1iTHfkvK6oWnmc2Q0o5CrtLZl0LkA==", + "version": "7.16.13", + "resolved": "https://registry.npmjs.org/@wdio/utils/-/utils-7.16.13.tgz", + "integrity": "sha512-O6D89Ghtm5XtTv4DPKvCBKZOZYNONIcBM5/hmdr3V9mzVrTFq8Q3uE8pmmq303Oh91KcoN8Em5zoAG7Zpc5tRg==", "dev": true, "dependencies": { "@wdio/logger": "7.16.0", - "@wdio/types": "7.16.11", + "@wdio/types": "7.16.13", "p-iteration": "^1.1.8" }, "engines": { @@ -9339,13 +9351,13 @@ } }, "node_modules/puppeteer-core": { - "version": "13.0.0", - "resolved": "https://registry.npmjs.org/puppeteer-core/-/puppeteer-core-13.0.0.tgz", - "integrity": "sha512-JJvGCuUNpONaFK/1tizyVthfqkEaiTCteL9HkdxN3//P9cVa+YnehlKIoJCStiKRaa3CjRu/dIJftA5XJ2EGrQ==", + "version": "13.1.1", + "resolved": "https://registry.npmjs.org/puppeteer-core/-/puppeteer-core-13.1.1.tgz", + "integrity": "sha512-pXVcEFv5wgayHtwl5WBB8dyFHkdA7eLcAUuF9cprsoJQVU1sgA32OCfmXqNfvcej85Y5ceAcin09c8qLopdkfQ==", "dev": true, "dependencies": { "debug": "4.3.2", - "devtools-protocol": "0.0.937139", + "devtools-protocol": "0.0.948846", "extract-zip": "2.0.1", "https-proxy-agent": "5.0.0", "node-fetch": "2.6.5", @@ -9379,9 +9391,9 @@ } }, "node_modules/puppeteer-core/node_modules/devtools-protocol": { - "version": "0.0.937139", - "resolved": "https://registry.npmjs.org/devtools-protocol/-/devtools-protocol-0.0.937139.tgz", - "integrity": "sha512-daj+rzR3QSxsPRy5vjjthn58axO8c11j58uY0lG5vvlJk/EiOdCWOptGdkXDjtuRHr78emKq0udHCXM4trhoDQ==", + "version": "0.0.948846", + "resolved": "https://registry.npmjs.org/devtools-protocol/-/devtools-protocol-0.0.948846.tgz", + "integrity": "sha512-5fGyt9xmMqUl2VI7+rnUkKCiAQIpLns8sfQtTENy5L70ktbNw0Z3TFJ1JoFNYdx/jffz4YXU45VF75wKZD7sZQ==", "dev": true }, "node_modules/puppeteer-core/node_modules/node-fetch": { @@ -11857,17 +11869,17 @@ } }, "node_modules/webdriver": { - "version": "7.16.11", - "resolved": "https://registry.npmjs.org/webdriver/-/webdriver-7.16.11.tgz", - "integrity": "sha512-6nBOXae4xuBH4Nqvi/zvtwjnxSLTONBpxOiRJtQ68CYTYv5+w3m8CsaWy3HbK/0XXa++NYl62bDNn70OGEKb+Q==", + "version": "7.16.13", + "resolved": "https://registry.npmjs.org/webdriver/-/webdriver-7.16.13.tgz", + "integrity": "sha512-Vfr952W1uIgDeWHPGzqH43dYLeRSZshh3TzA9ICUkvnC+Q7YziQdv/8xI8tuuyvb7lSr3VsuB2cGzyCRoC/NWw==", "dev": true, "dependencies": { - "@types/node": "^16.11.1", - "@wdio/config": "7.16.11", + "@types/node": "^17.0.4", + "@wdio/config": "7.16.13", "@wdio/logger": "7.16.0", "@wdio/protocols": "7.16.7", - "@wdio/types": "7.16.11", - "@wdio/utils": "7.16.11", + "@wdio/types": "7.16.13", + "@wdio/utils": "7.16.13", "got": "^11.0.2", "ky": "^0.28.5", "lodash.merge": "^4.6.1" @@ -11876,14 +11888,20 @@ "node": ">=12.0.0" } }, + "node_modules/webdriver/node_modules/@types/node": { + "version": "17.0.10", + "resolved": "https://registry.npmjs.org/@types/node/-/node-17.0.10.tgz", + "integrity": "sha512-S/3xB4KzyFxYGCppyDt68yzBU9ysL88lSdIah4D6cptdcltc4NCPCAMc0+PCpg/lLIyC7IPvj2Z52OJWeIUkog==", + "dev": true + }, "node_modules/webdriver/node_modules/@wdio/config": { - "version": "7.16.11", - "resolved": "https://registry.npmjs.org/@wdio/config/-/config-7.16.11.tgz", - "integrity": "sha512-sIk9FINQfXohuDONb8RA1uv+29XvUw6OBHfaaU7/c9gfKiOWiRczdfiLqfySZRwYgEgNhzCw5vHIogTry1h+xQ==", + "version": "7.16.13", + "resolved": "https://registry.npmjs.org/@wdio/config/-/config-7.16.13.tgz", + "integrity": "sha512-LSGoa83tWQIBppB+LeHjY40B9tuuvmDV1qdBLVXR1ROcOUWWz/oQP3NFLtLm3266LXoJUbwebzGcRIK1EcNk3Q==", "dev": true, "dependencies": { "@wdio/logger": "7.16.0", - "@wdio/types": "7.16.11", + "@wdio/types": "7.16.13", "deepmerge": "^4.0.0", "glob": "^7.1.2" }, @@ -11892,12 +11910,12 @@ } }, "node_modules/webdriver/node_modules/@wdio/types": { - "version": "7.16.11", - "resolved": "https://registry.npmjs.org/@wdio/types/-/types-7.16.11.tgz", - "integrity": "sha512-OFVTFEB6qdG84Y+cOWIacV0loGMgq2SF/rGGlGxai89V3UQxzCFTYVoAx6odAuSNZ37wmfWCykyAR/lAlMItoQ==", + "version": "7.16.13", + "resolved": "https://registry.npmjs.org/@wdio/types/-/types-7.16.13.tgz", + "integrity": "sha512-HIeXKCL+mUjyJxvnHSoaIo3NRgZLbeekyRIwo6USfd9qGlQ8dQ6fyCR3ZU9VqNz9j4+JIn+LRQ7imbz5SdnGbw==", "dev": true, "dependencies": { - "@types/node": "^16.11.1", + "@types/node": "^17.0.4", "got": "^11.8.1" }, "engines": { @@ -11905,13 +11923,13 @@ } }, "node_modules/webdriver/node_modules/@wdio/utils": { - "version": "7.16.11", - "resolved": "https://registry.npmjs.org/@wdio/utils/-/utils-7.16.11.tgz", - "integrity": "sha512-qeXHREZJ7mz3C2cWGOmFG6MS6njp1js4f8zca3iqxaorWshwkrlNsps3B1iTHfkvK6oWnmc2Q0o5CrtLZl0LkA==", + "version": "7.16.13", + "resolved": "https://registry.npmjs.org/@wdio/utils/-/utils-7.16.13.tgz", + "integrity": "sha512-O6D89Ghtm5XtTv4DPKvCBKZOZYNONIcBM5/hmdr3V9mzVrTFq8Q3uE8pmmq303Oh91KcoN8Em5zoAG7Zpc5tRg==", "dev": true, "dependencies": { "@wdio/logger": "7.16.0", - "@wdio/types": "7.16.11", + "@wdio/types": "7.16.13", "p-iteration": "^1.1.8" }, "engines": { @@ -11919,25 +11937,25 @@ } }, "node_modules/webdriverio": { - "version": "7.16.12", - "resolved": "https://registry.npmjs.org/webdriverio/-/webdriverio-7.16.12.tgz", - "integrity": "sha512-pRKDRnfaE3xrNPI4TFT3kEf29l9aS6BylQOoX6DHM6gla8Xf/4seykWn1uJOCP71M9cvL8uuTZRTkfNTLGJcdQ==", + "version": "7.16.13", + "resolved": "https://registry.npmjs.org/webdriverio/-/webdriverio-7.16.13.tgz", + "integrity": "sha512-jl1VRZYL1+cPeG6klskKX7mCEBWNQWDFaNtaIl5pwWgtKWPau6fCzKntSARzfNV8+hKJKwJ2mZn5Nsxfw28Oeg==", "dev": true, "dependencies": { "@types/aria-query": "^5.0.0", - "@types/node": "^16.11.1", - "@wdio/config": "7.16.11", + "@types/node": "^17.0.4", + "@wdio/config": "7.16.13", "@wdio/logger": "7.16.0", "@wdio/protocols": "7.16.7", - "@wdio/repl": "7.16.11", - "@wdio/types": "7.16.11", - "@wdio/utils": "7.16.11", + "@wdio/repl": "7.16.13", + "@wdio/types": "7.16.13", + "@wdio/utils": "7.16.13", "archiver": "^5.0.0", "aria-query": "^5.0.0", "css-shorthand-properties": "^1.1.1", "css-value": "^0.0.1", - "devtools": "7.16.12", - "devtools-protocol": "^0.0.948846", + "devtools": "7.16.13", + "devtools-protocol": "^0.0.953906", "fs-extra": "^10.0.0", "get-port": "^5.1.1", "grapheme-splitter": "^1.0.2", @@ -11951,20 +11969,26 @@ "resq": "^1.9.1", "rgb2hex": "0.2.5", "serialize-error": "^8.0.0", - "webdriver": "7.16.11" + "webdriver": "7.16.13" }, "engines": { "node": ">=12.0.0" } }, + "node_modules/webdriverio/node_modules/@types/node": { + "version": "17.0.10", + "resolved": "https://registry.npmjs.org/@types/node/-/node-17.0.10.tgz", + "integrity": "sha512-S/3xB4KzyFxYGCppyDt68yzBU9ysL88lSdIah4D6cptdcltc4NCPCAMc0+PCpg/lLIyC7IPvj2Z52OJWeIUkog==", + "dev": true + }, "node_modules/webdriverio/node_modules/@wdio/config": { - "version": "7.16.11", - "resolved": "https://registry.npmjs.org/@wdio/config/-/config-7.16.11.tgz", - "integrity": "sha512-sIk9FINQfXohuDONb8RA1uv+29XvUw6OBHfaaU7/c9gfKiOWiRczdfiLqfySZRwYgEgNhzCw5vHIogTry1h+xQ==", + "version": "7.16.13", + "resolved": "https://registry.npmjs.org/@wdio/config/-/config-7.16.13.tgz", + "integrity": "sha512-LSGoa83tWQIBppB+LeHjY40B9tuuvmDV1qdBLVXR1ROcOUWWz/oQP3NFLtLm3266LXoJUbwebzGcRIK1EcNk3Q==", "dev": true, "dependencies": { "@wdio/logger": "7.16.0", - "@wdio/types": "7.16.11", + "@wdio/types": "7.16.13", "deepmerge": "^4.0.0", "glob": "^7.1.2" }, @@ -11973,12 +11997,12 @@ } }, "node_modules/webdriverio/node_modules/@wdio/types": { - "version": "7.16.11", - "resolved": "https://registry.npmjs.org/@wdio/types/-/types-7.16.11.tgz", - "integrity": "sha512-OFVTFEB6qdG84Y+cOWIacV0loGMgq2SF/rGGlGxai89V3UQxzCFTYVoAx6odAuSNZ37wmfWCykyAR/lAlMItoQ==", + "version": "7.16.13", + "resolved": "https://registry.npmjs.org/@wdio/types/-/types-7.16.13.tgz", + "integrity": "sha512-HIeXKCL+mUjyJxvnHSoaIo3NRgZLbeekyRIwo6USfd9qGlQ8dQ6fyCR3ZU9VqNz9j4+JIn+LRQ7imbz5SdnGbw==", "dev": true, "dependencies": { - "@types/node": "^16.11.1", + "@types/node": "^17.0.4", "got": "^11.8.1" }, "engines": { @@ -11986,13 +12010,13 @@ } }, "node_modules/webdriverio/node_modules/@wdio/utils": { - "version": "7.16.11", - "resolved": "https://registry.npmjs.org/@wdio/utils/-/utils-7.16.11.tgz", - "integrity": "sha512-qeXHREZJ7mz3C2cWGOmFG6MS6njp1js4f8zca3iqxaorWshwkrlNsps3B1iTHfkvK6oWnmc2Q0o5CrtLZl0LkA==", + "version": "7.16.13", + "resolved": "https://registry.npmjs.org/@wdio/utils/-/utils-7.16.13.tgz", + "integrity": "sha512-O6D89Ghtm5XtTv4DPKvCBKZOZYNONIcBM5/hmdr3V9mzVrTFq8Q3uE8pmmq303Oh91KcoN8Em5zoAG7Zpc5tRg==", "dev": true, "dependencies": { "@wdio/logger": "7.16.0", - "@wdio/types": "7.16.11", + "@wdio/types": "7.16.13", "p-iteration": "^1.1.8" }, "engines": { @@ -13151,32 +13175,38 @@ "dev": true }, "@wdio/repl": { - "version": "7.16.11", - "resolved": "https://registry.npmjs.org/@wdio/repl/-/repl-7.16.11.tgz", - "integrity": "sha512-wcKkb8L4VmotiE00wxn+RybG5FIUu4Ll7VvLM+DRd9TqEs1IEYwqKLaZKEP1lo/O2nKdcYFHtiAYZ9hon9947Q==", + "version": "7.16.13", + "resolved": "https://registry.npmjs.org/@wdio/repl/-/repl-7.16.13.tgz", + "integrity": "sha512-XWh3dzp6U8LLL4cNGWFra+quVyXZ25Ym38zpsBVtV0/z5NCHJmjRS4ytyvvkzbQ8SyqQ7Y3G8MjfGNi2sBNkIQ==", "dev": true, "requires": { - "@wdio/utils": "7.16.11" + "@wdio/utils": "7.16.13" }, "dependencies": { + "@types/node": { + "version": "17.0.10", + "resolved": "https://registry.npmjs.org/@types/node/-/node-17.0.10.tgz", + "integrity": "sha512-S/3xB4KzyFxYGCppyDt68yzBU9ysL88lSdIah4D6cptdcltc4NCPCAMc0+PCpg/lLIyC7IPvj2Z52OJWeIUkog==", + "dev": true + }, "@wdio/types": { - "version": "7.16.11", - "resolved": "https://registry.npmjs.org/@wdio/types/-/types-7.16.11.tgz", - "integrity": "sha512-OFVTFEB6qdG84Y+cOWIacV0loGMgq2SF/rGGlGxai89V3UQxzCFTYVoAx6odAuSNZ37wmfWCykyAR/lAlMItoQ==", + "version": "7.16.13", + "resolved": "https://registry.npmjs.org/@wdio/types/-/types-7.16.13.tgz", + "integrity": "sha512-HIeXKCL+mUjyJxvnHSoaIo3NRgZLbeekyRIwo6USfd9qGlQ8dQ6fyCR3ZU9VqNz9j4+JIn+LRQ7imbz5SdnGbw==", "dev": true, "requires": { - "@types/node": "^16.11.1", + "@types/node": "^17.0.4", "got": "^11.8.1" } }, "@wdio/utils": { - "version": "7.16.11", - "resolved": "https://registry.npmjs.org/@wdio/utils/-/utils-7.16.11.tgz", - "integrity": "sha512-qeXHREZJ7mz3C2cWGOmFG6MS6njp1js4f8zca3iqxaorWshwkrlNsps3B1iTHfkvK6oWnmc2Q0o5CrtLZl0LkA==", + "version": "7.16.13", + "resolved": "https://registry.npmjs.org/@wdio/utils/-/utils-7.16.13.tgz", + "integrity": "sha512-O6D89Ghtm5XtTv4DPKvCBKZOZYNONIcBM5/hmdr3V9mzVrTFq8Q3uE8pmmq303Oh91KcoN8Em5zoAG7Zpc5tRg==", "dev": true, "requires": { "@wdio/logger": "7.16.0", - "@wdio/types": "7.16.11", + "@wdio/types": "7.16.13", "p-iteration": "^1.1.8" } } @@ -14949,18 +14979,18 @@ "dev": true }, "devtools": { - "version": "7.16.12", - "resolved": "https://registry.npmjs.org/devtools/-/devtools-7.16.12.tgz", - "integrity": "sha512-gKe2DV1VkcZ4omTEss3cTeVg/ZmAUkJArAQp22ceDEbeE6AYYDeCpFDlZmbVgsjMxh+gY2mU5IWQlRIY/7Vyrg==", + "version": "7.16.13", + "resolved": "https://registry.npmjs.org/devtools/-/devtools-7.16.13.tgz", + "integrity": "sha512-jm/DL5tlOUUMe0pUgahDqixw3z+NANLN6DYDeZPFv7z0CBtmnaTyOe2zbT0apLxCBpi800VeXaISVZwmKE2NiQ==", "dev": true, "requires": { - "@types/node": "^16.11.1", + "@types/node": "^17.0.4", "@types/ua-parser-js": "^0.7.33", - "@wdio/config": "7.16.11", + "@wdio/config": "7.16.13", "@wdio/logger": "7.16.0", "@wdio/protocols": "7.16.7", - "@wdio/types": "7.16.11", - "@wdio/utils": "7.16.11", + "@wdio/types": "7.16.13", + "@wdio/utils": "7.16.13", "chrome-launcher": "^0.15.0", "edge-paths": "^2.1.0", "puppeteer-core": "^13.0.0", @@ -14969,36 +14999,42 @@ "uuid": "^8.0.0" }, "dependencies": { + "@types/node": { + "version": "17.0.10", + "resolved": "https://registry.npmjs.org/@types/node/-/node-17.0.10.tgz", + "integrity": "sha512-S/3xB4KzyFxYGCppyDt68yzBU9ysL88lSdIah4D6cptdcltc4NCPCAMc0+PCpg/lLIyC7IPvj2Z52OJWeIUkog==", + "dev": true + }, "@wdio/config": { - "version": "7.16.11", - "resolved": "https://registry.npmjs.org/@wdio/config/-/config-7.16.11.tgz", - "integrity": "sha512-sIk9FINQfXohuDONb8RA1uv+29XvUw6OBHfaaU7/c9gfKiOWiRczdfiLqfySZRwYgEgNhzCw5vHIogTry1h+xQ==", + "version": "7.16.13", + "resolved": "https://registry.npmjs.org/@wdio/config/-/config-7.16.13.tgz", + "integrity": "sha512-LSGoa83tWQIBppB+LeHjY40B9tuuvmDV1qdBLVXR1ROcOUWWz/oQP3NFLtLm3266LXoJUbwebzGcRIK1EcNk3Q==", "dev": true, "requires": { "@wdio/logger": "7.16.0", - "@wdio/types": "7.16.11", + "@wdio/types": "7.16.13", "deepmerge": "^4.0.0", "glob": "^7.1.2" } }, "@wdio/types": { - "version": "7.16.11", - "resolved": "https://registry.npmjs.org/@wdio/types/-/types-7.16.11.tgz", - "integrity": "sha512-OFVTFEB6qdG84Y+cOWIacV0loGMgq2SF/rGGlGxai89V3UQxzCFTYVoAx6odAuSNZ37wmfWCykyAR/lAlMItoQ==", + "version": "7.16.13", + "resolved": "https://registry.npmjs.org/@wdio/types/-/types-7.16.13.tgz", + "integrity": "sha512-HIeXKCL+mUjyJxvnHSoaIo3NRgZLbeekyRIwo6USfd9qGlQ8dQ6fyCR3ZU9VqNz9j4+JIn+LRQ7imbz5SdnGbw==", "dev": true, "requires": { - "@types/node": "^16.11.1", + "@types/node": "^17.0.4", "got": "^11.8.1" } }, "@wdio/utils": { - "version": "7.16.11", - "resolved": "https://registry.npmjs.org/@wdio/utils/-/utils-7.16.11.tgz", - "integrity": "sha512-qeXHREZJ7mz3C2cWGOmFG6MS6njp1js4f8zca3iqxaorWshwkrlNsps3B1iTHfkvK6oWnmc2Q0o5CrtLZl0LkA==", + "version": "7.16.13", + "resolved": "https://registry.npmjs.org/@wdio/utils/-/utils-7.16.13.tgz", + "integrity": "sha512-O6D89Ghtm5XtTv4DPKvCBKZOZYNONIcBM5/hmdr3V9mzVrTFq8Q3uE8pmmq303Oh91KcoN8Em5zoAG7Zpc5tRg==", "dev": true, "requires": { "@wdio/logger": "7.16.0", - "@wdio/types": "7.16.11", + "@wdio/types": "7.16.13", "p-iteration": "^1.1.8" } }, @@ -15011,9 +15047,9 @@ } }, "devtools-protocol": { - "version": "0.0.948846", - "resolved": "https://registry.npmjs.org/devtools-protocol/-/devtools-protocol-0.0.948846.tgz", - "integrity": "sha512-5fGyt9xmMqUl2VI7+rnUkKCiAQIpLns8sfQtTENy5L70ktbNw0Z3TFJ1JoFNYdx/jffz4YXU45VF75wKZD7sZQ==", + "version": "0.0.953906", + "resolved": "https://registry.npmjs.org/devtools-protocol/-/devtools-protocol-0.0.953906.tgz", + "integrity": "sha512-Z2vAafCNnl0Iw/u7TUjqOXW1sOhAMDOviflmUoUIxfq2rgfsoCO3qruB/LUJCdqF9aTJ32DUjXyMsX3+if6kDQ==", "dev": true }, "diff": { @@ -19854,13 +19890,13 @@ "integrity": "sha512-XRsRjdf+j5ml+y/6GKHPZbrF/8p2Yga0JPtdqTIY2Xe5ohJPD9saDJJLPvp9+NSBprVvevdXZybnj2cv8OEd0A==" }, "puppeteer-core": { - "version": "13.0.0", - "resolved": "https://registry.npmjs.org/puppeteer-core/-/puppeteer-core-13.0.0.tgz", - "integrity": "sha512-JJvGCuUNpONaFK/1tizyVthfqkEaiTCteL9HkdxN3//P9cVa+YnehlKIoJCStiKRaa3CjRu/dIJftA5XJ2EGrQ==", + "version": "13.1.1", + "resolved": "https://registry.npmjs.org/puppeteer-core/-/puppeteer-core-13.1.1.tgz", + "integrity": "sha512-pXVcEFv5wgayHtwl5WBB8dyFHkdA7eLcAUuF9cprsoJQVU1sgA32OCfmXqNfvcej85Y5ceAcin09c8qLopdkfQ==", "dev": true, "requires": { "debug": "4.3.2", - "devtools-protocol": "0.0.937139", + "devtools-protocol": "0.0.948846", "extract-zip": "2.0.1", "https-proxy-agent": "5.0.0", "node-fetch": "2.6.5", @@ -19883,9 +19919,9 @@ } }, "devtools-protocol": { - "version": "0.0.937139", - "resolved": "https://registry.npmjs.org/devtools-protocol/-/devtools-protocol-0.0.937139.tgz", - "integrity": "sha512-daj+rzR3QSxsPRy5vjjthn58axO8c11j58uY0lG5vvlJk/EiOdCWOptGdkXDjtuRHr78emKq0udHCXM4trhoDQ==", + "version": "0.0.948846", + "resolved": "https://registry.npmjs.org/devtools-protocol/-/devtools-protocol-0.0.948846.tgz", + "integrity": "sha512-5fGyt9xmMqUl2VI7+rnUkKCiAQIpLns8sfQtTENy5L70ktbNw0Z3TFJ1JoFNYdx/jffz4YXU45VF75wKZD7sZQ==", "dev": true }, "node-fetch": { @@ -21924,77 +21960,83 @@ } }, "webdriver": { - "version": "7.16.11", - "resolved": "https://registry.npmjs.org/webdriver/-/webdriver-7.16.11.tgz", - "integrity": "sha512-6nBOXae4xuBH4Nqvi/zvtwjnxSLTONBpxOiRJtQ68CYTYv5+w3m8CsaWy3HbK/0XXa++NYl62bDNn70OGEKb+Q==", + "version": "7.16.13", + "resolved": "https://registry.npmjs.org/webdriver/-/webdriver-7.16.13.tgz", + "integrity": "sha512-Vfr952W1uIgDeWHPGzqH43dYLeRSZshh3TzA9ICUkvnC+Q7YziQdv/8xI8tuuyvb7lSr3VsuB2cGzyCRoC/NWw==", "dev": true, "requires": { - "@types/node": "^16.11.1", - "@wdio/config": "7.16.11", + "@types/node": "^17.0.4", + "@wdio/config": "7.16.13", "@wdio/logger": "7.16.0", "@wdio/protocols": "7.16.7", - "@wdio/types": "7.16.11", - "@wdio/utils": "7.16.11", + "@wdio/types": "7.16.13", + "@wdio/utils": "7.16.13", "got": "^11.0.2", "ky": "^0.28.5", "lodash.merge": "^4.6.1" }, "dependencies": { + "@types/node": { + "version": "17.0.10", + "resolved": "https://registry.npmjs.org/@types/node/-/node-17.0.10.tgz", + "integrity": "sha512-S/3xB4KzyFxYGCppyDt68yzBU9ysL88lSdIah4D6cptdcltc4NCPCAMc0+PCpg/lLIyC7IPvj2Z52OJWeIUkog==", + "dev": true + }, "@wdio/config": { - "version": "7.16.11", - "resolved": "https://registry.npmjs.org/@wdio/config/-/config-7.16.11.tgz", - "integrity": "sha512-sIk9FINQfXohuDONb8RA1uv+29XvUw6OBHfaaU7/c9gfKiOWiRczdfiLqfySZRwYgEgNhzCw5vHIogTry1h+xQ==", + "version": "7.16.13", + "resolved": "https://registry.npmjs.org/@wdio/config/-/config-7.16.13.tgz", + "integrity": "sha512-LSGoa83tWQIBppB+LeHjY40B9tuuvmDV1qdBLVXR1ROcOUWWz/oQP3NFLtLm3266LXoJUbwebzGcRIK1EcNk3Q==", "dev": true, "requires": { "@wdio/logger": "7.16.0", - "@wdio/types": "7.16.11", + "@wdio/types": "7.16.13", "deepmerge": "^4.0.0", "glob": "^7.1.2" } }, "@wdio/types": { - "version": "7.16.11", - "resolved": "https://registry.npmjs.org/@wdio/types/-/types-7.16.11.tgz", - "integrity": "sha512-OFVTFEB6qdG84Y+cOWIacV0loGMgq2SF/rGGlGxai89V3UQxzCFTYVoAx6odAuSNZ37wmfWCykyAR/lAlMItoQ==", + "version": "7.16.13", + "resolved": "https://registry.npmjs.org/@wdio/types/-/types-7.16.13.tgz", + "integrity": "sha512-HIeXKCL+mUjyJxvnHSoaIo3NRgZLbeekyRIwo6USfd9qGlQ8dQ6fyCR3ZU9VqNz9j4+JIn+LRQ7imbz5SdnGbw==", "dev": true, "requires": { - "@types/node": "^16.11.1", + "@types/node": "^17.0.4", "got": "^11.8.1" } }, "@wdio/utils": { - "version": "7.16.11", - "resolved": "https://registry.npmjs.org/@wdio/utils/-/utils-7.16.11.tgz", - "integrity": "sha512-qeXHREZJ7mz3C2cWGOmFG6MS6njp1js4f8zca3iqxaorWshwkrlNsps3B1iTHfkvK6oWnmc2Q0o5CrtLZl0LkA==", + "version": "7.16.13", + "resolved": "https://registry.npmjs.org/@wdio/utils/-/utils-7.16.13.tgz", + "integrity": "sha512-O6D89Ghtm5XtTv4DPKvCBKZOZYNONIcBM5/hmdr3V9mzVrTFq8Q3uE8pmmq303Oh91KcoN8Em5zoAG7Zpc5tRg==", "dev": true, "requires": { "@wdio/logger": "7.16.0", - "@wdio/types": "7.16.11", + "@wdio/types": "7.16.13", "p-iteration": "^1.1.8" } } } }, "webdriverio": { - "version": "7.16.12", - "resolved": "https://registry.npmjs.org/webdriverio/-/webdriverio-7.16.12.tgz", - "integrity": "sha512-pRKDRnfaE3xrNPI4TFT3kEf29l9aS6BylQOoX6DHM6gla8Xf/4seykWn1uJOCP71M9cvL8uuTZRTkfNTLGJcdQ==", + "version": "7.16.13", + "resolved": "https://registry.npmjs.org/webdriverio/-/webdriverio-7.16.13.tgz", + "integrity": "sha512-jl1VRZYL1+cPeG6klskKX7mCEBWNQWDFaNtaIl5pwWgtKWPau6fCzKntSARzfNV8+hKJKwJ2mZn5Nsxfw28Oeg==", "dev": true, "requires": { "@types/aria-query": "^5.0.0", - "@types/node": "^16.11.1", - "@wdio/config": "7.16.11", + "@types/node": "^17.0.4", + "@wdio/config": "7.16.13", "@wdio/logger": "7.16.0", "@wdio/protocols": "7.16.7", - "@wdio/repl": "7.16.11", - "@wdio/types": "7.16.11", - "@wdio/utils": "7.16.11", + "@wdio/repl": "7.16.13", + "@wdio/types": "7.16.13", + "@wdio/utils": "7.16.13", "archiver": "^5.0.0", "aria-query": "^5.0.0", "css-shorthand-properties": "^1.1.1", "css-value": "^0.0.1", - "devtools": "7.16.12", - "devtools-protocol": "^0.0.948846", + "devtools": "7.16.13", + "devtools-protocol": "^0.0.953906", "fs-extra": "^10.0.0", "get-port": "^5.1.1", "grapheme-splitter": "^1.0.2", @@ -22008,39 +22050,45 @@ "resq": "^1.9.1", "rgb2hex": "0.2.5", "serialize-error": "^8.0.0", - "webdriver": "7.16.11" + "webdriver": "7.16.13" }, "dependencies": { + "@types/node": { + "version": "17.0.10", + "resolved": "https://registry.npmjs.org/@types/node/-/node-17.0.10.tgz", + "integrity": "sha512-S/3xB4KzyFxYGCppyDt68yzBU9ysL88lSdIah4D6cptdcltc4NCPCAMc0+PCpg/lLIyC7IPvj2Z52OJWeIUkog==", + "dev": true + }, "@wdio/config": { - "version": "7.16.11", - "resolved": "https://registry.npmjs.org/@wdio/config/-/config-7.16.11.tgz", - "integrity": "sha512-sIk9FINQfXohuDONb8RA1uv+29XvUw6OBHfaaU7/c9gfKiOWiRczdfiLqfySZRwYgEgNhzCw5vHIogTry1h+xQ==", + "version": "7.16.13", + "resolved": "https://registry.npmjs.org/@wdio/config/-/config-7.16.13.tgz", + "integrity": "sha512-LSGoa83tWQIBppB+LeHjY40B9tuuvmDV1qdBLVXR1ROcOUWWz/oQP3NFLtLm3266LXoJUbwebzGcRIK1EcNk3Q==", "dev": true, "requires": { "@wdio/logger": "7.16.0", - "@wdio/types": "7.16.11", + "@wdio/types": "7.16.13", "deepmerge": "^4.0.0", "glob": "^7.1.2" } }, "@wdio/types": { - "version": "7.16.11", - "resolved": "https://registry.npmjs.org/@wdio/types/-/types-7.16.11.tgz", - "integrity": "sha512-OFVTFEB6qdG84Y+cOWIacV0loGMgq2SF/rGGlGxai89V3UQxzCFTYVoAx6odAuSNZ37wmfWCykyAR/lAlMItoQ==", + "version": "7.16.13", + "resolved": "https://registry.npmjs.org/@wdio/types/-/types-7.16.13.tgz", + "integrity": "sha512-HIeXKCL+mUjyJxvnHSoaIo3NRgZLbeekyRIwo6USfd9qGlQ8dQ6fyCR3ZU9VqNz9j4+JIn+LRQ7imbz5SdnGbw==", "dev": true, "requires": { - "@types/node": "^16.11.1", + "@types/node": "^17.0.4", "got": "^11.8.1" } }, "@wdio/utils": { - "version": "7.16.11", - "resolved": "https://registry.npmjs.org/@wdio/utils/-/utils-7.16.11.tgz", - "integrity": "sha512-qeXHREZJ7mz3C2cWGOmFG6MS6njp1js4f8zca3iqxaorWshwkrlNsps3B1iTHfkvK6oWnmc2Q0o5CrtLZl0LkA==", + "version": "7.16.13", + "resolved": "https://registry.npmjs.org/@wdio/utils/-/utils-7.16.13.tgz", + "integrity": "sha512-O6D89Ghtm5XtTv4DPKvCBKZOZYNONIcBM5/hmdr3V9mzVrTFq8Q3uE8pmmq303Oh91KcoN8Em5zoAG7Zpc5tRg==", "dev": true, "requires": { "@wdio/logger": "7.16.0", - "@wdio/types": "7.16.11", + "@wdio/types": "7.16.13", "p-iteration": "^1.1.8" } } From 5d7c890243ba7d0501514ba48778715097ce5a3b Mon Sep 17 00:00:00 2001 From: Andrew Wyer <92339165+AndrewWyer-Dover@users.noreply.github.com> Date: Tue, 25 Jan 2022 10:35:47 -0600 Subject: [PATCH 044/128] fix: TypeScript exporting of the serialization functions (#5890) * Relocates serialization typing to be adjacent * Gathers serialization imports and exports from Blockly --- typings/blockly.d.ts | 107 ++++++++++++++++++++++++------------------- 1 file changed, 59 insertions(+), 48 deletions(-) diff --git a/typings/blockly.d.ts b/typings/blockly.d.ts index 291f472fd..e66df1331 100644 --- a/typings/blockly.d.ts +++ b/typings/blockly.d.ts @@ -1036,6 +1036,63 @@ declare module "serialization/exceptions" { } import { Block } from "block"; } + +declare module "serialization/variables" { + /** + * Represents the state of a given variable. + */ + export type State = { + name: string; + id: string; + type: (string | undefined); + }; + /** + * Represents the state of a given variable. + * @typedef {{ + * name: string, + * id: string, + * type: (string|undefined) + * }} + * @alias Blockly.serialization.variables.State + */ + export let State: any; +} +declare module "serialization/workspaces" { + /** + * Returns the state of the workspace as a plain JavaScript object. + * @param {!Workspace} workspace The workspace to serialize. + * @return {!Object} The serialized state of the workspace. + * @alias Blockly.serialization.workspaces.save + */ + export function save(workspace: Workspace): { + [x: string]: any; + }; + /** + * Loads the variable represented by the given state into the given workspace. + * @param {!Object} state The state of the workspace to deserialize + * into the workspace. + * @param {!Workspace} workspace The workspace to add the new state to. + * @param {{recordUndo: (boolean|undefined)}=} param1 + * recordUndo: If true, events triggered by this function will be undo-able + * by the user. False by default. + * @alias Blockly.serialization.workspaces.load + */ + export function load(state: { + [x: string]: any; + }, workspace: Workspace, { recordUndo }?: { + recordUndo: (boolean | undefined); + } | undefined): void; + import { Workspace } from "workspace"; +} +declare module "serialization" { + import * as blocks from "serialization/blocks"; + import * as exceptions from "serialization/exceptions"; + import * as priorities from "serialization/priorities"; + import * as registry from "serialization/registry"; + import * as variables from "serialization/variables"; + import * as workspaces from "serialization/workspaces"; + export {blocks, exceptions, priorities, registry, variables, workspaces}; +} declare module "utils/size" { /** * @license @@ -25497,6 +25554,7 @@ declare module "blockly" { import { RenderedConnection } from "rendered_connection"; import { Scrollbar } from "scrollbar"; import { ScrollbarPair } from "scrollbar_pair"; + import * as serialization from "serialization"; import * as ShortcutItems from "shortcut_items"; import { ShortcutRegistry } from "shortcut_registry"; import { TabNavigateCursor } from "keyboard_nav/tab_navigate_cursor"; @@ -25542,54 +25600,7 @@ declare module "blockly" { import * as thrasos from "renderers/thrasos/thrasos"; import * as uiPosition from "positionable_helpers"; import * as zelos from "renderers/zelos/zelos"; - export { resizeSvgContentsLocal as resizeSvgContents, ASTNode, BasicCursor, Block, BlocklyOptions, BlockDragger, BlockDragSurfaceSvg, BlockSvg, Blocks, Bubble, BubbleDragger, CollapsibleToolboxCategory, Comment, ComponentManager, Connection, ConnectionType, ConnectionChecker, ConnectionDB, ContextMenu, ContextMenuItems, ContextMenuRegistry, Css, Cursor, DeleteArea, DragTarget, DropDownDiv, Events, Extensions, Field, FieldAngle, FieldCheckbox, FieldColour, FieldDropdown, FieldImage, FieldLabel, FieldLabelSerializable, FieldMultilineInput, FieldNumber, FieldTextInput, FieldVariable, Flyout, FlyoutButton, FlyoutMetricsManager, Generator, Gesture, Grid, HorizontalFlyout, IASTNodeLocation, IASTNodeLocationSvg, IASTNodeLocationWithBlock, IAutoHideable, IBlockDragger, IBoundedElement, IBubble, ICollapsibleToolboxItem, IComponent, IConnectionChecker, IContextMenu, Icon, ICopyable, IDeletable, IDeleteArea, IDragTarget, IDraggable, IFlyout, IKeyboardAccessible, IMetricsManager, IMovable, Input, InsertionMarkerManager, IPositionable, IRegistrable, IRegistrableField, ISelectable, ISelectableToolboxItem, IStyleable, IToolbox, IToolboxItem, Marker, MarkerManager, Menu, MenuItem, MetricsManager, Mutator, Names, Options, Procedures, RenderedConnection, Scrollbar, ScrollbarPair, ShortcutItems, ShortcutRegistry, TabNavigateCursor, Theme, Themes, ThemeManager, Toolbox, ToolboxCategory, ToolboxItem, ToolboxSeparator, Tooltip, Touch, TouchGesture, Trashcan, VariableMap, VariableModel, Variables, VariablesDynamic, VerticalFlyout, Warning, WidgetDiv, Workspace, WorkspaceAudio, WorkspaceComment, WorkspaceCommentSvg, WorkspaceDragSurfaceSvg, WorkspaceDragger, WorkspaceSvg, Xml, ZoomControls, blockAnimations, blockRendering, browserEvents, bumpObjects, clipboard, common, ConnectionType as connectionTypes, constants, dialog, fieldRegistry, geras, inject, inputTypes, minimalist, registry, thrasos, uiPosition, utils, zelos }; -} -declare module "serialization/variables" { - /** - * Represents the state of a given variable. - */ - export type State = { - name: string; - id: string; - type: (string | undefined); - }; - /** - * Represents the state of a given variable. - * @typedef {{ - * name: string, - * id: string, - * type: (string|undefined) - * }} - * @alias Blockly.serialization.variables.State - */ - export let State: any; -} -declare module "serialization/workspaces" { - /** - * Returns the state of the workspace as a plain JavaScript object. - * @param {!Workspace} workspace The workspace to serialize. - * @return {!Object} The serialized state of the workspace. - * @alias Blockly.serialization.workspaces.save - */ - export function save(workspace: Workspace): { - [x: string]: any; - }; - /** - * Loads the variable represented by the given state into the given workspace. - * @param {!Object} state The state of the workspace to deserialize - * into the workspace. - * @param {!Workspace} workspace The workspace to add the new state to. - * @param {{recordUndo: (boolean|undefined)}=} param1 - * recordUndo: If true, events triggered by this function will be undo-able - * by the user. False by default. - * @alias Blockly.serialization.workspaces.load - */ - export function load(state: { - [x: string]: any; - }, workspace: Workspace, { recordUndo }?: { - recordUndo: (boolean | undefined); - } | undefined): void; - import { Workspace } from "workspace"; + export { resizeSvgContentsLocal as resizeSvgContents, ASTNode, BasicCursor, Block, BlocklyOptions, BlockDragger, BlockDragSurfaceSvg, BlockSvg, Blocks, Bubble, BubbleDragger, CollapsibleToolboxCategory, Comment, ComponentManager, Connection, ConnectionType, ConnectionChecker, ConnectionDB, ContextMenu, ContextMenuItems, ContextMenuRegistry, Css, Cursor, DeleteArea, DragTarget, DropDownDiv, Events, Extensions, Field, FieldAngle, FieldCheckbox, FieldColour, FieldDropdown, FieldImage, FieldLabel, FieldLabelSerializable, FieldMultilineInput, FieldNumber, FieldTextInput, FieldVariable, Flyout, FlyoutButton, FlyoutMetricsManager, Generator, Gesture, Grid, HorizontalFlyout, IASTNodeLocation, IASTNodeLocationSvg, IASTNodeLocationWithBlock, IAutoHideable, IBlockDragger, IBoundedElement, IBubble, ICollapsibleToolboxItem, IComponent, IConnectionChecker, IContextMenu, Icon, ICopyable, IDeletable, IDeleteArea, IDragTarget, IDraggable, IFlyout, IKeyboardAccessible, IMetricsManager, IMovable, Input, InsertionMarkerManager, IPositionable, IRegistrable, IRegistrableField, ISelectable, ISelectableToolboxItem, IStyleable, IToolbox, IToolboxItem, Marker, MarkerManager, Menu, MenuItem, MetricsManager, Mutator, Names, Options, Procedures, RenderedConnection, Scrollbar, ScrollbarPair, serialization, ShortcutItems, ShortcutRegistry, TabNavigateCursor, Theme, Themes, ThemeManager, Toolbox, ToolboxCategory, ToolboxItem, ToolboxSeparator, Tooltip, Touch, TouchGesture, Trashcan, VariableMap, VariableModel, Variables, VariablesDynamic, VerticalFlyout, Warning, WidgetDiv, Workspace, WorkspaceAudio, WorkspaceComment, WorkspaceCommentSvg, WorkspaceDragSurfaceSvg, WorkspaceDragger, WorkspaceSvg, Xml, ZoomControls, blockAnimations, blockRendering, browserEvents, bumpObjects, clipboard, common, ConnectionType as connectionTypes, constants, dialog, fieldRegistry, geras, inject, inputTypes, minimalist, registry, thrasos, uiPosition, utils, zelos }; } declare module "requires" { export {}; From 3f4f5057919fdb4a329e9d2b15378c5c5831ae3b Mon Sep 17 00:00:00 2001 From: alschmiedt Date: Tue, 25 Jan 2022 14:50:00 -0800 Subject: [PATCH 045/128] fix: Adds check for changedTouches (#5869) --- core/touch.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/touch.js b/core/touch.js index b0eb0b347..53f3440d0 100644 --- a/core/touch.js +++ b/core/touch.js @@ -217,7 +217,7 @@ exports.checkTouchIdentifier = checkTouchIdentifier; * @alias Blockly.Touch.setClientFromTouch */ const setClientFromTouch = function(e) { - if (utilsString.startsWith(e.type, 'touch')) { + if (utilsString.startsWith(e.type, 'touch') && e.changedTouches) { // Map the touch event's properties to the event. const touchPoint = e.changedTouches[0]; e.clientX = touchPoint.clientX; From efdb6549d9f5cd6bf670c6ba86b8c32bd2193cf8 Mon Sep 17 00:00:00 2001 From: Rachel Fenichel Date: Tue, 25 Jan 2022 15:26:20 -0800 Subject: [PATCH 046/128] refactor: convert some classes to es6 classes (#5873) * refactor: convert flyout_button.js to ES6 class * chore: move some properties into constructor and add annotations for flyout base * refactor: convert flyout_horizontal.js to ES6 class * refactor: convert flyout_vertical.js to ES6 class * refactor: convert flyout_base.js to ES6 class * refactor: convert flyout_metrics_manager.js to ES6 class * refactor: convert insertion_marker_manager.js to ES6 class * refactor: convert metrics_manager.js to ES6 class * refactor: convert grid.js to ES6 class * refactor: convert input.js to ES6 class * refactor: convert touch_gesture.js to ES6 class * refactor: convert gesture.js to ES6 class * refactor: convert trashcan.js to ES6 class * chore: rebuild and run format * chore: fix review comments * chore: respond to PR comments --- core/flyout_base.js | 2089 +++++++++++++++--------------- core/flyout_button.js | 541 ++++---- core/flyout_horizontal.js | 630 ++++----- core/flyout_metrics_manager.js | 132 +- core/flyout_vertical.js | 684 +++++----- core/gesture.js | 1878 ++++++++++++++------------- core/grid.js | 359 ++--- core/input.js | 523 ++++---- core/insertion_marker_manager.js | 1377 ++++++++++---------- core/metrics_manager.js | 795 ++++++------ core/touch_gesture.js | 527 ++++---- core/trashcan.js | 1190 ++++++++--------- tests/deps.js | 14 +- 13 files changed, 5430 insertions(+), 5309 deletions(-) diff --git a/core/flyout_base.js b/core/flyout_base.js index 5e8f1c6cc..4490617e0 100644 --- a/core/flyout_base.js +++ b/core/flyout_base.js @@ -24,7 +24,6 @@ const common = goog.require('Blockly.common'); const dom = goog.require('Blockly.utils.dom'); const eventUtils = goog.require('Blockly.Events.utils'); const idGenerator = goog.require('Blockly.utils.idGenerator'); -const object = goog.require('Blockly.utils.object'); const toolbox = goog.require('Blockly.utils.toolbox'); /* eslint-disable-next-line no-unused-vars */ const {BlockSvg} = goog.requireType('Blockly.BlockSvg'); @@ -59,1076 +58,1122 @@ goog.require('Blockly.blockRendering'); /** * Class for a flyout. - * @param {!Options} workspaceOptions Dictionary of options for the - * workspace. - * @constructor * @abstract * @implements {IFlyout} * @extends {DeleteArea} - * @alias Blockly.Flyout */ -const Flyout = function(workspaceOptions) { - Flyout.superClass_.constructor.call(this); - workspaceOptions.setMetrics = this.setMetrics_.bind(this); - +class Flyout extends DeleteArea { /** - * @type {!WorkspaceSvg} - * @protected + * @param {!Options} workspaceOptions Dictionary of options for the + * workspace. + * @alias Blockly.Flyout */ - this.workspace_ = new WorkspaceSvg(workspaceOptions); - this.workspace_.setMetricsManager( - new FlyoutMetricsManager(this.workspace_, this)); + constructor(workspaceOptions) { + super(); + workspaceOptions.setMetrics = this.setMetrics_.bind(this); - this.workspace_.isFlyout = true; - // Keep the workspace visibility consistent with the flyout's visibility. - this.workspace_.setVisible(this.isVisible_); + /** + * @type {!WorkspaceSvg} + * @protected + */ + this.workspace_ = new WorkspaceSvg(workspaceOptions); + this.workspace_.setMetricsManager( + new FlyoutMetricsManager(this.workspace_, this)); - /** - * The unique id for this component that is used to register with the - * ComponentManager. - * @type {string} - */ - this.id = idGenerator.genUid(); + this.workspace_.isFlyout = true; + // Keep the workspace visibility consistent with the flyout's visibility. + this.workspace_.setVisible(this.isVisible_); - /** - * Is RTL vs LTR. - * @type {boolean} - */ - this.RTL = !!workspaceOptions.RTL; + /** + * The unique id for this component that is used to register with the + * ComponentManager. + * @type {string} + */ + this.id = idGenerator.genUid(); - /** - * Whether the flyout should be laid out horizontally or not. - * @type {boolean} - * @package - */ - this.horizontalLayout = false; + /** + * Is RTL vs LTR. + * @type {boolean} + */ + this.RTL = !!workspaceOptions.RTL; - /** - * Position of the toolbox and flyout relative to the workspace. - * @type {number} - * @protected - */ - this.toolboxPosition_ = workspaceOptions.toolboxPosition; + /** + * Whether the flyout should be laid out horizontally or not. + * @type {boolean} + * @package + */ + this.horizontalLayout = false; - /** - * Opaque data that can be passed to Blockly.unbindEvent_. - * @type {!Array} - * @private - */ - this.eventWrappers_ = []; + /** + * Position of the toolbox and flyout relative to the workspace. + * @type {number} + * @protected + */ + this.toolboxPosition_ = workspaceOptions.toolboxPosition; - /** - * List of background mats that lurk behind each block to catch clicks - * landing in the blocks' lakes and bays. - * @type {!Array} - * @private - */ - this.mats_ = []; + /** + * Opaque data that can be passed to Blockly.unbindEvent_. + * @type {!Array} + * @private + */ + this.eventWrappers_ = []; - /** - * List of visible buttons. - * @type {!Array} - * @protected - */ - this.buttons_ = []; + /** + * Function that will be registered as a change listener on the workspace + * to reflow when blocks in the flyout workspace change. + * @type {?Function} + * @private + */ + this.reflowWrapper_ = null; - /** - * List of event listeners. - * @type {!Array} - * @private - */ - this.listeners_ = []; - - /** - * List of blocks that should always be disabled. - * @type {!Array} - * @private - */ - this.permanentlyDisabled_ = []; - - /** - * Width of output tab. - * @type {number} - * @protected - * @const - */ - this.tabWidth_ = this.workspace_.getRenderer().getConstants().TAB_WIDTH; - - /** - * The target workspace - * @type {?WorkspaceSvg} - * @package - */ - this.targetWorkspace = null; - - /** - * A list of blocks that can be reused. - * @type {!Array} - * @private - */ - this.recycledBlocks_ = []; - - /** - * Does the flyout automatically close when a block is created? - * @type {boolean} - */ - this.autoClose = true; - - /** - * Whether the flyout is visible. - * @type {boolean} - * @private - */ - this.isVisible_ = false; - - /** - * Whether the workspace containing this flyout is visible. - * @type {boolean} - * @private - */ - this.containerVisible_ = true; - - /** - * Corner radius of the flyout background. - * @type {number} - * @const - */ - this.CORNER_RADIUS = 8; - - /** - * Margin around the edges of the blocks in the flyout. - * @type {number} - * @const - */ - this.MARGIN = this.CORNER_RADIUS; - - // TODO: Move GAP_X and GAP_Y to their appropriate files. - - /** - * Gap between items in horizontal flyouts. Can be overridden with the "sep" - * element. - * @const {number} - */ - this.GAP_X = this.MARGIN * 3; - - /** - * Gap between items in vertical flyouts. Can be overridden with the "sep" - * element. - * @const {number} - */ - this.GAP_Y = this.MARGIN * 3; - - /** - * Top/bottom padding between scrollbar and edge of flyout background. - * @type {number} - * @const - */ - this.SCROLLBAR_MARGIN = 2.5; - - /** - * Width of flyout. - * @type {number} - * @protected - */ - this.width_ = 0; - - /** - * Height of flyout. - * @type {number} - * @protected - */ - this.height_ = 0; - - /** - * Range of a drag angle from a flyout considered "dragging toward workspace". - * Drags that are within the bounds of this many degrees from the orthogonal - * line to the flyout edge are considered to be "drags toward the workspace". - * Example: - * Flyout Edge Workspace - * [block] / <-within this angle, drags "toward workspace" | - * [block] ---- orthogonal to flyout boundary ---- | - * [block] \ | - * The angle is given in degrees from the orthogonal. - * - * This is used to know when to create a new block and when to scroll the - * flyout. Setting it to 360 means that all drags create a new block. - * @type {number} - * @protected - */ - this.dragAngleRange_ = 70; -}; -object.inherits(Flyout, DeleteArea); - -/** - * Creates the flyout's DOM. Only needs to be called once. The flyout can - * either exist as its own SVG element or be a g element nested inside a - * separate SVG element. - * @param {string| - * !Svg| - * !Svg} tagName The type of tag to - * put the flyout in. This should be or . - * @return {!SVGElement} The flyout's SVG group. - */ -Flyout.prototype.createDom = function(tagName) { - /* - - - - - */ - // Setting style to display:none to start. The toolbox and flyout - // hide/show code will set up proper visibility and size later. - this.svgGroup_ = dom.createSvgElement( - tagName, {'class': 'blocklyFlyout', 'style': 'display: none'}, null); - this.svgBackground_ = dom.createSvgElement( - Svg.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'); - return this.svgGroup_; -}; - -/** - * Initializes the flyout. - * @param {!WorkspaceSvg} targetWorkspace The workspace in which to - * create new blocks. - */ -Flyout.prototype.init = function(targetWorkspace) { - this.targetWorkspace = targetWorkspace; - this.workspace_.targetWorkspace = targetWorkspace; - - this.workspace_.scrollbar = new ScrollbarPair( - this.workspace_, this.horizontalLayout, !this.horizontalLayout, - 'blocklyFlyoutScrollbar', this.SCROLLBAR_MARGIN); - - this.hide(); - - Array.prototype.push.apply( - this.eventWrappers_, - browserEvents.conditionalBind( - this.svgGroup_, 'wheel', this, this.wheel_)); - if (!this.autoClose) { - this.filterWrapper_ = this.filterForCapacity_.bind(this); - this.targetWorkspace.addChangeListener(this.filterWrapper_); - } - - // Dragging the flyout up and down. - Array.prototype.push.apply( - this.eventWrappers_, - browserEvents.conditionalBind( - this.svgBackground_, 'mousedown', this, this.onMouseDown_)); - - // A flyout connected to a workspace doesn't have its own current gesture. - this.workspace_.getGesture = - this.targetWorkspace.getGesture.bind(this.targetWorkspace); - - // Get variables from the main workspace rather than the target workspace. - this.workspace_.setVariableMap(this.targetWorkspace.getVariableMap()); - - this.workspace_.createPotentialVariableMap(); - - targetWorkspace.getComponentManager().addComponent({ - component: this, - weight: 1, - capabilities: [ - ComponentManager.Capability.DELETE_AREA, - ComponentManager.Capability.DRAG_TARGET, - ], - }); -}; - -/** - * Dispose of this flyout. - * Unlink from all DOM elements to prevent memory leaks. - * @suppress {checkTypes} - */ -Flyout.prototype.dispose = function() { - this.hide(); - this.workspace_.getComponentManager().removeComponent(this.id); - browserEvents.unbind(this.eventWrappers_); - if (this.filterWrapper_) { - this.targetWorkspace.removeChangeListener(this.filterWrapper_); + /** + * Function that disables blocks in the flyout based on max block counts + * allowed in the target workspace. Registered as a change listener on the + * target workspace. + * @type {?Function} + * @private + */ this.filterWrapper_ = null; - } - if (this.workspace_) { - this.workspace_.getThemeManager().unsubscribe(this.svgBackground_); - this.workspace_.targetWorkspace = null; - this.workspace_.dispose(); - this.workspace_ = null; - } - if (this.svgGroup_) { - dom.removeNode(this.svgGroup_); + + /** + * List of background mats that lurk behind each block to catch clicks + * landing in the blocks' lakes and bays. + * @type {!Array} + * @private + */ + this.mats_ = []; + + /** + * List of visible buttons. + * @type {!Array} + * @protected + */ + this.buttons_ = []; + + /** + * List of event listeners. + * @type {!Array} + * @private + */ + this.listeners_ = []; + + /** + * List of blocks that should always be disabled. + * @type {!Array} + * @private + */ + this.permanentlyDisabled_ = []; + + /** + * Width of output tab. + * @type {number} + * @protected + * @const + */ + this.tabWidth_ = this.workspace_.getRenderer().getConstants().TAB_WIDTH; + + /** + * The target workspace + * @type {?WorkspaceSvg} + * @package + */ + this.targetWorkspace = null; + + /** + * A list of blocks that can be reused. + * @type {!Array} + * @private + */ + this.recycledBlocks_ = []; + + /** + * Does the flyout automatically close when a block is created? + * @type {boolean} + */ + this.autoClose = true; + + /** + * Whether the flyout is visible. + * @type {boolean} + * @private + */ + this.isVisible_ = false; + + /** + * Whether the workspace containing this flyout is visible. + * @type {boolean} + * @private + */ + this.containerVisible_ = true; + + /** + * Corner radius of the flyout background. + * @type {number} + * @const + */ + this.CORNER_RADIUS = 8; + + /** + * Margin around the edges of the blocks in the flyout. + * @type {number} + * @const + */ + this.MARGIN = this.CORNER_RADIUS; + + // TODO: Move GAP_X and GAP_Y to their appropriate files. + + /** + * Gap between items in horizontal flyouts. Can be overridden with the "sep" + * element. + * @const {number} + */ + this.GAP_X = this.MARGIN * 3; + + /** + * Gap between items in vertical flyouts. Can be overridden with the "sep" + * element. + * @const {number} + */ + this.GAP_Y = this.MARGIN * 3; + + /** + * Top/bottom padding between scrollbar and edge of flyout background. + * @type {number} + * @const + */ + this.SCROLLBAR_MARGIN = 2.5; + + /** + * Width of flyout. + * @type {number} + * @protected + */ + this.width_ = 0; + + /** + * Height of flyout. + * @type {number} + * @protected + */ + this.height_ = 0; + + // clang-format off + /** + * Range of a drag angle from a flyout considered "dragging toward + * workspace". Drags that are within the bounds of this many degrees from + * the orthogonal line to the flyout edge are considered to be "drags toward + * the workspace". + * Example: + * Flyout Edge Workspace + * [block] / <-within this angle, drags "toward workspace" | + * [block] ---- orthogonal to flyout boundary ---- | + * [block] \ | + * The angle is given in degrees from the orthogonal. + * + * This is used to know when to create a new block and when to scroll the + * flyout. Setting it to 360 means that all drags create a new block. + * @type {number} + * @protected + */ + // clang-format on + this.dragAngleRange_ = 70; + + /** + * The path around the background of the flyout, which will be filled with a + * background colour. + * @type {?SVGPathElement} + * @protected + */ + this.svgBackground_ = null; + + /** + * The root SVG group for the button or label. + * @type {?SVGGElement} + * @protected + */ this.svgGroup_ = null; } - this.svgBackground_ = null; - this.targetWorkspace = null; -}; -/** - * Get the width of the flyout. - * @return {number} The width of the flyout. - */ -Flyout.prototype.getWidth = function() { - return this.width_; -}; - -/** - * Get the height of the flyout. - * @return {number} The width of the flyout. - */ -Flyout.prototype.getHeight = function() { - return this.height_; -}; - -/** - * Get the scale (zoom level) of the flyout. By default, - * this matches the target workspace scale, but this can be overridden. - * @return {number} Flyout workspace scale. - */ -Flyout.prototype.getFlyoutScale = function() { - return this.targetWorkspace.scale; -}; - -/** - * Get the workspace inside the flyout. - * @return {!WorkspaceSvg} The workspace inside the flyout. - * @package - */ -Flyout.prototype.getWorkspace = function() { - return this.workspace_; -}; - -/** - * Is the flyout visible? - * @return {boolean} True if visible. - */ -Flyout.prototype.isVisible = function() { - return this.isVisible_; -}; - -/** - * Set whether the flyout is visible. A value of true does not necessarily mean - * that the flyout is shown. It could be hidden because its container is hidden. - * @param {boolean} visible True if visible. - */ -Flyout.prototype.setVisible = function(visible) { - const visibilityChanged = (visible !== this.isVisible()); - - this.isVisible_ = visible; - if (visibilityChanged) { - if (!this.autoClose) { - // Auto-close flyouts are ignored as drag targets, so only non auto-close - // flyouts need to have their drag target updated. - this.workspace_.recordDragTargets(); - } - this.updateDisplay_(); - } -}; - -/** - * Set whether this flyout's container is visible. - * @param {boolean} visible Whether the container is visible. - */ -Flyout.prototype.setContainerVisible = function(visible) { - const visibilityChanged = (visible !== this.containerVisible_); - this.containerVisible_ = visible; - if (visibilityChanged) { - this.updateDisplay_(); - } -}; - -/** - * Update the display property of the flyout based whether it thinks it should - * be visible and whether its containing workspace is visible. - * @private - */ -Flyout.prototype.updateDisplay_ = function() { - let show = true; - if (!this.containerVisible_) { - show = false; - } else { - show = this.isVisible(); - } - this.svgGroup_.style.display = show ? 'block' : 'none'; - // Update the scrollbar's visibility too since it should mimic the - // flyout's visibility. - this.workspace_.scrollbar.setContainerVisible(show); -}; - -/** - * Update the view based on coordinates calculated in position(). - * @param {number} width The computed width of the flyout's SVG group - * @param {number} height The computed height of the flyout's SVG group. - * @param {number} x The computed x origin of the flyout's SVG group. - * @param {number} y The computed y origin of the flyout's SVG group. - * @protected - */ -Flyout.prototype.positionAt_ = function(width, height, x, y) { - this.svgGroup_.setAttribute('width', width); - this.svgGroup_.setAttribute('height', height); - this.workspace_.setCachedParentSvgSize(width, height); - - if (this.svgGroup_.tagName === 'svg') { - const transform = 'translate(' + x + 'px,' + y + 'px)'; - dom.setCssTransform(this.svgGroup_, transform); - } else { - // IE and Edge don't support CSS transforms on SVG elements so - // it's important to set the transform on the SVG element itself - const transform = 'translate(' + x + ',' + y + ')'; - this.svgGroup_.setAttribute('transform', transform); + /** + * Creates the flyout's DOM. Only needs to be called once. The flyout can + * either exist as its own SVG element or be a g element nested inside a + * separate SVG element. + * @param {string| + * !Svg| + * !Svg} tagName The type of tag to + * put the flyout in. This should be or . + * @return {!SVGElement} The flyout's SVG group. + */ + createDom(tagName) { + /* + + + + + */ + // Setting style to display:none to start. The toolbox and flyout + // hide/show code will set up proper visibility and size later. + this.svgGroup_ = dom.createSvgElement( + tagName, {'class': 'blocklyFlyout', 'style': 'display: none'}, null); + this.svgBackground_ = dom.createSvgElement( + Svg.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'); + return this.svgGroup_; } - // Update the scrollbar (if one exists). - const scrollbar = this.workspace_.scrollbar; - if (scrollbar) { - // Set the scrollbars origin to be the top left of the flyout. - scrollbar.setOrigin(x, y); - scrollbar.resize(); - // If origin changed and metrics haven't changed enough to trigger - // reposition in resize, we need to call setPosition. See issue #4692. - if (scrollbar.hScroll) { - scrollbar.hScroll.setPosition( - scrollbar.hScroll.position.x, scrollbar.hScroll.position.y); - } - if (scrollbar.vScroll) { - scrollbar.vScroll.setPosition( - scrollbar.vScroll.position.x, scrollbar.vScroll.position.y); - } - } -}; + /** + * Initializes the flyout. + * @param {!WorkspaceSvg} targetWorkspace The workspace in which to + * create new blocks. + */ + init(targetWorkspace) { + this.targetWorkspace = targetWorkspace; + this.workspace_.targetWorkspace = targetWorkspace; -/** - * Hide and empty the flyout. - */ -Flyout.prototype.hide = function() { - if (!this.isVisible()) { - return; - } - this.setVisible(false); - // Delete all the event listeners. - for (let i = 0, listen; (listen = this.listeners_[i]); i++) { - browserEvents.unbind(listen); - } - this.listeners_.length = 0; - if (this.reflowWrapper_) { - this.workspace_.removeChangeListener(this.reflowWrapper_); - this.reflowWrapper_ = null; - } - // Do NOT delete the blocks here. Wait until Flyout.show. - // https://neil.fraser.name/news/2014/08/09/ -}; + this.workspace_.scrollbar = new ScrollbarPair( + this.workspace_, this.horizontalLayout, !this.horizontalLayout, + 'blocklyFlyoutScrollbar', this.SCROLLBAR_MARGIN); -/** - * Show and populate the flyout. - * @param {!toolbox.FlyoutDefinition|string} flyoutDef Contents to display - * in the flyout. This is either an array of Nodes, a NodeList, a - * toolbox definition, or a string with the name of the dynamic category. - */ -Flyout.prototype.show = function(flyoutDef) { - this.workspace_.setResizesEnabled(false); - this.hide(); - this.clearOldBlocks_(); - - // Handle dynamic categories, represented by a name instead of a list. - if (typeof flyoutDef === 'string') { - flyoutDef = this.getDynamicCategoryContents_(flyoutDef); - } - this.setVisible(true); - - // Parse the Array, Node or NodeList into a a list of flyout items. - const parsedContent = toolbox.convertFlyoutDefToJsonArray(flyoutDef); - const flyoutInfo = - /** @type {{contents:!Array, gaps:!Array}} */ ( - this.createFlyoutInfo_(parsedContent)); - - this.layout_(flyoutInfo.contents, flyoutInfo.gaps); - - // IE 11 is an incompetent browser that fails to fire mouseout events. - // When the mouse is over the background, deselect all blocks. - const deselectAll = - /** @this {Flyout} */ - function() { - const topBlocks = this.workspace_.getTopBlocks(false); - for (let i = 0, block; (block = topBlocks[i]); i++) { - block.removeSelect(); - } - }; - - this.listeners_.push(browserEvents.conditionalBind( - this.svgBackground_, 'mouseover', this, deselectAll)); - - if (this.horizontalLayout) { - this.height_ = 0; - } else { - this.width_ = 0; - } - this.workspace_.setResizesEnabled(true); - this.reflow(); - - this.filterForCapacity_(); - - // Correctly position the flyout's scrollbar when it opens. - this.position(); - - this.reflowWrapper_ = this.reflow.bind(this); - this.workspace_.addChangeListener(this.reflowWrapper_); - this.emptyRecycledBlocks_(); -}; - -/** - * Create the contents array and gaps array necessary to create the layout for - * the flyout. - * @param {!toolbox.FlyoutItemInfoArray} parsedContent The array - * of objects to show in the flyout. - * @return {{contents:Array, gaps:Array}} The list of contents - * and gaps needed to lay out the flyout. - * @private - */ -Flyout.prototype.createFlyoutInfo_ = function(parsedContent) { - const contents = []; - const gaps = []; - this.permanentlyDisabled_.length = 0; - const defaultGap = this.horizontalLayout ? this.GAP_X : this.GAP_Y; - for (let i = 0, contentInfo; (contentInfo = parsedContent[i]); i++) { - if (contentInfo['custom']) { - const customInfo = - /** @type {!toolbox.DynamicCategoryInfo} */ (contentInfo); - const categoryName = customInfo['custom']; - const flyoutDef = this.getDynamicCategoryContents_(categoryName); - const parsedDynamicContent = /** @type {!toolbox.FlyoutItemInfoArray} */ - (toolbox.convertFlyoutDefToJsonArray(flyoutDef)); - // Replace the element at i with the dynamic content it represents. - parsedContent.splice.apply( - parsedContent, [i, 1].concat(parsedDynamicContent)); - contentInfo = parsedContent[i]; - } - - switch (contentInfo['kind'].toUpperCase()) { - case 'BLOCK': { - const blockInfo = /** @type {!toolbox.BlockInfo} */ (contentInfo); - const block = this.createFlyoutBlock_(blockInfo); - contents.push({type: 'block', block: block}); - this.addBlockGap_(blockInfo, gaps, defaultGap); - break; - } - case 'SEP': { - const sepInfo = /** @type {!toolbox.SeparatorInfo} */ (contentInfo); - this.addSeparatorGap_(sepInfo, gaps, defaultGap); - break; - } - case 'LABEL': { - const labelInfo = /** @type {!toolbox.LabelInfo} */ (contentInfo); - // A label is a button with different styling. - const label = this.createButton_(labelInfo, /** isLabel */ true); - contents.push({type: 'button', button: label}); - gaps.push(defaultGap); - break; - } - case 'BUTTON': { - const buttonInfo = /** @type {!toolbox.ButtonInfo} */ (contentInfo); - const button = this.createButton_(buttonInfo, /** isLabel */ false); - contents.push({type: 'button', button: button}); - gaps.push(defaultGap); - break; - } - } - } - return {contents: contents, gaps: gaps}; -}; - -/** - * Gets the flyout definition for the dynamic category. - * @param {string} categoryName The name of the dynamic category. - * @return {!toolbox.FlyoutDefinition} The definition of the - * flyout in one of its many forms. - * @private - */ -Flyout.prototype.getDynamicCategoryContents_ = function(categoryName) { - // Look up the correct category generation function and call that to get a - // valid XML list. - const fnToApply = - this.workspace_.targetWorkspace.getToolboxCategoryCallback(categoryName); - if (typeof fnToApply !== 'function') { - throw TypeError( - 'Couldn\'t find a callback function when opening' + - ' a toolbox category.'); - } - return fnToApply(this.workspace_.targetWorkspace); -}; - -/** - * Creates a flyout button or a flyout label. - * @param {!toolbox.ButtonOrLabelInfo} btnInfo - * The object holding information about a button or a label. - * @param {boolean} isLabel True if the button is a label, false otherwise. - * @return {!FlyoutButton} The object used to display the button in the - * flyout. - * @private - */ -Flyout.prototype.createButton_ = function(btnInfo, isLabel) { - const {FlyoutButton} = goog.module.get('Blockly.FlyoutButton'); - if (!FlyoutButton) { - throw Error('Missing require for Blockly.FlyoutButton'); - } - const curButton = new FlyoutButton( - this.workspace_, - /** @type {!WorkspaceSvg} */ (this.targetWorkspace), btnInfo, isLabel); - return curButton; -}; - -/** - * Create a block from the xml and permanently disable any blocks that were - * defined as disabled. - * @param {!toolbox.BlockInfo} blockInfo The info of the block. - * @return {!BlockSvg} The block created from the blockInfo. - * @private - */ -Flyout.prototype.createFlyoutBlock_ = function(blockInfo) { - let block; - if (blockInfo['blockxml']) { - const xml = typeof blockInfo['blockxml'] === 'string' ? - Xml.textToDom(blockInfo['blockxml']) : - blockInfo['blockxml']; - block = this.getRecycledBlock_(xml.getAttribute('type')); - if (!block) { - block = Xml.domToBlock(xml, this.workspace_); - } - } else { - block = this.getRecycledBlock_(blockInfo['type']); - if (!block) { - if (blockInfo['enabled'] === undefined) { - blockInfo['enabled'] = - blockInfo['disabled'] !== 'true' && blockInfo['disabled'] !== true; - } - block = blocks.append( - /** @type {blocks.State} */ (blockInfo), this.workspace_); - } - } - - if (!block.isEnabled()) { - // Record blocks that were initially disabled. - // Do not enable these blocks as a result of capacity filtering. - this.permanentlyDisabled_.push(block); - } - return /** @type {!BlockSvg} */ (block); -}; - -/** - * Returns a block from the array of recycled blocks with the given type, or - * undefined if one cannot be found. - * @param {string} blockType The type of the block to try to recycle. - * @return {(!BlockSvg|undefined)} The recycled block, or undefined if - * one could not be recycled. - * @private - */ -Flyout.prototype.getRecycledBlock_ = function(blockType) { - let index = -1; - for (let i = 0; i < this.recycledBlocks_.length; i++) { - if (this.recycledBlocks_[i].type === blockType) { - index = i; - break; - } - } - return index === -1 ? undefined : this.recycledBlocks_.splice(index, 1)[0]; -}; - -/** - * Adds a gap in the flyout based on block info. - * @param {!toolbox.BlockInfo} blockInfo Information about a block. - * @param {!Array} gaps The list of gaps between items in the flyout. - * @param {number} defaultGap The default gap between one element and the next. - * @private - */ -Flyout.prototype.addBlockGap_ = function(blockInfo, gaps, defaultGap) { - let gap; - if (blockInfo['gap']) { - gap = parseInt(blockInfo['gap'], 10); - } else if (blockInfo['blockxml']) { - const xml = typeof blockInfo['blockxml'] === 'string' ? - Xml.textToDom(blockInfo['blockxml']) : - blockInfo['blockxml']; - gap = parseInt(xml.getAttribute('gap'), 10); - } - gaps.push(isNaN(gap) ? defaultGap : gap); -}; - -/** - * Add the necessary gap in the flyout for a separator. - * @param {!toolbox.SeparatorInfo} sepInfo The object holding - * information about a separator. - * @param {!Array} gaps The list gaps between items in the flyout. - * @param {number} defaultGap The default gap between the button and next - * element. - * @private - */ -Flyout.prototype.addSeparatorGap_ = function(sepInfo, gaps, defaultGap) { - // Change the gap between two toolbox elements. - // - // The default gap is 24, can be set larger or smaller. - // This overwrites the gap attribute on the previous element. - const newGap = parseInt(sepInfo['gap'], 10); - // Ignore gaps before the first block. - if (!isNaN(newGap) && gaps.length > 0) { - gaps[gaps.length - 1] = newGap; - } else { - gaps.push(defaultGap); - } -}; - -/** - * Delete blocks, mats and buttons from a previous showing of the flyout. - * @private - */ -Flyout.prototype.clearOldBlocks_ = function() { - // Delete any blocks from a previous showing. - const oldBlocks = this.workspace_.getTopBlocks(false); - for (let i = 0, block; (block = oldBlocks[i]); i++) { - if (this.blockIsRecyclable_(block)) { - this.recycleBlock_(block); - } else { - block.dispose(false, false); - } - } - // Delete any mats from a previous showing. - for (let j = 0; j < this.mats_.length; j++) { - const rect = this.mats_[j]; - if (rect) { - Tooltip.unbindMouseEvents(rect); - dom.removeNode(rect); - } - } - this.mats_.length = 0; - // Delete any buttons from a previous showing. - for (let i = 0, button; (button = this.buttons_[i]); i++) { - button.dispose(); - } - this.buttons_.length = 0; - - // Clear potential variables from the previous showing. - this.workspace_.getPotentialVariableMap().clear(); -}; - -/** - * Empties all of the recycled blocks, properly disposing of them. - * @private - */ -Flyout.prototype.emptyRecycledBlocks_ = function() { - for (let i = 0; i < this.recycledBlocks_.length; i++) { - this.recycledBlocks_[i].dispose(); - } - this.recycledBlocks_ = []; -}; - -/** - * Returns whether the given block can be recycled or not. - * @param {!BlockSvg} _block The block to check for recyclability. - * @return {boolean} True if the block can be recycled. False otherwise. - * @protected - */ -Flyout.prototype.blockIsRecyclable_ = function(_block) { - // By default, recycling is disabled. - return false; -}; - -/** - * Puts a previously created block into the recycle bin and moves it to the - * top of the workspace. Used during large workspace swaps to limit the number - * of new DOM elements we need to create. - * @param {!BlockSvg} block The block to recycle. - * @private - */ -Flyout.prototype.recycleBlock_ = function(block) { - const xy = block.getRelativeToSurfaceXY(); - block.moveBy(-xy.x, -xy.y); - this.recycledBlocks_.push(block); -}; - -/** - * Add listeners to a block that has been added to the flyout. - * @param {!SVGElement} root The root node of the SVG group the block is in. - * @param {!BlockSvg} block The block to add listeners for. - * @param {!SVGElement} rect The invisible rectangle under the block that acts - * as a mat for that block. - * @protected - */ -Flyout.prototype.addBlockListeners_ = function(root, block, rect) { - this.listeners_.push(browserEvents.conditionalBind( - root, 'mousedown', null, this.blockMouseDown_(block))); - this.listeners_.push(browserEvents.conditionalBind( - rect, 'mousedown', null, this.blockMouseDown_(block))); - this.listeners_.push( - browserEvents.bind(root, 'mouseenter', block, block.addSelect)); - this.listeners_.push( - browserEvents.bind(root, 'mouseleave', block, block.removeSelect)); - this.listeners_.push( - browserEvents.bind(rect, 'mouseenter', block, block.addSelect)); - this.listeners_.push( - browserEvents.bind(rect, 'mouseleave', block, block.removeSelect)); -}; - -/** - * Handle a mouse-down on an SVG block in a non-closing flyout. - * @param {!BlockSvg} block The flyout block to copy. - * @return {!Function} Function to call when block is clicked. - * @private - */ -Flyout.prototype.blockMouseDown_ = function(block) { - const flyout = this; - return function(e) { - const gesture = flyout.targetWorkspace.getGesture(e); - if (gesture) { - gesture.setStartBlock(block); - gesture.handleFlyoutStart(e, flyout); - } - }; -}; - -/** - * Mouse down on the flyout background. Start a vertical scroll drag. - * @param {!Event} e Mouse down event. - * @private - */ -Flyout.prototype.onMouseDown_ = function(e) { - const gesture = this.targetWorkspace.getGesture(e); - if (gesture) { - gesture.handleFlyoutStart(e, this); - } -}; - -/** - * Does this flyout allow you to create a new instance of the given block? - * Used for deciding if a block can be "dragged out of" the flyout. - * @param {!BlockSvg} block The block to copy from the flyout. - * @return {boolean} True if you can create a new instance of the block, false - * otherwise. - * @package - */ -Flyout.prototype.isBlockCreatable_ = function(block) { - return block.isEnabled(); -}; - -/** - * Create a copy of this block on the workspace. - * @param {!BlockSvg} originalBlock The block to copy from the flyout. - * @return {!BlockSvg} The newly created block. - * @throws {Error} if something went wrong with deserialization. - * @package - */ -Flyout.prototype.createBlock = function(originalBlock) { - let newBlock = null; - eventUtils.disable(); - const variablesBeforeCreation = this.targetWorkspace.getAllVariables(); - this.targetWorkspace.setResizesEnabled(false); - try { - newBlock = this.placeNewBlock_(originalBlock); - } finally { - eventUtils.enable(); - } - - // Close the flyout. - this.targetWorkspace.hideChaff(); - - const newVariables = Variables.getAddedVariables( - this.targetWorkspace, variablesBeforeCreation); - - if (eventUtils.isEnabled()) { - eventUtils.setGroup(true); - // Fire a VarCreate event for each (if any) new variable created. - for (let i = 0; i < newVariables.length; i++) { - const thisVariable = newVariables[i]; - eventUtils.fire( - new (eventUtils.get(eventUtils.VAR_CREATE))(thisVariable)); - } - - // Block events come after var events, in case they refer to newly created - // variables. - eventUtils.fire(new (eventUtils.get(eventUtils.BLOCK_CREATE))(newBlock)); - } - if (this.autoClose) { this.hide(); - } else { - this.filterForCapacity_(); + + Array.prototype.push.apply( + this.eventWrappers_, + browserEvents.conditionalBind( + /** @type {!SVGGElement} */ (this.svgGroup_), 'wheel', this, + this.wheel_)); + if (!this.autoClose) { + this.filterWrapper_ = this.filterForCapacity_.bind(this); + this.targetWorkspace.addChangeListener(this.filterWrapper_); + } + + // Dragging the flyout up and down. + Array.prototype.push.apply( + this.eventWrappers_, + browserEvents.conditionalBind( + /** @type {!SVGPathElement} */ (this.svgBackground_), 'mousedown', + this, this.onMouseDown_)); + + // A flyout connected to a workspace doesn't have its own current gesture. + this.workspace_.getGesture = + this.targetWorkspace.getGesture.bind(this.targetWorkspace); + + // Get variables from the main workspace rather than the target workspace. + this.workspace_.setVariableMap(this.targetWorkspace.getVariableMap()); + + this.workspace_.createPotentialVariableMap(); + + targetWorkspace.getComponentManager().addComponent({ + component: this, + weight: 1, + capabilities: [ + ComponentManager.Capability.DELETE_AREA, + ComponentManager.Capability.DRAG_TARGET, + ], + }); } - return newBlock; -}; -/** - * Initialize the given button: move it to the correct location, - * add listeners, etc. - * @param {!FlyoutButton} button The button to initialize and place. - * @param {number} x The x position of the cursor during this layout pass. - * @param {number} y The y position of the cursor during this layout pass. - * @protected - */ -Flyout.prototype.initFlyoutButton_ = function(button, x, y) { - const buttonSvg = button.createDom(); - button.moveTo(x, y); - button.show(); - // Clicking on a flyout button or label is a lot like clicking on the - // flyout background. - this.listeners_.push(browserEvents.conditionalBind( - buttonSvg, 'mousedown', this, this.onMouseDown_)); + /** + * Dispose of this flyout. + * Unlink from all DOM elements to prevent memory leaks. + * @suppress {checkTypes} + */ + dispose() { + this.hide(); + this.workspace_.getComponentManager().removeComponent(this.id); + browserEvents.unbind(this.eventWrappers_); + if (this.filterWrapper_) { + this.targetWorkspace.removeChangeListener(this.filterWrapper_); + this.filterWrapper_ = null; + } + if (this.workspace_) { + this.workspace_.getThemeManager().unsubscribe(this.svgBackground_); + this.workspace_.targetWorkspace = null; + this.workspace_.dispose(); + this.workspace_ = null; + } + if (this.svgGroup_) { + dom.removeNode(this.svgGroup_); + this.svgGroup_ = null; + } + this.svgBackground_ = null; + this.targetWorkspace = null; + } - this.buttons_.push(button); -}; + /** + * Get the width of the flyout. + * @return {number} The width of the flyout. + */ + getWidth() { + return this.width_; + } -/** - * Create and place a rectangle corresponding to the given block. - * @param {!BlockSvg} block The block to associate the rect to. - * @param {number} x The x position of the cursor during this layout pass. - * @param {number} y The y position of the cursor during this layout pass. - * @param {!{height: number, width: number}} blockHW The height and width of the - * block. - * @param {number} index The index into the mats list where this rect should be - * placed. - * @return {!SVGElement} Newly created SVG element for the rectangle behind the - * block. - * @protected - */ -Flyout.prototype.createRect_ = function(block, x, y, blockHW, index) { - // Create an invisible rectangle under the block to act as a button. Just - // using the block as a button is poor, since blocks have holes in them. - const rect = dom.createSvgElement( - Svg.RECT, { - 'fill-opacity': 0, - 'x': x, - 'y': y, - 'height': blockHW.height, - 'width': blockHW.width, - }, - null); - rect.tooltip = block; - Tooltip.bindMouseEvents(rect); - // Add the rectangles under the blocks, so that the blocks' tooltips work. - this.workspace_.getCanvas().insertBefore(rect, block.getSvgRoot()); + /** + * Get the height of the flyout. + * @return {number} The width of the flyout. + */ + getHeight() { + return this.height_; + } - block.flyoutRect_ = rect; - this.mats_[index] = rect; - return rect; -}; + /** + * Get the scale (zoom level) of the flyout. By default, + * this matches the target workspace scale, but this can be overridden. + * @return {number} Flyout workspace scale. + */ + getFlyoutScale() { + return this.targetWorkspace.scale; + } -/** - * Move a rectangle to sit exactly behind a block, taking into account tabs, - * hats, and any other protrusions we invent. - * @param {!SVGElement} rect The rectangle to move directly behind the block. - * @param {!BlockSvg} block The block the rectangle should be behind. - * @protected - */ -Flyout.prototype.moveRectToBlock_ = function(rect, block) { - const blockHW = block.getHeightWidth(); - rect.setAttribute('width', blockHW.width); - rect.setAttribute('height', blockHW.height); + /** + * Get the workspace inside the flyout. + * @return {!WorkspaceSvg} The workspace inside the flyout. + * @package + */ + getWorkspace() { + return this.workspace_; + } - const blockXY = block.getRelativeToSurfaceXY(); - rect.setAttribute('y', blockXY.y); - rect.setAttribute('x', this.RTL ? blockXY.x - blockHW.width : blockXY.x); -}; + /** + * Is the flyout visible? + * @return {boolean} True if visible. + */ + isVisible() { + return this.isVisible_; + } -/** - * Filter the blocks on the flyout to disable the ones that are above the - * capacity limit. For instance, if the user may only place two more blocks on - * the workspace, an "a + b" block that has two shadow blocks would be disabled. - * @private - */ -Flyout.prototype.filterForCapacity_ = function() { - const blocks = this.workspace_.getTopBlocks(false); - for (let i = 0, block; (block = blocks[i]); i++) { - if (this.permanentlyDisabled_.indexOf(block) === -1) { - const enable = this.targetWorkspace.isCapacityAvailable( - common.getBlockTypeCounts(block)); - while (block) { - block.setEnabled(enable); - block = block.getNextBlock(); + /** + * Set whether the flyout is visible. A value of true does not necessarily + * mean that the flyout is shown. It could be hidden because its container is + * hidden. + * @param {boolean} visible True if visible. + */ + setVisible(visible) { + const visibilityChanged = (visible !== this.isVisible()); + + this.isVisible_ = visible; + if (visibilityChanged) { + if (!this.autoClose) { + // Auto-close flyouts are ignored as drag targets, so only non + // auto-close flyouts need to have their drag target updated. + this.workspace_.recordDragTargets(); + } + this.updateDisplay_(); + } + } + + /** + * Set whether this flyout's container is visible. + * @param {boolean} visible Whether the container is visible. + */ + setContainerVisible(visible) { + const visibilityChanged = (visible !== this.containerVisible_); + this.containerVisible_ = visible; + if (visibilityChanged) { + this.updateDisplay_(); + } + } + + /** + * Update the display property of the flyout based whether it thinks it should + * be visible and whether its containing workspace is visible. + * @private + */ + updateDisplay_() { + let show = true; + if (!this.containerVisible_) { + show = false; + } else { + show = this.isVisible(); + } + this.svgGroup_.style.display = show ? 'block' : 'none'; + // Update the scrollbar's visibility too since it should mimic the + // flyout's visibility. + this.workspace_.scrollbar.setContainerVisible(show); + } + + /** + * Update the view based on coordinates calculated in position(). + * @param {number} width The computed width of the flyout's SVG group + * @param {number} height The computed height of the flyout's SVG group. + * @param {number} x The computed x origin of the flyout's SVG group. + * @param {number} y The computed y origin of the flyout's SVG group. + * @protected + */ + positionAt_(width, height, x, y) { + this.svgGroup_.setAttribute('width', width); + this.svgGroup_.setAttribute('height', height); + this.workspace_.setCachedParentSvgSize(width, height); + + if (this.svgGroup_.tagName === 'svg') { + const transform = 'translate(' + x + 'px,' + y + 'px)'; + dom.setCssTransform(this.svgGroup_, transform); + } else { + // IE and Edge don't support CSS transforms on SVG elements so + // it's important to set the transform on the SVG element itself + const transform = 'translate(' + x + ',' + y + ')'; + this.svgGroup_.setAttribute('transform', transform); + } + + // Update the scrollbar (if one exists). + const scrollbar = this.workspace_.scrollbar; + if (scrollbar) { + // Set the scrollbars origin to be the top left of the flyout. + scrollbar.setOrigin(x, y); + scrollbar.resize(); + // If origin changed and metrics haven't changed enough to trigger + // reposition in resize, we need to call setPosition. See issue #4692. + if (scrollbar.hScroll) { + scrollbar.hScroll.setPosition( + scrollbar.hScroll.position.x, scrollbar.hScroll.position.y); + } + if (scrollbar.vScroll) { + scrollbar.vScroll.setPosition( + scrollbar.vScroll.position.x, scrollbar.vScroll.position.y); } } } -}; -/** - * Reflow blocks and their mats. - */ -Flyout.prototype.reflow = function() { - if (this.reflowWrapper_) { - this.workspace_.removeChangeListener(this.reflowWrapper_); + /** + * Hide and empty the flyout. + */ + hide() { + if (!this.isVisible()) { + return; + } + this.setVisible(false); + // Delete all the event listeners. + for (let i = 0, listen; (listen = this.listeners_[i]); i++) { + browserEvents.unbind(listen); + } + this.listeners_.length = 0; + if (this.reflowWrapper_) { + this.workspace_.removeChangeListener(this.reflowWrapper_); + this.reflowWrapper_ = null; + } + // Do NOT delete the blocks here. Wait until Flyout.show. + // https://neil.fraser.name/news/2014/08/09/ } - this.reflowInternal_(); - if (this.reflowWrapper_) { + + /** + * Show and populate the flyout. + * @param {!toolbox.FlyoutDefinition|string} flyoutDef Contents to display + * in the flyout. This is either an array of Nodes, a NodeList, a + * toolbox definition, or a string with the name of the dynamic category. + */ + show(flyoutDef) { + this.workspace_.setResizesEnabled(false); + this.hide(); + this.clearOldBlocks_(); + + // Handle dynamic categories, represented by a name instead of a list. + if (typeof flyoutDef === 'string') { + flyoutDef = this.getDynamicCategoryContents_(flyoutDef); + } + this.setVisible(true); + + // Parse the Array, Node or NodeList into a a list of flyout items. + const parsedContent = toolbox.convertFlyoutDefToJsonArray(flyoutDef); + const flyoutInfo = + /** @type {{contents:!Array, gaps:!Array}} */ ( + this.createFlyoutInfo_(parsedContent)); + + this.layout_(flyoutInfo.contents, flyoutInfo.gaps); + + // IE 11 is an incompetent browser that fails to fire mouseout events. + // When the mouse is over the background, deselect all blocks. + const deselectAll = + /** @this {Flyout} */ + function() { + const topBlocks = this.workspace_.getTopBlocks(false); + for (let i = 0, block; (block = topBlocks[i]); i++) { + block.removeSelect(); + } + }; + + this.listeners_.push(browserEvents.conditionalBind( + /** @type {!SVGPathElement} */ (this.svgBackground_), 'mouseover', this, + deselectAll)); + + if (this.horizontalLayout) { + this.height_ = 0; + } else { + this.width_ = 0; + } + this.workspace_.setResizesEnabled(true); + this.reflow(); + + this.filterForCapacity_(); + + // Correctly position the flyout's scrollbar when it opens. + this.position(); + + this.reflowWrapper_ = this.reflow.bind(this); this.workspace_.addChangeListener(this.reflowWrapper_); - } -}; - -/** - * @return {boolean} True if this flyout may be scrolled with a scrollbar or by - * dragging. - * @package - */ -Flyout.prototype.isScrollable = function() { - return this.workspace_.scrollbar ? this.workspace_.scrollbar.isVisible() : - false; -}; - -/** - * Copy a block from the flyout to the workspace and position it correctly. - * @param {!BlockSvg} oldBlock The flyout block to copy. - * @return {!BlockSvg} The new block in the main workspace. - * @private - */ -Flyout.prototype.placeNewBlock_ = function(oldBlock) { - const targetWorkspace = this.targetWorkspace; - const svgRootOld = oldBlock.getSvgRoot(); - if (!svgRootOld) { - throw Error('oldBlock is not rendered.'); + this.emptyRecycledBlocks_(); } - // Clone the block. - const json = /** @type {!blocks.State} */ (blocks.save(oldBlock)); - // Normallly this resizes leading to weird jumps. Save it for terminateDrag. - targetWorkspace.setResizesEnabled(false); - const block = /** @type {!BlockSvg} */ (blocks.append(json, targetWorkspace)); + /** + * Create the contents array and gaps array necessary to create the layout for + * the flyout. + * @param {!toolbox.FlyoutItemInfoArray} parsedContent The array + * of objects to show in the flyout. + * @return {{contents:Array, gaps:Array}} The list of contents + * and gaps needed to lay out the flyout. + * @private + */ + createFlyoutInfo_(parsedContent) { + const contents = []; + const gaps = []; + this.permanentlyDisabled_.length = 0; + const defaultGap = this.horizontalLayout ? this.GAP_X : this.GAP_Y; + for (let i = 0, contentInfo; (contentInfo = parsedContent[i]); i++) { + if (contentInfo['custom']) { + const customInfo = + /** @type {!toolbox.DynamicCategoryInfo} */ (contentInfo); + const categoryName = customInfo['custom']; + const flyoutDef = this.getDynamicCategoryContents_(categoryName); + const parsedDynamicContent = /** @type {!toolbox.FlyoutItemInfoArray} */ + (toolbox.convertFlyoutDefToJsonArray(flyoutDef)); + // Replace the element at i with the dynamic content it represents. + parsedContent.splice.apply( + parsedContent, [i, 1].concat(parsedDynamicContent)); + contentInfo = parsedContent[i]; + } - this.positionNewBlock_(oldBlock, block); + switch (contentInfo['kind'].toUpperCase()) { + case 'BLOCK': { + const blockInfo = /** @type {!toolbox.BlockInfo} */ (contentInfo); + const block = this.createFlyoutBlock_(blockInfo); + contents.push({type: 'block', block: block}); + this.addBlockGap_(blockInfo, gaps, defaultGap); + break; + } + case 'SEP': { + const sepInfo = /** @type {!toolbox.SeparatorInfo} */ (contentInfo); + this.addSeparatorGap_(sepInfo, gaps, defaultGap); + break; + } + case 'LABEL': { + const labelInfo = /** @type {!toolbox.LabelInfo} */ (contentInfo); + // A label is a button with different styling. + const label = this.createButton_(labelInfo, /** isLabel */ true); + contents.push({type: 'button', button: label}); + gaps.push(defaultGap); + break; + } + case 'BUTTON': { + const buttonInfo = /** @type {!toolbox.ButtonInfo} */ (contentInfo); + const button = this.createButton_(buttonInfo, /** isLabel */ false); + contents.push({type: 'button', button: button}); + gaps.push(defaultGap); + break; + } + } + } + return {contents: contents, gaps: gaps}; + } - return block; -}; + /** + * Gets the flyout definition for the dynamic category. + * @param {string} categoryName The name of the dynamic category. + * @return {!toolbox.FlyoutDefinition} The definition of the + * flyout in one of its many forms. + * @private + */ + getDynamicCategoryContents_(categoryName) { + // Look up the correct category generation function and call that to get a + // valid XML list. + const fnToApply = + this.workspace_.targetWorkspace.getToolboxCategoryCallback( + categoryName); + if (typeof fnToApply !== 'function') { + throw TypeError( + 'Couldn\'t find a callback function when opening' + + ' a toolbox category.'); + } + return fnToApply(this.workspace_.targetWorkspace); + } -/** - * Positions a block on the target workspace. - * @param {!BlockSvg} oldBlock The flyout block being copied. - * @param {!BlockSvg} block The block to posiiton. - * @private - */ -Flyout.prototype.positionNewBlock_ = function(oldBlock, block) { - const targetWorkspace = this.targetWorkspace; + /** + * Creates a flyout button or a flyout label. + * @param {!toolbox.ButtonOrLabelInfo} btnInfo + * The object holding information about a button or a label. + * @param {boolean} isLabel True if the button is a label, false otherwise. + * @return {!FlyoutButton} The object used to display the button in the + * flyout. + * @private + */ + createButton_(btnInfo, isLabel) { + const {FlyoutButton} = goog.module.get('Blockly.FlyoutButton'); + if (!FlyoutButton) { + throw Error('Missing require for Blockly.FlyoutButton'); + } + const curButton = new FlyoutButton( + this.workspace_, + /** @type {!WorkspaceSvg} */ (this.targetWorkspace), btnInfo, isLabel); + return curButton; + } - // The offset in pixels between the main workspace's origin and the upper left - // corner of the injection div. - const mainOffsetPixels = targetWorkspace.getOriginOffsetInPixels(); + /** + * Create a block from the xml and permanently disable any blocks that were + * defined as disabled. + * @param {!toolbox.BlockInfo} blockInfo The info of the block. + * @return {!BlockSvg} The block created from the blockInfo. + * @private + */ + createFlyoutBlock_(blockInfo) { + let block; + if (blockInfo['blockxml']) { + const xml = typeof blockInfo['blockxml'] === 'string' ? + Xml.textToDom(blockInfo['blockxml']) : + blockInfo['blockxml']; + block = this.getRecycledBlock_(xml.getAttribute('type')); + if (!block) { + block = Xml.domToBlock(xml, this.workspace_); + } + } else { + block = this.getRecycledBlock_(blockInfo['type']); + if (!block) { + if (blockInfo['enabled'] === undefined) { + blockInfo['enabled'] = blockInfo['disabled'] !== 'true' && + blockInfo['disabled'] !== true; + } + block = blocks.append( + /** @type {blocks.State} */ (blockInfo), this.workspace_); + } + } - // The offset in pixels between the flyout workspace's origin and the upper - // left corner of the injection div. - const flyoutOffsetPixels = this.workspace_.getOriginOffsetInPixels(); + if (!block.isEnabled()) { + // Record blocks that were initially disabled. + // Do not enable these blocks as a result of capacity filtering. + this.permanentlyDisabled_.push(block); + } + return /** @type {!BlockSvg} */ (block); + } - // The position of the old block in flyout workspace coordinates. - const oldBlockPos = oldBlock.getRelativeToSurfaceXY(); - // The position of the old block in pixels relative to the flyout - // workspace's origin. - oldBlockPos.scale(this.workspace_.scale); + /** + * Returns a block from the array of recycled blocks with the given type, or + * undefined if one cannot be found. + * @param {string} blockType The type of the block to try to recycle. + * @return {(!BlockSvg|undefined)} The recycled block, or undefined if + * one could not be recycled. + * @private + */ + getRecycledBlock_(blockType) { + let index = -1; + for (let i = 0; i < this.recycledBlocks_.length; i++) { + if (this.recycledBlocks_[i].type === blockType) { + index = i; + break; + } + } + return index === -1 ? undefined : this.recycledBlocks_.splice(index, 1)[0]; + } - // The position of the old block in pixels relative to the upper left corner - // of the injection div. - const oldBlockOffsetPixels = Coordinate.sum(flyoutOffsetPixels, oldBlockPos); + /** + * Adds a gap in the flyout based on block info. + * @param {!toolbox.BlockInfo} blockInfo Information about a block. + * @param {!Array} gaps The list of gaps between items in the flyout. + * @param {number} defaultGap The default gap between one element and the + * next. + * @private + */ + addBlockGap_(blockInfo, gaps, defaultGap) { + let gap; + if (blockInfo['gap']) { + gap = parseInt(blockInfo['gap'], 10); + } else if (blockInfo['blockxml']) { + const xml = typeof blockInfo['blockxml'] === 'string' ? + Xml.textToDom(blockInfo['blockxml']) : + blockInfo['blockxml']; + gap = parseInt(xml.getAttribute('gap'), 10); + } + gaps.push(isNaN(gap) ? defaultGap : gap); + } - // The position of the old block in pixels relative to the origin of the - // main workspace. - const finalOffset = - Coordinate.difference(oldBlockOffsetPixels, mainOffsetPixels); - // The position of the old block in main workspace coordinates. - finalOffset.scale(1 / targetWorkspace.scale); + /** + * Add the necessary gap in the flyout for a separator. + * @param {!toolbox.SeparatorInfo} sepInfo The object holding + * information about a separator. + * @param {!Array} gaps The list gaps between items in the flyout. + * @param {number} defaultGap The default gap between the button and next + * element. + * @private + */ + addSeparatorGap_(sepInfo, gaps, defaultGap) { + // Change the gap between two toolbox elements. + // + // The default gap is 24, can be set larger or smaller. + // This overwrites the gap attribute on the previous element. + const newGap = parseInt(sepInfo['gap'], 10); + // Ignore gaps before the first block. + if (!isNaN(newGap) && gaps.length > 0) { + gaps[gaps.length - 1] = newGap; + } else { + gaps.push(defaultGap); + } + } - block.moveTo(new Coordinate(finalOffset.x, finalOffset.y)); -}; + /** + * Delete blocks, mats and buttons from a previous showing of the flyout. + * @private + */ + clearOldBlocks_() { + // Delete any blocks from a previous showing. + const oldBlocks = this.workspace_.getTopBlocks(false); + for (let i = 0, block; (block = oldBlocks[i]); i++) { + if (this.blockIsRecyclable_(block)) { + this.recycleBlock_(block); + } else { + block.dispose(false, false); + } + } + // Delete any mats from a previous showing. + for (let j = 0; j < this.mats_.length; j++) { + const rect = this.mats_[j]; + if (rect) { + Tooltip.unbindMouseEvents(rect); + dom.removeNode(rect); + } + } + this.mats_.length = 0; + // Delete any buttons from a previous showing. + for (let i = 0, button; (button = this.buttons_[i]); i++) { + button.dispose(); + } + this.buttons_.length = 0; + + // Clear potential variables from the previous showing. + this.workspace_.getPotentialVariableMap().clear(); + } + + /** + * Empties all of the recycled blocks, properly disposing of them. + * @private + */ + emptyRecycledBlocks_() { + for (let i = 0; i < this.recycledBlocks_.length; i++) { + this.recycledBlocks_[i].dispose(); + } + this.recycledBlocks_ = []; + } + + /** + * Returns whether the given block can be recycled or not. + * @param {!BlockSvg} _block The block to check for recyclability. + * @return {boolean} True if the block can be recycled. False otherwise. + * @protected + */ + blockIsRecyclable_(_block) { + // By default, recycling is disabled. + return false; + } + + /** + * Puts a previously created block into the recycle bin and moves it to the + * top of the workspace. Used during large workspace swaps to limit the number + * of new DOM elements we need to create. + * @param {!BlockSvg} block The block to recycle. + * @private + */ + recycleBlock_(block) { + const xy = block.getRelativeToSurfaceXY(); + block.moveBy(-xy.x, -xy.y); + this.recycledBlocks_.push(block); + } + + /** + * Add listeners to a block that has been added to the flyout. + * @param {!SVGElement} root The root node of the SVG group the block is in. + * @param {!BlockSvg} block The block to add listeners for. + * @param {!SVGElement} rect The invisible rectangle under the block that acts + * as a mat for that block. + * @protected + */ + addBlockListeners_(root, block, rect) { + this.listeners_.push(browserEvents.conditionalBind( + root, 'mousedown', null, this.blockMouseDown_(block))); + this.listeners_.push(browserEvents.conditionalBind( + rect, 'mousedown', null, this.blockMouseDown_(block))); + this.listeners_.push( + browserEvents.bind(root, 'mouseenter', block, block.addSelect)); + this.listeners_.push( + browserEvents.bind(root, 'mouseleave', block, block.removeSelect)); + this.listeners_.push( + browserEvents.bind(rect, 'mouseenter', block, block.addSelect)); + this.listeners_.push( + browserEvents.bind(rect, 'mouseleave', block, block.removeSelect)); + } + + /** + * Handle a mouse-down on an SVG block in a non-closing flyout. + * @param {!BlockSvg} block The flyout block to copy. + * @return {!Function} Function to call when block is clicked. + * @private + */ + blockMouseDown_(block) { + const flyout = this; + return function(e) { + const gesture = flyout.targetWorkspace.getGesture(e); + if (gesture) { + gesture.setStartBlock(block); + gesture.handleFlyoutStart(e, flyout); + } + }; + } + + /** + * Mouse down on the flyout background. Start a vertical scroll drag. + * @param {!Event} e Mouse down event. + * @private + */ + onMouseDown_(e) { + const gesture = this.targetWorkspace.getGesture(e); + if (gesture) { + gesture.handleFlyoutStart(e, this); + } + } + + /** + * Does this flyout allow you to create a new instance of the given block? + * Used for deciding if a block can be "dragged out of" the flyout. + * @param {!BlockSvg} block The block to copy from the flyout. + * @return {boolean} True if you can create a new instance of the block, false + * otherwise. + * @package + */ + isBlockCreatable_(block) { + return block.isEnabled(); + } + + /** + * Create a copy of this block on the workspace. + * @param {!BlockSvg} originalBlock The block to copy from the flyout. + * @return {!BlockSvg} The newly created block. + * @throws {Error} if something went wrong with deserialization. + * @package + */ + createBlock(originalBlock) { + let newBlock = null; + eventUtils.disable(); + const variablesBeforeCreation = this.targetWorkspace.getAllVariables(); + this.targetWorkspace.setResizesEnabled(false); + try { + newBlock = this.placeNewBlock_(originalBlock); + } finally { + eventUtils.enable(); + } + + // Close the flyout. + this.targetWorkspace.hideChaff(); + + const newVariables = Variables.getAddedVariables( + this.targetWorkspace, variablesBeforeCreation); + + if (eventUtils.isEnabled()) { + eventUtils.setGroup(true); + // Fire a VarCreate event for each (if any) new variable created. + for (let i = 0; i < newVariables.length; i++) { + const thisVariable = newVariables[i]; + eventUtils.fire( + new (eventUtils.get(eventUtils.VAR_CREATE))(thisVariable)); + } + + // Block events come after var events, in case they refer to newly created + // variables. + eventUtils.fire(new (eventUtils.get(eventUtils.BLOCK_CREATE))(newBlock)); + } + if (this.autoClose) { + this.hide(); + } else { + this.filterForCapacity_(); + } + return newBlock; + } + + /** + * Initialize the given button: move it to the correct location, + * add listeners, etc. + * @param {!FlyoutButton} button The button to initialize and place. + * @param {number} x The x position of the cursor during this layout pass. + * @param {number} y The y position of the cursor during this layout pass. + * @protected + */ + initFlyoutButton_(button, x, y) { + const buttonSvg = button.createDom(); + button.moveTo(x, y); + button.show(); + // Clicking on a flyout button or label is a lot like clicking on the + // flyout background. + this.listeners_.push(browserEvents.conditionalBind( + buttonSvg, 'mousedown', this, this.onMouseDown_)); + + this.buttons_.push(button); + } + + /** + * Create and place a rectangle corresponding to the given block. + * @param {!BlockSvg} block The block to associate the rect to. + * @param {number} x The x position of the cursor during this layout pass. + * @param {number} y The y position of the cursor during this layout pass. + * @param {!{height: number, width: number}} blockHW The height and width of + * the block. + * @param {number} index The index into the mats list where this rect should + * be placed. + * @return {!SVGElement} Newly created SVG element for the rectangle behind + * the block. + * @protected + */ + createRect_(block, x, y, blockHW, index) { + // Create an invisible rectangle under the block to act as a button. Just + // using the block as a button is poor, since blocks have holes in them. + const rect = dom.createSvgElement( + Svg.RECT, { + 'fill-opacity': 0, + 'x': x, + 'y': y, + 'height': blockHW.height, + 'width': blockHW.width, + }, + null); + rect.tooltip = block; + Tooltip.bindMouseEvents(rect); + // Add the rectangles under the blocks, so that the blocks' tooltips work. + this.workspace_.getCanvas().insertBefore(rect, block.getSvgRoot()); + + block.flyoutRect_ = rect; + this.mats_[index] = rect; + return rect; + } + + /** + * Move a rectangle to sit exactly behind a block, taking into account tabs, + * hats, and any other protrusions we invent. + * @param {!SVGElement} rect The rectangle to move directly behind the block. + * @param {!BlockSvg} block The block the rectangle should be behind. + * @protected + */ + moveRectToBlock_(rect, block) { + const blockHW = block.getHeightWidth(); + rect.setAttribute('width', blockHW.width); + rect.setAttribute('height', blockHW.height); + + const blockXY = block.getRelativeToSurfaceXY(); + rect.setAttribute('y', blockXY.y); + rect.setAttribute('x', this.RTL ? blockXY.x - blockHW.width : blockXY.x); + } + + /** + * Filter the blocks on the flyout to disable the ones that are above the + * capacity limit. For instance, if the user may only place two more blocks + * on the workspace, an "a + b" block that has two shadow blocks would be + * disabled. + * @private + */ + filterForCapacity_() { + const blocks = this.workspace_.getTopBlocks(false); + for (let i = 0, block; (block = blocks[i]); i++) { + if (this.permanentlyDisabled_.indexOf(block) === -1) { + const enable = this.targetWorkspace.isCapacityAvailable( + common.getBlockTypeCounts(block)); + while (block) { + block.setEnabled(enable); + block = block.getNextBlock(); + } + } + } + } + + /** + * Reflow blocks and their mats. + */ + reflow() { + if (this.reflowWrapper_) { + this.workspace_.removeChangeListener(this.reflowWrapper_); + } + this.reflowInternal_(); + if (this.reflowWrapper_) { + this.workspace_.addChangeListener(this.reflowWrapper_); + } + } + + /** + * @return {boolean} True if this flyout may be scrolled with a scrollbar or + * by dragging. + * @package + */ + isScrollable() { + return this.workspace_.scrollbar ? this.workspace_.scrollbar.isVisible() : + false; + } + + /** + * Copy a block from the flyout to the workspace and position it correctly. + * @param {!BlockSvg} oldBlock The flyout block to copy. + * @return {!BlockSvg} The new block in the main workspace. + * @private + */ + placeNewBlock_(oldBlock) { + const targetWorkspace = this.targetWorkspace; + const svgRootOld = oldBlock.getSvgRoot(); + if (!svgRootOld) { + throw Error('oldBlock is not rendered.'); + } + + // Clone the block. + const json = /** @type {!blocks.State} */ (blocks.save(oldBlock)); + // Normallly this resizes leading to weird jumps. Save it for terminateDrag. + targetWorkspace.setResizesEnabled(false); + const block = + /** @type {!BlockSvg} */ (blocks.append(json, targetWorkspace)); + + this.positionNewBlock_(oldBlock, block); + + return block; + } + + /** + * Positions a block on the target workspace. + * @param {!BlockSvg} oldBlock The flyout block being copied. + * @param {!BlockSvg} block The block to posiiton. + * @private + */ + positionNewBlock_(oldBlock, block) { + const targetWorkspace = this.targetWorkspace; + + // The offset in pixels between the main workspace's origin and the upper + // left corner of the injection div. + const mainOffsetPixels = targetWorkspace.getOriginOffsetInPixels(); + + // The offset in pixels between the flyout workspace's origin and the upper + // left corner of the injection div. + const flyoutOffsetPixels = this.workspace_.getOriginOffsetInPixels(); + + // The position of the old block in flyout workspace coordinates. + const oldBlockPos = oldBlock.getRelativeToSurfaceXY(); + // The position of the old block in pixels relative to the flyout + // workspace's origin. + oldBlockPos.scale(this.workspace_.scale); + + // The position of the old block in pixels relative to the upper left corner + // of the injection div. + const oldBlockOffsetPixels = + Coordinate.sum(flyoutOffsetPixels, oldBlockPos); + + // The position of the old block in pixels relative to the origin of the + // main workspace. + const finalOffset = + Coordinate.difference(oldBlockOffsetPixels, mainOffsetPixels); + // The position of the old block in main workspace coordinates. + finalOffset.scale(1 / targetWorkspace.scale); + + block.moveTo(new Coordinate(finalOffset.x, finalOffset.y)); + } +} /** * Returns the bounding rectangle of the drag target area in pixel units diff --git a/core/flyout_button.js b/core/flyout_button.js index a76b0fa85..427f2b694 100644 --- a/core/flyout_button.js +++ b/core/flyout_button.js @@ -29,286 +29,303 @@ const {WorkspaceSvg} = goog.requireType('Blockly.WorkspaceSvg'); /** - * Class for a button in the flyout. - * @param {!WorkspaceSvg} workspace The workspace in which to place this - * button. - * @param {!WorkspaceSvg} targetWorkspace The flyout's target workspace. - * @param {!toolbox.ButtonOrLabelInfo} json - * The JSON specifying the label/button. - * @param {boolean} isLabel Whether this button should be styled as a label. - * @constructor - * @package - * @alias Blockly.FlyoutButton + * Class for a button or label in the flyout. */ -const FlyoutButton = function(workspace, targetWorkspace, json, isLabel) { - // Labels behave the same as buttons, but are styled differently. +class FlyoutButton { + /** + * @param {!WorkspaceSvg} workspace The workspace in which to place this + * button. + * @param {!WorkspaceSvg} targetWorkspace The flyout's target workspace. + * @param {!toolbox.ButtonOrLabelInfo} json + * The JSON specifying the label/button. + * @param {boolean} isLabel Whether this button should be styled as a label. + * @package + * @alias Blockly.FlyoutButton + */ + constructor(workspace, targetWorkspace, json, isLabel) { + /** + * @type {!WorkspaceSvg} + * @private + */ + this.workspace_ = workspace; + + /** + * @type {!WorkspaceSvg} + * @private + */ + this.targetWorkspace_ = targetWorkspace; + + /** + * @type {string} + * @private + */ + this.text_ = json['text']; + + /** + * @type {!Coordinate} + * @private + */ + this.position_ = new Coordinate(0, 0); + + /** + * Whether this button should be styled as a label. + * Labels behave the same as buttons, but are styled differently. + * @type {boolean} + * @private + */ + this.isLabel_ = isLabel; + + /** + * The key to the function called when this button is clicked. + * @type {string} + * @private + */ + this.callbackKey_ = json['callbackKey'] || + /* Check the lower case version too to satisfy IE */ + json['callbackkey']; + + /** + * If specified, a CSS class to add to this button. + * @type {?string} + * @private + */ + this.cssClass_ = json['web-class'] || null; + + /** + * Mouse up event data. + * @type {?browserEvents.Data} + * @private + */ + this.onMouseUpWrapper_ = null; + + /** + * The JSON specifying the label / button. + * @type {!toolbox.ButtonOrLabelInfo} + */ + this.info = json; + + /** + * The width of the button's rect. + * @type {number} + */ + this.width = 0; + + /** + * The height of the button's rect. + * @type {number} + */ + this.height = 0; + + /** + * The root SVG group for the button or label. + * @type {?SVGGElement} + * @private + */ + this.svgGroup_ = null; + + /** + * The SVG element with the text of the label or button. + * @type {?SVGTextElement} + * @private + */ + this.svgText_ = null; + } /** - * @type {!WorkspaceSvg} + * Create the button elements. + * @return {!SVGElement} The button's SVG group. + */ + createDom() { + let cssClass = this.isLabel_ ? 'blocklyFlyoutLabel' : 'blocklyFlyoutButton'; + if (this.cssClass_) { + cssClass += ' ' + this.cssClass_; + } + + this.svgGroup_ = dom.createSvgElement( + Svg.G, {'class': cssClass}, this.workspace_.getCanvas()); + + let shadow; + if (!this.isLabel_) { + // Shadow rectangle (light source does not mirror in RTL). + shadow = dom.createSvgElement( + Svg.RECT, { + 'class': 'blocklyFlyoutButtonShadow', + 'rx': 4, + 'ry': 4, + 'x': 1, + 'y': 1, + }, + this.svgGroup_); + } + // Background rectangle. + const rect = dom.createSvgElement( + Svg.RECT, { + 'class': this.isLabel_ ? 'blocklyFlyoutLabelBackground' : + 'blocklyFlyoutButtonBackground', + 'rx': 4, + 'ry': 4, + }, + this.svgGroup_); + + const svgText = dom.createSvgElement( + Svg.TEXT, { + 'class': this.isLabel_ ? 'blocklyFlyoutLabelText' : 'blocklyText', + 'x': 0, + 'y': 0, + 'text-anchor': 'middle', + }, + this.svgGroup_); + let text = parsing.replaceMessageReferences(this.text_); + if (this.workspace_.RTL) { + // Force text to be RTL by adding an RLM. + text += '\u200F'; + } + svgText.textContent = text; + if (this.isLabel_) { + this.svgText_ = svgText; + this.workspace_.getThemeManager().subscribe( + this.svgText_, 'flyoutForegroundColour', 'fill'); + } + + const fontSize = style.getComputedStyle(svgText, 'fontSize'); + const fontWeight = style.getComputedStyle(svgText, 'fontWeight'); + const fontFamily = style.getComputedStyle(svgText, 'fontFamily'); + this.width = dom.getFastTextWidthWithSizeString( + svgText, fontSize, fontWeight, fontFamily); + const fontMetrics = + dom.measureFontMetrics(text, fontSize, fontWeight, fontFamily); + this.height = fontMetrics.height; + + if (!this.isLabel_) { + this.width += 2 * FlyoutButton.TEXT_MARGIN_X; + this.height += 2 * FlyoutButton.TEXT_MARGIN_Y; + shadow.setAttribute('width', this.width); + shadow.setAttribute('height', this.height); + } + rect.setAttribute('width', this.width); + rect.setAttribute('height', this.height); + + svgText.setAttribute('x', this.width / 2); + svgText.setAttribute( + 'y', this.height / 2 - fontMetrics.height / 2 + fontMetrics.baseline); + + this.updateTransform_(); + + this.onMouseUpWrapper_ = browserEvents.conditionalBind( + this.svgGroup_, 'mouseup', this, this.onMouseUp_); + return this.svgGroup_; + } + + /** + * Correctly position the flyout button and make it visible. + */ + show() { + this.updateTransform_(); + this.svgGroup_.setAttribute('display', 'block'); + } + + /** + * Update SVG attributes to match internal state. * @private */ - this.workspace_ = workspace; + updateTransform_() { + this.svgGroup_.setAttribute( + 'transform', + 'translate(' + this.position_.x + ',' + this.position_.y + ')'); + } /** - * @type {!WorkspaceSvg} + * Move the button to the given x, y coordinates. + * @param {number} x The new x coordinate. + * @param {number} y The new y coordinate. + */ + moveTo(x, y) { + this.position_.x = x; + this.position_.y = y; + this.updateTransform_(); + } + + /** + * @return {boolean} Whether or not the button is a label. + */ + isLabel() { + return this.isLabel_; + } + + /** + * Location of the button. + * @return {!Coordinate} x, y coordinates. + * @package + */ + getPosition() { + return this.position_; + } + + /** + * @return {string} Text of the button. + */ + getButtonText() { + return this.text_; + } + + /** + * Get the button's target workspace. + * @return {!WorkspaceSvg} The target workspace of the flyout where this + * button resides. + */ + getTargetWorkspace() { + return this.targetWorkspace_; + } + + /** + * Dispose of this button. + */ + dispose() { + if (this.onMouseUpWrapper_) { + browserEvents.unbind(this.onMouseUpWrapper_); + } + if (this.svgGroup_) { + dom.removeNode(this.svgGroup_); + } + if (this.svgText_) { + this.workspace_.getThemeManager().unsubscribe(this.svgText_); + } + } + + /** + * Do something when the button is clicked. + * @param {!Event} e Mouse up event. * @private */ - this.targetWorkspace_ = targetWorkspace; + onMouseUp_(e) { + const gesture = this.targetWorkspace_.getGesture(e); + if (gesture) { + gesture.cancel(); + } - /** - * @type {string} - * @private - */ - this.text_ = json['text']; - - /** - * @type {!Coordinate} - * @private - */ - this.position_ = new Coordinate(0, 0); - - /** - * Whether this button should be styled as a label. - * @type {boolean} - * @private - */ - this.isLabel_ = isLabel; - - /** - * The key to the function called when this button is clicked. - * @type {string} - * @private - */ - this.callbackKey_ = json['callbackKey'] || - /* Check the lower case version too to satisfy IE */ - json['callbackkey']; - - /** - * If specified, a CSS class to add to this button. - * @type {?string} - * @private - */ - this.cssClass_ = json['web-class'] || null; - - /** - * Mouse up event data. - * @type {?browserEvents.Data} - * @private - */ - this.onMouseUpWrapper_ = null; - - /** - * The JSON specifying the label / button. - * @type {!toolbox.ButtonOrLabelInfo} - */ - this.info = json; - - /** - * The width of the button's rect. - * @type {number} - */ - this.width = 0; - - /** - * The height of the button's rect. - * @type {number} - */ - this.height = 0; -}; + if (this.isLabel_ && this.callbackKey_) { + console.warn( + 'Labels should not have callbacks. Label text: ' + this.text_); + } else if ( + !this.isLabel_ && + !(this.callbackKey_ && + this.targetWorkspace_.getButtonCallback(this.callbackKey_))) { + console.warn('Buttons should have callbacks. Button text: ' + this.text_); + } else if (!this.isLabel_) { + this.targetWorkspace_.getButtonCallback(this.callbackKey_)(this); + } + } +} /** * The horizontal margin around the text in the button. */ -FlyoutButton.MARGIN_X = 5; +FlyoutButton.TEXT_MARGIN_X = 5; /** * The vertical margin around the text in the button. */ -FlyoutButton.MARGIN_Y = 2; - -/** - * Create the button elements. - * @return {!SVGElement} The button's SVG group. - */ -FlyoutButton.prototype.createDom = function() { - let cssClass = this.isLabel_ ? 'blocklyFlyoutLabel' : 'blocklyFlyoutButton'; - if (this.cssClass_) { - cssClass += ' ' + this.cssClass_; - } - - this.svgGroup_ = dom.createSvgElement( - Svg.G, {'class': cssClass}, this.workspace_.getCanvas()); - - let shadow; - if (!this.isLabel_) { - // Shadow rectangle (light source does not mirror in RTL). - shadow = dom.createSvgElement( - Svg.RECT, { - 'class': 'blocklyFlyoutButtonShadow', - 'rx': 4, - 'ry': 4, - 'x': 1, - 'y': 1, - }, - this.svgGroup_); - } - // Background rectangle. - const rect = dom.createSvgElement( - Svg.RECT, { - 'class': this.isLabel_ ? 'blocklyFlyoutLabelBackground' : - 'blocklyFlyoutButtonBackground', - 'rx': 4, - 'ry': 4, - }, - this.svgGroup_); - - const svgText = dom.createSvgElement( - Svg.TEXT, { - 'class': this.isLabel_ ? 'blocklyFlyoutLabelText' : 'blocklyText', - 'x': 0, - 'y': 0, - 'text-anchor': 'middle', - }, - this.svgGroup_); - let text = parsing.replaceMessageReferences(this.text_); - if (this.workspace_.RTL) { - // Force text to be RTL by adding an RLM. - text += '\u200F'; - } - svgText.textContent = text; - if (this.isLabel_) { - this.svgText_ = svgText; - this.workspace_.getThemeManager().subscribe( - this.svgText_, 'flyoutForegroundColour', 'fill'); - } - - const fontSize = style.getComputedStyle(svgText, 'fontSize'); - const fontWeight = style.getComputedStyle(svgText, 'fontWeight'); - const fontFamily = style.getComputedStyle(svgText, 'fontFamily'); - this.width = dom.getFastTextWidthWithSizeString( - svgText, fontSize, fontWeight, fontFamily); - const fontMetrics = - dom.measureFontMetrics(text, fontSize, fontWeight, fontFamily); - this.height = fontMetrics.height; - - if (!this.isLabel_) { - this.width += 2 * FlyoutButton.MARGIN_X; - this.height += 2 * FlyoutButton.MARGIN_Y; - shadow.setAttribute('width', this.width); - shadow.setAttribute('height', this.height); - } - rect.setAttribute('width', this.width); - rect.setAttribute('height', this.height); - - svgText.setAttribute('x', this.width / 2); - svgText.setAttribute( - 'y', this.height / 2 - fontMetrics.height / 2 + fontMetrics.baseline); - - this.updateTransform_(); - - this.onMouseUpWrapper_ = browserEvents.conditionalBind( - this.svgGroup_, 'mouseup', this, this.onMouseUp_); - return this.svgGroup_; -}; - -/** - * Correctly position the flyout button and make it visible. - */ -FlyoutButton.prototype.show = function() { - this.updateTransform_(); - this.svgGroup_.setAttribute('display', 'block'); -}; - -/** - * Update SVG attributes to match internal state. - * @private - */ -FlyoutButton.prototype.updateTransform_ = function() { - this.svgGroup_.setAttribute( - 'transform', - 'translate(' + this.position_.x + ',' + this.position_.y + ')'); -}; - -/** - * Move the button to the given x, y coordinates. - * @param {number} x The new x coordinate. - * @param {number} y The new y coordinate. - */ -FlyoutButton.prototype.moveTo = function(x, y) { - this.position_.x = x; - this.position_.y = y; - this.updateTransform_(); -}; - -/** - * @return {boolean} Whether or not the button is a label. - */ -FlyoutButton.prototype.isLabel = function() { - return this.isLabel_; -}; - -/** - * Location of the button. - * @return {!Coordinate} x, y coordinates. - * @package - */ -FlyoutButton.prototype.getPosition = function() { - return this.position_; -}; - -/** - * @return {string} Text of the button. - */ -FlyoutButton.prototype.getButtonText = function() { - return this.text_; -}; - -/** - * Get the button's target workspace. - * @return {!WorkspaceSvg} The target workspace of the flyout where this - * button resides. - */ -FlyoutButton.prototype.getTargetWorkspace = function() { - return this.targetWorkspace_; -}; - -/** - * Dispose of this button. - */ -FlyoutButton.prototype.dispose = function() { - if (this.onMouseUpWrapper_) { - browserEvents.unbind(this.onMouseUpWrapper_); - } - if (this.svgGroup_) { - dom.removeNode(this.svgGroup_); - } - if (this.svgText_) { - this.workspace_.getThemeManager().unsubscribe(this.svgText_); - } -}; - -/** - * Do something when the button is clicked. - * @param {!Event} e Mouse up event. - * @private - */ -FlyoutButton.prototype.onMouseUp_ = function(e) { - const gesture = this.targetWorkspace_.getGesture(e); - if (gesture) { - gesture.cancel(); - } - - if (this.isLabel_ && this.callbackKey_) { - console.warn('Labels should not have callbacks. Label text: ' + this.text_); - } else if ( - !this.isLabel_ && - !(this.callbackKey_ && - this.targetWorkspace_.getButtonCallback(this.callbackKey_))) { - console.warn('Buttons should have callbacks. Button text: ' + this.text_); - } else if (!this.isLabel_) { - this.targetWorkspace_.getButtonCallback(this.callbackKey_)(this); - } -}; +FlyoutButton.TEXT_MARGIN_Y = 2; /** * CSS for buttons and labels. See css.js for use. diff --git a/core/flyout_horizontal.js b/core/flyout_horizontal.js index 1ff150c4f..e09ced7f9 100644 --- a/core/flyout_horizontal.js +++ b/core/flyout_horizontal.js @@ -17,7 +17,6 @@ goog.module('Blockly.HorizontalFlyout'); const WidgetDiv = goog.require('Blockly.WidgetDiv'); const browserEvents = goog.require('Blockly.browserEvents'); -const object = goog.require('Blockly.utils.object'); const registry = goog.require('Blockly.registry'); const toolbox = goog.require('Blockly.utils.toolbox'); /* eslint-disable-next-line no-unused-vars */ @@ -32,355 +31,358 @@ const {Scrollbar} = goog.require('Blockly.Scrollbar'); /** * Class for a flyout. - * @param {!Options} workspaceOptions Dictionary of options for the - * workspace. * @extends {Flyout} - * @constructor - * @alias Blockly.HorizontalFlyout */ -const HorizontalFlyout = function(workspaceOptions) { - HorizontalFlyout.superClass_.constructor.call(this, workspaceOptions); - this.horizontalLayout = true; -}; -object.inherits(HorizontalFlyout, Flyout); - -/** - * Sets the translation of the flyout to match the scrollbars. - * @param {!{x:number,y:number}} xyRatio Contains a y property which is a float - * between 0 and 1 specifying the degree of scrolling and a - * similar x property. - * @protected - */ -HorizontalFlyout.prototype.setMetrics_ = function(xyRatio) { - if (!this.isVisible()) { - return; +class HorizontalFlyout extends Flyout { + /** + * @param {!Options} workspaceOptions Dictionary of options for the + * workspace. + * @alias Blockly.HorizontalFlyout + */ + constructor(workspaceOptions) { + super(workspaceOptions); + this.horizontalLayout = true; } - const metricsManager = this.workspace_.getMetricsManager(); - const scrollMetrics = metricsManager.getScrollMetrics(); - const viewMetrics = metricsManager.getViewMetrics(); - const absoluteMetrics = metricsManager.getAbsoluteMetrics(); + /** + * Sets the translation of the flyout to match the scrollbars. + * @param {!{x:number,y:number}} xyRatio Contains a y property which is a + * float between 0 and 1 specifying the degree of scrolling and a similar + * x property. + * @protected + */ + setMetrics_(xyRatio) { + if (!this.isVisible()) { + return; + } - if (typeof xyRatio.x === 'number') { - this.workspace_.scrollX = - -(scrollMetrics.left + - (scrollMetrics.width - viewMetrics.width) * xyRatio.x); + const metricsManager = this.workspace_.getMetricsManager(); + const scrollMetrics = metricsManager.getScrollMetrics(); + const viewMetrics = metricsManager.getViewMetrics(); + const absoluteMetrics = metricsManager.getAbsoluteMetrics(); + + if (typeof xyRatio.x === 'number') { + this.workspace_.scrollX = + -(scrollMetrics.left + + (scrollMetrics.width - viewMetrics.width) * xyRatio.x); + } + + this.workspace_.translate( + this.workspace_.scrollX + absoluteMetrics.left, + this.workspace_.scrollY + absoluteMetrics.top); } - this.workspace_.translate( - this.workspace_.scrollX + absoluteMetrics.left, - this.workspace_.scrollY + absoluteMetrics.top); -}; - -/** - * Calculates the x coordinate for the flyout position. - * @return {number} X coordinate. - */ -HorizontalFlyout.prototype.getX = function() { - // X is always 0 since this is a horizontal flyout. - return 0; -}; - -/** - * Calculates the y coordinate for the flyout position. - * @return {number} Y coordinate. - */ -HorizontalFlyout.prototype.getY = function() { - if (!this.isVisible()) { + /** + * Calculates the x coordinate for the flyout position. + * @return {number} X coordinate. + */ + getX() { + // X is always 0 since this is a horizontal flyout. return 0; } - const metricsManager = this.targetWorkspace.getMetricsManager(); - const absoluteMetrics = metricsManager.getAbsoluteMetrics(); - const viewMetrics = metricsManager.getViewMetrics(); - const toolboxMetrics = metricsManager.getToolboxMetrics(); - let y = 0; - const atTop = this.toolboxPosition_ === toolbox.Position.TOP; - // If this flyout is not the trashcan flyout (e.g. toolbox or mutator). - if (this.targetWorkspace.toolboxPosition === this.toolboxPosition_) { - // If there is a category toolbox. - if (this.targetWorkspace.getToolbox()) { - if (atTop) { - y = toolboxMetrics.height; + /** + * Calculates the y coordinate for the flyout position. + * @return {number} Y coordinate. + */ + getY() { + if (!this.isVisible()) { + return 0; + } + const metricsManager = this.targetWorkspace.getMetricsManager(); + const absoluteMetrics = metricsManager.getAbsoluteMetrics(); + const viewMetrics = metricsManager.getViewMetrics(); + const toolboxMetrics = metricsManager.getToolboxMetrics(); + + let y = 0; + const atTop = this.toolboxPosition_ === toolbox.Position.TOP; + // If this flyout is not the trashcan flyout (e.g. toolbox or mutator). + if (this.targetWorkspace.toolboxPosition === this.toolboxPosition_) { + // If there is a category toolbox. + if (this.targetWorkspace.getToolbox()) { + if (atTop) { + y = toolboxMetrics.height; + } else { + y = viewMetrics.height - this.height_; + } + // Simple (flyout-only) toolbox. } else { - y = viewMetrics.height - this.height_; + if (atTop) { + y = 0; + } else { + // The simple flyout does not cover the workspace. + y = viewMetrics.height; + } } - // Simple (flyout-only) toolbox. + // Trashcan flyout is opposite the main flyout. } else { if (atTop) { y = 0; } else { - // The simple flyout does not cover the workspace. - y = viewMetrics.height; + // Because the anchor point of the flyout is on the top, but we want + // to align the bottom edge of the flyout with the bottom edge of the + // blocklyDiv, we calculate the full height of the div minus the height + // of the flyout. + y = viewMetrics.height + absoluteMetrics.top - this.height_; } } - // Trashcan flyout is opposite the main flyout. - } else { + + return y; + } + + /** + * Move the flyout to the edge of the workspace. + */ + position() { + if (!this.isVisible() || !this.targetWorkspace.isVisible()) { + return; + } + const metricsManager = this.targetWorkspace.getMetricsManager(); + const targetWorkspaceViewMetrics = metricsManager.getViewMetrics(); + + // Record the width for workspace metrics. + this.width_ = targetWorkspaceViewMetrics.width; + + const edgeWidth = targetWorkspaceViewMetrics.width - 2 * this.CORNER_RADIUS; + const edgeHeight = this.height_ - this.CORNER_RADIUS; + this.setBackgroundPath_(edgeWidth, edgeHeight); + + const x = this.getX(); + const y = this.getY(); + + this.positionAt_(this.width_, this.height_, x, y); + } + + /** + * Create and set the path for the visible boundaries of the flyout. + * @param {number} width The width of the flyout, not including the + * rounded corners. + * @param {number} height The height of the flyout, not including + * rounded corners. + * @private + */ + setBackgroundPath_(width, height) { + const atTop = this.toolboxPosition_ === toolbox.Position.TOP; + // Start at top left. + const path = ['M 0,' + (atTop ? 0 : this.CORNER_RADIUS)]; + if (atTop) { - y = 0; + // Top. + path.push('h', width + 2 * this.CORNER_RADIUS); + // Right. + path.push('v', height); + // Bottom. + path.push( + 'a', this.CORNER_RADIUS, this.CORNER_RADIUS, 0, 0, 1, + -this.CORNER_RADIUS, this.CORNER_RADIUS); + path.push('h', -width); + // Left. + path.push( + 'a', this.CORNER_RADIUS, this.CORNER_RADIUS, 0, 0, 1, + -this.CORNER_RADIUS, -this.CORNER_RADIUS); + path.push('z'); } else { - // Because the anchor point of the flyout is on the top, but we want - // to align the bottom edge of the flyout with the bottom edge of the - // blocklyDiv, we calculate the full height of the div minus the height - // of the flyout. - y = viewMetrics.height + absoluteMetrics.top - this.height_; + // Top. + path.push( + 'a', this.CORNER_RADIUS, this.CORNER_RADIUS, 0, 0, 1, + this.CORNER_RADIUS, -this.CORNER_RADIUS); + path.push('h', width); + // Right. + path.push( + 'a', this.CORNER_RADIUS, this.CORNER_RADIUS, 0, 0, 1, + this.CORNER_RADIUS, this.CORNER_RADIUS); + path.push('v', height); + // Bottom. + path.push('h', -width - 2 * this.CORNER_RADIUS); + // Left. + path.push('z'); + } + this.svgBackground_.setAttribute('d', path.join(' ')); + } + + /** + * Scroll the flyout to the top. + */ + scrollToStart() { + this.workspace_.scrollbar.setX(this.RTL ? Infinity : 0); + } + + /** + * Scroll the flyout. + * @param {!Event} e Mouse wheel scroll event. + * @protected + */ + wheel_(e) { + const scrollDelta = browserEvents.getScrollDeltaPixels(e); + const delta = scrollDelta.x || scrollDelta.y; + + if (delta) { + const metricsManager = this.workspace_.getMetricsManager(); + const scrollMetrics = metricsManager.getScrollMetrics(); + const viewMetrics = metricsManager.getViewMetrics(); + + const pos = (viewMetrics.left - scrollMetrics.left) + delta; + this.workspace_.scrollbar.setX(pos); + // When the flyout moves from a wheel event, hide WidgetDiv and + // DropDownDiv. + WidgetDiv.hide(); + DropDownDiv.hideWithoutAnimation(); + } + + // Don't scroll the page. + e.preventDefault(); + // Don't propagate mousewheel event (zooming). + e.stopPropagation(); + } + + /** + * Lay out the blocks in the flyout. + * @param {!Array} contents The blocks and buttons to lay out. + * @param {!Array} gaps The visible gaps between blocks. + * @protected + */ + layout_(contents, gaps) { + this.workspace_.scale = this.targetWorkspace.scale; + const margin = this.MARGIN; + let cursorX = margin + this.tabWidth_; + const cursorY = margin; + if (this.RTL) { + contents = contents.reverse(); + } + + for (let i = 0, item; (item = contents[i]); i++) { + if (item.type === 'block') { + const block = item.block; + const allBlocks = block.getDescendants(false); + for (let j = 0, child; (child = allBlocks[j]); j++) { + // Mark blocks as being inside a flyout. This is used to detect and + // prevent the closure of the flyout if the user right-clicks on such + // a block. + child.isInFlyout = true; + } + block.render(); + const root = block.getSvgRoot(); + const blockHW = block.getHeightWidth(); + + // Figure out where to place the block. + const tab = block.outputConnection ? this.tabWidth_ : 0; + let moveX; + if (this.RTL) { + moveX = cursorX + blockHW.width; + } else { + moveX = cursorX - tab; + } + block.moveBy(moveX, cursorY); + + const rect = this.createRect_(block, moveX, cursorY, blockHW, i); + cursorX += (blockHW.width + gaps[i]); + + this.addBlockListeners_(root, block, rect); + } else if (item.type === 'button') { + this.initFlyoutButton_(item.button, cursorX, cursorY); + cursorX += (item.button.width + gaps[i]); + } } } - return y; -}; + /** + * Determine if a drag delta is toward the workspace, based on the position + * and orientation of the flyout. This is used in determineDragIntention_ to + * determine if a new block should be created or if the flyout should scroll. + * @param {!Coordinate} currentDragDeltaXY How far the pointer has + * moved from the position at mouse down, in pixel units. + * @return {boolean} True if the drag is toward the workspace. + * @package + */ + isDragTowardWorkspace(currentDragDeltaXY) { + const dx = currentDragDeltaXY.x; + const dy = currentDragDeltaXY.y; + // Direction goes from -180 to 180, with 0 toward the right and 90 on top. + const dragDirection = Math.atan2(dy, dx) / Math.PI * 180; -/** - * Move the flyout to the edge of the workspace. - */ -HorizontalFlyout.prototype.position = function() { - if (!this.isVisible() || !this.targetWorkspace.isVisible()) { - return; - } - const metricsManager = this.targetWorkspace.getMetricsManager(); - const targetWorkspaceViewMetrics = metricsManager.getViewMetrics(); - - // Record the width for workspace metrics. - this.width_ = targetWorkspaceViewMetrics.width; - - const edgeWidth = targetWorkspaceViewMetrics.width - 2 * this.CORNER_RADIUS; - const edgeHeight = this.height_ - this.CORNER_RADIUS; - this.setBackgroundPath_(edgeWidth, edgeHeight); - - const x = this.getX(); - const y = this.getY(); - - this.positionAt_(this.width_, this.height_, x, y); -}; - -/** - * Create and set the path for the visible boundaries of the flyout. - * @param {number} width The width of the flyout, not including the - * rounded corners. - * @param {number} height The height of the flyout, not including - * rounded corners. - * @private - */ -HorizontalFlyout.prototype.setBackgroundPath_ = function(width, height) { - const atTop = this.toolboxPosition_ === toolbox.Position.TOP; - // Start at top left. - const path = ['M 0,' + (atTop ? 0 : this.CORNER_RADIUS)]; - - if (atTop) { - // Top. - path.push('h', width + 2 * this.CORNER_RADIUS); - // Right. - path.push('v', height); - // Bottom. - path.push( - 'a', this.CORNER_RADIUS, this.CORNER_RADIUS, 0, 0, 1, - -this.CORNER_RADIUS, this.CORNER_RADIUS); - path.push('h', -width); - // Left. - path.push( - 'a', this.CORNER_RADIUS, this.CORNER_RADIUS, 0, 0, 1, - -this.CORNER_RADIUS, -this.CORNER_RADIUS); - path.push('z'); - } else { - // Top. - path.push( - 'a', this.CORNER_RADIUS, this.CORNER_RADIUS, 0, 0, 1, - this.CORNER_RADIUS, -this.CORNER_RADIUS); - path.push('h', width); - // Right. - path.push( - 'a', this.CORNER_RADIUS, this.CORNER_RADIUS, 0, 0, 1, - this.CORNER_RADIUS, this.CORNER_RADIUS); - path.push('v', height); - // Bottom. - path.push('h', -width - 2 * this.CORNER_RADIUS); - // Left. - path.push('z'); - } - this.svgBackground_.setAttribute('d', path.join(' ')); -}; - -/** - * Scroll the flyout to the top. - */ -HorizontalFlyout.prototype.scrollToStart = function() { - this.workspace_.scrollbar.setX(this.RTL ? Infinity : 0); -}; - -/** - * Scroll the flyout. - * @param {!Event} e Mouse wheel scroll event. - * @protected - */ -HorizontalFlyout.prototype.wheel_ = function(e) { - const scrollDelta = browserEvents.getScrollDeltaPixels(e); - const delta = scrollDelta.x || scrollDelta.y; - - if (delta) { - const metricsManager = this.workspace_.getMetricsManager(); - const scrollMetrics = metricsManager.getScrollMetrics(); - const viewMetrics = metricsManager.getViewMetrics(); - - const pos = (viewMetrics.left - scrollMetrics.left) + delta; - this.workspace_.scrollbar.setX(pos); - // When the flyout moves from a wheel event, hide WidgetDiv and DropDownDiv. - WidgetDiv.hide(); - DropDownDiv.hideWithoutAnimation(); + const range = this.dragAngleRange_; + // Check for up or down dragging. + if ((dragDirection < 90 + range && dragDirection > 90 - range) || + (dragDirection > -90 - range && dragDirection < -90 + range)) { + return true; + } + return false; } - // Don't scroll the page. - e.preventDefault(); - // Don't propagate mousewheel event (zooming). - e.stopPropagation(); -}; + /** + * Returns the bounding rectangle of the drag target area in pixel units + * relative to viewport. + * @return {?Rect} The component's bounding box. Null if drag + * target area should be ignored. + */ + getClientRect() { + if (!this.svgGroup_ || this.autoClose || !this.isVisible()) { + // The bounding rectangle won't compute correctly if the flyout is closed + // and auto-close flyouts aren't valid drag targets (or delete areas). + return null; + } -/** - * Lay out the blocks in the flyout. - * @param {!Array} contents The blocks and buttons to lay out. - * @param {!Array} gaps The visible gaps between blocks. - * @protected - */ -HorizontalFlyout.prototype.layout_ = function(contents, gaps) { - this.workspace_.scale = this.targetWorkspace.scale; - const margin = this.MARGIN; - let cursorX = margin + this.tabWidth_; - const cursorY = margin; - if (this.RTL) { - contents = contents.reverse(); - } + const flyoutRect = this.svgGroup_.getBoundingClientRect(); + // BIG_NUM is offscreen padding so that blocks dragged beyond the shown + // flyout area are still deleted. Must be larger than the largest screen + // size, but be smaller than half Number.MAX_SAFE_INTEGER (not available on + // IE). + const BIG_NUM = 1000000000; + const top = flyoutRect.top; - for (let i = 0, item; (item = contents[i]); i++) { - if (item.type === 'block') { - const block = item.block; - const allBlocks = block.getDescendants(false); - for (let j = 0, child; (child = allBlocks[j]); j++) { - // Mark blocks as being inside a flyout. This is used to detect and - // prevent the closure of the flyout if the user right-clicks on such a - // block. - child.isInFlyout = true; - } - block.render(); - const root = block.getSvgRoot(); - const blockHW = block.getHeightWidth(); - - // Figure out where to place the block. - const tab = block.outputConnection ? this.tabWidth_ : 0; - let moveX; - if (this.RTL) { - moveX = cursorX + blockHW.width; - } else { - moveX = cursorX - tab; - } - block.moveBy(moveX, cursorY); - - const rect = this.createRect_(block, moveX, cursorY, blockHW, i); - cursorX += (blockHW.width + gaps[i]); - - this.addBlockListeners_(root, block, rect); - } else if (item.type === 'button') { - this.initFlyoutButton_(item.button, cursorX, cursorY); - cursorX += (item.button.width + gaps[i]); + if (this.toolboxPosition_ === toolbox.Position.TOP) { + const height = flyoutRect.height; + return new Rect(-BIG_NUM, top + height, -BIG_NUM, BIG_NUM); + } else { // Bottom. + return new Rect(top, BIG_NUM, -BIG_NUM, BIG_NUM); } } -}; -/** - * Determine if a drag delta is toward the workspace, based on the position - * and orientation of the flyout. This is used in determineDragIntention_ to - * determine if a new block should be created or if the flyout should scroll. - * @param {!Coordinate} currentDragDeltaXY How far the pointer has - * moved from the position at mouse down, in pixel units. - * @return {boolean} True if the drag is toward the workspace. - * @package - */ -HorizontalFlyout.prototype.isDragTowardWorkspace = function( - currentDragDeltaXY) { - const dx = currentDragDeltaXY.x; - const dy = currentDragDeltaXY.y; - // Direction goes from -180 to 180, with 0 toward the right and 90 on top. - const dragDirection = Math.atan2(dy, dx) / Math.PI * 180; - - const range = this.dragAngleRange_; - // Check for up or down dragging. - if ((dragDirection < 90 + range && dragDirection > 90 - range) || - (dragDirection > -90 - range && dragDirection < -90 + range)) { - return true; - } - return false; -}; - -/** - * Returns the bounding rectangle of the drag target area in pixel units - * relative to viewport. - * @return {?Rect} The component's bounding box. Null if drag - * target area should be ignored. - */ -HorizontalFlyout.prototype.getClientRect = function() { - if (!this.svgGroup_ || this.autoClose || !this.isVisible()) { - // The bounding rectangle won't compute correctly if the flyout is closed - // and auto-close flyouts aren't valid drag targets (or delete areas). - return null; - } - - const flyoutRect = this.svgGroup_.getBoundingClientRect(); - // BIG_NUM is offscreen padding so that blocks dragged beyond the shown flyout - // area are still deleted. Must be larger than the largest screen size, - // but be smaller than half Number.MAX_SAFE_INTEGER (not available on IE). - const BIG_NUM = 1000000000; - const top = flyoutRect.top; - - if (this.toolboxPosition_ === toolbox.Position.TOP) { - const height = flyoutRect.height; - return new Rect(-BIG_NUM, top + height, -BIG_NUM, BIG_NUM); - } else { // Bottom. - return new Rect(top, BIG_NUM, -BIG_NUM, BIG_NUM); - } -}; - -/** - * Compute height of flyout. toolbox.Position mat under each block. - * For RTL: Lay out the blocks right-aligned. - * @protected - */ -HorizontalFlyout.prototype.reflowInternal_ = function() { - this.workspace_.scale = this.getFlyoutScale(); - let flyoutHeight = 0; - const blocks = this.workspace_.getTopBlocks(false); - for (let i = 0, block; (block = blocks[i]); i++) { - flyoutHeight = Math.max(flyoutHeight, block.getHeightWidth().height); - } - const buttons = this.buttons_; - for (let i = 0, button; (button = buttons[i]); i++) { - flyoutHeight = Math.max(flyoutHeight, button.height); - } - flyoutHeight += this.MARGIN * 1.5; - flyoutHeight *= this.workspace_.scale; - flyoutHeight += Scrollbar.scrollbarThickness; - - if (this.height_ !== flyoutHeight) { + /** + * Compute height of flyout. toolbox.Position mat under each block. + * For RTL: Lay out the blocks right-aligned. + * @protected + */ + reflowInternal_() { + this.workspace_.scale = this.getFlyoutScale(); + let flyoutHeight = 0; + const blocks = this.workspace_.getTopBlocks(false); for (let i = 0, block; (block = blocks[i]); i++) { - if (block.flyoutRect_) { - this.moveRectToBlock_(block.flyoutRect_, block); + flyoutHeight = Math.max(flyoutHeight, block.getHeightWidth().height); + } + const buttons = this.buttons_; + for (let i = 0, button; (button = buttons[i]); i++) { + flyoutHeight = Math.max(flyoutHeight, button.height); + } + flyoutHeight += this.MARGIN * 1.5; + flyoutHeight *= this.workspace_.scale; + flyoutHeight += Scrollbar.scrollbarThickness; + + if (this.height_ !== flyoutHeight) { + for (let i = 0, block; (block = blocks[i]); i++) { + if (block.flyoutRect_) { + this.moveRectToBlock_(block.flyoutRect_, block); + } } - } - if (this.targetWorkspace.toolboxPosition === this.toolboxPosition_ && - this.toolboxPosition_ === toolbox.Position.TOP && - !this.targetWorkspace.getToolbox()) { - // This flyout is a simple toolbox. Reposition the workspace so that (0,0) - // is in the correct position relative to the new absolute edge (ie - // toolbox edge). - this.targetWorkspace.translate( - this.targetWorkspace.scrollX, - this.targetWorkspace.scrollY + flyoutHeight); - } + if (this.targetWorkspace.toolboxPosition === this.toolboxPosition_ && + this.toolboxPosition_ === toolbox.Position.TOP && + !this.targetWorkspace.getToolbox()) { + // This flyout is a simple toolbox. Reposition the workspace so that + // (0,0) is in the correct position relative to the new absolute edge + // (ie toolbox edge). + this.targetWorkspace.translate( + this.targetWorkspace.scrollX, + this.targetWorkspace.scrollY + flyoutHeight); + } - // Record the height for workspace metrics and .position. - this.height_ = flyoutHeight; - this.position(); - this.targetWorkspace.recordDragTargets(); + // Record the height for workspace metrics and .position. + this.height_ = flyoutHeight; + this.position(); + this.targetWorkspace.recordDragTargets(); + } } -}; +} registry.register( registry.Type.FLYOUTS_HORIZONTAL_TOOLBOX, registry.DEFAULT, diff --git a/core/flyout_metrics_manager.js b/core/flyout_metrics_manager.js index ddbabd2a6..ec01db1b3 100644 --- a/core/flyout_metrics_manager.js +++ b/core/flyout_metrics_manager.js @@ -15,7 +15,6 @@ */ goog.module('Blockly.FlyoutMetricsManager'); -const object = goog.require('Blockly.utils.object'); /* eslint-disable-next-line no-unused-vars */ const {IFlyout} = goog.requireType('Blockly.IFlyout'); const {MetricsManager} = goog.require('Blockly.MetricsManager'); @@ -26,81 +25,82 @@ const {WorkspaceSvg} = goog.requireType('Blockly.WorkspaceSvg'); /** * Calculates metrics for a flyout's workspace. * The metrics are mainly used to size scrollbars for the flyout. - * @param {!WorkspaceSvg} workspace The flyout's workspace. - * @param {!IFlyout} flyout The flyout. * @extends {MetricsManager} - * @constructor - * @alias Blockly.FlyoutMetricsManager */ -const FlyoutMetricsManager = function(workspace, flyout) { +class FlyoutMetricsManager extends MetricsManager { /** - * The flyout that owns the workspace to calculate metrics for. - * @type {!IFlyout} - * @protected + * @param {!WorkspaceSvg} workspace The flyout's workspace. + * @param {!IFlyout} flyout The flyout. + * @alias Blockly.FlyoutMetricsManager */ - this.flyout_ = flyout; + constructor(workspace, flyout) { + super(workspace); - FlyoutMetricsManager.superClass_.constructor.call(this, workspace); -}; -object.inherits(FlyoutMetricsManager, MetricsManager); - -/** - * Gets the bounding box of the blocks on the flyout's workspace. - * This is in workspace coordinates. - * @return {!SVGRect|{height: number, y: number, width: number, x: number}} The - * bounding box of the blocks on the workspace. - * @private - */ -FlyoutMetricsManager.prototype.getBoundingBox_ = function() { - let blockBoundingBox; - try { - blockBoundingBox = this.workspace_.getCanvas().getBBox(); - } catch (e) { - // Firefox has trouble with hidden elements (Bug 528969). - // 2021 Update: It looks like this was fixed around Firefox 77 released in - // 2020. - blockBoundingBox = {height: 0, y: 0, width: 0, x: 0}; + /** + * The flyout that owns the workspace to calculate metrics for. + * @type {!IFlyout} + * @protected + */ + this.flyout_ = flyout; } - return blockBoundingBox; -}; -/** - * @override - */ -FlyoutMetricsManager.prototype.getContentMetrics = function( - opt_getWorkspaceCoordinates) { - // The bounding box is in workspace coordinates. - const blockBoundingBox = this.getBoundingBox_(); - const scale = opt_getWorkspaceCoordinates ? 1 : this.workspace_.scale; + /** + * Gets the bounding box of the blocks on the flyout's workspace. + * This is in workspace coordinates. + * @return {!SVGRect|{height: number, y: number, width: number, x: number}} + * The bounding box of the blocks on the workspace. + * @private + */ + getBoundingBox_() { + let blockBoundingBox; + try { + blockBoundingBox = this.workspace_.getCanvas().getBBox(); + } catch (e) { + // Firefox has trouble with hidden elements (Bug 528969). + // 2021 Update: It looks like this was fixed around Firefox 77 released in + // 2020. + blockBoundingBox = {height: 0, y: 0, width: 0, x: 0}; + } + return blockBoundingBox; + } - return { - height: blockBoundingBox.height * scale, - width: blockBoundingBox.width * scale, - top: blockBoundingBox.y * scale, - left: blockBoundingBox.x * scale, - }; -}; + /** + * @override + */ + getContentMetrics(opt_getWorkspaceCoordinates) { + // The bounding box is in workspace coordinates. + const blockBoundingBox = this.getBoundingBox_(); + const scale = opt_getWorkspaceCoordinates ? 1 : this.workspace_.scale; -/** - * @override - */ -FlyoutMetricsManager.prototype.getScrollMetrics = function( - opt_getWorkspaceCoordinates, opt_viewMetrics, opt_contentMetrics) { - const contentMetrics = opt_contentMetrics || this.getContentMetrics(); - const margin = this.flyout_.MARGIN * this.workspace_.scale; - const scale = opt_getWorkspaceCoordinates ? this.workspace_.scale : 1; + return { + height: blockBoundingBox.height * scale, + width: blockBoundingBox.width * scale, + top: blockBoundingBox.y * scale, + left: blockBoundingBox.x * scale, + }; + } - // The left padding isn't just the margin. Some blocks are also offset by - // tabWidth so that value and statement blocks line up. - // The contentMetrics.left value is equivalent to the variable left padding. - const leftPadding = contentMetrics.left; + /** + * @override + */ + getScrollMetrics( + opt_getWorkspaceCoordinates, opt_viewMetrics, opt_contentMetrics) { + const contentMetrics = opt_contentMetrics || this.getContentMetrics(); + const margin = this.flyout_.MARGIN * this.workspace_.scale; + const scale = opt_getWorkspaceCoordinates ? this.workspace_.scale : 1; - return { - height: (contentMetrics.height + 2 * margin) / scale, - width: (contentMetrics.width + leftPadding + margin) / scale, - top: 0, - left: 0, - }; -}; + // The left padding isn't just the margin. Some blocks are also offset by + // tabWidth so that value and statement blocks line up. + // The contentMetrics.left value is equivalent to the variable left padding. + const leftPadding = contentMetrics.left; + + return { + height: (contentMetrics.height + 2 * margin) / scale, + width: (contentMetrics.width + leftPadding + margin) / scale, + top: 0, + left: 0, + }; + } +} exports.FlyoutMetricsManager = FlyoutMetricsManager; diff --git a/core/flyout_vertical.js b/core/flyout_vertical.js index b6e985f99..546124eeb 100644 --- a/core/flyout_vertical.js +++ b/core/flyout_vertical.js @@ -17,7 +17,6 @@ goog.module('Blockly.VerticalFlyout'); const WidgetDiv = goog.require('Blockly.WidgetDiv'); const browserEvents = goog.require('Blockly.browserEvents'); -const object = goog.require('Blockly.utils.object'); const registry = goog.require('Blockly.registry'); const toolbox = goog.require('Blockly.utils.toolbox'); /* eslint-disable-next-line no-unused-vars */ @@ -36,16 +35,353 @@ goog.require('Blockly.constants'); /** * Class for a flyout. - * @param {!Options} workspaceOptions Dictionary of options for the - * workspace. * @extends {Flyout} - * @constructor - * @alias Blockly.VerticalFlyout */ -const VerticalFlyout = function(workspaceOptions) { - VerticalFlyout.superClass_.constructor.call(this, workspaceOptions); -}; -object.inherits(VerticalFlyout, Flyout); +class VerticalFlyout extends Flyout { + /** + * @param {!Options} workspaceOptions Dictionary of options for the + * workspace. + * @alias Blockly.VerticalFlyout + */ + constructor(workspaceOptions) { + super(workspaceOptions); + } + + /** + * Sets the translation of the flyout to match the scrollbars. + * @param {!{x:number,y:number}} xyRatio Contains a y property which is a + * float between 0 and 1 specifying the degree of scrolling and a similar + * x property. + * @protected + */ + setMetrics_(xyRatio) { + if (!this.isVisible()) { + return; + } + const metricsManager = this.workspace_.getMetricsManager(); + const scrollMetrics = metricsManager.getScrollMetrics(); + const viewMetrics = metricsManager.getViewMetrics(); + const absoluteMetrics = metricsManager.getAbsoluteMetrics(); + + if (typeof xyRatio.y === 'number') { + this.workspace_.scrollY = + -(scrollMetrics.top + + (scrollMetrics.height - viewMetrics.height) * xyRatio.y); + } + this.workspace_.translate( + this.workspace_.scrollX + absoluteMetrics.left, + this.workspace_.scrollY + absoluteMetrics.top); + } + + /** + * Calculates the x coordinate for the flyout position. + * @return {number} X coordinate. + */ + getX() { + if (!this.isVisible()) { + return 0; + } + const metricsManager = this.targetWorkspace.getMetricsManager(); + const absoluteMetrics = metricsManager.getAbsoluteMetrics(); + const viewMetrics = metricsManager.getViewMetrics(); + const toolboxMetrics = metricsManager.getToolboxMetrics(); + let x = 0; + + // If this flyout is not the trashcan flyout (e.g. toolbox or mutator). + if (this.targetWorkspace.toolboxPosition === this.toolboxPosition_) { + // If there is a category toolbox. + if (this.targetWorkspace.getToolbox()) { + if (this.toolboxPosition_ === toolbox.Position.LEFT) { + x = toolboxMetrics.width; + } else { + x = viewMetrics.width - this.width_; + } + // Simple (flyout-only) toolbox. + } else { + if (this.toolboxPosition_ === toolbox.Position.LEFT) { + x = 0; + } else { + // The simple flyout does not cover the workspace. + x = viewMetrics.width; + } + } + // Trashcan flyout is opposite the main flyout. + } else { + if (this.toolboxPosition_ === toolbox.Position.LEFT) { + x = 0; + } else { + // Because the anchor point of the flyout is on the left, but we want + // to align the right edge of the flyout with the right edge of the + // blocklyDiv, we calculate the full width of the div minus the width + // of the flyout. + x = viewMetrics.width + absoluteMetrics.left - this.width_; + } + } + + return x; + } + + /** + * Calculates the y coordinate for the flyout position. + * @return {number} Y coordinate. + */ + getY() { + // Y is always 0 since this is a vertical flyout. + return 0; + } + + /** + * Move the flyout to the edge of the workspace. + */ + position() { + if (!this.isVisible() || !this.targetWorkspace.isVisible()) { + return; + } + const metricsManager = this.targetWorkspace.getMetricsManager(); + const targetWorkspaceViewMetrics = metricsManager.getViewMetrics(); + + // Record the height for workspace metrics. + this.height_ = targetWorkspaceViewMetrics.height; + + const edgeWidth = this.width_ - this.CORNER_RADIUS; + const edgeHeight = + targetWorkspaceViewMetrics.height - 2 * this.CORNER_RADIUS; + this.setBackgroundPath_(edgeWidth, edgeHeight); + + const x = this.getX(); + const y = this.getY(); + + this.positionAt_(this.width_, this.height_, x, y); + } + + /** + * Create and set the path for the visible boundaries of the flyout. + * @param {number} width The width of the flyout, not including the + * rounded corners. + * @param {number} height The height of the flyout, not including + * rounded corners. + * @private + */ + setBackgroundPath_(width, height) { + const atRight = this.toolboxPosition_ === toolbox.Position.RIGHT; + const totalWidth = width + this.CORNER_RADIUS; + + // Decide whether to start on the left or right. + const path = ['M ' + (atRight ? totalWidth : 0) + ',0']; + // Top. + path.push('h', atRight ? -width : width); + // Rounded corner. + path.push( + 'a', this.CORNER_RADIUS, this.CORNER_RADIUS, 0, 0, atRight ? 0 : 1, + atRight ? -this.CORNER_RADIUS : this.CORNER_RADIUS, this.CORNER_RADIUS); + // Side closest to workspace. + path.push('v', Math.max(0, height)); + // Rounded corner. + path.push( + 'a', this.CORNER_RADIUS, this.CORNER_RADIUS, 0, 0, atRight ? 0 : 1, + atRight ? this.CORNER_RADIUS : -this.CORNER_RADIUS, this.CORNER_RADIUS); + // Bottom. + path.push('h', atRight ? width : -width); + path.push('z'); + this.svgBackground_.setAttribute('d', path.join(' ')); + } + + /** + * Scroll the flyout to the top. + */ + scrollToStart() { + this.workspace_.scrollbar.setY(0); + } + + /** + * Scroll the flyout. + * @param {!Event} e Mouse wheel scroll event. + * @protected + */ + wheel_(e) { + const scrollDelta = browserEvents.getScrollDeltaPixels(e); + + if (scrollDelta.y) { + const metricsManager = this.workspace_.getMetricsManager(); + const scrollMetrics = metricsManager.getScrollMetrics(); + const viewMetrics = metricsManager.getViewMetrics(); + const pos = (viewMetrics.top - scrollMetrics.top) + scrollDelta.y; + + this.workspace_.scrollbar.setY(pos); + // When the flyout moves from a wheel event, hide WidgetDiv and + // DropDownDiv. + WidgetDiv.hide(); + DropDownDiv.hideWithoutAnimation(); + } + + // Don't scroll the page. + e.preventDefault(); + // Don't propagate mousewheel event (zooming). + e.stopPropagation(); + } + + /** + * Lay out the blocks in the flyout. + * @param {!Array} contents The blocks and buttons to lay out. + * @param {!Array} gaps The visible gaps between blocks. + * @protected + */ + layout_(contents, gaps) { + this.workspace_.scale = this.targetWorkspace.scale; + const margin = this.MARGIN; + const cursorX = this.RTL ? margin : margin + this.tabWidth_; + let cursorY = margin; + + for (let i = 0, item; (item = contents[i]); i++) { + if (item.type === 'block') { + const block = item.block; + const allBlocks = block.getDescendants(false); + for (let j = 0, child; (child = allBlocks[j]); j++) { + // Mark blocks as being inside a flyout. This is used to detect and + // prevent the closure of the flyout if the user right-clicks on such + // a block. + child.isInFlyout = true; + } + block.render(); + const root = block.getSvgRoot(); + const blockHW = block.getHeightWidth(); + const moveX = + block.outputConnection ? cursorX - this.tabWidth_ : cursorX; + block.moveBy(moveX, cursorY); + + const rect = this.createRect_( + block, this.RTL ? moveX - blockHW.width : moveX, cursorY, blockHW, + i); + + this.addBlockListeners_(root, block, rect); + + cursorY += blockHW.height + gaps[i]; + } else if (item.type === 'button') { + this.initFlyoutButton_(item.button, cursorX, cursorY); + cursorY += item.button.height + gaps[i]; + } + } + } + + /** + * Determine if a drag delta is toward the workspace, based on the position + * and orientation of the flyout. This is used in determineDragIntention_ to + * determine if a new block should be created or if the flyout should scroll. + * @param {!Coordinate} currentDragDeltaXY How far the pointer has + * moved from the position at mouse down, in pixel units. + * @return {boolean} True if the drag is toward the workspace. + * @package + */ + isDragTowardWorkspace(currentDragDeltaXY) { + const dx = currentDragDeltaXY.x; + const dy = currentDragDeltaXY.y; + // Direction goes from -180 to 180, with 0 toward the right and 90 on top. + const dragDirection = Math.atan2(dy, dx) / Math.PI * 180; + + const range = this.dragAngleRange_; + // Check for left or right dragging. + if ((dragDirection < range && dragDirection > -range) || + (dragDirection < -180 + range || dragDirection > 180 - range)) { + return true; + } + return false; + } + + /** + * Returns the bounding rectangle of the drag target area in pixel units + * relative to viewport. + * @return {?Rect} The component's bounding box. Null if drag + * target area should be ignored. + */ + getClientRect() { + if (!this.svgGroup_ || this.autoClose || !this.isVisible()) { + // The bounding rectangle won't compute correctly if the flyout is closed + // and auto-close flyouts aren't valid drag targets (or delete areas). + return null; + } + + const flyoutRect = this.svgGroup_.getBoundingClientRect(); + // BIG_NUM is offscreen padding so that blocks dragged beyond the shown + // flyout area are still deleted. Must be larger than the largest screen + // size, but be smaller than half Number.MAX_SAFE_INTEGER (not available on + // IE). + const BIG_NUM = 1000000000; + const left = flyoutRect.left; + + if (this.toolboxPosition_ === toolbox.Position.LEFT) { + const width = flyoutRect.width; + return new Rect(-BIG_NUM, BIG_NUM, -BIG_NUM, left + width); + } else { // Right + return new Rect(-BIG_NUM, BIG_NUM, left, BIG_NUM); + } + } + + /** + * Compute width of flyout. toolbox.Position mat under each block. + * For RTL: Lay out the blocks and buttons to be right-aligned. + * @protected + */ + reflowInternal_() { + this.workspace_.scale = this.getFlyoutScale(); + let flyoutWidth = 0; + const blocks = this.workspace_.getTopBlocks(false); + for (let i = 0, block; (block = blocks[i]); i++) { + let width = block.getHeightWidth().width; + if (block.outputConnection) { + width -= this.tabWidth_; + } + flyoutWidth = Math.max(flyoutWidth, width); + } + for (let i = 0, button; (button = this.buttons_[i]); i++) { + flyoutWidth = Math.max(flyoutWidth, button.width); + } + flyoutWidth += this.MARGIN * 1.5 + this.tabWidth_; + flyoutWidth *= this.workspace_.scale; + flyoutWidth += Scrollbar.scrollbarThickness; + + if (this.width_ !== flyoutWidth) { + for (let i = 0, block; (block = blocks[i]); i++) { + if (this.RTL) { + // With the flyoutWidth known, right-align the blocks. + const oldX = block.getRelativeToSurfaceXY().x; + let newX = flyoutWidth / this.workspace_.scale - this.MARGIN; + if (!block.outputConnection) { + newX -= this.tabWidth_; + } + block.moveBy(newX - oldX, 0); + } + if (block.flyoutRect_) { + this.moveRectToBlock_(block.flyoutRect_, block); + } + } + if (this.RTL) { + // With the flyoutWidth known, right-align the buttons. + for (let i = 0, button; (button = this.buttons_[i]); i++) { + const y = button.getPosition().y; + const x = flyoutWidth / this.workspace_.scale - button.width - + this.MARGIN - this.tabWidth_; + button.moveTo(x, y); + } + } + + if (this.targetWorkspace.toolboxPosition === this.toolboxPosition_ && + this.toolboxPosition_ === toolbox.Position.LEFT && + !this.targetWorkspace.getToolbox()) { + // This flyout is a simple toolbox. Reposition the workspace so that + // (0,0) is in the correct position relative to the new absolute edge + // (ie toolbox edge). + this.targetWorkspace.translate( + this.targetWorkspace.scrollX + flyoutWidth, + this.targetWorkspace.scrollY); + } + + // Record the width for workspace metrics and .position. + this.width_ = flyoutWidth; + this.position(); + this.targetWorkspace.recordDragTargets(); + } + } +} /** * The name of the vertical flyout in the registry. @@ -53,336 +389,6 @@ object.inherits(VerticalFlyout, Flyout); */ VerticalFlyout.registryName = 'verticalFlyout'; -/** - * Sets the translation of the flyout to match the scrollbars. - * @param {!{x:number,y:number}} xyRatio Contains a y property which is a float - * between 0 and 1 specifying the degree of scrolling and a - * similar x property. - * @protected - */ -VerticalFlyout.prototype.setMetrics_ = function(xyRatio) { - if (!this.isVisible()) { - return; - } - const metricsManager = this.workspace_.getMetricsManager(); - const scrollMetrics = metricsManager.getScrollMetrics(); - const viewMetrics = metricsManager.getViewMetrics(); - const absoluteMetrics = metricsManager.getAbsoluteMetrics(); - - if (typeof xyRatio.y === 'number') { - this.workspace_.scrollY = - -(scrollMetrics.top + - (scrollMetrics.height - viewMetrics.height) * xyRatio.y); - } - this.workspace_.translate( - this.workspace_.scrollX + absoluteMetrics.left, - this.workspace_.scrollY + absoluteMetrics.top); -}; - -/** - * Calculates the x coordinate for the flyout position. - * @return {number} X coordinate. - */ -VerticalFlyout.prototype.getX = function() { - if (!this.isVisible()) { - return 0; - } - const metricsManager = this.targetWorkspace.getMetricsManager(); - const absoluteMetrics = metricsManager.getAbsoluteMetrics(); - const viewMetrics = metricsManager.getViewMetrics(); - const toolboxMetrics = metricsManager.getToolboxMetrics(); - let x = 0; - - // If this flyout is not the trashcan flyout (e.g. toolbox or mutator). - if (this.targetWorkspace.toolboxPosition === this.toolboxPosition_) { - // If there is a category toolbox. - if (this.targetWorkspace.getToolbox()) { - if (this.toolboxPosition_ === toolbox.Position.LEFT) { - x = toolboxMetrics.width; - } else { - x = viewMetrics.width - this.width_; - } - // Simple (flyout-only) toolbox. - } else { - if (this.toolboxPosition_ === toolbox.Position.LEFT) { - x = 0; - } else { - // The simple flyout does not cover the workspace. - x = viewMetrics.width; - } - } - // Trashcan flyout is opposite the main flyout. - } else { - if (this.toolboxPosition_ === toolbox.Position.LEFT) { - x = 0; - } else { - // Because the anchor point of the flyout is on the left, but we want - // to align the right edge of the flyout with the right edge of the - // blocklyDiv, we calculate the full width of the div minus the width - // of the flyout. - x = viewMetrics.width + absoluteMetrics.left - this.width_; - } - } - - return x; -}; - -/** - * Calculates the y coordinate for the flyout position. - * @return {number} Y coordinate. - */ -VerticalFlyout.prototype.getY = function() { - // Y is always 0 since this is a vertical flyout. - return 0; -}; - -/** - * Move the flyout to the edge of the workspace. - */ -VerticalFlyout.prototype.position = function() { - if (!this.isVisible() || !this.targetWorkspace.isVisible()) { - return; - } - const metricsManager = this.targetWorkspace.getMetricsManager(); - const targetWorkspaceViewMetrics = metricsManager.getViewMetrics(); - - // Record the height for workspace metrics. - this.height_ = targetWorkspaceViewMetrics.height; - - const edgeWidth = this.width_ - this.CORNER_RADIUS; - const edgeHeight = targetWorkspaceViewMetrics.height - 2 * this.CORNER_RADIUS; - this.setBackgroundPath_(edgeWidth, edgeHeight); - - const x = this.getX(); - const y = this.getY(); - - this.positionAt_(this.width_, this.height_, x, y); -}; - -/** - * Create and set the path for the visible boundaries of the flyout. - * @param {number} width The width of the flyout, not including the - * rounded corners. - * @param {number} height The height of the flyout, not including - * rounded corners. - * @private - */ -VerticalFlyout.prototype.setBackgroundPath_ = function(width, height) { - const atRight = this.toolboxPosition_ === toolbox.Position.RIGHT; - const totalWidth = width + this.CORNER_RADIUS; - - // Decide whether to start on the left or right. - const path = ['M ' + (atRight ? totalWidth : 0) + ',0']; - // Top. - path.push('h', atRight ? -width : width); - // Rounded corner. - path.push( - 'a', this.CORNER_RADIUS, this.CORNER_RADIUS, 0, 0, atRight ? 0 : 1, - atRight ? -this.CORNER_RADIUS : this.CORNER_RADIUS, this.CORNER_RADIUS); - // Side closest to workspace. - path.push('v', Math.max(0, height)); - // Rounded corner. - path.push( - 'a', this.CORNER_RADIUS, this.CORNER_RADIUS, 0, 0, atRight ? 0 : 1, - atRight ? this.CORNER_RADIUS : -this.CORNER_RADIUS, this.CORNER_RADIUS); - // Bottom. - path.push('h', atRight ? width : -width); - path.push('z'); - this.svgBackground_.setAttribute('d', path.join(' ')); -}; - -/** - * Scroll the flyout to the top. - */ -VerticalFlyout.prototype.scrollToStart = function() { - this.workspace_.scrollbar.setY(0); -}; - -/** - * Scroll the flyout. - * @param {!Event} e Mouse wheel scroll event. - * @protected - */ -VerticalFlyout.prototype.wheel_ = function(e) { - const scrollDelta = browserEvents.getScrollDeltaPixels(e); - - if (scrollDelta.y) { - const metricsManager = this.workspace_.getMetricsManager(); - const scrollMetrics = metricsManager.getScrollMetrics(); - const viewMetrics = metricsManager.getViewMetrics(); - const pos = (viewMetrics.top - scrollMetrics.top) + scrollDelta.y; - - this.workspace_.scrollbar.setY(pos); - // When the flyout moves from a wheel event, hide WidgetDiv and DropDownDiv. - WidgetDiv.hide(); - DropDownDiv.hideWithoutAnimation(); - } - - // Don't scroll the page. - e.preventDefault(); - // Don't propagate mousewheel event (zooming). - e.stopPropagation(); -}; - -/** - * Lay out the blocks in the flyout. - * @param {!Array} contents The blocks and buttons to lay out. - * @param {!Array} gaps The visible gaps between blocks. - * @protected - */ -VerticalFlyout.prototype.layout_ = function(contents, gaps) { - this.workspace_.scale = this.targetWorkspace.scale; - const margin = this.MARGIN; - const cursorX = this.RTL ? margin : margin + this.tabWidth_; - let cursorY = margin; - - for (let i = 0, item; (item = contents[i]); i++) { - if (item.type === 'block') { - const block = item.block; - const allBlocks = block.getDescendants(false); - for (let j = 0, child; (child = allBlocks[j]); j++) { - // Mark blocks as being inside a flyout. This is used to detect and - // prevent the closure of the flyout if the user right-clicks on such a - // block. - child.isInFlyout = true; - } - block.render(); - const root = block.getSvgRoot(); - const blockHW = block.getHeightWidth(); - const moveX = block.outputConnection ? cursorX - this.tabWidth_ : cursorX; - block.moveBy(moveX, cursorY); - - const rect = this.createRect_( - block, this.RTL ? moveX - blockHW.width : moveX, cursorY, blockHW, i); - - this.addBlockListeners_(root, block, rect); - - cursorY += blockHW.height + gaps[i]; - } else if (item.type === 'button') { - this.initFlyoutButton_(item.button, cursorX, cursorY); - cursorY += item.button.height + gaps[i]; - } - } -}; - -/** - * Determine if a drag delta is toward the workspace, based on the position - * and orientation of the flyout. This is used in determineDragIntention_ to - * determine if a new block should be created or if the flyout should scroll. - * @param {!Coordinate} currentDragDeltaXY How far the pointer has - * moved from the position at mouse down, in pixel units. - * @return {boolean} True if the drag is toward the workspace. - * @package - */ -VerticalFlyout.prototype.isDragTowardWorkspace = function(currentDragDeltaXY) { - const dx = currentDragDeltaXY.x; - const dy = currentDragDeltaXY.y; - // Direction goes from -180 to 180, with 0 toward the right and 90 on top. - const dragDirection = Math.atan2(dy, dx) / Math.PI * 180; - - const range = this.dragAngleRange_; - // Check for left or right dragging. - if ((dragDirection < range && dragDirection > -range) || - (dragDirection < -180 + range || dragDirection > 180 - range)) { - return true; - } - return false; -}; - -/** - * Returns the bounding rectangle of the drag target area in pixel units - * relative to viewport. - * @return {?Rect} The component's bounding box. Null if drag - * target area should be ignored. - */ -VerticalFlyout.prototype.getClientRect = function() { - if (!this.svgGroup_ || this.autoClose || !this.isVisible()) { - // The bounding rectangle won't compute correctly if the flyout is closed - // and auto-close flyouts aren't valid drag targets (or delete areas). - return null; - } - - const flyoutRect = this.svgGroup_.getBoundingClientRect(); - // BIG_NUM is offscreen padding so that blocks dragged beyond the shown flyout - // area are still deleted. Must be larger than the largest screen size, - // but be smaller than half Number.MAX_SAFE_INTEGER (not available on IE). - const BIG_NUM = 1000000000; - const left = flyoutRect.left; - - if (this.toolboxPosition_ === toolbox.Position.LEFT) { - const width = flyoutRect.width; - return new Rect(-BIG_NUM, BIG_NUM, -BIG_NUM, left + width); - } else { // Right - return new Rect(-BIG_NUM, BIG_NUM, left, BIG_NUM); - } -}; - -/** - * Compute width of flyout. toolbox.Position mat under each block. - * For RTL: Lay out the blocks and buttons to be right-aligned. - * @protected - */ -VerticalFlyout.prototype.reflowInternal_ = function() { - this.workspace_.scale = this.getFlyoutScale(); - let flyoutWidth = 0; - const blocks = this.workspace_.getTopBlocks(false); - for (let i = 0, block; (block = blocks[i]); i++) { - let width = block.getHeightWidth().width; - if (block.outputConnection) { - width -= this.tabWidth_; - } - flyoutWidth = Math.max(flyoutWidth, width); - } - for (let i = 0, button; (button = this.buttons_[i]); i++) { - flyoutWidth = Math.max(flyoutWidth, button.width); - } - flyoutWidth += this.MARGIN * 1.5 + this.tabWidth_; - flyoutWidth *= this.workspace_.scale; - flyoutWidth += Scrollbar.scrollbarThickness; - - if (this.width_ !== flyoutWidth) { - for (let i = 0, block; (block = blocks[i]); i++) { - if (this.RTL) { - // With the flyoutWidth known, right-align the blocks. - const oldX = block.getRelativeToSurfaceXY().x; - let newX = flyoutWidth / this.workspace_.scale - this.MARGIN; - if (!block.outputConnection) { - newX -= this.tabWidth_; - } - block.moveBy(newX - oldX, 0); - } - if (block.flyoutRect_) { - this.moveRectToBlock_(block.flyoutRect_, block); - } - } - if (this.RTL) { - // With the flyoutWidth known, right-align the buttons. - for (let i = 0, button; (button = this.buttons_[i]); i++) { - const y = button.getPosition().y; - const x = flyoutWidth / this.workspace_.scale - button.width - - this.MARGIN - this.tabWidth_; - button.moveTo(x, y); - } - } - - if (this.targetWorkspace.toolboxPosition === this.toolboxPosition_ && - this.toolboxPosition_ === toolbox.Position.LEFT && - !this.targetWorkspace.getToolbox()) { - // This flyout is a simple toolbox. Reposition the workspace so that (0,0) - // is in the correct position relative to the new absolute edge (ie - // toolbox edge). - this.targetWorkspace.translate( - this.targetWorkspace.scrollX + flyoutWidth, - this.targetWorkspace.scrollY); - } - - // Record the width for workspace metrics and .position. - this.width_ = flyoutWidth; - this.position(); - this.targetWorkspace.recordDragTargets(); - } -}; - registry.register( registry.Type.FLYOUTS_VERTICAL_TOOLBOX, registry.DEFAULT, VerticalFlyout); diff --git a/core/gesture.js b/core/gesture.js index faa178076..c0f6df674 100644 --- a/core/gesture.js +++ b/core/gesture.js @@ -55,956 +55,968 @@ goog.require('Blockly.Events.Click'); /** * Class for one gesture. - * @param {!Event} e The event that kicked off this gesture. - * @param {!WorkspaceSvg} creatorWorkspace The workspace that created - * this gesture and has a reference to it. - * @constructor - * @alias Blockly.Gesture */ -const Gesture = function(e, creatorWorkspace) { +class Gesture { /** - * The position of the mouse when the gesture started. Units are CSS pixels, - * with (0, 0) at the top left of the browser window (mouseEvent clientX/Y). - * @type {Coordinate} - * @private + * @param {!Event} e The event that kicked off this gesture. + * @param {!WorkspaceSvg} creatorWorkspace The workspace that created + * this gesture and has a reference to it. + * @alias Blockly.Gesture */ - this.mouseDownXY_ = null; + constructor(e, creatorWorkspace) { + /** + * The position of the mouse when the gesture started. Units are CSS + * pixels, with (0, 0) at the top left of the browser window (mouseEvent + * clientX/Y). + * @type {Coordinate} + * @private + */ + this.mouseDownXY_ = null; - /** - * How far the mouse has moved during this drag, in pixel units. - * (0, 0) is at this.mouseDownXY_. - * @type {!Coordinate} - * @private - */ - this.currentDragDeltaXY_ = new Coordinate(0, 0); + /** + * How far the mouse has moved during this drag, in pixel units. + * (0, 0) is at this.mouseDownXY_. + * @type {!Coordinate} + * @private + */ + this.currentDragDeltaXY_ = new Coordinate(0, 0); - /** - * The bubble that the gesture started on, or null if it did not start on a - * bubble. - * @type {IBubble} - * @private - */ - this.startBubble_ = null; + /** + * The bubble that the gesture started on, or null if it did not start on a + * bubble. + * @type {IBubble} + * @private + */ + this.startBubble_ = null; - /** - * The field that the gesture started on, or null if it did not start on a - * field. - * @type {Field} - * @private - */ - this.startField_ = null; + /** + * The field that the gesture started on, or null if it did not start on a + * field. + * @type {Field} + * @private + */ + this.startField_ = null; - /** - * The block that the gesture started on, or null if it did not start on a - * block. - * @type {BlockSvg} - * @private - */ - this.startBlock_ = null; - - /** - * The block that this gesture targets. If the gesture started on a - * shadow block, this is the first non-shadow parent of the block. If the - * gesture started in the flyout, this is the root block of the block group - * that was clicked or dragged. - * @type {BlockSvg} - * @private - */ - this.targetBlock_ = null; - - /** - * The workspace that the gesture started on. There may be multiple - * workspaces on a page; this is more accurate than using - * Blockly.common.getMainWorkspace(). - * @type {WorkspaceSvg} - * @protected - */ - this.startWorkspace_ = null; - - /** - * The workspace that created this gesture. This workspace keeps a reference - * to the gesture, which will need to be cleared at deletion. - * This may be different from the start workspace. For instance, a flyout is - * a workspace, but its parent workspace manages gestures for it. - * @type {!WorkspaceSvg} - * @private - */ - this.creatorWorkspace_ = creatorWorkspace; - - /** - * Whether the pointer has at any point moved out of the drag radius. - * A gesture that exceeds the drag radius is a drag even if it ends exactly - * at its start point. - * @type {boolean} - * @private - */ - this.hasExceededDragRadius_ = false; - - /** - * Whether the workspace is currently being dragged. - * @type {boolean} - * @private - */ - this.isDraggingWorkspace_ = false; - - /** - * Whether the block is currently being dragged. - * @type {boolean} - * @private - */ - this.isDraggingBlock_ = false; - - /** - * Whether the bubble is currently being dragged. - * @type {boolean} - * @private - */ - this.isDraggingBubble_ = false; - - /** - * The event that most recently updated this gesture. - * @type {!Event} - * @private - */ - this.mostRecentEvent_ = e; - - /** - * A handle to use to unbind a mouse move listener at the end of a drag. - * Opaque data returned from Blockly.bindEventWithChecks_. - * @type {?browserEvents.Data} - * @protected - */ - this.onMoveWrapper_ = null; - - /** - * A handle to use to unbind a mouse up listener at the end of a drag. - * Opaque data returned from Blockly.bindEventWithChecks_. - * @type {?browserEvents.Data} - * @protected - */ - this.onUpWrapper_ = null; - - /** - * The object tracking a bubble drag, or null if none is in progress. - * @type {BubbleDragger} - * @private - */ - this.bubbleDragger_ = null; - - /** - * The object tracking a block drag, or null if none is in progress. - * @type {?IBlockDragger} - * @private - */ - this.blockDragger_ = null; - - /** - * The object tracking a workspace or flyout workspace drag, or null if none - * is in progress. - * @type {WorkspaceDragger} - * @private - */ - this.workspaceDragger_ = null; - - /** - * The flyout a gesture started in, if any. - * @type {IFlyout} - * @private - */ - this.flyout_ = null; - - /** - * Boolean for sanity-checking that some code is only called once. - * @type {boolean} - * @private - */ - this.calledUpdateIsDragging_ = false; - - /** - * Boolean for sanity-checking that some code is only called once. - * @type {boolean} - * @private - */ - this.hasStarted_ = false; - - /** - * Boolean used internally to break a cycle in disposal. - * @type {boolean} - * @protected - */ - this.isEnding_ = false; - - /** - * Boolean used to indicate whether or not to heal the stack after - * disconnecting a block. - * @type {boolean} - * @private - */ - this.healStack_ = !internalConstants.DRAG_STACK; -}; - -/** - * Sever all links from this object. - * @package - */ -Gesture.prototype.dispose = function() { - Touch.clearTouchIdentifier(); - Tooltip.unblock(); - // Clear the owner's reference to this gesture. - this.creatorWorkspace_.clearGesture(); - - if (this.onMoveWrapper_) { - browserEvents.unbind(this.onMoveWrapper_); - } - if (this.onUpWrapper_) { - browserEvents.unbind(this.onUpWrapper_); - } - - if (this.blockDragger_) { - this.blockDragger_.dispose(); - } - if (this.workspaceDragger_) { - this.workspaceDragger_.dispose(); - } - if (this.bubbleDragger_) { - this.bubbleDragger_.dispose(); - } -}; - -/** - * Update internal state based on an event. - * @param {!Event} e The most recent mouse or touch event. - * @private - */ -Gesture.prototype.updateFromEvent_ = function(e) { - const currentXY = new Coordinate(e.clientX, e.clientY); - const changed = this.updateDragDelta_(currentXY); - // Exceeded the drag radius for the first time. - if (changed) { - this.updateIsDragging_(); - Touch.longStop(); - } - this.mostRecentEvent_ = e; -}; - -/** - * DO MATH to set currentDragDeltaXY_ based on the most recent mouse position. - * @param {!Coordinate} currentXY The most recent mouse/pointer - * position, in pixel units, with (0, 0) at the window's top left corner. - * @return {boolean} True if the drag just exceeded the drag radius for the - * first time. - * @private - */ -Gesture.prototype.updateDragDelta_ = function(currentXY) { - this.currentDragDeltaXY_ = Coordinate.difference( - currentXY, - /** @type {!Coordinate} */ (this.mouseDownXY_)); - - if (!this.hasExceededDragRadius_) { - const currentDragDelta = Coordinate.magnitude(this.currentDragDeltaXY_); - - // The flyout has a different drag radius from the rest of Blockly. - const limitRadius = this.flyout_ ? internalConstants.FLYOUT_DRAG_RADIUS : - internalConstants.DRAG_RADIUS; - - this.hasExceededDragRadius_ = currentDragDelta > limitRadius; - return this.hasExceededDragRadius_; - } - return false; -}; - -/** - * Update this gesture to record whether a block is being dragged from the - * flyout. - * This function should be called on a mouse/touch move event the first time the - * drag radius is exceeded. It should be called no more than once per gesture. - * If a block should be dragged from the flyout this function creates the new - * block on the main workspace and updates targetBlock_ and startWorkspace_. - * @return {boolean} True if a block is being dragged from the flyout. - * @private - */ -Gesture.prototype.updateIsDraggingFromFlyout_ = function() { - if (!this.targetBlock_) { - return false; - } - if (!this.flyout_.isBlockCreatable_(this.targetBlock_)) { - return false; - } - if (!this.flyout_.isScrollable() || - this.flyout_.isDragTowardWorkspace(this.currentDragDeltaXY_)) { - this.startWorkspace_ = this.flyout_.targetWorkspace; - this.startWorkspace_.updateScreenCalculationsIfScrolled(); - // Start the event group now, so that the same event group is used for block - // creation and block dragging. - if (!eventUtils.getGroup()) { - eventUtils.setGroup(true); - } - // The start block is no longer relevant, because this is a drag. + /** + * The block that the gesture started on, or null if it did not start on a + * block. + * @type {BlockSvg} + * @private + */ this.startBlock_ = null; - this.targetBlock_ = this.flyout_.createBlock(this.targetBlock_); - this.targetBlock_.select(); - return true; - } - return false; -}; -/** - * Update this gesture to record whether a bubble is being dragged. - * This function should be called on a mouse/touch move event the first time the - * drag radius is exceeded. It should be called no more than once per gesture. - * If a bubble should be dragged this function creates the necessary - * BubbleDragger and starts the drag. - * @return {boolean} True if a bubble is being dragged. - * @private - */ -Gesture.prototype.updateIsDraggingBubble_ = function() { - if (!this.startBubble_) { + /** + * The block that this gesture targets. If the gesture started on a + * shadow block, this is the first non-shadow parent of the block. If the + * gesture started in the flyout, this is the root block of the block group + * that was clicked or dragged. + * @type {BlockSvg} + * @private + */ + this.targetBlock_ = null; + + /** + * The workspace that the gesture started on. There may be multiple + * workspaces on a page; this is more accurate than using + * Blockly.common.getMainWorkspace(). + * @type {WorkspaceSvg} + * @protected + */ + this.startWorkspace_ = null; + + /** + * The workspace that created this gesture. This workspace keeps a + * reference to the gesture, which will need to be cleared at deletion. This + * may be different from the start workspace. For instance, a flyout is a + * workspace, but its parent workspace manages gestures for it. + * @type {!WorkspaceSvg} + * @private + */ + this.creatorWorkspace_ = creatorWorkspace; + + /** + * Whether the pointer has at any point moved out of the drag radius. + * A gesture that exceeds the drag radius is a drag even if it ends exactly + * at its start point. + * @type {boolean} + * @private + */ + this.hasExceededDragRadius_ = false; + + /** + * Whether the workspace is currently being dragged. + * @type {boolean} + * @private + */ + this.isDraggingWorkspace_ = false; + + /** + * Whether the block is currently being dragged. + * @type {boolean} + * @private + */ + this.isDraggingBlock_ = false; + + /** + * Whether the bubble is currently being dragged. + * @type {boolean} + * @private + */ + this.isDraggingBubble_ = false; + + /** + * The event that most recently updated this gesture. + * @type {!Event} + * @private + */ + this.mostRecentEvent_ = e; + + /** + * A handle to use to unbind a mouse move listener at the end of a drag. + * Opaque data returned from Blockly.bindEventWithChecks_. + * @type {?browserEvents.Data} + * @protected + */ + this.onMoveWrapper_ = null; + + /** + * A handle to use to unbind a mouse up listener at the end of a drag. + * Opaque data returned from Blockly.bindEventWithChecks_. + * @type {?browserEvents.Data} + * @protected + */ + this.onUpWrapper_ = null; + + /** + * The object tracking a bubble drag, or null if none is in progress. + * @type {BubbleDragger} + * @private + */ + this.bubbleDragger_ = null; + + /** + * The object tracking a block drag, or null if none is in progress. + * @type {?IBlockDragger} + * @private + */ + this.blockDragger_ = null; + + /** + * The object tracking a workspace or flyout workspace drag, or null if none + * is in progress. + * @type {WorkspaceDragger} + * @private + */ + this.workspaceDragger_ = null; + + /** + * The flyout a gesture started in, if any. + * @type {IFlyout} + * @private + */ + this.flyout_ = null; + + /** + * Boolean for sanity-checking that some code is only called once. + * @type {boolean} + * @private + */ + this.calledUpdateIsDragging_ = false; + + /** + * Boolean for sanity-checking that some code is only called once. + * @type {boolean} + * @private + */ + this.hasStarted_ = false; + + /** + * Boolean used internally to break a cycle in disposal. + * @type {boolean} + * @protected + */ + this.isEnding_ = false; + + /** + * Boolean used to indicate whether or not to heal the stack after + * disconnecting a block. + * @type {boolean} + * @private + */ + this.healStack_ = !internalConstants.DRAG_STACK; + } + + /** + * Sever all links from this object. + * @package + */ + dispose() { + Touch.clearTouchIdentifier(); + Tooltip.unblock(); + // Clear the owner's reference to this gesture. + this.creatorWorkspace_.clearGesture(); + + if (this.onMoveWrapper_) { + browserEvents.unbind(this.onMoveWrapper_); + } + if (this.onUpWrapper_) { + browserEvents.unbind(this.onUpWrapper_); + } + + if (this.blockDragger_) { + this.blockDragger_.dispose(); + } + if (this.workspaceDragger_) { + this.workspaceDragger_.dispose(); + } + if (this.bubbleDragger_) { + this.bubbleDragger_.dispose(); + } + } + + /** + * Update internal state based on an event. + * @param {!Event} e The most recent mouse or touch event. + * @private + */ + updateFromEvent_(e) { + const currentXY = new Coordinate(e.clientX, e.clientY); + const changed = this.updateDragDelta_(currentXY); + // Exceeded the drag radius for the first time. + if (changed) { + this.updateIsDragging_(); + Touch.longStop(); + } + this.mostRecentEvent_ = e; + } + + /** + * DO MATH to set currentDragDeltaXY_ based on the most recent mouse position. + * @param {!Coordinate} currentXY The most recent mouse/pointer + * position, in pixel units, with (0, 0) at the window's top left corner. + * @return {boolean} True if the drag just exceeded the drag radius for the + * first time. + * @private + */ + updateDragDelta_(currentXY) { + this.currentDragDeltaXY_ = Coordinate.difference( + currentXY, + /** @type {!Coordinate} */ (this.mouseDownXY_)); + + if (!this.hasExceededDragRadius_) { + const currentDragDelta = Coordinate.magnitude(this.currentDragDeltaXY_); + + // The flyout has a different drag radius from the rest of Blockly. + const limitRadius = this.flyout_ ? internalConstants.FLYOUT_DRAG_RADIUS : + internalConstants.DRAG_RADIUS; + + this.hasExceededDragRadius_ = currentDragDelta > limitRadius; + return this.hasExceededDragRadius_; + } return false; } - this.isDraggingBubble_ = true; - this.startDraggingBubble_(); - return true; -}; - -/** - * Update this gesture to record whether a block is being dragged. - * This function should be called on a mouse/touch move event the first time the - * drag radius is exceeded. It should be called no more than once per gesture. - * If a block should be dragged, either from the flyout or in the workspace, - * this function creates the necessary BlockDragger and starts the drag. - * @return {boolean} True if a block is being dragged. - * @private - */ -Gesture.prototype.updateIsDraggingBlock_ = function() { - if (!this.targetBlock_) { - return false; - } - - if (this.flyout_) { - this.isDraggingBlock_ = this.updateIsDraggingFromFlyout_(); - } else if (this.targetBlock_.isMovable()) { - this.isDraggingBlock_ = true; - } - - if (this.isDraggingBlock_) { - this.startDraggingBlock_(); - return true; - } - return false; -}; - -/** - * Update this gesture to record whether a workspace is being dragged. - * This function should be called on a mouse/touch move event the first time the - * drag radius is exceeded. It should be called no more than once per gesture. - * If a workspace is being dragged this function creates the necessary - * WorkspaceDragger and starts the drag. - * @private - */ -Gesture.prototype.updateIsDraggingWorkspace_ = function() { - const wsMovable = this.flyout_ ? - this.flyout_.isScrollable() : - this.startWorkspace_ && this.startWorkspace_.isDraggable(); - - if (!wsMovable) { - return; - } - - this.workspaceDragger_ = new WorkspaceDragger( - /** @type {!WorkspaceSvg} */ (this.startWorkspace_)); - - this.isDraggingWorkspace_ = true; - this.workspaceDragger_.startDrag(); -}; - -/** - * Update this gesture to record whether anything is being dragged. - * This function should be called on a mouse/touch move event the first time the - * drag radius is exceeded. It should be called no more than once per gesture. - * @private - */ -Gesture.prototype.updateIsDragging_ = function() { - // Sanity check. - if (this.calledUpdateIsDragging_) { - throw Error('updateIsDragging_ should only be called once per gesture.'); - } - this.calledUpdateIsDragging_ = true; - - // First check if it was a bubble drag. Bubbles always sit on top of blocks. - if (this.updateIsDraggingBubble_()) { - return; - } - // Then check if it was a block drag. - if (this.updateIsDraggingBlock_()) { - return; - } - // Then check if it's a workspace drag. - this.updateIsDraggingWorkspace_(); -}; - -/** - * Create a block dragger and start dragging the selected block. - * @private - */ -Gesture.prototype.startDraggingBlock_ = function() { - const BlockDraggerClass = registry.getClassFromOptions( - registry.Type.BLOCK_DRAGGER, this.creatorWorkspace_.options, true); - - this.blockDragger_ = new BlockDraggerClass( - /** @type {!BlockSvg} */ (this.targetBlock_), - /** @type {!WorkspaceSvg} */ (this.startWorkspace_)); - this.blockDragger_.startDrag(this.currentDragDeltaXY_, this.healStack_); - this.blockDragger_.drag(this.mostRecentEvent_, this.currentDragDeltaXY_); -}; - -/** - * Create a bubble dragger and start dragging the selected bubble. - * @private - */ -// TODO (fenichel): Possibly combine this and startDraggingBlock_. -Gesture.prototype.startDraggingBubble_ = function() { - this.bubbleDragger_ = new BubbleDragger( - /** @type {!IBubble} */ (this.startBubble_), - /** @type {!WorkspaceSvg} */ (this.startWorkspace_)); - this.bubbleDragger_.startBubbleDrag(); - this.bubbleDragger_.dragBubble( - this.mostRecentEvent_, this.currentDragDeltaXY_); -}; -/** - * Start a gesture: update the workspace to indicate that a gesture is in - * progress and bind mousemove and mouseup handlers. - * @param {!Event} e A mouse down or touch start event. - * @package - */ -Gesture.prototype.doStart = function(e) { - if (browserEvents.isTargetInput(e)) { - this.cancel(); - return; - } - this.hasStarted_ = true; - - blockAnimations.disconnectUiStop(); - this.startWorkspace_.updateScreenCalculationsIfScrolled(); - if (this.startWorkspace_.isMutator) { - // Mutator's coordinate system could be out of date because the bubble was - // dragged, the block was moved, the parent workspace zoomed, etc. - this.startWorkspace_.resize(); - } - - // Hide chaff also hides the flyout, so don't do it if the click is in a - // flyout. - this.startWorkspace_.hideChaff(!!this.flyout_); - - this.startWorkspace_.markFocused(); - this.mostRecentEvent_ = e; - - Tooltip.block(); - - if (this.targetBlock_) { - this.targetBlock_.select(); - } - - if (browserEvents.isRightButton(e)) { - this.handleRightClick(e); - return; - } - - if ((e.type.toLowerCase() === 'touchstart' || - e.type.toLowerCase() === 'pointerdown') && - e.pointerType !== 'mouse') { - Touch.longStart(e, this); - } - - this.mouseDownXY_ = new Coordinate(e.clientX, e.clientY); - this.healStack_ = e.altKey || e.ctrlKey || e.metaKey; - - this.bindMouseEvents(e); -}; - -/** - * Bind gesture events. - * @param {!Event} e A mouse down or touch start event. - * @package - */ -Gesture.prototype.bindMouseEvents = function(e) { - this.onMoveWrapper_ = browserEvents.conditionalBind( - document, 'mousemove', null, this.handleMove.bind(this)); - this.onUpWrapper_ = browserEvents.conditionalBind( - document, 'mouseup', null, this.handleUp.bind(this)); - - e.preventDefault(); - e.stopPropagation(); -}; - -/** - * Handle a mouse move or touch move event. - * @param {!Event} e A mouse move or touch move event. - * @package - */ -Gesture.prototype.handleMove = function(e) { - this.updateFromEvent_(e); - if (this.isDraggingWorkspace_) { - this.workspaceDragger_.drag(this.currentDragDeltaXY_); - } else if (this.isDraggingBlock_) { - this.blockDragger_.drag(this.mostRecentEvent_, this.currentDragDeltaXY_); - } else if (this.isDraggingBubble_) { - this.bubbleDragger_.dragBubble( - this.mostRecentEvent_, this.currentDragDeltaXY_); - } - e.preventDefault(); - e.stopPropagation(); -}; - -/** - * Handle a mouse up or touch end event. - * @param {!Event} e A mouse up or touch end event. - * @package - */ -Gesture.prototype.handleUp = function(e) { - this.updateFromEvent_(e); - Touch.longStop(); - - if (this.isEnding_) { - console.log('Trying to end a gesture recursively.'); - return; - } - this.isEnding_ = true; - // The ordering of these checks is important: drags have higher priority than - // clicks. Fields have higher priority than blocks; blocks have higher - // priority than workspaces. - // The ordering within drags does not matter, because the three types of - // dragging are exclusive. - if (this.isDraggingBubble_) { - this.bubbleDragger_.endBubbleDrag(e, this.currentDragDeltaXY_); - } else if (this.isDraggingBlock_) { - this.blockDragger_.endDrag(e, this.currentDragDeltaXY_); - } else if (this.isDraggingWorkspace_) { - this.workspaceDragger_.endDrag(this.currentDragDeltaXY_); - } else if (this.isBubbleClick_()) { - // Bubbles are in front of all fields and blocks. - this.doBubbleClick_(); - } else if (this.isFieldClick_()) { - this.doFieldClick_(); - } else if (this.isBlockClick_()) { - this.doBlockClick_(); - } else if (this.isWorkspaceClick_()) { - this.doWorkspaceClick_(e); - } - - e.preventDefault(); - e.stopPropagation(); - - this.dispose(); -}; - -/** - * Cancel an in-progress gesture. If a workspace or block drag is in progress, - * end the drag at the most recent location. - * @package - */ -Gesture.prototype.cancel = function() { - // Disposing of a block cancels in-progress drags, but dragging to a delete - // area disposes of a block and leads to recursive disposal. Break that cycle. - if (this.isEnding_) { - return; - } - Touch.longStop(); - if (this.isDraggingBubble_) { - this.bubbleDragger_.endBubbleDrag( - this.mostRecentEvent_, this.currentDragDeltaXY_); - } else if (this.isDraggingBlock_) { - this.blockDragger_.endDrag(this.mostRecentEvent_, this.currentDragDeltaXY_); - } else if (this.isDraggingWorkspace_) { - this.workspaceDragger_.endDrag(this.currentDragDeltaXY_); - } - this.dispose(); -}; - -/** - * Handle a real or faked right-click event by showing a context menu. - * @param {!Event} e A mouse move or touch move event. - * @package - */ -Gesture.prototype.handleRightClick = function(e) { - if (this.targetBlock_) { - this.bringBlockToFront_(); - this.targetBlock_.workspace.hideChaff(!!this.flyout_); - this.targetBlock_.showContextMenu(e); - } else if (this.startBubble_) { - this.startBubble_.showContextMenu(e); - } else if (this.startWorkspace_ && !this.flyout_) { - this.startWorkspace_.hideChaff(); - this.startWorkspace_.showContextMenu(e); - } - - // TODO: Handle right-click on a bubble. - e.preventDefault(); - e.stopPropagation(); - - this.dispose(); -}; - -/** - * Handle a mousedown/touchstart event on a workspace. - * @param {!Event} e A mouse down or touch start event. - * @param {!WorkspaceSvg} ws The workspace the event hit. - * @package - */ -Gesture.prototype.handleWsStart = function(e, ws) { - if (this.hasStarted_) { - throw Error( - 'Tried to call gesture.handleWsStart, ' + - 'but the gesture had already been started.'); - } - this.setStartWorkspace_(ws); - this.mostRecentEvent_ = e; - this.doStart(e); -}; - -/** - * Fires a workspace click event. - * @param {!WorkspaceSvg} ws The workspace that a user clicks on. - * @private - */ -Gesture.prototype.fireWorkspaceClick_ = function(ws) { - eventUtils.fire( - new (eventUtils.get(eventUtils.CLICK))(null, ws.id, 'workspace')); -}; - -/** - * Handle a mousedown/touchstart event on a flyout. - * @param {!Event} e A mouse down or touch start event. - * @param {!IFlyout} flyout The flyout the event hit. - * @package - */ -Gesture.prototype.handleFlyoutStart = function(e, flyout) { - if (this.hasStarted_) { - throw Error( - 'Tried to call gesture.handleFlyoutStart, ' + - 'but the gesture had already been started.'); - } - this.setStartFlyout_(flyout); - this.handleWsStart(e, flyout.getWorkspace()); -}; - -/** - * Handle a mousedown/touchstart event on a block. - * @param {!Event} e A mouse down or touch start event. - * @param {!BlockSvg} block The block the event hit. - * @package - */ -Gesture.prototype.handleBlockStart = function(e, block) { - if (this.hasStarted_) { - throw Error( - 'Tried to call gesture.handleBlockStart, ' + - 'but the gesture had already been started.'); - } - this.setStartBlock(block); - this.mostRecentEvent_ = e; -}; - -/** - * Handle a mousedown/touchstart event on a bubble. - * @param {!Event} e A mouse down or touch start event. - * @param {!IBubble} bubble The bubble the event hit. - * @package - */ -Gesture.prototype.handleBubbleStart = function(e, bubble) { - if (this.hasStarted_) { - throw Error( - 'Tried to call gesture.handleBubbleStart, ' + - 'but the gesture had already been started.'); - } - this.setStartBubble(bubble); - this.mostRecentEvent_ = e; -}; - -/* Begin functions defining what actions to take to execute clicks on each type - * of target. Any developer wanting to add behaviour on clicks should modify - * only this code. */ - -/** - * Execute a bubble click. - * @private - */ -Gesture.prototype.doBubbleClick_ = function() { - // TODO (#1673): Consistent handling of single clicks. - this.startBubble_.setFocus && this.startBubble_.setFocus(); - this.startBubble_.select && this.startBubble_.select(); -}; - -/** - * Execute a field click. - * @private - */ -Gesture.prototype.doFieldClick_ = function() { - this.startField_.showEditor(this.mostRecentEvent_); - this.bringBlockToFront_(); -}; - -/** - * Execute a block click. - * @private - */ -Gesture.prototype.doBlockClick_ = function() { - // Block click in an autoclosing flyout. - if (this.flyout_ && this.flyout_.autoClose) { - if (this.targetBlock_.isEnabled()) { + /** + * Update this gesture to record whether a block is being dragged from the + * flyout. + * This function should be called on a mouse/touch move event the first time + * the drag radius is exceeded. It should be called no more than once per + * gesture. If a block should be dragged from the flyout this function creates + * the new block on the main workspace and updates targetBlock_ and + * startWorkspace_. + * @return {boolean} True if a block is being dragged from the flyout. + * @private + */ + updateIsDraggingFromFlyout_() { + if (!this.targetBlock_) { + return false; + } + if (!this.flyout_.isBlockCreatable_(this.targetBlock_)) { + return false; + } + if (!this.flyout_.isScrollable() || + this.flyout_.isDragTowardWorkspace(this.currentDragDeltaXY_)) { + this.startWorkspace_ = this.flyout_.targetWorkspace; + this.startWorkspace_.updateScreenCalculationsIfScrolled(); + // Start the event group now, so that the same event group is used for + // block creation and block dragging. if (!eventUtils.getGroup()) { eventUtils.setGroup(true); } - const newBlock = this.flyout_.createBlock(this.targetBlock_); - newBlock.scheduleSnapAndBump(); - } - } else { - // Clicks events are on the start block, even if it was a shadow. - const event = new (eventUtils.get(eventUtils.CLICK))( - this.startBlock_, this.startWorkspace_.id, 'block'); - eventUtils.fire(event); - } - this.bringBlockToFront_(); - eventUtils.setGroup(false); -}; - -/** - * Execute a workspace click. When in accessibility mode shift clicking will - * move the cursor. - * @param {!Event} _e A mouse up or touch end event. - * @private - */ -Gesture.prototype.doWorkspaceClick_ = function(_e) { - const ws = this.creatorWorkspace_; - if (common.getSelected()) { - common.getSelected().unselect(); - } - this.fireWorkspaceClick_(this.startWorkspace_ || ws); -}; - -/* End functions defining what actions to take to execute clicks on each type - * of target. */ - -// TODO (fenichel): Move bubbles to the front. -/** - * Move the dragged/clicked block to the front of the workspace so that it is - * not occluded by other blocks. - * @private - */ -Gesture.prototype.bringBlockToFront_ = function() { - // Blocks in the flyout don't overlap, so skip the work. - if (this.targetBlock_ && !this.flyout_) { - this.targetBlock_.bringToFront(); - } -}; - -/* Begin functions for populating a gesture at mouse down. */ - -/** - * Record the field that a gesture started on. - * @param {Field} field The field the gesture started on. - * @package - */ -Gesture.prototype.setStartField = function(field) { - if (this.hasStarted_) { - throw Error( - 'Tried to call gesture.setStartField, ' + - 'but the gesture had already been started.'); - } - if (!this.startField_) { - this.startField_ = field; - } -}; - -/** - * Record the bubble that a gesture started on - * @param {IBubble} bubble The bubble the gesture started on. - * @package - */ -Gesture.prototype.setStartBubble = function(bubble) { - if (!this.startBubble_) { - this.startBubble_ = bubble; - } -}; - -/** - * Record the block that a gesture started on, and set the target block - * appropriately. - * @param {BlockSvg} block The block the gesture started on. - * @package - */ -Gesture.prototype.setStartBlock = function(block) { - // If the gesture already went through a bubble, don't set the start block. - if (!this.startBlock_ && !this.startBubble_) { - this.startBlock_ = block; - if (block.isInFlyout && block !== block.getRootBlock()) { - this.setTargetBlock_(block.getRootBlock()); - } else { - this.setTargetBlock_(block); - } - } -}; - -/** - * Record the block that a gesture targets, meaning the block that will be - * dragged if this turns into a drag. If this block is a shadow, that will be - * its first non-shadow parent. - * @param {BlockSvg} block The block the gesture targets. - * @private - */ -Gesture.prototype.setTargetBlock_ = function(block) { - if (block.isShadow()) { - this.setTargetBlock_(block.getParent()); - } else { - this.targetBlock_ = block; - } -}; - -/** - * Record the workspace that a gesture started on. - * @param {WorkspaceSvg} ws The workspace the gesture started on. - * @private - */ -Gesture.prototype.setStartWorkspace_ = function(ws) { - if (!this.startWorkspace_) { - this.startWorkspace_ = ws; - } -}; - -/** - * Record the flyout that a gesture started on. - * @param {IFlyout} flyout The flyout the gesture started on. - * @private - */ -Gesture.prototype.setStartFlyout_ = function(flyout) { - if (!this.flyout_) { - this.flyout_ = flyout; - } -}; - - -/* End functions for populating a gesture at mouse down. */ - -/* Begin helper functions defining types of clicks. Any developer wanting - * to change the definition of a click should modify only this code. */ - -/** - * Whether this gesture is a click on a bubble. This should only be called when - * ending a gesture (mouse up, touch end). - * @return {boolean} Whether this gesture was a click on a bubble. - * @private - */ -Gesture.prototype.isBubbleClick_ = function() { - // A bubble click starts on a bubble and never escapes the drag radius. - const hasStartBubble = !!this.startBubble_; - return hasStartBubble && !this.hasExceededDragRadius_; -}; - -/** - * Whether this gesture is a click on a block. This should only be called when - * ending a gesture (mouse up, touch end). - * @return {boolean} Whether this gesture was a click on a block. - * @private - */ -Gesture.prototype.isBlockClick_ = function() { - // A block click starts on a block, never escapes the drag radius, and is not - // a field click. - const hasStartBlock = !!this.startBlock_; - return hasStartBlock && !this.hasExceededDragRadius_ && !this.isFieldClick_(); -}; - -/** - * Whether this gesture is a click on a field. This should only be called when - * ending a gesture (mouse up, touch end). - * @return {boolean} Whether this gesture was a click on a field. - * @private - */ -Gesture.prototype.isFieldClick_ = function() { - const fieldClickable = - this.startField_ ? this.startField_.isClickable() : false; - return fieldClickable && !this.hasExceededDragRadius_ && - (!this.flyout_ || !this.flyout_.autoClose); -}; - -/** - * Whether this gesture is a click on a workspace. This should only be called - * when ending a gesture (mouse up, touch end). - * @return {boolean} Whether this gesture was a click on a workspace. - * @private - */ -Gesture.prototype.isWorkspaceClick_ = function() { - const onlyTouchedWorkspace = - !this.startBlock_ && !this.startBubble_ && !this.startField_; - return onlyTouchedWorkspace && !this.hasExceededDragRadius_; -}; - -/* End helper functions defining types of clicks. */ - -/** - * Whether this gesture is a drag of either a workspace or block. - * This function is called externally to block actions that cannot be taken - * mid-drag (e.g. using the keyboard to delete the selected blocks). - * @return {boolean} True if this gesture is a drag of a workspace or block. - * @package - */ -Gesture.prototype.isDragging = function() { - return this.isDraggingWorkspace_ || this.isDraggingBlock_ || - this.isDraggingBubble_; -}; - -/** - * Whether this gesture has already been started. In theory every mouse down - * has a corresponding mouse up, but in reality it is possible to lose a - * mouse up, leaving an in-process gesture hanging. - * @return {boolean} Whether this gesture was a click on a workspace. - * @package - */ -Gesture.prototype.hasStarted = function() { - return this.hasStarted_; -}; - -/** - * Get a list of the insertion markers that currently exist. Block drags have - * 0, 1, or 2 insertion markers. - * @return {!Array} A possibly empty list of insertion - * marker blocks. - * @package - */ -Gesture.prototype.getInsertionMarkers = function() { - if (this.blockDragger_) { - return this.blockDragger_.getInsertionMarkers(); - } - return []; -}; - -/** - * Gets the current dragger if an item is being dragged. Null if nothing is - * being dragged. - * @return {!WorkspaceDragger|!BubbleDragger|!IBlockDragger|null} - * The dragger that is currently in use or null if no drag is in progress. - */ -Gesture.prototype.getCurrentDragger = function() { - if (this.isDraggingBlock_) { - return this.blockDragger_; - } else if (this.isDraggingWorkspace_) { - return this.workspaceDragger_; - } else if (this.isDraggingBubble_) { - return this.bubbleDragger_; - } - return null; -}; - -/** - * Is a drag or other gesture currently in progress on any workspace? - * @return {boolean} True if gesture is occurring. - */ -Gesture.inProgress = function() { - const workspaces = Workspace.getAll(); - for (let i = 0, workspace; (workspace = workspaces[i]); i++) { - if (workspace.currentGesture_) { + // The start block is no longer relevant, because this is a drag. + this.startBlock_ = null; + this.targetBlock_ = this.flyout_.createBlock(this.targetBlock_); + this.targetBlock_.select(); return true; } + return false; } - return false; -}; + + /** + * Update this gesture to record whether a bubble is being dragged. + * This function should be called on a mouse/touch move event the first time + * the drag radius is exceeded. It should be called no more than once per + * gesture. If a bubble should be dragged this function creates the necessary + * BubbleDragger and starts the drag. + * @return {boolean} True if a bubble is being dragged. + * @private + */ + updateIsDraggingBubble_() { + if (!this.startBubble_) { + return false; + } + + this.isDraggingBubble_ = true; + this.startDraggingBubble_(); + return true; + } + + /** + * Update this gesture to record whether a block is being dragged. + * This function should be called on a mouse/touch move event the first time + * the drag radius is exceeded. It should be called no more than once per + * gesture. If a block should be dragged, either from the flyout or in the + * workspace, this function creates the necessary BlockDragger and starts the + * drag. + * @return {boolean} True if a block is being dragged. + * @private + */ + updateIsDraggingBlock_() { + if (!this.targetBlock_) { + return false; + } + + if (this.flyout_) { + this.isDraggingBlock_ = this.updateIsDraggingFromFlyout_(); + } else if (this.targetBlock_.isMovable()) { + this.isDraggingBlock_ = true; + } + + if (this.isDraggingBlock_) { + this.startDraggingBlock_(); + return true; + } + return false; + } + + /** + * Update this gesture to record whether a workspace is being dragged. + * This function should be called on a mouse/touch move event the first time + * the drag radius is exceeded. It should be called no more than once per + * gesture. If a workspace is being dragged this function creates the + * necessary WorkspaceDragger and starts the drag. + * @private + */ + updateIsDraggingWorkspace_() { + const wsMovable = this.flyout_ ? + this.flyout_.isScrollable() : + this.startWorkspace_ && this.startWorkspace_.isDraggable(); + + if (!wsMovable) { + return; + } + + this.workspaceDragger_ = new WorkspaceDragger( + /** @type {!WorkspaceSvg} */ (this.startWorkspace_)); + + this.isDraggingWorkspace_ = true; + this.workspaceDragger_.startDrag(); + } + + /** + * Update this gesture to record whether anything is being dragged. + * This function should be called on a mouse/touch move event the first time + * the drag radius is exceeded. It should be called no more than once per + * gesture. + * @private + */ + updateIsDragging_() { + // Sanity check. + if (this.calledUpdateIsDragging_) { + throw Error('updateIsDragging_ should only be called once per gesture.'); + } + this.calledUpdateIsDragging_ = true; + + // First check if it was a bubble drag. Bubbles always sit on top of + // blocks. + if (this.updateIsDraggingBubble_()) { + return; + } + // Then check if it was a block drag. + if (this.updateIsDraggingBlock_()) { + return; + } + // Then check if it's a workspace drag. + this.updateIsDraggingWorkspace_(); + } + + /** + * Create a block dragger and start dragging the selected block. + * @private + */ + startDraggingBlock_() { + const BlockDraggerClass = registry.getClassFromOptions( + registry.Type.BLOCK_DRAGGER, this.creatorWorkspace_.options, true); + + this.blockDragger_ = new BlockDraggerClass( + /** @type {!BlockSvg} */ (this.targetBlock_), + /** @type {!WorkspaceSvg} */ (this.startWorkspace_)); + this.blockDragger_.startDrag(this.currentDragDeltaXY_, this.healStack_); + this.blockDragger_.drag(this.mostRecentEvent_, this.currentDragDeltaXY_); + } + + // TODO (fenichel): Possibly combine this and startDraggingBlock_. + /** + * Create a bubble dragger and start dragging the selected bubble. + * @private + */ + startDraggingBubble_() { + this.bubbleDragger_ = new BubbleDragger( + /** @type {!IBubble} */ (this.startBubble_), + /** @type {!WorkspaceSvg} */ (this.startWorkspace_)); + this.bubbleDragger_.startBubbleDrag(); + this.bubbleDragger_.dragBubble( + this.mostRecentEvent_, this.currentDragDeltaXY_); + } + + /** + * Start a gesture: update the workspace to indicate that a gesture is in + * progress and bind mousemove and mouseup handlers. + * @param {!Event} e A mouse down or touch start event. + * @package + */ + doStart(e) { + if (browserEvents.isTargetInput(e)) { + this.cancel(); + return; + } + this.hasStarted_ = true; + + blockAnimations.disconnectUiStop(); + this.startWorkspace_.updateScreenCalculationsIfScrolled(); + if (this.startWorkspace_.isMutator) { + // Mutator's coordinate system could be out of date because the bubble was + // dragged, the block was moved, the parent workspace zoomed, etc. + this.startWorkspace_.resize(); + } + + // Hide chaff also hides the flyout, so don't do it if the click is in a + // flyout. + this.startWorkspace_.hideChaff(!!this.flyout_); + + this.startWorkspace_.markFocused(); + this.mostRecentEvent_ = e; + + Tooltip.block(); + + if (this.targetBlock_) { + this.targetBlock_.select(); + } + + if (browserEvents.isRightButton(e)) { + this.handleRightClick(e); + return; + } + + if ((e.type.toLowerCase() === 'touchstart' || + e.type.toLowerCase() === 'pointerdown') && + e.pointerType !== 'mouse') { + Touch.longStart(e, this); + } + + this.mouseDownXY_ = new Coordinate(e.clientX, e.clientY); + this.healStack_ = e.altKey || e.ctrlKey || e.metaKey; + + this.bindMouseEvents(e); + } + + /** + * Bind gesture events. + * @param {!Event} e A mouse down or touch start event. + * @package + */ + bindMouseEvents(e) { + this.onMoveWrapper_ = browserEvents.conditionalBind( + document, 'mousemove', null, this.handleMove.bind(this)); + this.onUpWrapper_ = browserEvents.conditionalBind( + document, 'mouseup', null, this.handleUp.bind(this)); + + e.preventDefault(); + e.stopPropagation(); + } + + /** + * Handle a mouse move or touch move event. + * @param {!Event} e A mouse move or touch move event. + * @package + */ + handleMove(e) { + this.updateFromEvent_(e); + if (this.isDraggingWorkspace_) { + this.workspaceDragger_.drag(this.currentDragDeltaXY_); + } else if (this.isDraggingBlock_) { + this.blockDragger_.drag(this.mostRecentEvent_, this.currentDragDeltaXY_); + } else if (this.isDraggingBubble_) { + this.bubbleDragger_.dragBubble( + this.mostRecentEvent_, this.currentDragDeltaXY_); + } + e.preventDefault(); + e.stopPropagation(); + } + + /** + * Handle a mouse up or touch end event. + * @param {!Event} e A mouse up or touch end event. + * @package + */ + handleUp(e) { + this.updateFromEvent_(e); + Touch.longStop(); + + if (this.isEnding_) { + console.log('Trying to end a gesture recursively.'); + return; + } + this.isEnding_ = true; + // The ordering of these checks is important: drags have higher priority + // than clicks. Fields have higher priority than blocks; blocks have higher + // priority than workspaces. + // The ordering within drags does not matter, because the three types of + // dragging are exclusive. + if (this.isDraggingBubble_) { + this.bubbleDragger_.endBubbleDrag(e, this.currentDragDeltaXY_); + } else if (this.isDraggingBlock_) { + this.blockDragger_.endDrag(e, this.currentDragDeltaXY_); + } else if (this.isDraggingWorkspace_) { + this.workspaceDragger_.endDrag(this.currentDragDeltaXY_); + } else if (this.isBubbleClick_()) { + // Bubbles are in front of all fields and blocks. + this.doBubbleClick_(); + } else if (this.isFieldClick_()) { + this.doFieldClick_(); + } else if (this.isBlockClick_()) { + this.doBlockClick_(); + } else if (this.isWorkspaceClick_()) { + this.doWorkspaceClick_(e); + } + + e.preventDefault(); + e.stopPropagation(); + + this.dispose(); + } + + /** + * Cancel an in-progress gesture. If a workspace or block drag is in + * progress, end the drag at the most recent location. + * @package + */ + cancel() { + // Disposing of a block cancels in-progress drags, but dragging to a delete + // area disposes of a block and leads to recursive disposal. Break that + // cycle. + if (this.isEnding_) { + return; + } + Touch.longStop(); + if (this.isDraggingBubble_) { + this.bubbleDragger_.endBubbleDrag( + this.mostRecentEvent_, this.currentDragDeltaXY_); + } else if (this.isDraggingBlock_) { + this.blockDragger_.endDrag( + this.mostRecentEvent_, this.currentDragDeltaXY_); + } else if (this.isDraggingWorkspace_) { + this.workspaceDragger_.endDrag(this.currentDragDeltaXY_); + } + this.dispose(); + } + + /** + * Handle a real or faked right-click event by showing a context menu. + * @param {!Event} e A mouse move or touch move event. + * @package + */ + handleRightClick(e) { + if (this.targetBlock_) { + this.bringBlockToFront_(); + this.targetBlock_.workspace.hideChaff(!!this.flyout_); + this.targetBlock_.showContextMenu(e); + } else if (this.startBubble_) { + this.startBubble_.showContextMenu(e); + } else if (this.startWorkspace_ && !this.flyout_) { + this.startWorkspace_.hideChaff(); + this.startWorkspace_.showContextMenu(e); + } + + // TODO: Handle right-click on a bubble. + e.preventDefault(); + e.stopPropagation(); + + this.dispose(); + } + + /** + * Handle a mousedown/touchstart event on a workspace. + * @param {!Event} e A mouse down or touch start event. + * @param {!WorkspaceSvg} ws The workspace the event hit. + * @package + */ + handleWsStart(e, ws) { + if (this.hasStarted_) { + throw Error( + 'Tried to call gesture.handleWsStart, ' + + 'but the gesture had already been started.'); + } + this.setStartWorkspace_(ws); + this.mostRecentEvent_ = e; + this.doStart(e); + } + + /** + * Fires a workspace click event. + * @param {!WorkspaceSvg} ws The workspace that a user clicks on. + * @private + */ + fireWorkspaceClick_(ws) { + eventUtils.fire( + new (eventUtils.get(eventUtils.CLICK))(null, ws.id, 'workspace')); + } + + /** + * Handle a mousedown/touchstart event on a flyout. + * @param {!Event} e A mouse down or touch start event. + * @param {!IFlyout} flyout The flyout the event hit. + * @package + */ + handleFlyoutStart(e, flyout) { + if (this.hasStarted_) { + throw Error( + 'Tried to call gesture.handleFlyoutStart, ' + + 'but the gesture had already been started.'); + } + this.setStartFlyout_(flyout); + this.handleWsStart(e, flyout.getWorkspace()); + } + + /** + * Handle a mousedown/touchstart event on a block. + * @param {!Event} e A mouse down or touch start event. + * @param {!BlockSvg} block The block the event hit. + * @package + */ + handleBlockStart(e, block) { + if (this.hasStarted_) { + throw Error( + 'Tried to call gesture.handleBlockStart, ' + + 'but the gesture had already been started.'); + } + this.setStartBlock(block); + this.mostRecentEvent_ = e; + } + + /** + * Handle a mousedown/touchstart event on a bubble. + * @param {!Event} e A mouse down or touch start event. + * @param {!IBubble} bubble The bubble the event hit. + * @package + */ + handleBubbleStart(e, bubble) { + if (this.hasStarted_) { + throw Error( + 'Tried to call gesture.handleBubbleStart, ' + + 'but the gesture had already been started.'); + } + this.setStartBubble(bubble); + this.mostRecentEvent_ = e; + } + + /* Begin functions defining what actions to take to execute clicks on each + * type of target. Any developer wanting to add behaviour on clicks should + * modify only this code. */ + + /** + * Execute a bubble click. + * @private + */ + doBubbleClick_() { + // TODO (#1673): Consistent handling of single clicks. + this.startBubble_.setFocus && this.startBubble_.setFocus(); + this.startBubble_.select && this.startBubble_.select(); + } + + /** + * Execute a field click. + * @private + */ + doFieldClick_() { + this.startField_.showEditor(this.mostRecentEvent_); + this.bringBlockToFront_(); + } + + /** + * Execute a block click. + * @private + */ + doBlockClick_() { + // Block click in an autoclosing flyout. + if (this.flyout_ && this.flyout_.autoClose) { + if (this.targetBlock_.isEnabled()) { + if (!eventUtils.getGroup()) { + eventUtils.setGroup(true); + } + const newBlock = this.flyout_.createBlock(this.targetBlock_); + newBlock.scheduleSnapAndBump(); + } + } else { + // Clicks events are on the start block, even if it was a shadow. + const event = new (eventUtils.get(eventUtils.CLICK))( + this.startBlock_, this.startWorkspace_.id, 'block'); + eventUtils.fire(event); + } + this.bringBlockToFront_(); + eventUtils.setGroup(false); + } + + /** + * Execute a workspace click. When in accessibility mode shift clicking will + * move the cursor. + * @param {!Event} _e A mouse up or touch end event. + * @private + */ + doWorkspaceClick_(_e) { + const ws = this.creatorWorkspace_; + if (common.getSelected()) { + common.getSelected().unselect(); + } + this.fireWorkspaceClick_(this.startWorkspace_ || ws); + } + + /* End functions defining what actions to take to execute clicks on each type + * of target. */ + + // TODO (fenichel): Move bubbles to the front. + + /** + * Move the dragged/clicked block to the front of the workspace so that it is + * not occluded by other blocks. + * @private + */ + bringBlockToFront_() { + // Blocks in the flyout don't overlap, so skip the work. + if (this.targetBlock_ && !this.flyout_) { + this.targetBlock_.bringToFront(); + } + } + + /* Begin functions for populating a gesture at mouse down. */ + + /** + * Record the field that a gesture started on. + * @param {Field} field The field the gesture started on. + * @package + */ + setStartField(field) { + if (this.hasStarted_) { + throw Error( + 'Tried to call gesture.setStartField, ' + + 'but the gesture had already been started.'); + } + if (!this.startField_) { + this.startField_ = field; + } + } + + /** + * Record the bubble that a gesture started on + * @param {IBubble} bubble The bubble the gesture started on. + * @package + */ + setStartBubble(bubble) { + if (!this.startBubble_) { + this.startBubble_ = bubble; + } + } + + /** + * Record the block that a gesture started on, and set the target block + * appropriately. + * @param {BlockSvg} block The block the gesture started on. + * @package + */ + setStartBlock(block) { + // If the gesture already went through a bubble, don't set the start block. + if (!this.startBlock_ && !this.startBubble_) { + this.startBlock_ = block; + if (block.isInFlyout && block !== block.getRootBlock()) { + this.setTargetBlock_(block.getRootBlock()); + } else { + this.setTargetBlock_(block); + } + } + } + + /** + * Record the block that a gesture targets, meaning the block that will be + * dragged if this turns into a drag. If this block is a shadow, that will be + * its first non-shadow parent. + * @param {BlockSvg} block The block the gesture targets. + * @private + */ + setTargetBlock_(block) { + if (block.isShadow()) { + this.setTargetBlock_(block.getParent()); + } else { + this.targetBlock_ = block; + } + } + + /** + * Record the workspace that a gesture started on. + * @param {WorkspaceSvg} ws The workspace the gesture started on. + * @private + */ + setStartWorkspace_(ws) { + if (!this.startWorkspace_) { + this.startWorkspace_ = ws; + } + } + + /** + * Record the flyout that a gesture started on. + * @param {IFlyout} flyout The flyout the gesture started on. + * @private + */ + setStartFlyout_(flyout) { + if (!this.flyout_) { + this.flyout_ = flyout; + } + } + + /* End functions for populating a gesture at mouse down. */ + + /* Begin helper functions defining types of clicks. Any developer wanting + * to change the definition of a click should modify only this code. */ + + /** + * Whether this gesture is a click on a bubble. This should only be called + * when ending a gesture (mouse up, touch end). + * @return {boolean} Whether this gesture was a click on a bubble. + * @private + */ + isBubbleClick_() { + // A bubble click starts on a bubble and never escapes the drag radius. + const hasStartBubble = !!this.startBubble_; + return hasStartBubble && !this.hasExceededDragRadius_; + } + + /** + * Whether this gesture is a click on a block. This should only be called + * when ending a gesture (mouse up, touch end). + * @return {boolean} Whether this gesture was a click on a block. + * @private + */ + isBlockClick_() { + // A block click starts on a block, never escapes the drag radius, and is + // not a field click. + const hasStartBlock = !!this.startBlock_; + return hasStartBlock && !this.hasExceededDragRadius_ && + !this.isFieldClick_(); + } + + /** + * Whether this gesture is a click on a field. This should only be called + * when ending a gesture (mouse up, touch end). + * @return {boolean} Whether this gesture was a click on a field. + * @private + */ + isFieldClick_() { + const fieldClickable = + this.startField_ ? this.startField_.isClickable() : false; + return fieldClickable && !this.hasExceededDragRadius_ && + (!this.flyout_ || !this.flyout_.autoClose); + } + + /** + * Whether this gesture is a click on a workspace. This should only be called + * when ending a gesture (mouse up, touch end). + * @return {boolean} Whether this gesture was a click on a workspace. + * @private + */ + isWorkspaceClick_() { + const onlyTouchedWorkspace = + !this.startBlock_ && !this.startBubble_ && !this.startField_; + return onlyTouchedWorkspace && !this.hasExceededDragRadius_; + } + + /* End helper functions defining types of clicks. */ + + /** + * Whether this gesture is a drag of either a workspace or block. + * This function is called externally to block actions that cannot be taken + * mid-drag (e.g. using the keyboard to delete the selected blocks). + * @return {boolean} True if this gesture is a drag of a workspace or block. + * @package + */ + isDragging() { + return this.isDraggingWorkspace_ || this.isDraggingBlock_ || + this.isDraggingBubble_; + } + + /** + * Whether this gesture has already been started. In theory every mouse down + * has a corresponding mouse up, but in reality it is possible to lose a + * mouse up, leaving an in-process gesture hanging. + * @return {boolean} Whether this gesture was a click on a workspace. + * @package + */ + hasStarted() { + return this.hasStarted_; + } + + /** + * Get a list of the insertion markers that currently exist. Block drags have + * 0, 1, or 2 insertion markers. + * @return {!Array} A possibly empty list of insertion + * marker blocks. + * @package + */ + getInsertionMarkers() { + if (this.blockDragger_) { + return this.blockDragger_.getInsertionMarkers(); + } + return []; + } + + /** + * Gets the current dragger if an item is being dragged. Null if nothing is + * being dragged. + * @return {!WorkspaceDragger|!BubbleDragger|!IBlockDragger|null} + * The dragger that is currently in use or null if no drag is in progress. + */ + getCurrentDragger() { + if (this.isDraggingBlock_) { + return this.blockDragger_; + } else if (this.isDraggingWorkspace_) { + return this.workspaceDragger_; + } else if (this.isDraggingBubble_) { + return this.bubbleDragger_; + } + return null; + } + + /** + * Is a drag or other gesture currently in progress on any workspace? + * @return {boolean} True if gesture is occurring. + */ + static inProgress() { + const workspaces = Workspace.getAll(); + for (let i = 0, workspace; (workspace = workspaces[i]); i++) { + if (workspace.currentGesture_) { + return true; + } + } + return false; + } +} exports.Gesture = Gesture; diff --git a/core/grid.js b/core/grid.js index 950175607..272d909ea 100644 --- a/core/grid.js +++ b/core/grid.js @@ -24,200 +24,203 @@ const {Svg} = goog.require('Blockly.utils.Svg'); /** * Class for a workspace's grid. - * @param {!SVGElement} pattern The grid's SVG pattern, created during - * injection. - * @param {!Object} options A dictionary of normalized options for the grid. - * See grid documentation: - * https://developers.google.com/blockly/guides/configure/web/grid - * @constructor - * @alias Blockly.Grid */ -const Grid = function(pattern, options) { +class Grid { /** - * The scale of the grid, used to set stroke width on grid lines. - * This should always be the same as the workspace scale. - * @type {number} - * @private + * @param {!SVGElement} pattern The grid's SVG pattern, created during + * injection. + * @param {!Object} options A dictionary of normalized options for the grid. + * See grid documentation: + * https://developers.google.com/blockly/guides/configure/web/grid + * @alias Blockly.Grid */ - this.scale_ = 1; + constructor(pattern, options) { + /** + * The scale of the grid, used to set stroke width on grid lines. + * This should always be the same as the workspace scale. + * @type {number} + * @private + */ + this.scale_ = 1; - /** - * The grid's SVG pattern, created during injection. - * @type {!SVGElement} - * @private - */ - this.gridPattern_ = pattern; + /** + * The grid's SVG pattern, created during injection. + * @type {!SVGElement} + * @private + */ + this.gridPattern_ = pattern; - /** - * The spacing of the grid lines (in px). - * @type {number} - * @private - */ - this.spacing_ = options['spacing']; + /** + * The spacing of the grid lines (in px). + * @type {number} + * @private + */ + this.spacing_ = options['spacing']; - /** - * How long the grid lines should be (in px). - * @type {number} - * @private - */ - this.length_ = options['length']; + /** + * How long the grid lines should be (in px). + * @type {number} + * @private + */ + this.length_ = options['length']; - /** - * The horizontal grid line, if it exists. - * @type {SVGElement} - * @private - */ - this.line1_ = /** @type {SVGElement} */ (pattern.firstChild); + /** + * The horizontal grid line, if it exists. + * @type {SVGElement} + * @private + */ + this.line1_ = /** @type {SVGElement} */ (pattern.firstChild); - /** - * The vertical grid line, if it exists. - * @type {SVGElement} - * @private - */ - this.line2_ = - this.line1_ && (/** @type {SVGElement} */ (this.line1_.nextSibling)); + /** + * The vertical grid line, if it exists. + * @type {SVGElement} + * @private + */ + this.line2_ = + this.line1_ && (/** @type {SVGElement} */ (this.line1_.nextSibling)); - /** - * Whether blocks should snap to the grid. - * @type {boolean} - * @private - */ - this.snapToGrid_ = options['snap']; -}; - -/** - * Dispose of this grid and unlink from the DOM. - * @package - * @suppress {checkTypes} - */ -Grid.prototype.dispose = function() { - this.gridPattern_ = null; -}; - -/** - * Whether blocks should snap to the grid, based on the initial configuration. - * @return {boolean} True if blocks should snap, false otherwise. - * @package - */ -Grid.prototype.shouldSnap = function() { - return this.snapToGrid_; -}; - -/** - * Get the spacing of the grid points (in px). - * @return {number} The spacing of the grid points. - * @package - */ -Grid.prototype.getSpacing = function() { - return this.spacing_; -}; - -/** - * Get the ID of the pattern element, which should be randomized to avoid - * conflicts with other Blockly instances on the page. - * @return {string} The pattern ID. - * @package - */ -Grid.prototype.getPatternId = function() { - return this.gridPattern_.id; -}; - -/** - * Update the grid with a new scale. - * @param {number} scale The new workspace scale. - * @package - */ -Grid.prototype.update = function(scale) { - this.scale_ = scale; - // MSIE freaks if it sees a 0x0 pattern, so set empty patterns to 100x100. - const safeSpacing = (this.spacing_ * scale) || 100; - - this.gridPattern_.setAttribute('width', safeSpacing); - this.gridPattern_.setAttribute('height', safeSpacing); - - let half = Math.floor(this.spacing_ / 2) + 0.5; - let start = half - this.length_ / 2; - let end = half + this.length_ / 2; - - half *= scale; - start *= scale; - end *= scale; - - this.setLineAttributes_(this.line1_, scale, start, end, half, half); - this.setLineAttributes_(this.line2_, scale, half, half, start, end); -}; - -/** - * Set the attributes on one of the lines in the grid. Use this to update the - * length and stroke width of the grid lines. - * @param {SVGElement} line Which line to update. - * @param {number} width The new stroke size (in px). - * @param {number} x1 The new x start position of the line (in px). - * @param {number} x2 The new x end position of the line (in px). - * @param {number} y1 The new y start position of the line (in px). - * @param {number} y2 The new y end position of the line (in px). - * @private - */ -Grid.prototype.setLineAttributes_ = function(line, width, x1, x2, y1, y2) { - if (line) { - line.setAttribute('stroke-width', width); - line.setAttribute('x1', x1); - line.setAttribute('y1', y1); - line.setAttribute('x2', x2); - line.setAttribute('y2', y2); + /** + * Whether blocks should snap to the grid. + * @type {boolean} + * @private + */ + this.snapToGrid_ = options['snap']; } -}; -/** - * Move the grid to a new x and y position, and make sure that change is - * visible. - * @param {number} x The new x position of the grid (in px). - * @param {number} y The new y position of the grid (in px). - * @package - */ -Grid.prototype.moveTo = function(x, y) { - this.gridPattern_.setAttribute('x', x); - this.gridPattern_.setAttribute('y', y); - - if (userAgent.IE || userAgent.EDGE) { - // IE/Edge doesn't notice that the x/y offsets have changed. - // Force an update. - this.update(this.scale_); + /** + * Dispose of this grid and unlink from the DOM. + * @package + * @suppress {checkTypes} + */ + dispose() { + this.gridPattern_ = null; } -}; -/** - * Create the DOM for the grid described by options. - * @param {string} rnd A random ID to append to the pattern's ID. - * @param {!Object} gridOptions The object containing grid configuration. - * @param {!SVGElement} defs The root SVG element for this workspace's defs. - * @return {!SVGElement} The SVG element for the grid pattern. - * @package - */ -Grid.createDom = function(rnd, gridOptions, defs) { - /* - - - - - */ - const gridPattern = dom.createSvgElement( - Svg.PATTERN, - {'id': 'blocklyGridPattern' + rnd, 'patternUnits': 'userSpaceOnUse'}, - defs); - if (gridOptions['length'] > 0 && gridOptions['spacing'] > 0) { - dom.createSvgElement( - Svg.LINE, {'stroke': gridOptions['colour']}, gridPattern); - if (gridOptions['length'] > 1) { + /** + * Whether blocks should snap to the grid, based on the initial configuration. + * @return {boolean} True if blocks should snap, false otherwise. + * @package + */ + shouldSnap() { + return this.snapToGrid_; + } + + /** + * Get the spacing of the grid points (in px). + * @return {number} The spacing of the grid points. + * @package + */ + getSpacing() { + return this.spacing_; + } + + /** + * Get the ID of the pattern element, which should be randomized to avoid + * conflicts with other Blockly instances on the page. + * @return {string} The pattern ID. + * @package + */ + getPatternId() { + return this.gridPattern_.id; + } + + /** + * Update the grid with a new scale. + * @param {number} scale The new workspace scale. + * @package + */ + update(scale) { + this.scale_ = scale; + // MSIE freaks if it sees a 0x0 pattern, so set empty patterns to 100x100. + const safeSpacing = (this.spacing_ * scale) || 100; + + this.gridPattern_.setAttribute('width', safeSpacing); + this.gridPattern_.setAttribute('height', safeSpacing); + + let half = Math.floor(this.spacing_ / 2) + 0.5; + let start = half - this.length_ / 2; + let end = half + this.length_ / 2; + + half *= scale; + start *= scale; + end *= scale; + + this.setLineAttributes_(this.line1_, scale, start, end, half, half); + this.setLineAttributes_(this.line2_, scale, half, half, start, end); + } + + /** + * Set the attributes on one of the lines in the grid. Use this to update the + * length and stroke width of the grid lines. + * @param {SVGElement} line Which line to update. + * @param {number} width The new stroke size (in px). + * @param {number} x1 The new x start position of the line (in px). + * @param {number} x2 The new x end position of the line (in px). + * @param {number} y1 The new y start position of the line (in px). + * @param {number} y2 The new y end position of the line (in px). + * @private + */ + setLineAttributes_(line, width, x1, x2, y1, y2) { + if (line) { + line.setAttribute('stroke-width', width); + line.setAttribute('x1', x1); + line.setAttribute('y1', y1); + line.setAttribute('x2', x2); + line.setAttribute('y2', y2); + } + } + + /** + * Move the grid to a new x and y position, and make sure that change is + * visible. + * @param {number} x The new x position of the grid (in px). + * @param {number} y The new y position of the grid (in px). + * @package + */ + moveTo(x, y) { + this.gridPattern_.setAttribute('x', x); + this.gridPattern_.setAttribute('y', y); + + if (userAgent.IE || userAgent.EDGE) { + // IE/Edge doesn't notice that the x/y offsets have changed. + // Force an update. + this.update(this.scale_); + } + } + + /** + * Create the DOM for the grid described by options. + * @param {string} rnd A random ID to append to the pattern's ID. + * @param {!Object} gridOptions The object containing grid configuration. + * @param {!SVGElement} defs The root SVG element for this workspace's defs. + * @return {!SVGElement} The SVG element for the grid pattern. + * @package + */ + static createDom(rnd, gridOptions, defs) { + /* + + + + + */ + const gridPattern = dom.createSvgElement( + Svg.PATTERN, + {'id': 'blocklyGridPattern' + rnd, 'patternUnits': 'userSpaceOnUse'}, + defs); + if (gridOptions['length'] > 0 && gridOptions['spacing'] > 0) { dom.createSvgElement( Svg.LINE, {'stroke': gridOptions['colour']}, gridPattern); + if (gridOptions['length'] > 1) { + dom.createSvgElement( + Svg.LINE, {'stroke': gridOptions['colour']}, gridPattern); + } + // x1, y1, x1, x2 properties will be set later in update. + } else { + // Edge 16 doesn't handle empty patterns + dom.createSvgElement(Svg.LINE, {}, gridPattern); } - // x1, y1, x1, x2 properties will be set later in update. - } else { - // Edge 16 doesn't handle empty patterns - dom.createSvgElement(Svg.LINE, {}, gridPattern); + return gridPattern; } - return gridPattern; -}; +} exports.Grid = Grid; diff --git a/core/input.js b/core/input.js index 318063022..c4f1fa074 100644 --- a/core/input.js +++ b/core/input.js @@ -15,18 +15,6 @@ */ goog.module('Blockly.Input'); -/** - * Enum for alignment of inputs. - * @enum {number} - * @alias Blockly.Input.Align - */ -const Align = { - LEFT: -1, - CENTRE: 0, - RIGHT: 1, -}; -exports.Align = Align; - const fieldRegistry = goog.require('Blockly.fieldRegistry'); /* eslint-disable-next-line no-unused-vars */ const {BlockSvg} = goog.requireType('Blockly.BlockSvg'); @@ -42,286 +30,303 @@ const {inputTypes} = goog.require('Blockly.inputTypes'); /** @suppress {extraRequire} */ goog.require('Blockly.FieldLabel'); + +/** + * Enum for alignment of inputs. + * @enum {number} + * @alias Blockly.Input.Align + */ +const Align = { + LEFT: -1, + CENTRE: 0, + RIGHT: 1, +}; +exports.Align = Align; + /** * Class for an input with an optional field. - * @param {number} type The type of the input. - * @param {string} name Language-neutral identifier which may used to find this - * input again. - * @param {!Block} block The block containing this input. - * @param {Connection} connection Optional connection for this input. - * @constructor - * @alias Blockly.Input */ -const Input = function(type, name, block, connection) { - if (type !== inputTypes.DUMMY && !name) { - throw Error('Value inputs and statement inputs must have non-empty name.'); +class Input { + /** + * @param {number} type The type of the input. + * @param {string} name Language-neutral identifier which may used to find + * this input again. + * @param {!Block} block The block containing this input. + * @param {Connection} connection Optional connection for this input. + * @alias Blockly.Input + */ + constructor(type, name, block, connection) { + if (type !== inputTypes.DUMMY && !name) { + throw Error( + 'Value inputs and statement inputs must have non-empty name.'); + } + /** @type {number} */ + this.type = type; + /** @type {string} */ + this.name = name; + /** + * @type {!Block} + * @private + */ + this.sourceBlock_ = block; + /** @type {Connection} */ + this.connection = connection; + /** @type {!Array} */ + this.fieldRow = []; + + /** + * Alignment of input's fields (left, right or centre). + * @type {number} + */ + this.align = Align.LEFT; + + /** + * Is the input visible? + * @type {boolean} + * @private + */ + this.visible_ = true; } - /** @type {number} */ - this.type = type; - /** @type {string} */ - this.name = name; - /** - * @type {!Block} - * @private - */ - this.sourceBlock_ = block; - /** @type {Connection} */ - this.connection = connection; - /** @type {!Array} */ - this.fieldRow = []; /** - * Alignment of input's fields (left, right or centre). - * @type {number} + * Get the source block for this input. + * @return {?Block} The source block, or null if there is none. */ - this.align = Align.LEFT; - - /** - * Is the input visible? - * @type {boolean} - * @private - */ - this.visible_ = true; -}; - - -/** - * Get the source block for this input. - * @return {?Block} The source block, or null if there is none. - */ -Input.prototype.getSourceBlock = function() { - return this.sourceBlock_; -}; - -/** - * Add a field (or label from string), and all prefix and suffix fields, to the - * end of the input's field row. - * @param {string|!Field} field Something to add as a field. - * @param {string=} opt_name Language-neutral identifier which may used to find - * this field again. Should be unique to the host block. - * @return {!Input} The input being append to (to allow chaining). - */ -Input.prototype.appendField = function(field, opt_name) { - this.insertFieldAt(this.fieldRow.length, field, opt_name); - return this; -}; - -/** - * Inserts a field (or label from string), and all prefix and suffix fields, at - * the location of the input's field row. - * @param {number} index The index at which to insert field. - * @param {string|!Field} field Something to add as a field. - * @param {string=} opt_name Language-neutral identifier which may used to find - * this field again. Should be unique to the host block. - * @return {number} The index following the last inserted field. - */ -Input.prototype.insertFieldAt = function(index, field, opt_name) { - if (index < 0 || index > this.fieldRow.length) { - throw Error('index ' + index + ' out of bounds.'); + getSourceBlock() { + return this.sourceBlock_; } - // Falsy field values don't generate a field, unless the field is an empty - // string and named. - if (!field && !(field === '' && opt_name)) { + + /** + * Add a field (or label from string), and all prefix and suffix fields, to + * the end of the input's field row. + * @param {string|!Field} field Something to add as a field. + * @param {string=} opt_name Language-neutral identifier which may used to + * find this field again. Should be unique to the host block. + * @return {!Input} The input being append to (to allow chaining). + */ + appendField(field, opt_name) { + this.insertFieldAt(this.fieldRow.length, field, opt_name); + return this; + } + + /** + * Inserts a field (or label from string), and all prefix and suffix fields, + * at the location of the input's field row. + * @param {number} index The index at which to insert field. + * @param {string|!Field} field Something to add as a field. + * @param {string=} opt_name Language-neutral identifier which may used to + * find this field again. Should be unique to the host block. + * @return {number} The index following the last inserted field. + */ + insertFieldAt(index, field, opt_name) { + if (index < 0 || index > this.fieldRow.length) { + throw Error('index ' + index + ' out of bounds.'); + } + // Falsy field values don't generate a field, unless the field is an empty + // string and named. + if (!field && !(field === '' && opt_name)) { + return index; + } + + // Generate a FieldLabel when given a plain text field. + if (typeof field === 'string') { + field = /** @type {!Field} **/ (fieldRegistry.fromJson({ + 'type': 'field_label', + 'text': field, + })); + } + + field.setSourceBlock(this.sourceBlock_); + if (this.sourceBlock_.rendered) { + field.init(); + field.applyColour(); + } + field.name = opt_name; + field.setVisible(this.isVisible()); + + if (field.prefixField) { + // Add any prefix. + index = this.insertFieldAt(index, field.prefixField); + } + // Add the field to the field row. + this.fieldRow.splice(index, 0, field); + index++; + if (field.suffixField) { + // Add any suffix. + index = this.insertFieldAt(index, field.suffixField); + } + + if (this.sourceBlock_.rendered) { + this.sourceBlock_ = /** @type {!BlockSvg} */ (this.sourceBlock_); + this.sourceBlock_.render(); + // Adding a field will cause the block to change shape. + this.sourceBlock_.bumpNeighbours(); + } return index; } - // Generate a FieldLabel when given a plain text field. - if (typeof field === 'string') { - field = /** @type {!Field} **/ (fieldRegistry.fromJson({ - 'type': 'field_label', - 'text': field, - })); - } - - field.setSourceBlock(this.sourceBlock_); - if (this.sourceBlock_.rendered) { - field.init(); - field.applyColour(); - } - field.name = opt_name; - field.setVisible(this.isVisible()); - - if (field.prefixField) { - // Add any prefix. - index = this.insertFieldAt(index, field.prefixField); - } - // Add the field to the field row. - this.fieldRow.splice(index, 0, field); - index++; - if (field.suffixField) { - // Add any suffix. - index = this.insertFieldAt(index, field.suffixField); - } - - if (this.sourceBlock_.rendered) { - this.sourceBlock_ = /** @type {!BlockSvg} */ (this.sourceBlock_); - this.sourceBlock_.render(); - // Adding a field will cause the block to change shape. - this.sourceBlock_.bumpNeighbours(); - } - return index; -}; - -/** - * Remove a field from this input. - * @param {string} name The name of the field. - * @param {boolean=} opt_quiet True to prevent an error if field is not present. - * @return {boolean} True if operation succeeds, false if field is not present - * and opt_quiet is true. - * @throws {Error} if the field is not present and opt_quiet is false. - */ -Input.prototype.removeField = function(name, opt_quiet) { - for (let i = 0, field; (field = this.fieldRow[i]); i++) { - if (field.name === name) { - field.dispose(); - this.fieldRow.splice(i, 1); - if (this.sourceBlock_.rendered) { - this.sourceBlock_ = /** @type {!BlockSvg} */ (this.sourceBlock_); - this.sourceBlock_.render(); - // Removing a field will cause the block to change shape. - this.sourceBlock_.bumpNeighbours(); + /** + * Remove a field from this input. + * @param {string} name The name of the field. + * @param {boolean=} opt_quiet True to prevent an error if field is not + * present. + * @return {boolean} True if operation succeeds, false if field is not present + * and opt_quiet is true. + * @throws {Error} if the field is not present and opt_quiet is false. + */ + removeField(name, opt_quiet) { + for (let i = 0, field; (field = this.fieldRow[i]); i++) { + if (field.name === name) { + field.dispose(); + this.fieldRow.splice(i, 1); + if (this.sourceBlock_.rendered) { + this.sourceBlock_ = /** @type {!BlockSvg} */ (this.sourceBlock_); + this.sourceBlock_.render(); + // Removing a field will cause the block to change shape. + this.sourceBlock_.bumpNeighbours(); + } + return true; } - return true; } + if (opt_quiet) { + return false; + } + throw Error('Field "' + name + '" not found.'); } - if (opt_quiet) { - return false; + + /** + * Gets whether this input is visible or not. + * @return {boolean} True if visible. + */ + isVisible() { + return this.visible_; } - throw Error('Field "' + name + '" not found.'); -}; -/** - * Gets whether this input is visible or not. - * @return {boolean} True if visible. - */ -Input.prototype.isVisible = function() { - return this.visible_; -}; + /** + * Sets whether this input is visible or not. + * Should only be used to collapse/uncollapse a block. + * @param {boolean} visible True if visible. + * @return {!Array} List of blocks to render. + * @package + */ + setVisible(visible) { + // Note: Currently there are only unit tests for block.setCollapsed() + // because this function is package. If this function goes back to being a + // public API tests (lots of tests) should be added. + let renderList = []; + if (this.visible_ === visible) { + return renderList; + } + this.visible_ = visible; -/** - * Sets whether this input is visible or not. - * Should only be used to collapse/uncollapse a block. - * @param {boolean} visible True if visible. - * @return {!Array} List of blocks to render. - * @package - */ -Input.prototype.setVisible = function(visible) { - // Note: Currently there are only unit tests for block.setCollapsed() - // because this function is package. If this function goes back to being a - // public API tests (lots of tests) should be added. - let renderList = []; - if (this.visible_ === visible) { + for (let y = 0, field; (field = this.fieldRow[y]); y++) { + field.setVisible(visible); + } + if (this.connection) { + this.connection = + /** @type {!RenderedConnection} */ (this.connection); + // Has a connection. + if (visible) { + renderList = this.connection.startTrackingAll(); + } else { + this.connection.stopTrackingAll(); + } + const child = this.connection.targetBlock(); + if (child) { + child.getSvgRoot().style.display = visible ? 'block' : 'none'; + } + } return renderList; } - this.visible_ = visible; - for (let y = 0, field; (field = this.fieldRow[y]); y++) { - field.setVisible(visible); - } - if (this.connection) { - this.connection = - /** @type {!RenderedConnection} */ (this.connection); - // Has a connection. - if (visible) { - renderList = this.connection.startTrackingAll(); - } else { - this.connection.stopTrackingAll(); - } - const child = this.connection.targetBlock(); - if (child) { - child.getSvgRoot().style.display = visible ? 'block' : 'none'; + /** + * Mark all fields on this input as dirty. + * @package + */ + markDirty() { + for (let y = 0, field; (field = this.fieldRow[y]); y++) { + field.markDirty(); } } - return renderList; -}; -/** - * Mark all fields on this input as dirty. - * @package - */ -Input.prototype.markDirty = function() { - for (let y = 0, field; (field = this.fieldRow[y]); y++) { - field.markDirty(); + /** + * Change a connection's compatibility. + * @param {string|Array|null} check Compatible value type or + * list of value types. Null if all types are compatible. + * @return {!Input} The input being modified (to allow chaining). + */ + setCheck(check) { + if (!this.connection) { + throw Error('This input does not have a connection.'); + } + this.connection.setCheck(check); + return this; } -}; -/** - * Change a connection's compatibility. - * @param {string|Array|null} check Compatible value type or - * list of value types. Null if all types are compatible. - * @return {!Input} The input being modified (to allow chaining). - */ -Input.prototype.setCheck = function(check) { - if (!this.connection) { - throw Error('This input does not have a connection.'); + /** + * Change the alignment of the connection's field(s). + * @param {number} align One of the values of Align + * In RTL mode directions are reversed, and Align.RIGHT aligns to the left. + * @return {!Input} The input being modified (to allow chaining). + */ + setAlign(align) { + this.align = align; + if (this.sourceBlock_.rendered) { + this.sourceBlock_ = /** @type {!BlockSvg} */ (this.sourceBlock_); + this.sourceBlock_.render(); + } + return this; } - this.connection.setCheck(check); - return this; -}; -/** - * Change the alignment of the connection's field(s). - * @param {number} align One of the values of Align - * In RTL mode directions are reversed, and Align.RIGHT aligns to the left. - * @return {!Input} The input being modified (to allow chaining). - */ -Input.prototype.setAlign = function(align) { - this.align = align; - if (this.sourceBlock_.rendered) { - this.sourceBlock_ = /** @type {!BlockSvg} */ (this.sourceBlock_); - this.sourceBlock_.render(); + /** + * Changes the connection's shadow block. + * @param {?Element} shadow DOM representation of a block or null. + * @return {!Input} The input being modified (to allow chaining). + */ + setShadowDom(shadow) { + if (!this.connection) { + throw Error('This input does not have a connection.'); + } + this.connection.setShadowDom(shadow); + return this; } - return this; -}; -/** - * Changes the connection's shadow block. - * @param {?Element} shadow DOM representation of a block or null. - * @return {!Input} The input being modified (to allow chaining). - */ -Input.prototype.setShadowDom = function(shadow) { - if (!this.connection) { - throw Error('This input does not have a connection.'); + /** + * Returns the XML representation of the connection's shadow block. + * @return {?Element} Shadow DOM representation of a block or null. + */ + getShadowDom() { + if (!this.connection) { + throw Error('This input does not have a connection.'); + } + return this.connection.getShadowDom(); } - this.connection.setShadowDom(shadow); - return this; -}; -/** - * Returns the XML representation of the connection's shadow block. - * @return {?Element} Shadow DOM representation of a block or null. - */ -Input.prototype.getShadowDom = function() { - if (!this.connection) { - throw Error('This input does not have a connection.'); + /** + * Initialize the fields on this input. + */ + init() { + if (!this.sourceBlock_.workspace.rendered) { + return; // Headless blocks don't need fields initialized. + } + for (let i = 0; i < this.fieldRow.length; i++) { + this.fieldRow[i].init(); + } } - return this.connection.getShadowDom(); -}; -/** - * Initialize the fields on this input. - */ -Input.prototype.init = function() { - if (!this.sourceBlock_.workspace.rendered) { - return; // Headless blocks don't need fields initialized. + /** + * Sever all links to this input. + * @suppress {checkTypes} + */ + dispose() { + for (let i = 0, field; (field = this.fieldRow[i]); i++) { + field.dispose(); + } + if (this.connection) { + this.connection.dispose(); + } + this.sourceBlock_ = null; } - for (let i = 0; i < this.fieldRow.length; i++) { - this.fieldRow[i].init(); - } -}; - -/** - * Sever all links to this input. - * @suppress {checkTypes} - */ -Input.prototype.dispose = function() { - for (let i = 0, field; (field = this.fieldRow[i]); i++) { - field.dispose(); - } - if (this.connection) { - this.connection.dispose(); - } - this.sourceBlock_ = null; -}; +} exports.Input = Input; diff --git a/core/insertion_marker_manager.js b/core/insertion_marker_manager.js index b2592d491..627eb44ff 100644 --- a/core/insertion_marker_manager.js +++ b/core/insertion_marker_manager.js @@ -36,119 +36,746 @@ const {RenderedConnection} = goog.requireType('Blockly.RenderedConnection'); const {WorkspaceSvg} = goog.requireType('Blockly.WorkspaceSvg'); +/** + * An error message to throw if the block created by createMarkerBlock_ is + * missing any components. + * @type {string} + * @const + */ +const DUPLICATE_BLOCK_ERROR = 'The insertion marker ' + + 'manager tried to create a marker but the result is missing %1. If ' + + 'you are using a mutator, make sure your domToMutation method is ' + + 'properly defined.'; + + /** * Class that controls updates to connections during drags. It is primarily * responsible for finding the closest eligible connection and highlighting or * unhighlighting it as needed during a drag. - * @param {!BlockSvg} block The top block in the stack being dragged. - * @constructor - * @alias Blockly.InsertionMarkerManager */ -const InsertionMarkerManager = function(block) { - common.setSelected(block); +class InsertionMarkerManager { + /** + * @param {!BlockSvg} block The top block in the stack being dragged. + * @alias Blockly.InsertionMarkerManager + */ + constructor(block) { + common.setSelected(block); + + /** + * The top block in the stack being dragged. + * Does not change during a drag. + * @type {!BlockSvg} + * @private + */ + this.topBlock_ = block; + + /** + * The workspace on which these connections are being dragged. + * Does not change during a drag. + * @type {!WorkspaceSvg} + * @private + */ + this.workspace_ = block.workspace; + + /** + * The last connection on the stack, if it's not the last connection on the + * first block. + * Set in initAvailableConnections, if at all. + * @type {RenderedConnection} + * @private + */ + this.lastOnStack_ = null; + + /** + * The insertion marker corresponding to the last block in the stack, if + * that's not the same as the first block in the stack. + * Set in initAvailableConnections, if at all + * @type {BlockSvg} + * @private + */ + this.lastMarker_ = null; + + /** + * The insertion marker that shows up between blocks to show where a block + * would go if dropped immediately. + * @type {BlockSvg} + * @private + */ + this.firstMarker_ = this.createMarkerBlock_(this.topBlock_); + + /** + * The connection that this block would connect to if released immediately. + * Updated on every mouse move. + * This is not on any of the blocks that are being dragged. + * @type {RenderedConnection} + * @private + */ + this.closestConnection_ = null; + + /** + * The connection that would connect to this.closestConnection_ if this + * block were released immediately. Updated on every mouse move. This is on + * the top block that is being dragged or the last block in the dragging + * stack. + * @type {RenderedConnection} + * @private + */ + this.localConnection_ = null; + + /** + * Whether the block would be deleted if it were dropped immediately. + * Updated on every mouse move. + * @type {boolean} + * @private + */ + this.wouldDeleteBlock_ = false; + + /** + * Connection on the insertion marker block that corresponds to + * this.localConnection_ on the currently dragged block. + * @type {RenderedConnection} + * @private + */ + this.markerConnection_ = null; + + /** + * The block that currently has an input being highlighted, or null. + * @type {BlockSvg} + * @private + */ + this.highlightedBlock_ = null; + + /** + * The block being faded to indicate replacement, or null. + * @type {BlockSvg} + * @private + */ + this.fadedBlock_ = null; + + /** + * The connections on the dragging blocks that are available to connect to + * other blocks. This includes all open connections on the top block, as + * well as the last connection on the block stack. Does not change during a + * drag. + * @type {!Array} + * @private + */ + this.availableConnections_ = this.initAvailableConnections_(); + } /** - * The top block in the stack being dragged. - * Does not change during a drag. - * @type {!BlockSvg} - * @private + * Sever all links from this object. + * @package */ - this.topBlock_ = block; + dispose() { + this.availableConnections_.length = 0; + + eventUtils.disable(); + try { + if (this.firstMarker_) { + this.firstMarker_.dispose(); + } + if (this.lastMarker_) { + this.lastMarker_.dispose(); + } + } finally { + eventUtils.enable(); + } + } /** - * The workspace on which these connections are being dragged. - * Does not change during a drag. - * @type {!WorkspaceSvg} - * @private + * Update the available connections for the top block. These connections can + * change if a block is unplugged and the stack is healed. + * @package */ - this.workspace_ = block.workspace; + updateAvailableConnections() { + this.availableConnections_ = this.initAvailableConnections_(); + } /** - * The last connection on the stack, if it's not the last connection on the - * first block. - * Set in initAvailableConnections, if at all. - * @type {RenderedConnection} - * @private + * Return whether the block would be deleted if dropped immediately, based on + * information from the most recent move event. + * @return {boolean} True if the block would be deleted if dropped + * immediately. + * @package */ - this.lastOnStack_ = null; + wouldDeleteBlock() { + return this.wouldDeleteBlock_; + } /** - * The insertion marker corresponding to the last block in the stack, if - * that's not the same as the first block in the stack. - * Set in initAvailableConnections, if at all - * @type {BlockSvg} - * @private + * Return whether the block would be connected if dropped immediately, based + * on information from the most recent move event. + * @return {boolean} True if the block would be connected if dropped + * immediately. + * @package */ - this.lastMarker_ = null; + wouldConnectBlock() { + return !!this.closestConnection_; + } /** - * The insertion marker that shows up between blocks to show where a block - * would go if dropped immediately. - * @type {BlockSvg} - * @private + * Connect to the closest connection and render the results. + * This should be called at the end of a drag. + * @package */ - this.firstMarker_ = this.createMarkerBlock_(this.topBlock_); + applyConnections() { + if (this.closestConnection_) { + // Don't fire events for insertion markers. + eventUtils.disable(); + this.hidePreview_(); + eventUtils.enable(); + // Connect two blocks together. + this.localConnection_.connect(this.closestConnection_); + if (this.topBlock_.rendered) { + // Trigger a connection animation. + // Determine which connection is inferior (lower in the source stack). + const inferiorConnection = this.localConnection_.isSuperior() ? + this.closestConnection_ : + this.localConnection_; + blockAnimations.connectionUiEffect(inferiorConnection.getSourceBlock()); + // Bring the just-edited stack to the front. + const rootBlock = this.topBlock_.getRootBlock(); + rootBlock.bringToFront(); + } + } + } /** - * The connection that this block would connect to if released immediately. - * Updated on every mouse move. - * This is not on any of the blocks that are being dragged. - * @type {RenderedConnection} - * @private + * Update connections based on the most recent move location. + * @param {!Coordinate} dxy Position relative to drag start, + * in workspace units. + * @param {?IDragTarget} dragTarget The drag target that the block is + * currently over. + * @package */ - this.closestConnection_ = null; + update(dxy, dragTarget) { + const candidate = this.getCandidate_(dxy); + + this.wouldDeleteBlock_ = this.shouldDelete_(candidate, dragTarget); + + const shouldUpdate = + this.wouldDeleteBlock_ || this.shouldUpdatePreviews_(candidate, dxy); + + if (shouldUpdate) { + // Don't fire events for insertion marker creation or movement. + eventUtils.disable(); + this.maybeHidePreview_(candidate); + this.maybeShowPreview_(candidate); + eventUtils.enable(); + } + } /** - * The connection that would connect to this.closestConnection_ if this block - * were released immediately. - * Updated on every mouse move. - * This is on the top block that is being dragged or the last block in the - * dragging stack. - * @type {RenderedConnection} + * Create an insertion marker that represents the given block. + * @param {!BlockSvg} sourceBlock The block that the insertion marker + * will represent. + * @return {!BlockSvg} The insertion marker that represents the given + * block. * @private */ - this.localConnection_ = null; + createMarkerBlock_(sourceBlock) { + const imType = sourceBlock.type; + + eventUtils.disable(); + let result; + try { + result = this.workspace_.newBlock(imType); + result.setInsertionMarker(true); + if (sourceBlock.saveExtraState) { + const state = sourceBlock.saveExtraState(); + if (state) { + result.loadExtraState(state); + } + } else if (sourceBlock.mutationToDom) { + const oldMutationDom = sourceBlock.mutationToDom(); + if (oldMutationDom) { + result.domToMutation(oldMutationDom); + } + } + // Copy field values from the other block. These values may impact the + // rendered size of the insertion marker. Note that we do not care about + // child blocks here. + for (let i = 0; i < sourceBlock.inputList.length; i++) { + const sourceInput = sourceBlock.inputList[i]; + if (sourceInput.name === constants.COLLAPSED_INPUT_NAME) { + continue; // Ignore the collapsed input. + } + const resultInput = result.inputList[i]; + if (!resultInput) { + throw new Error(DUPLICATE_BLOCK_ERROR.replace('%1', 'an input')); + } + for (let j = 0; j < sourceInput.fieldRow.length; j++) { + const sourceField = sourceInput.fieldRow[j]; + const resultField = resultInput.fieldRow[j]; + if (!resultField) { + throw new Error(DUPLICATE_BLOCK_ERROR.replace('%1', 'a field')); + } + resultField.setValue(sourceField.getValue()); + } + } + + result.setCollapsed(sourceBlock.isCollapsed()); + result.setInputsInline(sourceBlock.getInputsInline()); + + result.initSvg(); + result.getSvgRoot().setAttribute('visibility', 'hidden'); + } finally { + eventUtils.enable(); + } + + return result; + } /** - * Whether the block would be deleted if it were dropped immediately. - * Updated on every mouse move. - * @type {boolean} + * Populate the list of available connections on this block stack. This + * should only be called once, at the beginning of a drag. If the stack has + * more than one block, this function will populate lastOnStack_ and create + * the corresponding insertion marker. + * @return {!Array} A list of available + * connections. * @private */ - this.wouldDeleteBlock_ = false; + initAvailableConnections_() { + const available = this.topBlock_.getConnections_(false); + // Also check the last connection on this stack + const lastOnStack = this.topBlock_.lastConnectionInStack(true); + if (lastOnStack && lastOnStack !== this.topBlock_.nextConnection) { + available.push(lastOnStack); + this.lastOnStack_ = lastOnStack; + if (this.lastMarker_) { + eventUtils.disable(); + try { + this.lastMarker_.dispose(); + } finally { + eventUtils.enable(); + } + } + this.lastMarker_ = this.createMarkerBlock_(lastOnStack.getSourceBlock()); + } + return available; + } /** - * Connection on the insertion marker block that corresponds to - * this.localConnection_ on the currently dragged block. - * @type {RenderedConnection} + * Whether the previews (insertion marker and replacement marker) should be + * updated based on the closest candidate and the current drag distance. + * @param {!Object} candidate An object containing a local connection, a + * closest connection, and a radius. Returned by getCandidate_. + * @param {!Coordinate} dxy Position relative to drag start, + * in workspace units. + * @return {boolean} Whether the preview should be updated. * @private */ - this.markerConnection_ = null; + shouldUpdatePreviews_(candidate, dxy) { + const candidateLocal = candidate.local; + const candidateClosest = candidate.closest; + const radius = candidate.radius; + + // Found a connection! + if (candidateLocal && candidateClosest) { + // We're already showing an insertion marker. + // Decide whether the new connection has higher priority. + if (this.localConnection_ && this.closestConnection_) { + // The connection was the same as the current connection. + if (this.closestConnection_ === candidateClosest && + this.localConnection_ === candidateLocal) { + return false; + } + const xDiff = + this.localConnection_.x + dxy.x - this.closestConnection_.x; + const yDiff = + this.localConnection_.y + dxy.y - this.closestConnection_.y; + const curDistance = Math.sqrt(xDiff * xDiff + yDiff * yDiff); + // Slightly prefer the existing preview over a new preview. + return !( + candidateClosest && + radius > + curDistance - internalConstants.CURRENT_CONNECTION_PREFERENCE); + } else if (!this.localConnection_ && !this.closestConnection_) { + // We weren't showing a preview before, but we should now. + return true; + } else { + console.error( + 'Only one of localConnection_ and closestConnection_ was set.'); + } + } else { // No connection found. + // Only need to update if we were showing a preview before. + return !!(this.localConnection_ && this.closestConnection_); + } + + console.error( + 'Returning true from shouldUpdatePreviews, but it\'s not clear why.'); + return true; + } /** - * The block that currently has an input being highlighted, or null. - * @type {BlockSvg} + * Find the nearest valid connection, which may be the same as the current + * closest connection. + * @param {!Coordinate} dxy Position relative to drag start, + * in workspace units. + * @return {!Object} An object containing a local connection, a closest + * connection, and a radius. * @private */ - this.highlightedBlock_ = null; + getCandidate_(dxy) { + let radius = this.getStartRadius_(); + let candidateClosest = null; + let candidateLocal = null; + + // It's possible that a block has added or removed connections during a + // drag, (e.g. in a drag/move event handler), so let's update the available + // connections. Note that this will be called on every move while dragging, + // so it might cause slowness, especially if the block stack is large. If + // so, maybe it could be made more efficient. Also note that we won't update + // the connections if we've already connected the insertion marker to a + // block. + if (!this.markerConnection_ || !this.markerConnection_.isConnected()) { + this.updateAvailableConnections(); + } + + for (let i = 0; i < this.availableConnections_.length; i++) { + const myConnection = this.availableConnections_[i]; + const neighbour = myConnection.closest(radius, dxy); + if (neighbour.connection) { + candidateClosest = neighbour.connection; + candidateLocal = myConnection; + radius = neighbour.radius; + } + } + return {closest: candidateClosest, local: candidateLocal, radius: radius}; + } /** - * The block being faded to indicate replacement, or null. - * @type {BlockSvg} + * Decide the radius at which to start searching for the closest connection. + * @return {number} The radius at which to start the search for the closest + * connection. * @private */ - this.fadedBlock_ = null; + getStartRadius_() { + // If there is already a connection highlighted, + // increase the radius we check for making new connections. + // Why? When a connection is highlighted, blocks move around when the + // insertion marker is created, which could cause the connection became out + // of range. By increasing radiusConnection when a connection already + // exists, we never "lose" the connection from the offset. + if (this.closestConnection_ && this.localConnection_) { + return internalConstants.CONNECTING_SNAP_RADIUS; + } + return internalConstants.SNAP_RADIUS; + } /** - * The connections on the dragging blocks that are available to connect to - * other blocks. This includes all open connections on the top block, as well - * as the last connection on the block stack. - * Does not change during a drag. - * @type {!Array} + * Whether ending the drag would delete the block. + * @param {!Object} candidate An object containing a local connection, a + * closest + * connection, and a radius. + * @param {?IDragTarget} dragTarget The drag target that the block is + * currently over. + * @return {boolean} Whether dropping the block immediately would delete the + * block. * @private */ - this.availableConnections_ = this.initAvailableConnections_(); -}; + shouldDelete_(candidate, dragTarget) { + if (dragTarget) { + const componentManager = this.workspace_.getComponentManager(); + const isDeleteArea = componentManager.hasCapability( + dragTarget.id, ComponentManager.Capability.DELETE_AREA); + if (isDeleteArea) { + return ( + /** @type {!IDeleteArea} */ (dragTarget)) + .wouldDelete(this.topBlock_, candidate && !!candidate.closest); + } + } + return false; + } + + /** + * Show an insertion marker or replacement highlighting during a drag, if + * needed. + * At the beginning of this function, this.localConnection_ and + * this.closestConnection_ should both be null. + * @param {!Object} candidate An object containing a local connection, a + * closest connection, and a radius. + * @private + */ + maybeShowPreview_(candidate) { + // Nope, don't add a marker. + if (this.wouldDeleteBlock_) { + return; + } + const closest = candidate.closest; + const local = candidate.local; + + // Nothing to connect to. + if (!closest) { + return; + } + + // Something went wrong and we're trying to connect to an invalid + // connection. + if (closest === this.closestConnection_ || + closest.getSourceBlock().isInsertionMarker()) { + console.log('Trying to connect to an insertion marker'); + return; + } + // Add an insertion marker or replacement marker. + this.closestConnection_ = closest; + this.localConnection_ = local; + this.showPreview_(); + } + + /** + * A preview should be shown. This function figures out if it should be a + * block highlight or an insertion marker, and shows the appropriate one. + * @private + */ + showPreview_() { + const closest = this.closestConnection_; + const renderer = this.workspace_.getRenderer(); + const method = renderer.getConnectionPreviewMethod( + /** @type {!RenderedConnection} */ (closest), + /** @type {!RenderedConnection} */ (this.localConnection_), + this.topBlock_); + + switch (method) { + case InsertionMarkerManager.PREVIEW_TYPE.INPUT_OUTLINE: + this.showInsertionInputOutline_(); + break; + case InsertionMarkerManager.PREVIEW_TYPE.INSERTION_MARKER: + this.showInsertionMarker_(); + break; + case InsertionMarkerManager.PREVIEW_TYPE.REPLACEMENT_FADE: + this.showReplacementFade_(); + break; + } + + // Optionally highlight the actual connection, as a nod to previous + // behaviour. + if (closest && renderer.shouldHighlightConnection(closest)) { + closest.highlight(); + } + } + + /** + * Show an insertion marker or replacement highlighting during a drag, if + * needed. + * At the end of this function, this.localConnection_ and + * this.closestConnection_ should both be null. + * @param {!Object} candidate An object containing a local connection, a + * closest connection, and a radius. + * @private + */ + maybeHidePreview_(candidate) { + // If there's no new preview, remove the old one but don't bother deleting + // it. We might need it later, and this saves disposing of it and recreating + // it. + if (!candidate.closest) { + this.hidePreview_(); + } else { + // If there's a new preview and there was an preview before, and either + // connection has changed, remove the old preview. + const hadPreview = this.closestConnection_ && this.localConnection_; + const closestChanged = this.closestConnection_ !== candidate.closest; + const localChanged = this.localConnection_ !== candidate.local; + + // Also hide if we had a preview before but now we're going to delete + // instead. + if (hadPreview && + (closestChanged || localChanged || this.wouldDeleteBlock_)) { + this.hidePreview_(); + } + } + + // Either way, clear out old state. + this.markerConnection_ = null; + this.closestConnection_ = null; + this.localConnection_ = null; + } + + /** + * A preview should be hidden. This function figures out if it is a block + * highlight or an insertion marker, and hides the appropriate one. + * @private + */ + hidePreview_() { + if (this.closestConnection_ && this.closestConnection_.targetBlock() && + this.workspace_.getRenderer().shouldHighlightConnection( + this.closestConnection_)) { + this.closestConnection_.unhighlight(); + } + if (this.fadedBlock_) { + this.hideReplacementFade_(); + } else if (this.highlightedBlock_) { + this.hideInsertionInputOutline_(); + } else if (this.markerConnection_) { + this.hideInsertionMarker_(); + } + } + + /** + * Shows an insertion marker connected to the appropriate blocks (based on + * manager state). + * @private + */ + showInsertionMarker_() { + const local = this.localConnection_; + const closest = this.closestConnection_; + + const isLastInStack = this.lastOnStack_ && local === this.lastOnStack_; + let imBlock = isLastInStack ? this.lastMarker_ : this.firstMarker_; + let imConn; + try { + imConn = imBlock.getMatchingConnection(local.getSourceBlock(), local); + } catch (e) { + // It's possible that the number of connections on the local block has + // changed since the insertion marker was originally created. Let's + // recreate the insertion marker and try again. In theory we could + // probably recreate the marker block (e.g. in getCandidate_), which is + // called more often during the drag, but creating a block that often + // might be too slow, so we only do it if necessary. + this.firstMarker_ = this.createMarkerBlock_(this.topBlock_); + imBlock = isLastInStack ? this.lastMarker_ : this.firstMarker_; + imConn = imBlock.getMatchingConnection(local.getSourceBlock(), local); + } + + if (imConn === this.markerConnection_) { + throw Error( + 'Made it to showInsertionMarker_ even though the marker isn\'t ' + + 'changing'); + } + + // Render disconnected from everything else so that we have a valid + // connection location. + imBlock.render(); + imBlock.rendered = true; + imBlock.getSvgRoot().setAttribute('visibility', 'visible'); + + if (imConn && closest) { + // Position so that the existing block doesn't move. + imBlock.positionNearConnection(imConn, closest); + } + if (closest) { + // Connect() also renders the insertion marker. + imConn.connect(closest); + } + + this.markerConnection_ = imConn; + } + + /** + * Disconnects and hides the current insertion marker. Should return the + * blocks to their original state. + * @private + */ + hideInsertionMarker_() { + if (!this.markerConnection_) { + console.log('No insertion marker connection to disconnect'); + return; + } + + const imConn = this.markerConnection_; + const imBlock = imConn.getSourceBlock(); + const markerNext = imBlock.nextConnection; + const markerPrev = imBlock.previousConnection; + const markerOutput = imBlock.outputConnection; + + const isFirstInStatementStack = + (imConn === markerNext && !(markerPrev && markerPrev.targetConnection)); + + const isFirstInOutputStack = imConn.type === ConnectionType.INPUT_VALUE && + !(markerOutput && markerOutput.targetConnection); + // The insertion marker is the first block in a stack. Unplug won't do + // anything in that case. Instead, unplug the following block. + if (isFirstInStatementStack || isFirstInOutputStack) { + imConn.targetBlock().unplug(false); + } else if ( + imConn.type === ConnectionType.NEXT_STATEMENT && + imConn !== markerNext) { + // Inside of a C-block, first statement connection. + const innerConnection = imConn.targetConnection; + innerConnection.getSourceBlock().unplug(false); + + const previousBlockNextConnection = + markerPrev ? markerPrev.targetConnection : null; + + imBlock.unplug(true); + if (previousBlockNextConnection) { + previousBlockNextConnection.connect(innerConnection); + } + } else { + imBlock.unplug(true /* healStack */); + } + + if (imConn.targetConnection) { + throw Error( + 'markerConnection_ still connected at the end of ' + + 'disconnectInsertionMarker'); + } + + this.markerConnection_ = null; + const svg = imBlock.getSvgRoot(); + if (svg) { + svg.setAttribute('visibility', 'hidden'); + } + } + + /** + * Shows an outline around the input the closest connection belongs to. + * @private + */ + showInsertionInputOutline_() { + const closest = this.closestConnection_; + this.highlightedBlock_ = closest.getSourceBlock(); + this.highlightedBlock_.highlightShapeForInput(closest, true); + } + + /** + * Hides any visible input outlines. + * @private + */ + hideInsertionInputOutline_() { + this.highlightedBlock_.highlightShapeForInput( + this.closestConnection_, false); + this.highlightedBlock_ = null; + } + + /** + * Shows a replacement fade affect on the closest connection's target block + * (the block that is currently connected to it). + * @private + */ + showReplacementFade_() { + this.fadedBlock_ = this.closestConnection_.targetBlock(); + this.fadedBlock_.fadeForReplacement(true); + } + + /** + * Hides/Removes any visible fade affects. + * @private + */ + hideReplacementFade_() { + this.fadedBlock_.fadeForReplacement(false); + this.fadedBlock_ = null; + } + + /** + * Get a list of the insertion markers that currently exist. Drags have 0, 1, + * or 2 insertion markers. + * @return {!Array} A possibly empty list of insertion + * marker blocks. + * @package + */ + getInsertionMarkers() { + const result = []; + if (this.firstMarker_) { + result.push(this.firstMarker_); + } + if (this.lastMarker_) { + result.push(this.lastMarker_); + } + return result; + } +} /** * An enum describing different kinds of previews the InsertionMarkerManager @@ -161,622 +788,4 @@ InsertionMarkerManager.PREVIEW_TYPE = { REPLACEMENT_FADE: 2, }; -/** - * An error message to throw if the block created by createMarkerBlock_ is - * missing any components. - * @type {string} - * @const - */ -InsertionMarkerManager.DUPLICATE_BLOCK_ERROR = 'The insertion marker ' + - 'manager tried to create a marker but the result is missing %1. If ' + - 'you are using a mutator, make sure your domToMutation method is ' + - 'properly defined.'; - -/** - * Sever all links from this object. - * @package - */ -InsertionMarkerManager.prototype.dispose = function() { - this.availableConnections_.length = 0; - - eventUtils.disable(); - try { - if (this.firstMarker_) { - this.firstMarker_.dispose(); - } - if (this.lastMarker_) { - this.lastMarker_.dispose(); - } - } finally { - eventUtils.enable(); - } -}; - -/** - * Update the available connections for the top block. These connections can - * change if a block is unplugged and the stack is healed. - * @package - */ -InsertionMarkerManager.prototype.updateAvailableConnections = function() { - this.availableConnections_ = this.initAvailableConnections_(); -}; - -/** - * Return whether the block would be deleted if dropped immediately, based on - * information from the most recent move event. - * @return {boolean} True if the block would be deleted if dropped immediately. - * @package - */ -InsertionMarkerManager.prototype.wouldDeleteBlock = function() { - return this.wouldDeleteBlock_; -}; - -/** - * Return whether the block would be connected if dropped immediately, based on - * information from the most recent move event. - * @return {boolean} True if the block would be connected if dropped - * immediately. - * @package - */ -InsertionMarkerManager.prototype.wouldConnectBlock = function() { - return !!this.closestConnection_; -}; - -/** - * Connect to the closest connection and render the results. - * This should be called at the end of a drag. - * @package - */ -InsertionMarkerManager.prototype.applyConnections = function() { - if (this.closestConnection_) { - // Don't fire events for insertion markers. - eventUtils.disable(); - this.hidePreview_(); - eventUtils.enable(); - // Connect two blocks together. - this.localConnection_.connect(this.closestConnection_); - if (this.topBlock_.rendered) { - // Trigger a connection animation. - // Determine which connection is inferior (lower in the source stack). - const inferiorConnection = this.localConnection_.isSuperior() ? - this.closestConnection_ : - this.localConnection_; - blockAnimations.connectionUiEffect(inferiorConnection.getSourceBlock()); - // Bring the just-edited stack to the front. - const rootBlock = this.topBlock_.getRootBlock(); - rootBlock.bringToFront(); - } - } -}; - -/** - * Update connections based on the most recent move location. - * @param {!Coordinate} dxy Position relative to drag start, - * in workspace units. - * @param {?IDragTarget} dragTarget The drag target that the block is - * currently over. - * @package - */ -InsertionMarkerManager.prototype.update = function(dxy, dragTarget) { - const candidate = this.getCandidate_(dxy); - - this.wouldDeleteBlock_ = this.shouldDelete_(candidate, dragTarget); - - const shouldUpdate = - this.wouldDeleteBlock_ || this.shouldUpdatePreviews_(candidate, dxy); - - if (shouldUpdate) { - // Don't fire events for insertion marker creation or movement. - eventUtils.disable(); - this.maybeHidePreview_(candidate); - this.maybeShowPreview_(candidate); - eventUtils.enable(); - } -}; - -/** - * Create an insertion marker that represents the given block. - * @param {!BlockSvg} sourceBlock The block that the insertion marker - * will represent. - * @return {!BlockSvg} The insertion marker that represents the given - * block. - * @private - */ -InsertionMarkerManager.prototype.createMarkerBlock_ = function(sourceBlock) { - const imType = sourceBlock.type; - - eventUtils.disable(); - let result; - try { - result = this.workspace_.newBlock(imType); - result.setInsertionMarker(true); - if (sourceBlock.saveExtraState) { - const state = sourceBlock.saveExtraState(); - if (state) { - result.loadExtraState(state); - } - } else if (sourceBlock.mutationToDom) { - const oldMutationDom = sourceBlock.mutationToDom(); - if (oldMutationDom) { - result.domToMutation(oldMutationDom); - } - } - // Copy field values from the other block. These values may impact the - // rendered size of the insertion marker. Note that we do not care about - // child blocks here. - for (let i = 0; i < sourceBlock.inputList.length; i++) { - const sourceInput = sourceBlock.inputList[i]; - if (sourceInput.name === constants.COLLAPSED_INPUT_NAME) { - continue; // Ignore the collapsed input. - } - const resultInput = result.inputList[i]; - if (!resultInput) { - throw new Error(InsertionMarkerManager.DUPLICATE_BLOCK_ERROR.replace( - '%1', 'an input')); - } - for (let j = 0; j < sourceInput.fieldRow.length; j++) { - const sourceField = sourceInput.fieldRow[j]; - const resultField = resultInput.fieldRow[j]; - if (!resultField) { - throw new Error(InsertionMarkerManager.DUPLICATE_BLOCK_ERROR.replace( - '%1', 'a field')); - } - resultField.setValue(sourceField.getValue()); - } - } - - result.setCollapsed(sourceBlock.isCollapsed()); - result.setInputsInline(sourceBlock.getInputsInline()); - - result.initSvg(); - result.getSvgRoot().setAttribute('visibility', 'hidden'); - } finally { - eventUtils.enable(); - } - - return result; -}; - -/** - * Populate the list of available connections on this block stack. This should - * only be called once, at the beginning of a drag. - * If the stack has more than one block, this function will populate - * lastOnStack_ and create the corresponding insertion marker. - * @return {!Array} A list of available - * connections. - * @private - */ -InsertionMarkerManager.prototype.initAvailableConnections_ = function() { - const available = this.topBlock_.getConnections_(false); - // Also check the last connection on this stack - const lastOnStack = this.topBlock_.lastConnectionInStack(true); - if (lastOnStack && lastOnStack !== this.topBlock_.nextConnection) { - available.push(lastOnStack); - this.lastOnStack_ = lastOnStack; - if (this.lastMarker_) { - eventUtils.disable(); - try { - this.lastMarker_.dispose(); - } finally { - eventUtils.enable(); - } - } - this.lastMarker_ = this.createMarkerBlock_(lastOnStack.getSourceBlock()); - } - return available; -}; - -/** - * Whether the previews (insertion marker and replacement marker) should be - * updated based on the closest candidate and the current drag distance. - * @param {!Object} candidate An object containing a local connection, a closest - * connection, and a radius. Returned by getCandidate_. - * @param {!Coordinate} dxy Position relative to drag start, - * in workspace units. - * @return {boolean} Whether the preview should be updated. - * @private - */ -InsertionMarkerManager.prototype.shouldUpdatePreviews_ = function( - candidate, dxy) { - const candidateLocal = candidate.local; - const candidateClosest = candidate.closest; - const radius = candidate.radius; - - // Found a connection! - if (candidateLocal && candidateClosest) { - // We're already showing an insertion marker. - // Decide whether the new connection has higher priority. - if (this.localConnection_ && this.closestConnection_) { - // The connection was the same as the current connection. - if (this.closestConnection_ === candidateClosest && - this.localConnection_ === candidateLocal) { - return false; - } - const xDiff = this.localConnection_.x + dxy.x - this.closestConnection_.x; - const yDiff = this.localConnection_.y + dxy.y - this.closestConnection_.y; - const curDistance = Math.sqrt(xDiff * xDiff + yDiff * yDiff); - // Slightly prefer the existing preview over a new preview. - return !( - candidateClosest && - radius > - curDistance - internalConstants.CURRENT_CONNECTION_PREFERENCE); - } else if (!this.localConnection_ && !this.closestConnection_) { - // We weren't showing a preview before, but we should now. - return true; - } else { - console.error( - 'Only one of localConnection_ and closestConnection_ was set.'); - } - } else { // No connection found. - // Only need to update if we were showing a preview before. - return !!(this.localConnection_ && this.closestConnection_); - } - - console.error( - 'Returning true from shouldUpdatePreviews, but it\'s not clear why.'); - return true; -}; - -/** - * Find the nearest valid connection, which may be the same as the current - * closest connection. - * @param {!Coordinate} dxy Position relative to drag start, - * in workspace units. - * @return {!Object} An object containing a local connection, a closest - * connection, and a radius. - * @private - */ -InsertionMarkerManager.prototype.getCandidate_ = function(dxy) { - let radius = this.getStartRadius_(); - let candidateClosest = null; - let candidateLocal = null; - - // It's possible that a block has added or removed connections during a drag, - // (e.g. in a drag/move event handler), so let's update the available - // connections. Note that this will be called on every move while dragging, so - // it might cause slowness, especially if the block stack is large. If so, - // maybe it could be made more efficient. Also note that we won't update the - // connections if we've already connected the insertion marker to a block. - if (!this.markerConnection_ || !this.markerConnection_.isConnected()) { - this.updateAvailableConnections(); - } - - for (let i = 0; i < this.availableConnections_.length; i++) { - const myConnection = this.availableConnections_[i]; - const neighbour = myConnection.closest(radius, dxy); - if (neighbour.connection) { - candidateClosest = neighbour.connection; - candidateLocal = myConnection; - radius = neighbour.radius; - } - } - return {closest: candidateClosest, local: candidateLocal, radius: radius}; -}; - -/** - * Decide the radius at which to start searching for the closest connection. - * @return {number} The radius at which to start the search for the closest - * connection. - * @private - */ -InsertionMarkerManager.prototype.getStartRadius_ = function() { - // If there is already a connection highlighted, - // increase the radius we check for making new connections. - // Why? When a connection is highlighted, blocks move around when the - // insertion marker is created, which could cause the connection became out of - // range. By increasing radiusConnection when a connection already exists, we - // never "lose" the connection from the offset. - if (this.closestConnection_ && this.localConnection_) { - return internalConstants.CONNECTING_SNAP_RADIUS; - } - return internalConstants.SNAP_RADIUS; -}; - -/** - * Whether ending the drag would delete the block. - * @param {!Object} candidate An object containing a local connection, a closest - * connection, and a radius. - * @param {?IDragTarget} dragTarget The drag target that the block is - * currently over. - * @return {boolean} Whether dropping the block immediately would delete the - * block. - * @private - */ -InsertionMarkerManager.prototype.shouldDelete_ = function( - candidate, dragTarget) { - if (dragTarget) { - const componentManager = this.workspace_.getComponentManager(); - const isDeleteArea = componentManager.hasCapability( - dragTarget.id, ComponentManager.Capability.DELETE_AREA); - if (isDeleteArea) { - return ( - /** @type {!IDeleteArea} */ (dragTarget)) - .wouldDelete(this.topBlock_, candidate && !!candidate.closest); - } - } - return false; -}; - -/** - * Show an insertion marker or replacement highlighting during a drag, if - * needed. - * At the beginning of this function, this.localConnection_ and - * this.closestConnection_ should both be null. - * @param {!Object} candidate An object containing a local connection, a closest - * connection, and a radius. - * @private - */ -InsertionMarkerManager.prototype.maybeShowPreview_ = function(candidate) { - // Nope, don't add a marker. - if (this.wouldDeleteBlock_) { - return; - } - const closest = candidate.closest; - const local = candidate.local; - - // Nothing to connect to. - if (!closest) { - return; - } - - // Something went wrong and we're trying to connect to an invalid connection. - if (closest === this.closestConnection_ || - closest.getSourceBlock().isInsertionMarker()) { - console.log('Trying to connect to an insertion marker'); - return; - } - // Add an insertion marker or replacement marker. - this.closestConnection_ = closest; - this.localConnection_ = local; - this.showPreview_(); -}; - -/** - * A preview should be shown. This function figures out if it should be a block - * highlight or an insertion marker, and shows the appropriate one. - * @private - */ -InsertionMarkerManager.prototype.showPreview_ = function() { - const closest = this.closestConnection_; - const renderer = this.workspace_.getRenderer(); - const method = renderer.getConnectionPreviewMethod( - /** @type {!RenderedConnection} */ (closest), - /** @type {!RenderedConnection} */ (this.localConnection_), - this.topBlock_); - - switch (method) { - case InsertionMarkerManager.PREVIEW_TYPE.INPUT_OUTLINE: - this.showInsertionInputOutline_(); - break; - case InsertionMarkerManager.PREVIEW_TYPE.INSERTION_MARKER: - this.showInsertionMarker_(); - break; - case InsertionMarkerManager.PREVIEW_TYPE.REPLACEMENT_FADE: - this.showReplacementFade_(); - break; - } - - // Optionally highlight the actual connection, as a nod to previous behaviour. - if (closest && renderer.shouldHighlightConnection(closest)) { - closest.highlight(); - } -}; - -/** - * Show an insertion marker or replacement highlighting during a drag, if - * needed. - * At the end of this function, this.localConnection_ and - * this.closestConnection_ should both be null. - * @param {!Object} candidate An object containing a local connection, a closest - * connection, and a radius. - * @private - */ -InsertionMarkerManager.prototype.maybeHidePreview_ = function(candidate) { - // If there's no new preview, remove the old one but don't bother deleting it. - // We might need it later, and this saves disposing of it and recreating it. - if (!candidate.closest) { - this.hidePreview_(); - } else { - // If there's a new preview and there was an preview before, and either - // connection has changed, remove the old preview. - const hadPreview = this.closestConnection_ && this.localConnection_; - const closestChanged = this.closestConnection_ !== candidate.closest; - const localChanged = this.localConnection_ !== candidate.local; - - // Also hide if we had a preview before but now we're going to delete - // instead. - if (hadPreview && - (closestChanged || localChanged || this.wouldDeleteBlock_)) { - this.hidePreview_(); - } - } - - // Either way, clear out old state. - this.markerConnection_ = null; - this.closestConnection_ = null; - this.localConnection_ = null; -}; - -/** - * A preview should be hidden. This function figures out if it is a block - * highlight or an insertion marker, and hides the appropriate one. - * @private - */ -InsertionMarkerManager.prototype.hidePreview_ = function() { - if (this.closestConnection_ && this.closestConnection_.targetBlock() && - this.workspace_.getRenderer().shouldHighlightConnection( - this.closestConnection_)) { - this.closestConnection_.unhighlight(); - } - if (this.fadedBlock_) { - this.hideReplacementFade_(); - } else if (this.highlightedBlock_) { - this.hideInsertionInputOutline_(); - } else if (this.markerConnection_) { - this.hideInsertionMarker_(); - } -}; - -/** - * Shows an insertion marker connected to the appropriate blocks (based on - * manager state). - * @private - */ -InsertionMarkerManager.prototype.showInsertionMarker_ = function() { - const local = this.localConnection_; - const closest = this.closestConnection_; - - const isLastInStack = this.lastOnStack_ && local === this.lastOnStack_; - let imBlock = isLastInStack ? this.lastMarker_ : this.firstMarker_; - let imConn; - try { - imConn = imBlock.getMatchingConnection(local.getSourceBlock(), local); - } catch (e) { - // It's possible that the number of connections on the local block has - // changed since the insertion marker was originally created. Let's - // recreate the insertion marker and try again. In theory we could probably - // recreate the marker block (e.g. in getCandidate_), which is called more - // often during the drag, but creating a block that often might be too slow, - // so we only do it if necessary. - this.firstMarker_ = this.createMarkerBlock_(this.topBlock_); - imBlock = isLastInStack ? this.lastMarker_ : this.firstMarker_; - imConn = imBlock.getMatchingConnection(local.getSourceBlock(), local); - } - - if (imConn === this.markerConnection_) { - throw Error( - 'Made it to showInsertionMarker_ even though the marker isn\'t ' + - 'changing'); - } - - // Render disconnected from everything else so that we have a valid - // connection location. - imBlock.render(); - imBlock.rendered = true; - imBlock.getSvgRoot().setAttribute('visibility', 'visible'); - - if (imConn && closest) { - // Position so that the existing block doesn't move. - imBlock.positionNearConnection(imConn, closest); - } - if (closest) { - // Connect() also renders the insertion marker. - imConn.connect(closest); - } - - this.markerConnection_ = imConn; -}; - -/** - * Disconnects and hides the current insertion marker. Should return the blocks - * to their original state. - * @private - */ -InsertionMarkerManager.prototype.hideInsertionMarker_ = function() { - if (!this.markerConnection_) { - console.log('No insertion marker connection to disconnect'); - return; - } - - const imConn = this.markerConnection_; - const imBlock = imConn.getSourceBlock(); - const markerNext = imBlock.nextConnection; - const markerPrev = imBlock.previousConnection; - const markerOutput = imBlock.outputConnection; - - const isFirstInStatementStack = - (imConn === markerNext && !(markerPrev && markerPrev.targetConnection)); - - const isFirstInOutputStack = imConn.type === ConnectionType.INPUT_VALUE && - !(markerOutput && markerOutput.targetConnection); - // The insertion marker is the first block in a stack. Unplug won't do - // anything in that case. Instead, unplug the following block. - if (isFirstInStatementStack || isFirstInOutputStack) { - imConn.targetBlock().unplug(false); - } else if ( - imConn.type === ConnectionType.NEXT_STATEMENT && imConn !== markerNext) { - // Inside of a C-block, first statement connection. - const innerConnection = imConn.targetConnection; - innerConnection.getSourceBlock().unplug(false); - - const previousBlockNextConnection = - markerPrev ? markerPrev.targetConnection : null; - - imBlock.unplug(true); - if (previousBlockNextConnection) { - previousBlockNextConnection.connect(innerConnection); - } - } else { - imBlock.unplug(true /* healStack */); - } - - if (imConn.targetConnection) { - throw Error( - 'markerConnection_ still connected at the end of ' + - 'disconnectInsertionMarker'); - } - - this.markerConnection_ = null; - const svg = imBlock.getSvgRoot(); - if (svg) { - svg.setAttribute('visibility', 'hidden'); - } -}; - -/** - * Shows an outline around the input the closest connection belongs to. - * @private - */ -InsertionMarkerManager.prototype.showInsertionInputOutline_ = function() { - const closest = this.closestConnection_; - this.highlightedBlock_ = closest.getSourceBlock(); - this.highlightedBlock_.highlightShapeForInput(closest, true); -}; - -/** - * Hides any visible input outlines. - * @private - */ -InsertionMarkerManager.prototype.hideInsertionInputOutline_ = function() { - this.highlightedBlock_.highlightShapeForInput(this.closestConnection_, false); - this.highlightedBlock_ = null; -}; - -/** - * Shows a replacement fade affect on the closest connection's target block - * (the block that is currently connected to it). - * @private - */ -InsertionMarkerManager.prototype.showReplacementFade_ = function() { - this.fadedBlock_ = this.closestConnection_.targetBlock(); - this.fadedBlock_.fadeForReplacement(true); -}; - -/** - * Hides/Removes any visible fade affects. - * @private - */ -InsertionMarkerManager.prototype.hideReplacementFade_ = function() { - this.fadedBlock_.fadeForReplacement(false); - this.fadedBlock_ = null; -}; - -/** - * Get a list of the insertion markers that currently exist. Drags have 0, 1, - * or 2 insertion markers. - * @return {!Array} A possibly empty list of insertion - * marker blocks. - * @package - */ -InsertionMarkerManager.prototype.getInsertionMarkers = function() { - const result = []; - if (this.firstMarker_) { - result.push(this.firstMarker_); - } - if (this.lastMarker_) { - result.push(this.lastMarker_); - } - return result; -}; - exports.InsertionMarkerManager = InsertionMarkerManager; diff --git a/core/metrics_manager.js b/core/metrics_manager.js index 072a812a7..11d4ae9fb 100644 --- a/core/metrics_manager.js +++ b/core/metrics_manager.js @@ -32,20 +32,409 @@ const {WorkspaceSvg} = goog.requireType('Blockly.WorkspaceSvg'); /** * The manager for all workspace metrics calculations. - * @param {!WorkspaceSvg} workspace The workspace to calculate metrics - * for. * @implements {IMetricsManager} - * @constructor - * @alias Blockly.MetricsManager */ -const MetricsManager = function(workspace) { +class MetricsManager { /** - * The workspace to calculate metrics for. - * @type {!WorkspaceSvg} + * @param {!WorkspaceSvg} workspace The workspace to calculate metrics + * for. + * @alias Blockly.MetricsManager + */ + constructor(workspace) { + /** + * The workspace to calculate metrics for. + * @type {!WorkspaceSvg} + * @protected + */ + this.workspace_ = workspace; + } + + /** + * Gets the dimensions of the given workspace component, in pixel coordinates. + * @param {?IToolbox|?IFlyout} elem The element to get the + * dimensions of, or null. It should be a toolbox or flyout, and should + * implement getWidth() and getHeight(). + * @return {!Size} An object containing width and height + * attributes, which will both be zero if elem did not exist. * @protected */ - this.workspace_ = workspace; -}; + getDimensionsPx_(elem) { + let width = 0; + let height = 0; + if (elem) { + width = elem.getWidth(); + height = elem.getHeight(); + } + return new Size(width, height); + } + + /** + * Gets the width and the height of the flyout on the workspace in pixel + * coordinates. Returns 0 for the width and height if the workspace has a + * category toolbox instead of a simple toolbox. + * @param {boolean=} opt_own Whether to only return the workspace's own + * flyout. + * @return {!MetricsManager.ToolboxMetrics} The width and height of the + * flyout. + * @public + */ + getFlyoutMetrics(opt_own) { + const flyoutDimensions = + this.getDimensionsPx_(this.workspace_.getFlyout(opt_own)); + return { + width: flyoutDimensions.width, + height: flyoutDimensions.height, + position: this.workspace_.toolboxPosition, + }; + } + + /** + * Gets the width, height and position of the toolbox on the workspace in + * pixel coordinates. Returns 0 for the width and height if the workspace has + * a simple toolbox instead of a category toolbox. To get the width and height + * of a + * simple toolbox @see {@link getFlyoutMetrics}. + * @return {!MetricsManager.ToolboxMetrics} The object with the width, + * height and position of the toolbox. + * @public + */ + getToolboxMetrics() { + const toolboxDimensions = + this.getDimensionsPx_(this.workspace_.getToolbox()); + + return { + width: toolboxDimensions.width, + height: toolboxDimensions.height, + position: this.workspace_.toolboxPosition, + }; + } + + /** + * Gets the width and height of the workspace's parent SVG element in pixel + * coordinates. This area includes the toolbox and the visible workspace area. + * @return {!Size} The width and height of the workspace's parent + * SVG element. + * @public + */ + getSvgMetrics() { + return this.workspace_.getCachedParentSvgSize(); + } + + /** + * Gets the absolute left and absolute top in pixel coordinates. + * This is where the visible workspace starts in relation to the SVG + * container. + * @return {!MetricsManager.AbsoluteMetrics} The absolute metrics for + * the workspace. + * @public + */ + getAbsoluteMetrics() { + let absoluteLeft = 0; + const toolboxMetrics = this.getToolboxMetrics(); + const flyoutMetrics = this.getFlyoutMetrics(true); + const doesToolboxExist = !!this.workspace_.getToolbox(); + const doesFlyoutExist = !!this.workspace_.getFlyout(true); + const toolboxPosition = + doesToolboxExist ? toolboxMetrics.position : flyoutMetrics.position; + + const atLeft = toolboxPosition === toolboxUtils.Position.LEFT; + const atTop = toolboxPosition === toolboxUtils.Position.TOP; + if (doesToolboxExist && atLeft) { + absoluteLeft = toolboxMetrics.width; + } else if (doesFlyoutExist && atLeft) { + absoluteLeft = flyoutMetrics.width; + } + let absoluteTop = 0; + if (doesToolboxExist && atTop) { + absoluteTop = toolboxMetrics.height; + } else if (doesFlyoutExist && atTop) { + absoluteTop = flyoutMetrics.height; + } + + return { + top: absoluteTop, + left: absoluteLeft, + }; + } + + /** + * Gets the metrics for the visible workspace in either pixel or workspace + * coordinates. The visible workspace does not include the toolbox or flyout. + * @param {boolean=} opt_getWorkspaceCoordinates True to get the view metrics + * in workspace coordinates, false to get them in pixel coordinates. + * @return {!MetricsManager.ContainerRegion} The width, height, top and + * left of the viewport in either workspace coordinates or pixel + * coordinates. + * @public + */ + getViewMetrics(opt_getWorkspaceCoordinates) { + const scale = opt_getWorkspaceCoordinates ? this.workspace_.scale : 1; + const svgMetrics = this.getSvgMetrics(); + const toolboxMetrics = this.getToolboxMetrics(); + const flyoutMetrics = this.getFlyoutMetrics(true); + const doesToolboxExist = !!this.workspace_.getToolbox(); + const toolboxPosition = + doesToolboxExist ? toolboxMetrics.position : flyoutMetrics.position; + + if (this.workspace_.getToolbox()) { + if (toolboxPosition === toolboxUtils.Position.TOP || + toolboxPosition === toolboxUtils.Position.BOTTOM) { + svgMetrics.height -= toolboxMetrics.height; + } else if ( + toolboxPosition === toolboxUtils.Position.LEFT || + toolboxPosition === toolboxUtils.Position.RIGHT) { + svgMetrics.width -= toolboxMetrics.width; + } + } else if (this.workspace_.getFlyout(true)) { + if (toolboxPosition === toolboxUtils.Position.TOP || + toolboxPosition === toolboxUtils.Position.BOTTOM) { + svgMetrics.height -= flyoutMetrics.height; + } else if ( + toolboxPosition === toolboxUtils.Position.LEFT || + toolboxPosition === toolboxUtils.Position.RIGHT) { + svgMetrics.width -= flyoutMetrics.width; + } + } + return { + height: svgMetrics.height / scale, + width: svgMetrics.width / scale, + top: -this.workspace_.scrollY / scale, + left: -this.workspace_.scrollX / scale, + }; + } + + /** + * Gets content metrics in either pixel or workspace coordinates. + * The content area is a rectangle around all the top bounded elements on the + * workspace (workspace comments and blocks). + * @param {boolean=} opt_getWorkspaceCoordinates True to get the content + * metrics in workspace coordinates, false to get them in pixel + * coordinates. + * @return {!MetricsManager.ContainerRegion} The + * metrics for the content container. + * @public + */ + getContentMetrics(opt_getWorkspaceCoordinates) { + const scale = opt_getWorkspaceCoordinates ? 1 : this.workspace_.scale; + + // Block bounding box is in workspace coordinates. + const blockBox = this.workspace_.getBlocksBoundingBox(); + + return { + height: (blockBox.bottom - blockBox.top) * scale, + width: (blockBox.right - blockBox.left) * scale, + top: blockBox.top * scale, + left: blockBox.left * scale, + }; + } + + /** + * Returns whether the scroll area has fixed edges. + * @return {boolean} Whether the scroll area has fixed edges. + * @package + */ + hasFixedEdges() { + // This exists for optimization of bump logic. + return !this.workspace_.isMovableHorizontally() || + !this.workspace_.isMovableVertically(); + } + + /** + * Computes the fixed edges of the scroll area. + * @param {!MetricsManager.ContainerRegion=} opt_viewMetrics The view + * metrics if they have been previously computed. Passing in null may + * cause the view metrics to be computed again, if it is needed. + * @return {!MetricsManager.FixedEdges} The fixed edges of the scroll + * area. + * @protected + */ + getComputedFixedEdges_(opt_viewMetrics) { + if (!this.hasFixedEdges()) { + // Return early if there are no edges. + return {}; + } + + const hScrollEnabled = this.workspace_.isMovableHorizontally(); + const vScrollEnabled = this.workspace_.isMovableVertically(); + + const viewMetrics = opt_viewMetrics || this.getViewMetrics(false); + + const edges = {}; + if (!vScrollEnabled) { + edges.top = viewMetrics.top; + edges.bottom = viewMetrics.top + viewMetrics.height; + } + if (!hScrollEnabled) { + edges.left = viewMetrics.left; + edges.right = viewMetrics.left + viewMetrics.width; + } + return edges; + } + + /** + * Returns the content area with added padding. + * @param {!MetricsManager.ContainerRegion} viewMetrics The view + * metrics. + * @param {!MetricsManager.ContainerRegion} contentMetrics The content + * metrics. + * @return {{top: number, bottom: number, left: number, right: number}} The + * padded content area. + * @protected + */ + getPaddedContent_(viewMetrics, contentMetrics) { + const contentBottom = contentMetrics.top + contentMetrics.height; + const contentRight = contentMetrics.left + contentMetrics.width; + + const viewWidth = viewMetrics.width; + const viewHeight = viewMetrics.height; + const halfWidth = viewWidth / 2; + const halfHeight = viewHeight / 2; + + // Add a padding around the content that is at least half a screen wide. + // Ensure padding is wide enough that blocks can scroll over entire screen. + const top = + Math.min(contentMetrics.top - halfHeight, contentBottom - viewHeight); + const left = + Math.min(contentMetrics.left - halfWidth, contentRight - viewWidth); + const bottom = + Math.max(contentBottom + halfHeight, contentMetrics.top + viewHeight); + const right = + Math.max(contentRight + halfWidth, contentMetrics.left + viewWidth); + + return {top: top, bottom: bottom, left: left, right: right}; + } + + /** + * Returns the metrics for the scroll area of the workspace. + * @param {boolean=} opt_getWorkspaceCoordinates True to get the scroll + * metrics in workspace coordinates, false to get them in pixel + * coordinates. + * @param {!MetricsManager.ContainerRegion=} opt_viewMetrics The view + * metrics if they have been previously computed. Passing in null may + * cause the view metrics to be computed again, if it is needed. + * @param {!MetricsManager.ContainerRegion=} opt_contentMetrics The + * content metrics if they have been previously computed. Passing in null + * may cause the content metrics to be computed again, if it is needed. + * @return {!MetricsManager.ContainerRegion} The metrics for the scroll + * container. + */ + getScrollMetrics( + opt_getWorkspaceCoordinates, opt_viewMetrics, opt_contentMetrics) { + const scale = opt_getWorkspaceCoordinates ? this.workspace_.scale : 1; + const viewMetrics = opt_viewMetrics || this.getViewMetrics(false); + const contentMetrics = opt_contentMetrics || this.getContentMetrics(); + const fixedEdges = this.getComputedFixedEdges_(viewMetrics); + + // Add padding around content. + const paddedContent = this.getPaddedContent_(viewMetrics, contentMetrics); + + // Use combination of fixed bounds and padded content to make scroll area. + const top = + fixedEdges.top !== undefined ? fixedEdges.top : paddedContent.top; + const left = + fixedEdges.left !== undefined ? fixedEdges.left : paddedContent.left; + const bottom = fixedEdges.bottom !== undefined ? fixedEdges.bottom : + paddedContent.bottom; + const right = + fixedEdges.right !== undefined ? fixedEdges.right : paddedContent.right; + + return { + top: top / scale, + left: left / scale, + width: (right - left) / scale, + height: (bottom - top) / scale, + }; + } + + /** + * Returns common metrics used by UI elements. + * @return {!MetricsManager.UiMetrics} The UI metrics. + */ + getUiMetrics() { + return { + viewMetrics: this.getViewMetrics(), + absoluteMetrics: this.getAbsoluteMetrics(), + toolboxMetrics: this.getToolboxMetrics(), + }; + } + + /** + * Returns an object with all the metrics required to size scrollbars for a + * top level workspace. The following properties are computed: + * Coordinate system: pixel coordinates, -left, -up, +right, +down + * .viewHeight: Height of the visible portion of the workspace. + * .viewWidth: Width of the visible portion of the workspace. + * .contentHeight: Height of the content. + * .contentWidth: Width of the content. + * .scrollHeight: Height of the scroll area. + * .scrollWidth: Width of the scroll area. + * .svgHeight: Height of the Blockly div (the view + the toolbox, + * simple or otherwise), + * .svgWidth: Width of the Blockly div (the view + the toolbox, + * simple or otherwise), + * .viewTop: Top-edge of the visible portion of the workspace, relative to + * the workspace origin. + * .viewLeft: Left-edge of the visible portion of the workspace, relative to + * the workspace origin. + * .contentTop: Top-edge of the content, relative to the workspace origin. + * .contentLeft: Left-edge of the content relative to the workspace origin. + * .scrollTop: Top-edge of the scroll area, relative to the workspace origin. + * .scrollLeft: Left-edge of the scroll area relative to the workspace origin. + * .absoluteTop: Top-edge of the visible portion of the workspace, relative + * to the blocklyDiv. + * .absoluteLeft: Left-edge of the visible portion of the workspace, relative + * to the blocklyDiv. + * .toolboxWidth: Width of the toolbox, if it exists. Otherwise zero. + * .toolboxHeight: Height of the toolbox, if it exists. Otherwise zero. + * .flyoutWidth: Width of the flyout if it is always open. Otherwise zero. + * .flyoutHeight: Height of the flyout if it is always open. Otherwise zero. + * .toolboxPosition: Top, bottom, left or right. Use TOOLBOX_AT constants to + * compare. + * @return {!Metrics} Contains size and position metrics of a top + * level workspace. + * @public + */ + getMetrics() { + const toolboxMetrics = this.getToolboxMetrics(); + const flyoutMetrics = this.getFlyoutMetrics(true); + const svgMetrics = this.getSvgMetrics(); + const absoluteMetrics = this.getAbsoluteMetrics(); + const viewMetrics = this.getViewMetrics(); + const contentMetrics = this.getContentMetrics(); + const scrollMetrics = + this.getScrollMetrics(false, viewMetrics, contentMetrics); + + return { + contentHeight: contentMetrics.height, + contentWidth: contentMetrics.width, + contentTop: contentMetrics.top, + contentLeft: contentMetrics.left, + + scrollHeight: scrollMetrics.height, + scrollWidth: scrollMetrics.width, + scrollTop: scrollMetrics.top, + scrollLeft: scrollMetrics.left, + + viewHeight: viewMetrics.height, + viewWidth: viewMetrics.width, + viewTop: viewMetrics.top, + viewLeft: viewMetrics.left, + + absoluteTop: absoluteMetrics.top, + absoluteLeft: absoluteMetrics.left, + + svgHeight: svgMetrics.height, + svgWidth: svgMetrics.width, + + toolboxWidth: toolboxMetrics.width, + toolboxHeight: toolboxMetrics.height, + toolboxPosition: toolboxMetrics.position, + + flyoutWidth: flyoutMetrics.width, + flyoutHeight: flyoutMetrics.height, + }; + } +} /** * Describes the width, height and location of the toolbox on the main @@ -57,6 +446,7 @@ const MetricsManager = function(workspace) { * }} */ MetricsManager.ToolboxMetrics; + /** * Describes where the viewport starts in relation to the workspace SVG. * @typedef {{ @@ -65,8 +455,10 @@ MetricsManager.ToolboxMetrics; * }} */ MetricsManager.AbsoluteMetrics; + /** - * All the measurements needed to describe the size and location of a container. + * All the measurements needed to describe the size and location of a + * container. * @typedef {{ * height: number, * width: number, @@ -75,6 +467,7 @@ MetricsManager.AbsoluteMetrics; * }} */ MetricsManager.ContainerRegion; + /** * Describes fixed edges of the workspace. * @typedef {{ @@ -85,6 +478,7 @@ MetricsManager.ContainerRegion; * }} */ MetricsManager.FixedEdges; + /** * Common metrics used for UI elements. * @typedef {{ @@ -94,387 +488,6 @@ MetricsManager.FixedEdges; * }} */ MetricsManager.UiMetrics; -/** - * Gets the dimensions of the given workspace component, in pixel coordinates. - * @param {?IToolbox|?IFlyout} elem The element to get the - * dimensions of, or null. It should be a toolbox or flyout, and should - * implement getWidth() and getHeight(). - * @return {!Size} An object containing width and height - * attributes, which will both be zero if elem did not exist. - * @protected - */ -MetricsManager.prototype.getDimensionsPx_ = function(elem) { - let width = 0; - let height = 0; - if (elem) { - width = elem.getWidth(); - height = elem.getHeight(); - } - return new Size(width, height); -}; - -/** - * Gets the width and the height of the flyout on the workspace in pixel - * coordinates. Returns 0 for the width and height if the workspace has a - * category toolbox instead of a simple toolbox. - * @param {boolean=} opt_own Whether to only return the workspace's own flyout. - * @return {!MetricsManager.ToolboxMetrics} The width and height of the - * flyout. - * @public - */ -MetricsManager.prototype.getFlyoutMetrics = function(opt_own) { - const flyoutDimensions = - this.getDimensionsPx_(this.workspace_.getFlyout(opt_own)); - return { - width: flyoutDimensions.width, - height: flyoutDimensions.height, - position: this.workspace_.toolboxPosition, - }; -}; - -/** - * Gets the width, height and position of the toolbox on the workspace in pixel - * coordinates. Returns 0 for the width and height if the workspace has a simple - * toolbox instead of a category toolbox. To get the width and height of a - * simple toolbox @see {@link getFlyoutMetrics}. - * @return {!MetricsManager.ToolboxMetrics} The object with the width, - * height and position of the toolbox. - * @public - */ -MetricsManager.prototype.getToolboxMetrics = function() { - const toolboxDimensions = this.getDimensionsPx_(this.workspace_.getToolbox()); - - return { - width: toolboxDimensions.width, - height: toolboxDimensions.height, - position: this.workspace_.toolboxPosition, - }; -}; - -/** - * Gets the width and height of the workspace's parent SVG element in pixel - * coordinates. This area includes the toolbox and the visible workspace area. - * @return {!Size} The width and height of the workspace's parent - * SVG element. - * @public - */ -MetricsManager.prototype.getSvgMetrics = function() { - return this.workspace_.getCachedParentSvgSize(); -}; - -/** - * Gets the absolute left and absolute top in pixel coordinates. - * This is where the visible workspace starts in relation to the SVG container. - * @return {!MetricsManager.AbsoluteMetrics} The absolute metrics for - * the workspace. - * @public - */ -MetricsManager.prototype.getAbsoluteMetrics = function() { - let absoluteLeft = 0; - const toolboxMetrics = this.getToolboxMetrics(); - const flyoutMetrics = this.getFlyoutMetrics(true); - const doesToolboxExist = !!this.workspace_.getToolbox(); - const doesFlyoutExist = !!this.workspace_.getFlyout(true); - const toolboxPosition = - doesToolboxExist ? toolboxMetrics.position : flyoutMetrics.position; - - const atLeft = toolboxPosition === toolboxUtils.Position.LEFT; - const atTop = toolboxPosition === toolboxUtils.Position.TOP; - if (doesToolboxExist && atLeft) { - absoluteLeft = toolboxMetrics.width; - } else if (doesFlyoutExist && atLeft) { - absoluteLeft = flyoutMetrics.width; - } - let absoluteTop = 0; - if (doesToolboxExist && atTop) { - absoluteTop = toolboxMetrics.height; - } else if (doesFlyoutExist && atTop) { - absoluteTop = flyoutMetrics.height; - } - - return { - top: absoluteTop, - left: absoluteLeft, - }; -}; - -/** - * Gets the metrics for the visible workspace in either pixel or workspace - * coordinates. The visible workspace does not include the toolbox or flyout. - * @param {boolean=} opt_getWorkspaceCoordinates True to get the view metrics in - * workspace coordinates, false to get them in pixel coordinates. - * @return {!MetricsManager.ContainerRegion} The width, height, top and - * left of the viewport in either workspace coordinates or pixel - * coordinates. - * @public - */ -MetricsManager.prototype.getViewMetrics = function( - opt_getWorkspaceCoordinates) { - const scale = opt_getWorkspaceCoordinates ? this.workspace_.scale : 1; - const svgMetrics = this.getSvgMetrics(); - const toolboxMetrics = this.getToolboxMetrics(); - const flyoutMetrics = this.getFlyoutMetrics(true); - const doesToolboxExist = !!this.workspace_.getToolbox(); - const toolboxPosition = - doesToolboxExist ? toolboxMetrics.position : flyoutMetrics.position; - - if (this.workspace_.getToolbox()) { - if (toolboxPosition === toolboxUtils.Position.TOP || - toolboxPosition === toolboxUtils.Position.BOTTOM) { - svgMetrics.height -= toolboxMetrics.height; - } else if ( - toolboxPosition === toolboxUtils.Position.LEFT || - toolboxPosition === toolboxUtils.Position.RIGHT) { - svgMetrics.width -= toolboxMetrics.width; - } - } else if (this.workspace_.getFlyout(true)) { - if (toolboxPosition === toolboxUtils.Position.TOP || - toolboxPosition === toolboxUtils.Position.BOTTOM) { - svgMetrics.height -= flyoutMetrics.height; - } else if ( - toolboxPosition === toolboxUtils.Position.LEFT || - toolboxPosition === toolboxUtils.Position.RIGHT) { - svgMetrics.width -= flyoutMetrics.width; - } - } - return { - height: svgMetrics.height / scale, - width: svgMetrics.width / scale, - top: -this.workspace_.scrollY / scale, - left: -this.workspace_.scrollX / scale, - }; -}; - -/** - * Gets content metrics in either pixel or workspace coordinates. - * The content area is a rectangle around all the top bounded elements on the - * workspace (workspace comments and blocks). - * @param {boolean=} opt_getWorkspaceCoordinates True to get the content metrics - * in workspace coordinates, false to get them in pixel coordinates. - * @return {!MetricsManager.ContainerRegion} The - * metrics for the content container. - * @public - */ -MetricsManager.prototype.getContentMetrics = function( - opt_getWorkspaceCoordinates) { - const scale = opt_getWorkspaceCoordinates ? 1 : this.workspace_.scale; - - // Block bounding box is in workspace coordinates. - const blockBox = this.workspace_.getBlocksBoundingBox(); - - return { - height: (blockBox.bottom - blockBox.top) * scale, - width: (blockBox.right - blockBox.left) * scale, - top: blockBox.top * scale, - left: blockBox.left * scale, - }; -}; - -/** - * Returns whether the scroll area has fixed edges. - * @return {boolean} Whether the scroll area has fixed edges. - * @package - */ -MetricsManager.prototype.hasFixedEdges = function() { - // This exists for optimization of bump logic. - return !this.workspace_.isMovableHorizontally() || - !this.workspace_.isMovableVertically(); -}; - -/** - * Computes the fixed edges of the scroll area. - * @param {!MetricsManager.ContainerRegion=} opt_viewMetrics The view - * metrics if they have been previously computed. Passing in null may cause - * the view metrics to be computed again, if it is needed. - * @return {!MetricsManager.FixedEdges} The fixed edges of the scroll - * area. - * @protected - */ -MetricsManager.prototype.getComputedFixedEdges_ = function(opt_viewMetrics) { - if (!this.hasFixedEdges()) { - // Return early if there are no edges. - return {}; - } - - const hScrollEnabled = this.workspace_.isMovableHorizontally(); - const vScrollEnabled = this.workspace_.isMovableVertically(); - - const viewMetrics = opt_viewMetrics || this.getViewMetrics(false); - - const edges = {}; - if (!vScrollEnabled) { - edges.top = viewMetrics.top; - edges.bottom = viewMetrics.top + viewMetrics.height; - } - if (!hScrollEnabled) { - edges.left = viewMetrics.left; - edges.right = viewMetrics.left + viewMetrics.width; - } - return edges; -}; - -/** - * Returns the content area with added padding. - * @param {!MetricsManager.ContainerRegion} viewMetrics The view - * metrics. - * @param {!MetricsManager.ContainerRegion} contentMetrics The content - * metrics. - * @return {{top: number, bottom: number, left: number, right: number}} The - * padded content area. - * @protected - */ -MetricsManager.prototype.getPaddedContent_ = function( - viewMetrics, contentMetrics) { - const contentBottom = contentMetrics.top + contentMetrics.height; - const contentRight = contentMetrics.left + contentMetrics.width; - - const viewWidth = viewMetrics.width; - const viewHeight = viewMetrics.height; - const halfWidth = viewWidth / 2; - const halfHeight = viewHeight / 2; - - // Add a padding around the content that is at least half a screen wide. - // Ensure padding is wide enough that blocks can scroll over entire screen. - const top = - Math.min(contentMetrics.top - halfHeight, contentBottom - viewHeight); - const left = - Math.min(contentMetrics.left - halfWidth, contentRight - viewWidth); - const bottom = - Math.max(contentBottom + halfHeight, contentMetrics.top + viewHeight); - const right = - Math.max(contentRight + halfWidth, contentMetrics.left + viewWidth); - - return {top: top, bottom: bottom, left: left, right: right}; -}; - -/** - * Returns the metrics for the scroll area of the workspace. - * @param {boolean=} opt_getWorkspaceCoordinates True to get the scroll metrics - * in workspace coordinates, false to get them in pixel coordinates. - * @param {!MetricsManager.ContainerRegion=} opt_viewMetrics The view - * metrics if they have been previously computed. Passing in null may cause - * the view metrics to be computed again, if it is needed. - * @param {!MetricsManager.ContainerRegion=} opt_contentMetrics The - * content metrics if they have been previously computed. Passing in null - * may cause the content metrics to be computed again, if it is needed. - * @return {!MetricsManager.ContainerRegion} The metrics for the scroll - * container. - */ -MetricsManager.prototype.getScrollMetrics = function( - opt_getWorkspaceCoordinates, opt_viewMetrics, opt_contentMetrics) { - const scale = opt_getWorkspaceCoordinates ? this.workspace_.scale : 1; - const viewMetrics = opt_viewMetrics || this.getViewMetrics(false); - const contentMetrics = opt_contentMetrics || this.getContentMetrics(); - const fixedEdges = this.getComputedFixedEdges_(viewMetrics); - - // Add padding around content. - const paddedContent = this.getPaddedContent_(viewMetrics, contentMetrics); - - // Use combination of fixed bounds and padded content to make scroll area. - const top = fixedEdges.top !== undefined ? fixedEdges.top : paddedContent.top; - const left = - fixedEdges.left !== undefined ? fixedEdges.left : paddedContent.left; - const bottom = fixedEdges.bottom !== undefined ? fixedEdges.bottom : - paddedContent.bottom; - const right = - fixedEdges.right !== undefined ? fixedEdges.right : paddedContent.right; - - return { - top: top / scale, - left: left / scale, - width: (right - left) / scale, - height: (bottom - top) / scale, - }; -}; - -/** - * Returns common metrics used by UI elements. - * @return {!MetricsManager.UiMetrics} The UI metrics. - */ -MetricsManager.prototype.getUiMetrics = function() { - return { - viewMetrics: this.getViewMetrics(), - absoluteMetrics: this.getAbsoluteMetrics(), - toolboxMetrics: this.getToolboxMetrics(), - }; -}; - -/** - * Returns an object with all the metrics required to size scrollbars for a - * top level workspace. The following properties are computed: - * Coordinate system: pixel coordinates, -left, -up, +right, +down - * .viewHeight: Height of the visible portion of the workspace. - * .viewWidth: Width of the visible portion of the workspace. - * .contentHeight: Height of the content. - * .contentWidth: Width of the content. - * .scrollHeight: Height of the scroll area. - * .scrollWidth: Width of the scroll area. - * .svgHeight: Height of the Blockly div (the view + the toolbox, - * simple or otherwise), - * .svgWidth: Width of the Blockly div (the view + the toolbox, - * simple or otherwise), - * .viewTop: Top-edge of the visible portion of the workspace, relative to - * the workspace origin. - * .viewLeft: Left-edge of the visible portion of the workspace, relative to - * the workspace origin. - * .contentTop: Top-edge of the content, relative to the workspace origin. - * .contentLeft: Left-edge of the content relative to the workspace origin. - * .scrollTop: Top-edge of the scroll area, relative to the workspace origin. - * .scrollLeft: Left-edge of the scroll area relative to the workspace origin. - * .absoluteTop: Top-edge of the visible portion of the workspace, relative - * to the blocklyDiv. - * .absoluteLeft: Left-edge of the visible portion of the workspace, relative - * to the blocklyDiv. - * .toolboxWidth: Width of the toolbox, if it exists. Otherwise zero. - * .toolboxHeight: Height of the toolbox, if it exists. Otherwise zero. - * .flyoutWidth: Width of the flyout if it is always open. Otherwise zero. - * .flyoutHeight: Height of the flyout if it is always open. Otherwise zero. - * .toolboxPosition: Top, bottom, left or right. Use TOOLBOX_AT constants to - * compare. - * @return {!Metrics} Contains size and position metrics of a top - * level workspace. - * @public - */ -MetricsManager.prototype.getMetrics = function() { - const toolboxMetrics = this.getToolboxMetrics(); - const flyoutMetrics = this.getFlyoutMetrics(true); - const svgMetrics = this.getSvgMetrics(); - const absoluteMetrics = this.getAbsoluteMetrics(); - const viewMetrics = this.getViewMetrics(); - const contentMetrics = this.getContentMetrics(); - const scrollMetrics = - this.getScrollMetrics(false, viewMetrics, contentMetrics); - - return { - contentHeight: contentMetrics.height, - contentWidth: contentMetrics.width, - contentTop: contentMetrics.top, - contentLeft: contentMetrics.left, - - scrollHeight: scrollMetrics.height, - scrollWidth: scrollMetrics.width, - scrollTop: scrollMetrics.top, - scrollLeft: scrollMetrics.left, - - viewHeight: viewMetrics.height, - viewWidth: viewMetrics.width, - viewTop: viewMetrics.top, - viewLeft: viewMetrics.left, - - absoluteTop: absoluteMetrics.top, - absoluteLeft: absoluteMetrics.left, - - svgHeight: svgMetrics.height, - svgWidth: svgMetrics.width, - - toolboxWidth: toolboxMetrics.width, - toolboxHeight: toolboxMetrics.height, - toolboxPosition: toolboxMetrics.position, - - flyoutWidth: flyoutMetrics.width, - flyoutHeight: flyoutMetrics.height, - }; -}; registry.register( registry.Type.METRICS_MANAGER, registry.DEFAULT, MetricsManager); diff --git a/core/touch_gesture.js b/core/touch_gesture.js index 815da7c63..c5b2396cc 100644 --- a/core/touch_gesture.js +++ b/core/touch_gesture.js @@ -19,7 +19,6 @@ goog.module('Blockly.TouchGesture'); const Touch = goog.require('Blockly.Touch'); const browserEvents = goog.require('Blockly.browserEvents'); -const object = goog.require('Blockly.utils.object'); const {Coordinate} = goog.require('Blockly.utils.Coordinate'); const {Gesture} = goog.require('Blockly.Gesture'); /* eslint-disable-next-line no-unused-vars */ @@ -31,300 +30,304 @@ const {WorkspaceSvg} = goog.requireType('Blockly.WorkspaceSvg'); * events. "End" refers to touchend, mouseup, and pointerend events. */ -/** - * Class for one gesture. - * @param {!Event} e The event that kicked off this gesture. - * @param {!WorkspaceSvg} creatorWorkspace The workspace that created - * this gesture and has a reference to it. - * @extends {Gesture} - * @constructor - * @alias Blockly.TouchGesture - */ -const TouchGesture = function(e, creatorWorkspace) { - TouchGesture.superClass_.constructor.call(this, e, creatorWorkspace); - - /** - * Boolean for whether or not this gesture is a multi-touch gesture. - * @type {boolean} - * @private - */ - this.isMultiTouch_ = false; - - /** - * A map of cached points used for tracking multi-touch gestures. - * @type {!Object} - * @private - */ - this.cachedPoints_ = Object.create(null); - - /** - * This is the ratio between the starting distance between the touch points - * and the most recent distance between the touch points. - * Scales between 0 and 1 mean the most recent zoom was a zoom out. - * Scales above 1.0 mean the most recent zoom was a zoom in. - * @type {number} - * @private - */ - this.previousScale_ = 0; - - /** - * The starting distance between two touch points. - * @type {number} - * @private - */ - this.startDistance_ = 0; - - /** - * A handle to use to unbind the second touch start or pointer down listener - * at the end of a drag. - * Opaque data returned from Blockly.bindEventWithChecks_. - * @type {?browserEvents.Data} - * @private - */ - this.onStartWrapper_ = null; - - /** - * Boolean for whether or not the workspace supports pinch-zoom. - * @type {?boolean} - * @private - */ - this.isPinchZoomEnabled_ = null; -}; -object.inherits(TouchGesture, Gesture); /** * A multiplier used to convert the gesture scale to a zoom in delta. * @const */ -TouchGesture.ZOOM_IN_MULTIPLIER = 5; +const ZOOM_IN_MULTIPLIER = 5; /** * A multiplier used to convert the gesture scale to a zoom out delta. * @const */ -TouchGesture.ZOOM_OUT_MULTIPLIER = 6; +const ZOOM_OUT_MULTIPLIER = 6; /** - * Start a gesture: update the workspace to indicate that a gesture is in - * progress and bind mousemove and mouseup handlers. - * @param {!Event} e A mouse down, touch start or pointer down event. - * @package + * Class for one gesture. + * @extends {Gesture} */ -TouchGesture.prototype.doStart = function(e) { - this.isPinchZoomEnabled_ = this.startWorkspace_.options.zoomOptions && - this.startWorkspace_.options.zoomOptions.pinch; - TouchGesture.superClass_.doStart.call(this, e); - if (!this.isEnding_ && Touch.isTouchEvent(e)) { - this.handleTouchStart(e); +class TouchGesture extends Gesture { + /** + * @param {!Event} e The event that kicked off this gesture. + * @param {!WorkspaceSvg} creatorWorkspace The workspace that created + * this gesture and has a reference to it. + * @alias Blockly.TouchGesture + */ + constructor(e, creatorWorkspace) { + super(e, creatorWorkspace); + + /** + * Boolean for whether or not this gesture is a multi-touch gesture. + * @type {boolean} + * @private + */ + this.isMultiTouch_ = false; + + /** + * A map of cached points used for tracking multi-touch gestures. + * @type {!Object} + * @private + */ + this.cachedPoints_ = Object.create(null); + + /** + * This is the ratio between the starting distance between the touch points + * and the most recent distance between the touch points. + * Scales between 0 and 1 mean the most recent zoom was a zoom out. + * Scales above 1.0 mean the most recent zoom was a zoom in. + * @type {number} + * @private + */ + this.previousScale_ = 0; + + /** + * The starting distance between two touch points. + * @type {number} + * @private + */ + this.startDistance_ = 0; + + /** + * A handle to use to unbind the second touch start or pointer down listener + * at the end of a drag. + * Opaque data returned from Blockly.bindEventWithChecks_. + * @type {?browserEvents.Data} + * @private + */ + this.onStartWrapper_ = null; + + /** + * Boolean for whether or not the workspace supports pinch-zoom. + * @type {?boolean} + * @private + */ + this.isPinchZoomEnabled_ = null; } -}; -/** - * Bind gesture events. - * Overriding the gesture definition of this function, binding the same - * functions for onMoveWrapper_ and onUpWrapper_ but passing - * opt_noCaptureIdentifier. - * In addition, binding a second mouse down event to detect multi-touch events. - * @param {!Event} e A mouse down or touch start event. - * @package - */ -TouchGesture.prototype.bindMouseEvents = function(e) { - this.onStartWrapper_ = browserEvents.conditionalBind( - document, 'mousedown', null, this.handleStart.bind(this), - /* opt_noCaptureIdentifier */ true); - this.onMoveWrapper_ = browserEvents.conditionalBind( - document, 'mousemove', null, this.handleMove.bind(this), - /* opt_noCaptureIdentifier */ true); - this.onUpWrapper_ = browserEvents.conditionalBind( - document, 'mouseup', null, this.handleUp.bind(this), - /* opt_noCaptureIdentifier */ true); - - e.preventDefault(); - e.stopPropagation(); -}; - -/** - * Handle a mouse down, touch start, or pointer down event. - * @param {!Event} e A mouse down, touch start, or pointer down event. - * @package - */ -TouchGesture.prototype.handleStart = function(e) { - if (this.isDragging()) { - // A drag has already started, so this can no longer be a pinch-zoom. - return; - } - if (Touch.isTouchEvent(e)) { - this.handleTouchStart(e); - - if (this.isMultiTouch()) { - Touch.longStop(); + /** + * Start a gesture: update the workspace to indicate that a gesture is in + * progress and bind mousemove and mouseup handlers. + * @param {!Event} e A mouse down, touch start or pointer down event. + * @package + */ + doStart(e) { + this.isPinchZoomEnabled_ = this.startWorkspace_.options.zoomOptions && + this.startWorkspace_.options.zoomOptions.pinch; + super.doStart(e); + if (!this.isEnding_ && Touch.isTouchEvent(e)) { + this.handleTouchStart(e); } } -}; -/** - * Handle a mouse move, touch move, or pointer move event. - * @param {!Event} e A mouse move, touch move, or pointer move event. - * @package - */ -TouchGesture.prototype.handleMove = function(e) { - if (this.isDragging()) { - // We are in the middle of a drag, only handle the relevant events - if (Touch.shouldHandleEvent(e)) { - TouchGesture.superClass_.handleMove.call(this, e); - } - return; - } - if (this.isMultiTouch()) { - if (Touch.isTouchEvent(e)) { - this.handleTouchMove(e); - } - Touch.longStop(); - } else { - TouchGesture.superClass_.handleMove.call(this, e); - } -}; + /** + * Bind gesture events. + * Overriding the gesture definition of this function, binding the same + * functions for onMoveWrapper_ and onUpWrapper_ but passing + * opt_noCaptureIdentifier. + * In addition, binding a second mouse down event to detect multi-touch + * events. + * @param {!Event} e A mouse down or touch start event. + * @package + */ + bindMouseEvents(e) { + this.onStartWrapper_ = browserEvents.conditionalBind( + document, 'mousedown', null, this.handleStart.bind(this), + /* opt_noCaptureIdentifier */ true); + this.onMoveWrapper_ = browserEvents.conditionalBind( + document, 'mousemove', null, this.handleMove.bind(this), + /* opt_noCaptureIdentifier */ true); + this.onUpWrapper_ = browserEvents.conditionalBind( + document, 'mouseup', null, this.handleUp.bind(this), + /* opt_noCaptureIdentifier */ true); -/** - * Handle a mouse up, touch end, or pointer up event. - * @param {!Event} e A mouse up, touch end, or pointer up event. - * @package - */ -TouchGesture.prototype.handleUp = function(e) { - if (Touch.isTouchEvent(e) && !this.isDragging()) { - this.handleTouchEnd(e); - } - if (!this.isMultiTouch() || this.isDragging()) { - if (!Touch.shouldHandleEvent(e)) { - return; - } - TouchGesture.superClass_.handleUp.call(this, e); - } else { e.preventDefault(); e.stopPropagation(); - - this.dispose(); } -}; -/** - * Whether this gesture is part of a multi-touch gesture. - * @return {boolean} Whether this gesture is part of a multi-touch gesture. - * @package - */ -TouchGesture.prototype.isMultiTouch = function() { - return this.isMultiTouch_; -}; + /** + * Handle a mouse down, touch start, or pointer down event. + * @param {!Event} e A mouse down, touch start, or pointer down event. + * @package + */ + handleStart(e) { + if (this.isDragging()) { + // A drag has already started, so this can no longer be a pinch-zoom. + return; + } + if (Touch.isTouchEvent(e)) { + this.handleTouchStart(e); -/** - * Sever all links from this object. - * @package - */ -TouchGesture.prototype.dispose = function() { - TouchGesture.superClass_.dispose.call(this); - - if (this.onStartWrapper_) { - browserEvents.unbind(this.onStartWrapper_); + if (this.isMultiTouch()) { + Touch.longStop(); + } + } } -}; -/** - * Handle a touch start or pointer down event and keep track of current - * pointers. - * @param {!Event} e A touch start, or pointer down event. - * @package - */ -TouchGesture.prototype.handleTouchStart = function(e) { - const pointerId = Touch.getTouchIdentifierFromEvent(e); - // store the pointerId in the current list of pointers - this.cachedPoints_[pointerId] = this.getTouchPoint(e); - const pointers = Object.keys(this.cachedPoints_); - // If two pointers are down, store info - if (pointers.length === 2) { + /** + * Handle a mouse move, touch move, or pointer move event. + * @param {!Event} e A mouse move, touch move, or pointer move event. + * @package + */ + handleMove(e) { + if (this.isDragging()) { + // We are in the middle of a drag, only handle the relevant events + if (Touch.shouldHandleEvent(e)) { + super.handleMove(e); + } + return; + } + if (this.isMultiTouch()) { + if (Touch.isTouchEvent(e)) { + this.handleTouchMove(e); + } + Touch.longStop(); + } else { + super.handleMove(e); + } + } + + /** + * Handle a mouse up, touch end, or pointer up event. + * @param {!Event} e A mouse up, touch end, or pointer up event. + * @package + */ + handleUp(e) { + if (Touch.isTouchEvent(e) && !this.isDragging()) { + this.handleTouchEnd(e); + } + if (!this.isMultiTouch() || this.isDragging()) { + if (!Touch.shouldHandleEvent(e)) { + return; + } + super.handleUp(e); + } else { + e.preventDefault(); + e.stopPropagation(); + + this.dispose(); + } + } + + /** + * Whether this gesture is part of a multi-touch gesture. + * @return {boolean} Whether this gesture is part of a multi-touch gesture. + * @package + */ + isMultiTouch() { + return this.isMultiTouch_; + } + + /** + * Sever all links from this object. + * @package + */ + dispose() { + super.dispose(); + + if (this.onStartWrapper_) { + browserEvents.unbind(this.onStartWrapper_); + } + } + + /** + * Handle a touch start or pointer down event and keep track of current + * pointers. + * @param {!Event} e A touch start, or pointer down event. + * @package + */ + handleTouchStart(e) { + const pointerId = Touch.getTouchIdentifierFromEvent(e); + // store the pointerId in the current list of pointers + this.cachedPoints_[pointerId] = this.getTouchPoint(e); + const pointers = Object.keys(this.cachedPoints_); + // If two pointers are down, store info + if (pointers.length === 2) { + const point0 = + /** @type {!Coordinate} */ (this.cachedPoints_[pointers[0]]); + const point1 = + /** @type {!Coordinate} */ (this.cachedPoints_[pointers[1]]); + this.startDistance_ = Coordinate.distance(point0, point1); + this.isMultiTouch_ = true; + e.preventDefault(); + } + } + + /** + * Handle a touch move or pointer move event and zoom in/out if two pointers + * are on the screen. + * @param {!Event} e A touch move, or pointer move event. + * @package + */ + handleTouchMove(e) { + const pointerId = Touch.getTouchIdentifierFromEvent(e); + // Update the cache + this.cachedPoints_[pointerId] = this.getTouchPoint(e); + + const pointers = Object.keys(this.cachedPoints_); + if (this.isPinchZoomEnabled_ && pointers.length === 2) { + this.handlePinch_(e); + } else { + super.handleMove(e); + } + } + + /** + * Handle pinch zoom gesture. + * @param {!Event} e A touch move, or pointer move event. + * @private + */ + handlePinch_(e) { + const pointers = Object.keys(this.cachedPoints_); + // Calculate the distance between the two pointers const point0 = /** @type {!Coordinate} */ (this.cachedPoints_[pointers[0]]); const point1 = /** @type {!Coordinate} */ (this.cachedPoints_[pointers[1]]); - this.startDistance_ = Coordinate.distance(point0, point1); - this.isMultiTouch_ = true; + const moveDistance = Coordinate.distance(point0, point1); + const scale = moveDistance / this.startDistance_; + + if (this.previousScale_ > 0 && this.previousScale_ < Infinity) { + const gestureScale = scale - this.previousScale_; + const delta = gestureScale > 0 ? gestureScale * ZOOM_IN_MULTIPLIER : + gestureScale * ZOOM_OUT_MULTIPLIER; + const workspace = this.startWorkspace_; + const position = browserEvents.mouseToSvg( + e, workspace.getParentSvg(), workspace.getInverseScreenCTM()); + workspace.zoom(position.x, position.y, delta); + } + this.previousScale_ = scale; e.preventDefault(); } -}; -/** - * Handle a touch move or pointer move event and zoom in/out if two pointers - * are on the screen. - * @param {!Event} e A touch move, or pointer move event. - * @package - */ -TouchGesture.prototype.handleTouchMove = function(e) { - const pointerId = Touch.getTouchIdentifierFromEvent(e); - // Update the cache - this.cachedPoints_[pointerId] = this.getTouchPoint(e); - - const pointers = Object.keys(this.cachedPoints_); - if (this.isPinchZoomEnabled_ && pointers.length === 2) { - this.handlePinch_(e); - } else { - TouchGesture.superClass_.handleMove.call(this, e); + /** + * Handle a touch end or pointer end event and end the gesture. + * @param {!Event} e A touch end, or pointer end event. + * @package + */ + handleTouchEnd(e) { + const pointerId = Touch.getTouchIdentifierFromEvent(e); + if (this.cachedPoints_[pointerId]) { + delete this.cachedPoints_[pointerId]; + } + if (Object.keys(this.cachedPoints_).length < 2) { + this.cachedPoints_ = Object.create(null); + this.previousScale_ = 0; + } } -}; -/** - * Handle pinch zoom gesture. - * @param {!Event} e A touch move, or pointer move event. - * @private - */ -TouchGesture.prototype.handlePinch_ = function(e) { - const pointers = Object.keys(this.cachedPoints_); - // Calculate the distance between the two pointers - const point0 = /** @type {!Coordinate} */ (this.cachedPoints_[pointers[0]]); - const point1 = /** @type {!Coordinate} */ (this.cachedPoints_[pointers[1]]); - const moveDistance = Coordinate.distance(point0, point1); - const scale = moveDistance / this.startDistance_; - - if (this.previousScale_ > 0 && this.previousScale_ < Infinity) { - const gestureScale = scale - this.previousScale_; - const delta = gestureScale > 0 ? - gestureScale * TouchGesture.ZOOM_IN_MULTIPLIER : - gestureScale * TouchGesture.ZOOM_OUT_MULTIPLIER; - const workspace = this.startWorkspace_; - const position = browserEvents.mouseToSvg( - e, workspace.getParentSvg(), workspace.getInverseScreenCTM()); - workspace.zoom(position.x, position.y, delta); + /** + * Helper function returning the current touch point coordinate. + * @param {!Event} e A touch or pointer event. + * @return {?Coordinate} The current touch point coordinate + * @package + */ + getTouchPoint(e) { + if (!this.startWorkspace_) { + return null; + } + return new Coordinate( + (e.changedTouches ? e.changedTouches[0].pageX : e.pageX), + (e.changedTouches ? e.changedTouches[0].pageY : e.pageY)); } - this.previousScale_ = scale; - e.preventDefault(); -}; - - -/** - * Handle a touch end or pointer end event and end the gesture. - * @param {!Event} e A touch end, or pointer end event. - * @package - */ -TouchGesture.prototype.handleTouchEnd = function(e) { - const pointerId = Touch.getTouchIdentifierFromEvent(e); - if (this.cachedPoints_[pointerId]) { - delete this.cachedPoints_[pointerId]; - } - if (Object.keys(this.cachedPoints_).length < 2) { - this.cachedPoints_ = Object.create(null); - this.previousScale_ = 0; - } -}; - -/** - * Helper function returning the current touch point coordinate. - * @param {!Event} e A touch or pointer event. - * @return {?Coordinate} The current touch point coordinate - * @package - */ -TouchGesture.prototype.getTouchPoint = function(e) { - if (!this.startWorkspace_) { - return null; - } - return new Coordinate( - (e.changedTouches ? e.changedTouches[0].pageX : e.pageX), - (e.changedTouches ? e.changedTouches[0].pageY : e.pageY)); -}; +} exports.TouchGesture = TouchGesture; diff --git a/core/trashcan.js b/core/trashcan.js index 3fa25e433..3b7dbafc8 100644 --- a/core/trashcan.js +++ b/core/trashcan.js @@ -23,7 +23,6 @@ const browserEvents = goog.require('Blockly.browserEvents'); const dom = goog.require('Blockly.utils.dom'); const eventUtils = goog.require('Blockly.Events.utils'); const internalConstants = goog.require('Blockly.internalConstants'); -const object = goog.require('Blockly.utils.object'); const registry = goog.require('Blockly.registry'); const toolbox = goog.require('Blockly.utils.toolbox'); const uiPosition = goog.require('Blockly.uiPosition'); @@ -53,146 +52,631 @@ goog.require('Blockly.Events.TrashcanOpen'); /** * Class for a trash can. - * @param {!WorkspaceSvg} workspace The workspace to sit in. - * @constructor * @implements {IAutoHideable} * @implements {IPositionable} * @extends {DeleteArea} - * @alias Blockly.Trashcan */ -const Trashcan = function(workspace) { - Trashcan.superClass_.constructor.call(this); +class Trashcan extends DeleteArea { /** - * The workspace the trashcan sits in. - * @type {!WorkspaceSvg} + * @param {!WorkspaceSvg} workspace The workspace to sit in. + * @alias Blockly.Trashcan + */ + constructor(workspace) { + super(); + /** + * The workspace the trashcan sits in. + * @type {!WorkspaceSvg} + * @private + */ + this.workspace_ = workspace; + + /** + * The unique id for this component that is used to register with the + * ComponentManager. + * @type {string} + */ + this.id = 'trashcan'; + + /** + * A list of JSON (stored as strings) representing blocks in the trashcan. + * @type {!Array} + * @private + */ + this.contents_ = []; + + /** + * The trashcan flyout. + * @type {IFlyout} + * @package + */ + this.flyout = null; + + if (this.workspace_.options.maxTrashcanContents <= 0) { + return; + } + + /** + * Current open/close state of the lid. + * @type {boolean} + */ + this.isLidOpen = false; + + /** + * The minimum openness of the lid. Used to indicate if the trashcan + * contains blocks. + * @type {number} + * @private + */ + this.minOpenness_ = 0; + + /** + * The SVG group containing the trash can. + * @type {SVGElement} + * @private + */ + this.svgGroup_ = null; + + /** + * The SVG image element of the trash can lid. + * @type {SVGElement} + * @private + */ + this.svgLid_ = null; + + /** + * Task ID of opening/closing animation. + * @type {number} + * @private + */ + this.lidTask_ = 0; + + /** + * Current state of lid opening (0.0 = closed, 1.0 = open). + * @type {number} + * @private + */ + this.lidOpen_ = 0; + + /** + * Left coordinate of the trash can. + * @type {number} + * @private + */ + this.left_ = 0; + + /** + * Top coordinate of the trash can. + * @type {number} + * @private + */ + this.top_ = 0; + + /** + * Whether this trash can has been initialized. + * @type {boolean} + * @private + */ + this.initialized_ = false; + + // Create flyout options. + const flyoutWorkspaceOptions = new Options( + /** @type {!BlocklyOptions} */ + ({ + 'scrollbars': true, + 'parentWorkspace': this.workspace_, + 'rtl': this.workspace_.RTL, + 'oneBasedIndex': this.workspace_.options.oneBasedIndex, + 'renderer': this.workspace_.options.renderer, + 'rendererOverrides': this.workspace_.options.rendererOverrides, + 'move': { + 'scrollbars': true, + }, + })); + // Create vertical or horizontal flyout. + if (this.workspace_.horizontalLayout) { + flyoutWorkspaceOptions.toolboxPosition = + this.workspace_.toolboxPosition === toolbox.Position.TOP ? + toolbox.Position.BOTTOM : + toolbox.Position.TOP; + const HorizontalFlyout = registry.getClassFromOptions( + registry.Type.FLYOUTS_HORIZONTAL_TOOLBOX, this.workspace_.options, + true); + this.flyout = new HorizontalFlyout(flyoutWorkspaceOptions); + } else { + flyoutWorkspaceOptions.toolboxPosition = + this.workspace_.toolboxPosition === toolbox.Position.RIGHT ? + toolbox.Position.LEFT : + toolbox.Position.RIGHT; + const VerticalFlyout = registry.getClassFromOptions( + registry.Type.FLYOUTS_VERTICAL_TOOLBOX, this.workspace_.options, + true); + this.flyout = new VerticalFlyout(flyoutWorkspaceOptions); + } + this.workspace_.addChangeListener(this.onDelete_.bind(this)); + } + + /** + * Create the trash can elements. + * @return {!SVGElement} The trash can's SVG group. + */ + createDom() { + /* Here's the markup that will be generated: + + + + + + + + + + + */ + this.svgGroup_ = + dom.createSvgElement(Svg.G, {'class': 'blocklyTrash'}, null); + let clip; + const rnd = String(Math.random()).substring(2); + clip = dom.createSvgElement( + Svg.CLIPPATH, {'id': 'blocklyTrashBodyClipPath' + rnd}, this.svgGroup_); + dom.createSvgElement( + Svg.RECT, {'width': WIDTH, 'height': BODY_HEIGHT, 'y': LID_HEIGHT}, + clip); + const body = dom.createSvgElement( + Svg.IMAGE, { + 'width': internalConstants.SPRITE.width, + 'x': -SPRITE_LEFT, + 'height': internalConstants.SPRITE.height, + 'y': -SPRITE_TOP, + 'clip-path': 'url(#blocklyTrashBodyClipPath' + rnd + ')', + }, + this.svgGroup_); + body.setAttributeNS( + dom.XLINK_NS, 'xlink:href', + this.workspace_.options.pathToMedia + internalConstants.SPRITE.url); + + clip = dom.createSvgElement( + Svg.CLIPPATH, {'id': 'blocklyTrashLidClipPath' + rnd}, this.svgGroup_); + dom.createSvgElement( + Svg.RECT, {'width': WIDTH, 'height': LID_HEIGHT}, clip); + this.svgLid_ = dom.createSvgElement( + Svg.IMAGE, { + 'width': internalConstants.SPRITE.width, + 'x': -SPRITE_LEFT, + 'height': internalConstants.SPRITE.height, + 'y': -SPRITE_TOP, + 'clip-path': 'url(#blocklyTrashLidClipPath' + rnd + ')', + }, + this.svgGroup_); + this.svgLid_.setAttributeNS( + dom.XLINK_NS, 'xlink:href', + this.workspace_.options.pathToMedia + internalConstants.SPRITE.url); + + // bindEventWithChecks_ quashes events too aggressively. See: + // https://groups.google.com/forum/#!topic/blockly/QF4yB9Wx00s + // Using bindEventWithChecks_ for blocking mousedown causes issue in mobile. + // See #4303 + browserEvents.bind( + this.svgGroup_, 'mousedown', this, this.blockMouseDownWhenOpenable_); + browserEvents.bind(this.svgGroup_, 'mouseup', this, this.click); + // Bind to body instead of this.svgGroup_ so that we don't get lid jitters + browserEvents.bind(body, 'mouseover', this, this.mouseOver_); + browserEvents.bind(body, 'mouseout', this, this.mouseOut_); + this.animateLid_(); + return this.svgGroup_; + } + + /** + * Initializes the trash can. + */ + init() { + if (this.workspace_.options.maxTrashcanContents > 0) { + dom.insertAfter( + this.flyout.createDom(Svg.SVG), this.workspace_.getParentSvg()); + this.flyout.init(this.workspace_); + } + this.workspace_.getComponentManager().addComponent({ + component: this, + weight: 1, + capabilities: [ + ComponentManager.Capability.AUTOHIDEABLE, + ComponentManager.Capability.DELETE_AREA, + ComponentManager.Capability.DRAG_TARGET, + ComponentManager.Capability.POSITIONABLE, + ], + }); + this.initialized_ = true; + this.setLidOpen(false); + } + + /** + * Dispose of this trash can. + * Unlink from all DOM elements to prevent memory leaks. + * @suppress {checkTypes} + */ + dispose() { + this.workspace_.getComponentManager().removeComponent('trashcan'); + if (this.svgGroup_) { + dom.removeNode(this.svgGroup_); + this.svgGroup_ = null; + } + this.svgLid_ = null; + this.workspace_ = null; + clearTimeout(this.lidTask_); + } + + /** + * Whether the trashcan has contents. + * @return {boolean} True if the trashcan has contents. * @private */ - this.workspace_ = workspace; + hasContents_() { + return !!this.contents_.length; + } /** - * The unique id for this component that is used to register with the - * ComponentManager. - * @type {string} + * Returns true if the trashcan contents-flyout is currently open. + * @return {boolean} True if the trashcan contents-flyout is currently open. */ - this.id = 'trashcan'; + contentsIsOpen() { + return !!this.flyout && this.flyout.isVisible(); + } /** - * A list of JSON (stored as strings) representing blocks in the trashcan. - * @type {!Array} - * @private + * Opens the trashcan flyout. */ - this.contents_ = []; + openFlyout() { + if (this.contentsIsOpen()) { + return; + } + const contents = this.contents_.map(function(string) { + return JSON.parse(string); + }); + this.flyout.show(contents); + this.fireUiEvent_(true); + } /** - * The trashcan flyout. - * @type {IFlyout} + * Closes the trashcan flyout. + */ + closeFlyout() { + if (!this.contentsIsOpen()) { + return; + } + this.flyout.hide(); + this.fireUiEvent_(false); + this.workspace_.recordDragTargets(); + } + + /** + * Hides the component. Called in WorkspaceSvg.hideChaff. + * @param {boolean} onlyClosePopups Whether only popups should be closed. + * Flyouts should not be closed if this is true. + */ + autoHide(onlyClosePopups) { + // For now the trashcan flyout always autocloses because it overlays the + // trashcan UI (no trashcan to click to close it). + if (!onlyClosePopups && this.flyout) { + this.closeFlyout(); + } + } + + /** + * Empties the trashcan's contents. If the contents-flyout is currently open + * it will be closed. + */ + emptyContents() { + if (!this.hasContents_()) { + return; + } + this.contents_.length = 0; + this.setMinOpenness_(0); + this.closeFlyout(); + } + + /** + * Positions the trashcan. + * It is positioned in the opposite corner to the corner the + * categories/toolbox starts at. + * @param {!MetricsManager.UiMetrics} metrics The workspace metrics. + * @param {!Array} savedPositions List of rectangles that + * are already on the workspace. + */ + position(metrics, savedPositions) { + // Not yet initialized. + if (!this.initialized_) { + return; + } + + const cornerPosition = + uiPosition.getCornerOppositeToolbox(this.workspace_, metrics); + + const height = BODY_HEIGHT + LID_HEIGHT; + const startRect = uiPosition.getStartPositionRect( + cornerPosition, new Size(WIDTH, height), MARGIN_HORIZONTAL, + MARGIN_VERTICAL, metrics, this.workspace_); + + const verticalPosition = cornerPosition.vertical; + const bumpDirection = verticalPosition === uiPosition.verticalPosition.TOP ? + uiPosition.bumpDirection.DOWN : + uiPosition.bumpDirection.UP; + const positionRect = uiPosition.bumpPositionRect( + startRect, MARGIN_VERTICAL, bumpDirection, savedPositions); + + this.top_ = positionRect.top; + this.left_ = positionRect.left; + this.svgGroup_.setAttribute( + 'transform', 'translate(' + this.left_ + ',' + this.top_ + ')'); + } + + /** + * Returns the bounding rectangle of the UI element in pixel units relative to + * the Blockly injection div. + * @return {?Rect} The UI elements's bounding box. Null if + * bounding box should be ignored by other UI elements. + */ + getBoundingRectangle() { + const bottom = this.top_ + BODY_HEIGHT + LID_HEIGHT; + const right = this.left_ + WIDTH; + return new Rect(this.top_, bottom, this.left_, right); + } + + /** + * Returns the bounding rectangle of the drag target area in pixel units + * relative to viewport. + * @return {?Rect} The component's bounding box. Null if drag + * target area should be ignored. + */ + getClientRect() { + if (!this.svgGroup_) { + return null; + } + + const trashRect = this.svgGroup_.getBoundingClientRect(); + const top = trashRect.top + SPRITE_TOP - MARGIN_HOTSPOT; + const bottom = top + LID_HEIGHT + BODY_HEIGHT + 2 * MARGIN_HOTSPOT; + const left = trashRect.left + SPRITE_LEFT - MARGIN_HOTSPOT; + const right = left + WIDTH + 2 * MARGIN_HOTSPOT; + return new Rect(top, bottom, left, right); + } + + /** + * Handles when a cursor with a block or bubble is dragged over this drag + * target. + * @param {!IDraggable} _dragElement The block or bubble currently being + * dragged. + * @override + */ + onDragOver(_dragElement) { + this.setLidOpen(this.wouldDelete_); + } + + /** + * Handles when a cursor with a block or bubble exits this drag target. + * @param {!IDraggable} _dragElement The block or bubble currently being + * dragged. + * @override + */ + onDragExit(_dragElement) { + this.setLidOpen(false); + } + + /** + * Handles when a block or bubble is dropped on this component. + * Should not handle delete here. + * @param {!IDraggable} _dragElement The block or bubble currently being + * dragged. + * @override + */ + onDrop(_dragElement) { + setTimeout(this.setLidOpen.bind(this, false), 100); + } + + /** + * Flip the lid open or shut. + * @param {boolean} state True if open. * @package */ - this.flyout = null; - - if (this.workspace_.options.maxTrashcanContents <= 0) { - return; + setLidOpen(state) { + if (this.isLidOpen === state) { + return; + } + clearTimeout(this.lidTask_); + this.isLidOpen = state; + this.animateLid_(); } /** - * Current open/close state of the lid. - * @type {boolean} - */ - this.isLidOpen = false; - - /** - * The minimum openness of the lid. Used to indicate if the trashcan contains - * blocks. - * @type {number} + * Rotate the lid open or closed by one step. Then wait and recurse. * @private */ - this.minOpenness_ = 0; + animateLid_() { + const frames = ANIMATION_FRAMES; - /** - * The SVG group containing the trash can. - * @type {SVGElement} - * @private - */ - this.svgGroup_ = null; + const delta = 1 / (frames + 1); + this.lidOpen_ += this.isLidOpen ? delta : -delta; + this.lidOpen_ = Math.min(Math.max(this.lidOpen_, this.minOpenness_), 1); - /** - * The SVG image element of the trash can lid. - * @type {SVGElement} - * @private - */ - this.svgLid_ = null; + this.setLidAngle_(this.lidOpen_ * MAX_LID_ANGLE); - /** - * Task ID of opening/closing animation. - * @type {number} - * @private - */ - this.lidTask_ = 0; + // Linear interpolation between min and max. + const opacity = OPACITY_MIN + this.lidOpen_ * (OPACITY_MAX - OPACITY_MIN); + this.svgGroup_.style.opacity = opacity; - /** - * Current state of lid opening (0.0 = closed, 1.0 = open). - * @type {number} - * @private - */ - this.lidOpen_ = 0; - - /** - * Left coordinate of the trash can. - * @type {number} - * @private - */ - this.left_ = 0; - - /** - * Top coordinate of the trash can. - * @type {number} - * @private - */ - this.top_ = 0; - - /** - * Whether this trash can has been initialized. - * @type {boolean} - * @private - */ - this.initialized_ = false; - - // Create flyout options. - const flyoutWorkspaceOptions = new Options( - /** @type {!BlocklyOptions} */ - ({ - 'scrollbars': true, - 'parentWorkspace': this.workspace_, - 'rtl': this.workspace_.RTL, - 'oneBasedIndex': this.workspace_.options.oneBasedIndex, - 'renderer': this.workspace_.options.renderer, - 'rendererOverrides': this.workspace_.options.rendererOverrides, - 'move': { - 'scrollbars': true, - }, - })); - // Create vertical or horizontal flyout. - if (this.workspace_.horizontalLayout) { - flyoutWorkspaceOptions.toolboxPosition = - this.workspace_.toolboxPosition === toolbox.Position.TOP ? - toolbox.Position.BOTTOM : - toolbox.Position.TOP; - const HorizontalFlyout = registry.getClassFromOptions( - registry.Type.FLYOUTS_HORIZONTAL_TOOLBOX, this.workspace_.options, - true); - this.flyout = new HorizontalFlyout(flyoutWorkspaceOptions); - } else { - flyoutWorkspaceOptions.toolboxPosition = - this.workspace_.toolboxPosition === toolbox.Position.RIGHT ? - toolbox.Position.LEFT : - toolbox.Position.RIGHT; - const VerticalFlyout = registry.getClassFromOptions( - registry.Type.FLYOUTS_VERTICAL_TOOLBOX, this.workspace_.options, true); - this.flyout = new VerticalFlyout(flyoutWorkspaceOptions); + if (this.lidOpen_ > this.minOpenness_ && this.lidOpen_ < 1) { + this.lidTask_ = + setTimeout(this.animateLid_.bind(this), ANIMATION_LENGTH / frames); + } } - this.workspace_.addChangeListener(this.onDelete_.bind(this)); -}; -object.inherits(Trashcan, DeleteArea); + + /** + * Set the angle of the trashcan's lid. + * @param {number} lidAngle The angle at which to set the lid. + * @private + */ + setLidAngle_(lidAngle) { + const openAtRight = + this.workspace_.toolboxPosition === toolbox.Position.RIGHT || + (this.workspace_.horizontalLayout && this.workspace_.RTL); + this.svgLid_.setAttribute( + 'transform', + 'rotate(' + (openAtRight ? -lidAngle : lidAngle) + ',' + + (openAtRight ? 4 : WIDTH - 4) + ',' + (LID_HEIGHT - 2) + ')'); + } + + /** + * Sets the minimum openness of the trashcan lid. If the lid is currently + * closed, this will update lid's position. + * @param {number} newMin The new minimum openness of the lid. Should be + * between 0 and 1. + * @private + */ + setMinOpenness_(newMin) { + this.minOpenness_ = newMin; + if (!this.isLidOpen) { + this.setLidAngle_(newMin * MAX_LID_ANGLE); + } + } + + /** + * Flip the lid shut. + * Called externally after a drag. + */ + closeLid() { + this.setLidOpen(false); + } + + /** + * Inspect the contents of the trash. + */ + click() { + if (!this.hasContents_()) { + return; + } + this.openFlyout(); + } + + /** + * Fires a UI event for trashcan flyout open or close. + * @param {boolean} trashcanOpen Whether the flyout is opening. + * @private + */ + fireUiEvent_(trashcanOpen) { + const uiEvent = new (eventUtils.get(eventUtils.TRASHCAN_OPEN))( + trashcanOpen, this.workspace_.id); + eventUtils.fire(uiEvent); + } + + /** + * Prevents a workspace scroll and click event if the trashcan has blocks. + * @param {!Event} e A mouse down event. + * @private + */ + blockMouseDownWhenOpenable_(e) { + if (!this.contentsIsOpen() && this.hasContents_()) { + e.stopPropagation(); // Don't start a workspace scroll. + } + } + + /** + * Indicate that the trashcan can be clicked (by opening it) if it has blocks. + * @private + */ + mouseOver_() { + if (this.hasContents_()) { + this.setLidOpen(true); + } + } + + /** + * Close the lid of the trashcan if it was open (Vis. it was indicating it had + * blocks). + * @private + */ + mouseOut_() { + // No need to do a .hasBlocks check here because if it doesn't the trashcan + // won't be open in the first place, and setOpen won't run. + this.setLidOpen(false); + } + + /** + * Handle a BLOCK_DELETE event. Adds deleted blocks oldXml to the content + * array. + * @param {!Abstract} event Workspace event. + * @private + */ + onDelete_(event) { + if (this.workspace_.options.maxTrashcanContents <= 0) { + return; + } + if (event.type === eventUtils.BLOCK_DELETE && !event.wasShadow) { + const cleanedJson = this.cleanBlockJson_(event.oldJson); + if (this.contents_.indexOf(cleanedJson) !== -1) { + return; + } + this.contents_.unshift(cleanedJson); + while (this.contents_.length > + this.workspace_.options.maxTrashcanContents) { + this.contents_.pop(); + } + + this.setMinOpenness_(HAS_BLOCKS_LID_ANGLE); + } + } + + /** + * Converts JSON representing a block into text that can be stored in the + * content array. + * @param {!blocks.State} json A JSON representation of + * a block's state. + * @return {string} Text representing the JSON, cleaned of all unnecessary + * attributes. + * @private + */ + cleanBlockJson_(json) { + // Create a deep copy. + json = /** @type {!blocks.State} */ (JSON.parse(JSON.stringify(json))); + + /** + * Reshape JSON into a nicer format. + * @param {!blocks.State} json The JSON to clean. + */ + function cleanRec(json) { + if (!json) { + return; + } + + delete json['id']; + delete json['x']; + delete json['y']; + delete json['enabled']; + + if (json['icons'] && json['icons']['comment']) { + const comment = json['icons']['comment']; + delete comment['height']; + delete comment['width']; + delete comment['pinned']; + } + + const inputs = json['inputs']; + for (const name in inputs) { + const input = inputs[name]; + cleanRec(input['block']); + cleanRec(input['shadow']); + } + if (json['next']) { + const next = json['next']; + cleanRec(next['block']); + cleanRec(next['shadow']); + } + } + + cleanRec(json); + json['kind'] = 'BLOCK'; + return JSON.stringify(json); + } +} /** * Width of both the trash can and lid images. @@ -266,482 +750,4 @@ const OPACITY_MAX = 0.8; */ const MAX_LID_ANGLE = 45; -/** - * Create the trash can elements. - * @return {!SVGElement} The trash can's SVG group. - */ -Trashcan.prototype.createDom = function() { - /* Here's the markup that will be generated: - - - - - - - - - - - */ - this.svgGroup_ = dom.createSvgElement(Svg.G, {'class': 'blocklyTrash'}, null); - let clip; - const rnd = String(Math.random()).substring(2); - clip = dom.createSvgElement( - Svg.CLIPPATH, {'id': 'blocklyTrashBodyClipPath' + rnd}, this.svgGroup_); - dom.createSvgElement( - Svg.RECT, {'width': WIDTH, 'height': BODY_HEIGHT, 'y': LID_HEIGHT}, clip); - const body = dom.createSvgElement( - Svg.IMAGE, { - 'width': internalConstants.SPRITE.width, - 'x': -SPRITE_LEFT, - 'height': internalConstants.SPRITE.height, - 'y': -SPRITE_TOP, - 'clip-path': 'url(#blocklyTrashBodyClipPath' + rnd + ')', - }, - this.svgGroup_); - body.setAttributeNS( - dom.XLINK_NS, 'xlink:href', - this.workspace_.options.pathToMedia + internalConstants.SPRITE.url); - - clip = dom.createSvgElement( - Svg.CLIPPATH, {'id': 'blocklyTrashLidClipPath' + rnd}, this.svgGroup_); - dom.createSvgElement(Svg.RECT, {'width': WIDTH, 'height': LID_HEIGHT}, clip); - this.svgLid_ = dom.createSvgElement( - Svg.IMAGE, { - 'width': internalConstants.SPRITE.width, - 'x': -SPRITE_LEFT, - 'height': internalConstants.SPRITE.height, - 'y': -SPRITE_TOP, - 'clip-path': 'url(#blocklyTrashLidClipPath' + rnd + ')', - }, - this.svgGroup_); - this.svgLid_.setAttributeNS( - dom.XLINK_NS, 'xlink:href', - this.workspace_.options.pathToMedia + internalConstants.SPRITE.url); - - // bindEventWithChecks_ quashes events too aggressively. See: - // https://groups.google.com/forum/#!topic/blockly/QF4yB9Wx00s - // Using bindEventWithChecks_ for blocking mousedown causes issue in mobile. - // See #4303 - browserEvents.bind( - this.svgGroup_, 'mousedown', this, this.blockMouseDownWhenOpenable_); - browserEvents.bind(this.svgGroup_, 'mouseup', this, this.click); - // Bind to body instead of this.svgGroup_ so that we don't get lid jitters - browserEvents.bind(body, 'mouseover', this, this.mouseOver_); - browserEvents.bind(body, 'mouseout', this, this.mouseOut_); - this.animateLid_(); - return this.svgGroup_; -}; - -/** - * Initializes the trash can. - */ -Trashcan.prototype.init = function() { - if (this.workspace_.options.maxTrashcanContents > 0) { - dom.insertAfter( - this.flyout.createDom(Svg.SVG), this.workspace_.getParentSvg()); - this.flyout.init(this.workspace_); - } - this.workspace_.getComponentManager().addComponent({ - component: this, - weight: 1, - capabilities: [ - ComponentManager.Capability.AUTOHIDEABLE, - ComponentManager.Capability.DELETE_AREA, - ComponentManager.Capability.DRAG_TARGET, - ComponentManager.Capability.POSITIONABLE, - ], - }); - this.initialized_ = true; - this.setLidOpen(false); -}; - -/** - * Dispose of this trash can. - * Unlink from all DOM elements to prevent memory leaks. - * @suppress {checkTypes} - */ -Trashcan.prototype.dispose = function() { - this.workspace_.getComponentManager().removeComponent('trashcan'); - if (this.svgGroup_) { - dom.removeNode(this.svgGroup_); - this.svgGroup_ = null; - } - this.svgLid_ = null; - this.workspace_ = null; - clearTimeout(this.lidTask_); -}; - -/** - * Whether the trashcan has contents. - * @return {boolean} True if the trashcan has contents. - * @private - */ -Trashcan.prototype.hasContents_ = function() { - return !!this.contents_.length; -}; - -/** - * Returns true if the trashcan contents-flyout is currently open. - * @return {boolean} True if the trashcan contents-flyout is currently open. - */ -Trashcan.prototype.contentsIsOpen = function() { - return !!this.flyout && this.flyout.isVisible(); -}; - -/** - * Opens the trashcan flyout. - */ -Trashcan.prototype.openFlyout = function() { - if (this.contentsIsOpen()) { - return; - } - const contents = this.contents_.map(function(string) { - return JSON.parse(string); - }); - this.flyout.show(contents); - this.fireUiEvent_(true); -}; - -/** - * Closes the trashcan flyout. - */ -Trashcan.prototype.closeFlyout = function() { - if (!this.contentsIsOpen()) { - return; - } - this.flyout.hide(); - this.fireUiEvent_(false); - this.workspace_.recordDragTargets(); -}; - -/** - * Hides the component. Called in WorkspaceSvg.hideChaff. - * @param {boolean} onlyClosePopups Whether only popups should be closed. - * Flyouts should not be closed if this is true. - */ -Trashcan.prototype.autoHide = function(onlyClosePopups) { - // For now the trashcan flyout always autocloses because it overlays the - // trashcan UI (no trashcan to click to close it). - if (!onlyClosePopups && this.flyout) { - this.closeFlyout(); - } -}; - -/** - * Empties the trashcan's contents. If the contents-flyout is currently open - * it will be closed. - */ -Trashcan.prototype.emptyContents = function() { - if (!this.hasContents_()) { - return; - } - this.contents_.length = 0; - this.setMinOpenness_(0); - this.closeFlyout(); -}; - -/** - * Positions the trashcan. - * It is positioned in the opposite corner to the corner the - * categories/toolbox starts at. - * @param {!MetricsManager.UiMetrics} metrics The workspace metrics. - * @param {!Array} savedPositions List of rectangles that - * are already on the workspace. - */ -Trashcan.prototype.position = function(metrics, savedPositions) { - // Not yet initialized. - if (!this.initialized_) { - return; - } - - const cornerPosition = - uiPosition.getCornerOppositeToolbox(this.workspace_, metrics); - - const height = BODY_HEIGHT + LID_HEIGHT; - const startRect = uiPosition.getStartPositionRect( - cornerPosition, new Size(WIDTH, height), MARGIN_HORIZONTAL, - MARGIN_VERTICAL, metrics, this.workspace_); - - const verticalPosition = cornerPosition.vertical; - const bumpDirection = verticalPosition === uiPosition.verticalPosition.TOP ? - uiPosition.bumpDirection.DOWN : - uiPosition.bumpDirection.UP; - const positionRect = uiPosition.bumpPositionRect( - startRect, MARGIN_VERTICAL, bumpDirection, savedPositions); - - this.top_ = positionRect.top; - this.left_ = positionRect.left; - this.svgGroup_.setAttribute( - 'transform', 'translate(' + this.left_ + ',' + this.top_ + ')'); -}; - -/** - * Returns the bounding rectangle of the UI element in pixel units relative to - * the Blockly injection div. - * @return {?Rect} The UI elements's bounding box. Null if - * bounding box should be ignored by other UI elements. - */ -Trashcan.prototype.getBoundingRectangle = function() { - const bottom = this.top_ + BODY_HEIGHT + LID_HEIGHT; - const right = this.left_ + WIDTH; - return new Rect(this.top_, bottom, this.left_, right); -}; - -/** - * Returns the bounding rectangle of the drag target area in pixel units - * relative to viewport. - * @return {?Rect} The component's bounding box. Null if drag - * target area should be ignored. - */ -Trashcan.prototype.getClientRect = function() { - if (!this.svgGroup_) { - return null; - } - - const trashRect = this.svgGroup_.getBoundingClientRect(); - const top = trashRect.top + SPRITE_TOP - MARGIN_HOTSPOT; - const bottom = top + LID_HEIGHT + BODY_HEIGHT + 2 * MARGIN_HOTSPOT; - const left = trashRect.left + SPRITE_LEFT - MARGIN_HOTSPOT; - const right = left + WIDTH + 2 * MARGIN_HOTSPOT; - return new Rect(top, bottom, left, right); -}; - -/** - * Handles when a cursor with a block or bubble is dragged over this drag - * target. - * @param {!IDraggable} _dragElement The block or bubble currently being - * dragged. - * @override - */ -Trashcan.prototype.onDragOver = function(_dragElement) { - this.setLidOpen(this.wouldDelete_); -}; - -/** - * Handles when a cursor with a block or bubble exits this drag target. - * @param {!IDraggable} _dragElement The block or bubble currently being - * dragged. - * @override - */ -Trashcan.prototype.onDragExit = function(_dragElement) { - this.setLidOpen(false); -}; - -/** - * Handles when a block or bubble is dropped on this component. - * Should not handle delete here. - * @param {!IDraggable} _dragElement The block or bubble currently being - * dragged. - * @override - */ -Trashcan.prototype.onDrop = function(_dragElement) { - setTimeout(this.setLidOpen.bind(this, false), 100); -}; - -/** - * Flip the lid open or shut. - * @param {boolean} state True if open. - * @package - */ -Trashcan.prototype.setLidOpen = function(state) { - if (this.isLidOpen === state) { - return; - } - clearTimeout(this.lidTask_); - this.isLidOpen = state; - this.animateLid_(); -}; - -/** - * Rotate the lid open or closed by one step. Then wait and recurse. - * @private - */ -Trashcan.prototype.animateLid_ = function() { - const frames = ANIMATION_FRAMES; - - const delta = 1 / (frames + 1); - this.lidOpen_ += this.isLidOpen ? delta : -delta; - this.lidOpen_ = Math.min(Math.max(this.lidOpen_, this.minOpenness_), 1); - - this.setLidAngle_(this.lidOpen_ * MAX_LID_ANGLE); - - // Linear interpolation between min and max. - const opacity = OPACITY_MIN + this.lidOpen_ * (OPACITY_MAX - OPACITY_MIN); - this.svgGroup_.style.opacity = opacity; - - if (this.lidOpen_ > this.minOpenness_ && this.lidOpen_ < 1) { - this.lidTask_ = - setTimeout(this.animateLid_.bind(this), ANIMATION_LENGTH / frames); - } -}; - -/** - * Set the angle of the trashcan's lid. - * @param {number} lidAngle The angle at which to set the lid. - * @private - */ -Trashcan.prototype.setLidAngle_ = function(lidAngle) { - const openAtRight = - this.workspace_.toolboxPosition === toolbox.Position.RIGHT || - (this.workspace_.horizontalLayout && this.workspace_.RTL); - this.svgLid_.setAttribute( - 'transform', - 'rotate(' + (openAtRight ? -lidAngle : lidAngle) + ',' + - (openAtRight ? 4 : WIDTH - 4) + ',' + (LID_HEIGHT - 2) + ')'); -}; - -/** - * Sets the minimum openness of the trashcan lid. If the lid is currently - * closed, this will update lid's position. - * @param {number} newMin The new minimum openness of the lid. Should be between - * 0 and 1. - * @private - */ -Trashcan.prototype.setMinOpenness_ = function(newMin) { - this.minOpenness_ = newMin; - if (!this.isLidOpen) { - this.setLidAngle_(newMin * MAX_LID_ANGLE); - } -}; - -/** - * Flip the lid shut. - * Called externally after a drag. - */ -Trashcan.prototype.closeLid = function() { - this.setLidOpen(false); -}; - -/** - * Inspect the contents of the trash. - */ -Trashcan.prototype.click = function() { - if (!this.hasContents_()) { - return; - } - this.openFlyout(); -}; - -/** - * Fires a UI event for trashcan flyout open or close. - * @param {boolean} trashcanOpen Whether the flyout is opening. - * @private - */ -Trashcan.prototype.fireUiEvent_ = function(trashcanOpen) { - const uiEvent = new (eventUtils.get(eventUtils.TRASHCAN_OPEN))( - trashcanOpen, this.workspace_.id); - eventUtils.fire(uiEvent); -}; - -/** - * Prevents a workspace scroll and click event if the trashcan has blocks. - * @param {!Event} e A mouse down event. - * @private - */ -Trashcan.prototype.blockMouseDownWhenOpenable_ = function(e) { - if (!this.contentsIsOpen() && this.hasContents_()) { - e.stopPropagation(); // Don't start a workspace scroll. - } -}; - -/** - * Indicate that the trashcan can be clicked (by opening it) if it has blocks. - * @private - */ -Trashcan.prototype.mouseOver_ = function() { - if (this.hasContents_()) { - this.setLidOpen(true); - } -}; - -/** - * Close the lid of the trashcan if it was open (Vis. it was indicating it had - * blocks). - * @private - */ -Trashcan.prototype.mouseOut_ = function() { - // No need to do a .hasBlocks check here because if it doesn't the trashcan - // won't be open in the first place, and setOpen won't run. - this.setLidOpen(false); -}; - -/** - * Handle a BLOCK_DELETE event. Adds deleted blocks oldXml to the content array. - * @param {!Abstract} event Workspace event. - * @private - */ -Trashcan.prototype.onDelete_ = function(event) { - if (this.workspace_.options.maxTrashcanContents <= 0) { - return; - } - if (event.type === eventUtils.BLOCK_DELETE && !event.wasShadow) { - const cleanedJson = this.cleanBlockJson_(event.oldJson); - if (this.contents_.indexOf(cleanedJson) !== -1) { - return; - } - this.contents_.unshift(cleanedJson); - while (this.contents_.length > - this.workspace_.options.maxTrashcanContents) { - this.contents_.pop(); - } - - this.setMinOpenness_(HAS_BLOCKS_LID_ANGLE); - } -}; - -/** - * Converts JSON representing a block into text that can be stored in the - * content array. - * @param {!blocks.State} json A JSON representation of - * a block's state. - * @return {string} Text representing the JSON, cleaned of all unnecessary - * attributes. - * @private - */ -Trashcan.prototype.cleanBlockJson_ = function(json) { - // Create a deep copy. - json = /** @type {!blocks.State} */ (JSON.parse(JSON.stringify(json))); - - /** - * Reshape JSON into a nicer format. - * @param {!blocks.State} json The JSON to clean. - */ - function cleanRec(json) { - if (!json) { - return; - } - - delete json['id']; - delete json['x']; - delete json['y']; - delete json['enabled']; - - if (json['icons'] && json['icons']['comment']) { - const comment = json['icons']['comment']; - delete comment['height']; - delete comment['width']; - delete comment['pinned']; - } - - const inputs = json['inputs']; - for (const name in inputs) { - const input = inputs[name]; - cleanRec(input['block']); - cleanRec(input['shadow']); - } - if (json['next']) { - const next = json['next']; - cleanRec(next['block']); - cleanRec(next['shadow']); - } - } - - cleanRec(json); - json['kind'] = 'BLOCK'; - return JSON.stringify(json); -}; - exports.Trashcan = Trashcan; diff --git a/tests/deps.js b/tests/deps.js index 4d422f483..1946968c4 100644 --- a/tests/deps.js +++ b/tests/deps.js @@ -16,7 +16,7 @@ goog.addDependency('../../core/block_svg.js', ['Blockly.BlockSvg'], ['Blockly.AS goog.addDependency('../../core/blockly.js', ['Blockly'], ['Blockly.ASTNode', 'Blockly.BasicCursor', 'Blockly.Block', 'Blockly.BlockDragSurfaceSvg', 'Blockly.BlockDragger', 'Blockly.BlockSvg', 'Blockly.BlocklyOptions', 'Blockly.Bubble', 'Blockly.BubbleDragger', 'Blockly.CollapsibleToolboxCategory', 'Blockly.Comment', 'Blockly.ComponentManager', 'Blockly.Connection', 'Blockly.ConnectionChecker', 'Blockly.ConnectionDB', 'Blockly.ConnectionType', 'Blockly.ContextMenu', 'Blockly.ContextMenuItems', 'Blockly.ContextMenuRegistry', 'Blockly.Css', 'Blockly.Cursor', 'Blockly.DeleteArea', 'Blockly.DragTarget', 'Blockly.DropDownDiv', 'Blockly.Events', 'Blockly.Events.BlockCreate', 'Blockly.Events.FinishedLoading', 'Blockly.Events.Ui', 'Blockly.Events.UiBase', 'Blockly.Events.VarCreate', 'Blockly.Extensions', 'Blockly.Field', 'Blockly.FieldAngle', 'Blockly.FieldCheckbox', 'Blockly.FieldColour', 'Blockly.FieldDropdown', 'Blockly.FieldImage', 'Blockly.FieldLabel', 'Blockly.FieldLabelSerializable', 'Blockly.FieldMultilineInput', 'Blockly.FieldNumber', 'Blockly.FieldTextInput', 'Blockly.FieldVariable', 'Blockly.Flyout', 'Blockly.FlyoutButton', 'Blockly.FlyoutMetricsManager', 'Blockly.Generator', 'Blockly.Gesture', 'Blockly.Grid', 'Blockly.HorizontalFlyout', 'Blockly.IASTNodeLocation', 'Blockly.IASTNodeLocationSvg', 'Blockly.IASTNodeLocationWithBlock', 'Blockly.IAutoHideable', 'Blockly.IBlockDragger', 'Blockly.IBoundedElement', 'Blockly.IBubble', 'Blockly.ICollapsibleToolboxItem', 'Blockly.IComponent', 'Blockly.IConnectionChecker', 'Blockly.IContextMenu', 'Blockly.ICopyable', 'Blockly.IDeletable', 'Blockly.IDeleteArea', 'Blockly.IDragTarget', 'Blockly.IDraggable', 'Blockly.IFlyout', 'Blockly.IKeyboardAccessible', 'Blockly.IMetricsManager', 'Blockly.IMovable', 'Blockly.IPositionable', 'Blockly.IRegistrable', 'Blockly.IRegistrableField', 'Blockly.ISelectable', 'Blockly.ISelectableToolboxItem', 'Blockly.IStyleable', 'Blockly.IToolbox', 'Blockly.IToolboxItem', 'Blockly.Icon', 'Blockly.Input', 'Blockly.InsertionMarkerManager', 'Blockly.Marker', 'Blockly.MarkerManager', 'Blockly.Menu', 'Blockly.MenuItem', 'Blockly.MetricsManager', 'Blockly.Msg', 'Blockly.Mutator', 'Blockly.Names', 'Blockly.Options', 'Blockly.Procedures', 'Blockly.RenderedConnection', 'Blockly.Scrollbar', 'Blockly.ScrollbarPair', 'Blockly.ShortcutItems', 'Blockly.ShortcutRegistry', 'Blockly.TabNavigateCursor', 'Blockly.Theme', 'Blockly.ThemeManager', 'Blockly.Themes', 'Blockly.Toolbox', 'Blockly.ToolboxCategory', 'Blockly.ToolboxItem', 'Blockly.ToolboxSeparator', 'Blockly.Tooltip', 'Blockly.Touch', 'Blockly.TouchGesture', 'Blockly.Trashcan', 'Blockly.VariableMap', 'Blockly.VariableModel', 'Blockly.Variables', 'Blockly.VariablesDynamic', 'Blockly.VerticalFlyout', 'Blockly.Warning', 'Blockly.WidgetDiv', 'Blockly.Workspace', 'Blockly.WorkspaceAudio', 'Blockly.WorkspaceComment', 'Blockly.WorkspaceCommentSvg', 'Blockly.WorkspaceDragSurfaceSvg', 'Blockly.WorkspaceDragger', 'Blockly.WorkspaceSvg', 'Blockly.Xml', 'Blockly.ZoomControls', 'Blockly.blockAnimations', 'Blockly.blockRendering', 'Blockly.blocks', 'Blockly.browserEvents', 'Blockly.bumpObjects', 'Blockly.clipboard', 'Blockly.common', 'Blockly.constants', 'Blockly.dialog', 'Blockly.fieldRegistry', 'Blockly.geras', 'Blockly.inject', 'Blockly.inputTypes', 'Blockly.internalConstants', 'Blockly.minimalist', 'Blockly.registry', 'Blockly.serialization.ISerializer', 'Blockly.serialization.blocks', 'Blockly.serialization.exceptions', 'Blockly.serialization.priorities', 'Blockly.serialization.registry', 'Blockly.serialization.variables', 'Blockly.serialization.workspaces', 'Blockly.thrasos', 'Blockly.uiPosition', 'Blockly.utils', 'Blockly.utils.colour', 'Blockly.utils.deprecation', 'Blockly.utils.global', 'Blockly.utils.svgMath', 'Blockly.utils.toolbox', 'Blockly.zelos'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/blockly_options.js', ['Blockly.BlocklyOptions'], [], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/blocks.js', ['Blockly.blocks'], [], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/browser_events.js', ['Blockly.browserEvents'], ['Blockly.Touch', 'Blockly.internalConstants', 'Blockly.utils.global', 'Blockly.utils.userAgent'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/browser_events.js', ['Blockly.browserEvents'], ['Blockly.Touch', 'Blockly.utils.global', 'Blockly.utils.userAgent'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/bubble.js', ['Blockly.Bubble'], ['Blockly.IBubble', 'Blockly.Scrollbar', 'Blockly.Touch', 'Blockly.Workspace', 'Blockly.browserEvents', 'Blockly.utils.Coordinate', 'Blockly.utils.Size', 'Blockly.utils.Svg', 'Blockly.utils.dom', 'Blockly.utils.math', 'Blockly.utils.userAgent'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/bubble_dragger.js', ['Blockly.BubbleDragger'], ['Blockly.Bubble', 'Blockly.ComponentManager', 'Blockly.Events.CommentMove', 'Blockly.Events.utils', 'Blockly.constants', 'Blockly.utils.Coordinate', 'Blockly.utils.svgMath'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/bump_objects.js', ['Blockly.bumpObjects'], ['Blockly.Events.utils', 'Blockly.utils.math'], {'lang': 'es6', 'module': 'goog'}); @@ -80,11 +80,11 @@ goog.addDependency('../../core/field_number.js', ['Blockly.FieldNumber'], ['Bloc goog.addDependency('../../core/field_registry.js', ['Blockly.fieldRegistry'], ['Blockly.registry'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/field_textinput.js', ['Blockly.FieldTextInput'], ['Blockly.DropDownDiv', 'Blockly.Events.BlockChange', 'Blockly.Events.utils', 'Blockly.Field', 'Blockly.Msg', 'Blockly.WidgetDiv', 'Blockly.browserEvents', 'Blockly.dialog', 'Blockly.fieldRegistry', 'Blockly.utils.Coordinate', 'Blockly.utils.KeyCodes', 'Blockly.utils.aria', 'Blockly.utils.dom', 'Blockly.utils.object', 'Blockly.utils.parsing', 'Blockly.utils.userAgent'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/field_variable.js', ['Blockly.FieldVariable'], ['Blockly.Events.BlockChange', 'Blockly.FieldDropdown', 'Blockly.Msg', 'Blockly.VariableModel', 'Blockly.Variables', 'Blockly.Xml', 'Blockly.fieldRegistry', 'Blockly.internalConstants', 'Blockly.utils.Size', 'Blockly.utils.object', 'Blockly.utils.parsing'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/flyout_base.js', ['Blockly.Flyout'], ['Blockly.ComponentManager', 'Blockly.DeleteArea', 'Blockly.Events.BlockCreate', 'Blockly.Events.VarCreate', 'Blockly.Events.utils', 'Blockly.FlyoutMetricsManager', 'Blockly.Gesture', 'Blockly.IFlyout', 'Blockly.ScrollbarPair', 'Blockly.Tooltip', 'Blockly.Touch', 'Blockly.Variables', 'Blockly.WorkspaceSvg', 'Blockly.Xml', 'Blockly.blockRendering', 'Blockly.browserEvents', 'Blockly.common', 'Blockly.serialization.blocks', 'Blockly.utils.Coordinate', 'Blockly.utils.Rect', 'Blockly.utils.Svg', 'Blockly.utils.dom', 'Blockly.utils.idGenerator', 'Blockly.utils.object', 'Blockly.utils.toolbox'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/flyout_base.js', ['Blockly.Flyout'], ['Blockly.ComponentManager', 'Blockly.DeleteArea', 'Blockly.Events.BlockCreate', 'Blockly.Events.VarCreate', 'Blockly.Events.utils', 'Blockly.FlyoutMetricsManager', 'Blockly.Gesture', 'Blockly.IFlyout', 'Blockly.ScrollbarPair', 'Blockly.Tooltip', 'Blockly.Touch', 'Blockly.Variables', 'Blockly.WorkspaceSvg', 'Blockly.Xml', 'Blockly.blockRendering', 'Blockly.browserEvents', 'Blockly.common', 'Blockly.serialization.blocks', 'Blockly.utils.Coordinate', 'Blockly.utils.Rect', 'Blockly.utils.Svg', 'Blockly.utils.dom', 'Blockly.utils.idGenerator', 'Blockly.utils.toolbox'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/flyout_button.js', ['Blockly.FlyoutButton'], ['Blockly.Css', 'Blockly.browserEvents', 'Blockly.utils.Coordinate', 'Blockly.utils.Svg', 'Blockly.utils.dom', 'Blockly.utils.parsing', 'Blockly.utils.style'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/flyout_horizontal.js', ['Blockly.HorizontalFlyout'], ['Blockly.DropDownDiv', 'Blockly.Flyout', 'Blockly.Scrollbar', 'Blockly.WidgetDiv', 'Blockly.browserEvents', 'Blockly.registry', 'Blockly.utils.Rect', 'Blockly.utils.object', 'Blockly.utils.toolbox'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/flyout_metrics_manager.js', ['Blockly.FlyoutMetricsManager'], ['Blockly.MetricsManager', 'Blockly.utils.object'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/flyout_vertical.js', ['Blockly.VerticalFlyout'], ['Blockly.Block', 'Blockly.DropDownDiv', 'Blockly.Flyout', 'Blockly.Scrollbar', 'Blockly.WidgetDiv', 'Blockly.browserEvents', 'Blockly.constants', 'Blockly.registry', 'Blockly.utils.Rect', 'Blockly.utils.object', 'Blockly.utils.toolbox'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/flyout_horizontal.js', ['Blockly.HorizontalFlyout'], ['Blockly.DropDownDiv', 'Blockly.Flyout', 'Blockly.Scrollbar', 'Blockly.WidgetDiv', 'Blockly.browserEvents', 'Blockly.registry', 'Blockly.utils.Rect', 'Blockly.utils.toolbox'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/flyout_metrics_manager.js', ['Blockly.FlyoutMetricsManager'], ['Blockly.MetricsManager'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/flyout_vertical.js', ['Blockly.VerticalFlyout'], ['Blockly.Block', 'Blockly.DropDownDiv', 'Blockly.Flyout', 'Blockly.Scrollbar', 'Blockly.WidgetDiv', 'Blockly.browserEvents', 'Blockly.constants', 'Blockly.registry', 'Blockly.utils.Rect', 'Blockly.utils.toolbox'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/generator.js', ['Blockly.Generator'], ['Blockly.Names', 'Blockly.common', 'Blockly.utils.deprecation'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/gesture.js', ['Blockly.Gesture'], ['Blockly.BlockDragger', 'Blockly.BubbleDragger', 'Blockly.Events.Click', 'Blockly.Events.utils', 'Blockly.Tooltip', 'Blockly.Touch', 'Blockly.Workspace', 'Blockly.WorkspaceDragger', 'Blockly.blockAnimations', 'Blockly.browserEvents', 'Blockly.common', 'Blockly.internalConstants', 'Blockly.registry', 'Blockly.utils.Coordinate'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/grid.js', ['Blockly.Grid'], ['Blockly.utils.Svg', 'Blockly.utils.dom', 'Blockly.utils.userAgent'], {'lang': 'es6', 'module': 'goog'}); @@ -223,8 +223,8 @@ goog.addDependency('../../core/toolbox/toolbox.js', ['Blockly.Toolbox'], ['Block goog.addDependency('../../core/toolbox/toolbox_item.js', ['Blockly.ToolboxItem'], ['Blockly.IToolboxItem', 'Blockly.utils.idGenerator'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/tooltip.js', ['Blockly.Tooltip'], ['Blockly.browserEvents', 'Blockly.common', 'Blockly.utils.deprecation', 'Blockly.utils.string'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/touch.js', ['Blockly.Touch'], ['Blockly.utils.global', 'Blockly.utils.string'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/touch_gesture.js', ['Blockly.TouchGesture'], ['Blockly.Gesture', 'Blockly.Touch', 'Blockly.browserEvents', 'Blockly.utils.Coordinate', 'Blockly.utils.object'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/trashcan.js', ['Blockly.Trashcan'], ['Blockly.ComponentManager', 'Blockly.DeleteArea', 'Blockly.Events.TrashcanOpen', 'Blockly.Events.utils', 'Blockly.IAutoHideable', 'Blockly.IPositionable', 'Blockly.Options', 'Blockly.browserEvents', 'Blockly.internalConstants', 'Blockly.registry', 'Blockly.uiPosition', 'Blockly.utils.Rect', 'Blockly.utils.Size', 'Blockly.utils.Svg', 'Blockly.utils.dom', 'Blockly.utils.object', 'Blockly.utils.toolbox'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/touch_gesture.js', ['Blockly.TouchGesture'], ['Blockly.Gesture', 'Blockly.Touch', 'Blockly.browserEvents', 'Blockly.utils.Coordinate'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/trashcan.js', ['Blockly.Trashcan'], ['Blockly.ComponentManager', 'Blockly.DeleteArea', 'Blockly.Events.TrashcanOpen', 'Blockly.Events.utils', 'Blockly.IAutoHideable', 'Blockly.IPositionable', 'Blockly.Options', 'Blockly.browserEvents', 'Blockly.internalConstants', 'Blockly.registry', 'Blockly.uiPosition', 'Blockly.utils.Rect', 'Blockly.utils.Size', 'Blockly.utils.Svg', 'Blockly.utils.dom', 'Blockly.utils.toolbox'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/utils.js', ['Blockly.utils'], ['Blockly.Extensions', 'Blockly.browserEvents', 'Blockly.common', 'Blockly.utils.Coordinate', 'Blockly.utils.KeyCodes', 'Blockly.utils.Metrics', 'Blockly.utils.Rect', 'Blockly.utils.Size', 'Blockly.utils.Svg', 'Blockly.utils.aria', 'Blockly.utils.array', 'Blockly.utils.colour', 'Blockly.utils.deprecation', 'Blockly.utils.dom', 'Blockly.utils.global', 'Blockly.utils.idGenerator', 'Blockly.utils.math', 'Blockly.utils.object', 'Blockly.utils.parsing', 'Blockly.utils.string', 'Blockly.utils.style', 'Blockly.utils.svgMath', 'Blockly.utils.svgPaths', 'Blockly.utils.toolbox', 'Blockly.utils.userAgent', 'Blockly.utils.xml'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/utils/aria.js', ['Blockly.utils.aria'], [], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/utils/array.js', ['Blockly.utils.array'], [], {'lang': 'es6', 'module': 'goog'}); From f68043d3eb58b276bf5f9453383597b595fbf889 Mon Sep 17 00:00:00 2001 From: Rachel Fenichel Date: Tue, 25 Jan 2022 15:33:34 -0800 Subject: [PATCH 047/128] chore(build): add a script to run the ts compiler and send the new files to closure compiler (#5894) * chore(build): add a script to run the ts compiler and send the new files to closure compiler * chore(build): clean up tsconfig * chore: apply suggestions from code review Cleanup from Chris Co-authored-by: Christopher Allen Co-authored-by: Christopher Allen --- gulpfile.js | 1 + package.json | 1 + scripts/gulpfiles/build_tasks.js | 56 ++++++++++++++++++++++---------- scripts/gulpfiles/config.js | 6 +++- tsconfig.json | 25 ++++++++++++++ 5 files changed, 71 insertions(+), 18 deletions(-) create mode 100644 tsconfig.json diff --git a/gulpfile.js b/gulpfile.js index 6cf2da365..fe2a0b90f 100644 --- a/gulpfile.js +++ b/gulpfile.js @@ -29,6 +29,7 @@ module.exports = { buildLangfiles: buildTasks.langfiles, buildCompiled: buildTasks.compiled, buildAdvancedCompilationTest: buildTasks.advancedCompilationTest, + buildTs: buildTasks.buildTypescript, // TODO(5621): Re-enable once typings generation is fixed. // checkin: gulp.parallel(buildTasks.checkinBuilt, typings.checkinTypings), checkin: gulp.parallel(buildTasks.checkinBuilt), diff --git a/package.json b/package.json index 42fee0197..101863a0a 100644 --- a/package.json +++ b/package.json @@ -26,6 +26,7 @@ "build:compressed": "npm run build:compiled", "build:deps": "gulp buildDeps", "build:langfiles": "gulp buildLangfiles", + "build-ts": "gulp buildTs && gulp build --compileTs", "bump": "npm --no-git-tag-version version 4.$(date +'%Y%m%d').0", "clean": "gulp clean", "clean:build": "gulp cleanBuildDir", diff --git a/scripts/gulpfiles/build_tasks.js b/scripts/gulpfiles/build_tasks.js index aeec016fb..0748ea118 100644 --- a/scripts/gulpfiles/build_tasks.js +++ b/scripts/gulpfiles/build_tasks.js @@ -25,7 +25,7 @@ var closureDeps = require('google-closure-deps'); var argv = require('yargs').argv; var rimraf = require('rimraf'); -var {BUILD_DIR} = require('./config'); +var {BUILD_DIR, TSC_OUTPUT_DIR} = require('./config'); var {getPackageJson} = require('./helper_tasks'); //////////////////////////////////////////////////////////// @@ -89,7 +89,7 @@ const NAMESPACE_OBJECT = '$'; * The function getChunkOptions will, after running * closure-calculate-chunks, update each chunk to add the following * properties: - * + * * - .dependencies: a list of the chunks the chunk depends upon. * - .wrapper: the chunk wrapper. * @@ -104,28 +104,34 @@ const chunks = [ factoryPreamble: `const ${NAMESPACE_OBJECT}={};`, factoryPostamble: `${NAMESPACE_OBJECT}.Blockly.internal_=${NAMESPACE_OBJECT};`, - }, { + }, + { name: 'blocks', entry: 'blocks/all.js', exports: 'Blockly.Blocks', importAs: 'BlocklyBlocks', - }, { + }, + { name: 'javascript', entry: 'generators/javascript/all.js', exports: 'Blockly.JavaScript', - }, { + }, + { name: 'python', entry: 'generators/python/all.js', exports: 'Blockly.Python', - }, { + }, + { name: 'php', entry: 'generators/php/all.js', exports: 'Blockly.PHP', - }, { + }, + { name: 'lua', entry: 'generators/lua/all.js', exports: 'Blockly.Lua', - }, { + }, + { name: 'dart', entry: 'generators/dart/all.js', exports: 'Blockly.Dart', @@ -224,9 +230,10 @@ function buildDeps(done) { 'node_modules/google-closure-library/closure/goog' : 'closure/goog'; + const coreDir = argv.compileTs ? path.join(TSC_OUTPUT_DIR, 'core') : 'core'; const roots = [ closurePath, - 'core', + coreDir, 'blocks', 'generators', ]; @@ -350,6 +357,9 @@ return ${NAMESPACE_OBJECT}.${chunk.exports}; * TODO(cpcallen): maybeAddClosureLibrary? Or maybe remove base.js? */ function getChunkOptions() { + if (argv.compileTs) { + chunks[0].entry = path.join(TSC_OUTPUT_DIR, chunks[0].entry); + } const cccArgs = [ '--closure-library-base-js-path ./closure/goog/base_minimal.js', '--deps-file ./tests/deps.js', @@ -432,12 +442,12 @@ function getChunkOptions() { return {chunk: chunkList, js: rawOptions.js, chunk_wrapper: chunkWrappers}; } -/** +/** * RegExp that globally matches path.sep (i.e., "/" or "\"). */ const pathSepRegExp = new RegExp(path.sep.replace(/\\/, '\\\\'), "g"); -/** +/** * Modify the supplied gulp.rename path object to relax @package * restrictions in core/. * @@ -457,10 +467,11 @@ const pathSepRegExp = new RegExp(path.sep.replace(/\\/, '\\\\'), "g"); */ function flattenCorePaths(pathObject) { const dirs = pathObject.dirname.split(path.sep); - if (dirs[0] === 'core') { - pathObject.dirname = dirs[0]; + const coreIndex = argv.compileTs ? 2 : 0; + if (dirs[coreIndex] === 'core') { + pathObject.dirname = path.join(...dirs.slice(0, coreIndex + 1)); pathObject.basename = - dirs.slice(1).concat(pathObject.basename).join('-slash-'); + dirs.slice(coreIndex + 1).concat(pathObject.basename).join('-slash-'); } } @@ -503,7 +514,7 @@ function compile(options) { } /** - * This task compiles the core library, blocks and generators, creating + * This task compiles the core library, blocks and generators, creating * blockly_compressed.js, blocks_compressed.js, etc. * * The deps.js file must be up-to-date. @@ -540,10 +551,15 @@ function buildCompiled() { * closure compiler's ADVANCED_COMPILATION mode. */ function buildAdvancedCompilationTest() { + const coreSrcs = argv.compileTs ? + TSC_OUTPUT_DIR + '/core/**/*.js' : 'core/**/*.js'; const srcs = [ 'closure/goog/base_minimal.js', - 'core/**/*.js', 'blocks/**/*.js', 'generators/**/*.js', - 'tests/compile/main.js', 'tests/compile/test_blocks.js', + coreSrcs, + 'blocks/**/*.js', + 'generators/**/*.js', + 'tests/compile/main.js', + 'tests/compile/test_blocks.js', ]; // Closure Compiler options. @@ -615,6 +631,11 @@ function format() { .pipe(gulp.dest('.')); }; +function buildTypescript(done) { + execSync('npx tsc', {stdio: 'inherit'}); + done(); +} + module.exports = { build: build, deps: buildDeps, @@ -625,4 +646,5 @@ module.exports = { checkinBuilt: checkinBuilt, cleanBuildDir: cleanBuildDir, advancedCompilationTest: buildAdvancedCompilationTest, + buildTypescript: buildTypescript } diff --git a/scripts/gulpfiles/config.js b/scripts/gulpfiles/config.js index c9eb518ca..f8ee8c1a8 100644 --- a/scripts/gulpfiles/config.js +++ b/scripts/gulpfiles/config.js @@ -15,7 +15,7 @@ var path = require('path'); // // TODO(#5007): If you modify these values, you must also modify the // corresponding values in the following files: -// +// // - tests/scripts/compile_typings.sh // - tests/scripts/check_metadata.sh module.exports = { @@ -28,4 +28,8 @@ module.exports = { // Directory to write typings output to. TYPINGS_BUILD_DIR: path.join('build', 'typings'), + + // Directory where typescript compiler output can be found. + // Matches the value in tsconfig.json: outDir + TSC_OUTPUT_DIR: path.join('build', 'ts'), }; diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 000000000..88c95700b --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,25 @@ +{ + "include": [ + "core/**/*", + "closure/goog/base_minimal.js", + ], + "compilerOptions": { + // Tells TypeScript to read JS files, as + // normally they are ignored as source files + "allowJs": true, + + // Enable the next few options for type declarations. + // Generate d.ts files + //"declaration": true, + // Types should go into this directory. + // Removing this would place the .d.ts files + // next to the .js files + //"declarationDir": "build/ts/declarations", + + "outDir": "build/ts", + "module": "ES2015", + "moduleResolution": "node", + "target": "ES2020", + "strict": true, + } +} From a31003fab964e529152389029ec3126a3802851b Mon Sep 17 00:00:00 2001 From: Richard Doherty Date: Thu, 27 Jan 2022 10:54:05 -0500 Subject: [PATCH 048/128] fix(generators): Fix an operator precedence issue in the math_number_property generators to remove extra parentheses (#5685) * Fixed issue where the mathIsPrime function inserted extra parenthesis around certain blocks. * Added tests to generated JS * Updated generated code in Lua * Updated Generated code for tests in Dart * Updated generated code for tests in PHP * Updated generated code for tests in Python * Also changed var to const and let. Co-authored-by: jeremyjacob123 <43049656+jeremyjacob123@users.noreply.github.com> Co-authored-by: LouisCatala <86700310+LouisCatala@users.noreply.github.com> Co-authored-by: jeremyjacob123 <43049656+jeremyjacob123@users.noreply.github.com> --- generators/dart/math.js | 105 +++++++------- generators/javascript/math.js | 59 ++++---- generators/lua/math.js | 107 +++++++------- generators/php/math.js | 96 +++++++------ generators/python/math.js | 111 ++++++++------- tests/generators/golden/generated.dart | 4 + tests/generators/golden/generated.js | 4 + tests/generators/golden/generated.lua | 4 + tests/generators/golden/generated.php | 4 + tests/generators/golden/generated.py | 4 + tests/generators/math.xml | 187 +++++++++++++++++++++---- 11 files changed, 427 insertions(+), 258 deletions(-) diff --git a/generators/dart/math.js b/generators/dart/math.js index 24b7e268e..ab2d0cc50 100644 --- a/generators/dart/math.js +++ b/generators/dart/math.js @@ -164,59 +164,64 @@ Dart['math_constant'] = function(block) { Dart['math_number_property'] = function(block) { // Check if a number is even, odd, prime, whole, positive, or negative // or if it is divisible by certain number. Returns true or false. - const number_to_check = - Dart.valueToCode(block, 'NUMBER_TO_CHECK', Dart.ORDER_MULTIPLICATIVE); - if (!number_to_check) { - return ['false', Dart.ORDER_ATOMIC]; - } - const dropdown_property = block.getFieldValue('PROPERTY'); + const PROPERTIES = { + 'EVEN': [' % 2 == 0', Dart.ORDER_MULTIPLICATIVE, + Dart.ORDER_EQUALITY], + 'ODD': [' % 2 == 1', Dart.ORDER_MULTIPLICATIVE, + Dart.ORDER_EQUALITY], + 'WHOLE': [' % 1 == 0', Dart.ORDER_MULTIPLICATIVE, + Dart.ORDER_EQUALITY], + 'POSITIVE': [' > 0', Dart.ORDER_RELATIONAL, + Dart.ORDER_RELATIONAL], + 'NEGATIVE': [' < 0', Dart.ORDER_RELATIONAL, + Dart.ORDER_RELATIONAL], + 'DIVISIBLE_BY': [null, Dart.ORDER_MULTIPLICATIVE, + Dart.ORDER_EQUALITY], + 'PRIME': [null, Dart.ORDER_NONE, + Dart.ORDER_UNARY_POSTFIX] + }; + const dropdownProperty = block.getFieldValue('PROPERTY'); + const [suffix, inputOrder, outputOrder] = PROPERTIES[dropdownProperty]; + const numberToCheck = Dart.valueToCode(block, 'NUMBER_TO_CHECK', + inputOrder) || '0'; let code; - if (dropdown_property === 'PRIME') { + if (dropdownProperty === 'PRIME') { // Prime is a special case as it is not a one-liner test. - Dart.definitions_['import_dart_math'] = 'import \'dart:math\' as Math;'; - const functionName = Dart.provideFunction_('math_isPrime', [ - 'bool ' + Dart.FUNCTION_NAME_PLACEHOLDER_ + '(n) {', - ' // https://en.wikipedia.org/wiki/Primality_test#Naive_methods', - ' if (n == 2 || n == 3) {', ' return true;', ' }', - ' // False if n is null, negative, is 1, or not whole.', - ' // And false if n is divisible by 2 or 3.', - ' if (n == null || 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;', '}' - ]); - code = functionName + '(' + number_to_check + ')'; - return [code, Dart.ORDER_UNARY_POSTFIX]; + Dart.definitions_['import_dart_math'] = + 'import \'dart:math\' as Math;'; + const functionName = Dart.provideFunction_( + 'math_isPrime', + ['bool ' + Dart.FUNCTION_NAME_PLACEHOLDER_ + '(n) {', + ' // https://en.wikipedia.org/wiki/Primality_test#Naive_methods', + ' if (n == 2 || n == 3) {', + ' return true;', + ' }', + ' // False if n is null, negative, is 1, or not whole.', + ' // And false if n is divisible by 2 or 3.', + ' if (n == null || 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;', + '}']); + code = functionName + '(' + numberToCheck + ')'; + } else if (dropdownProperty === 'DIVISIBLE_BY') { + const divisor = Dart.valueToCode(block, 'DIVISOR', + Dart.ORDER_MULTIPLICATIVE) || '0'; + if (divisor === '0') { + return ['false', Dart.ORDER_ATOMIC]; + } + code = numberToCheck + ' % ' + divisor + ' == 0'; + } else { + code = numberToCheck + suffix; } - switch (dropdown_property) { - case 'EVEN': - code = number_to_check + ' % 2 == 0'; - break; - case 'ODD': - code = number_to_check + ' % 2 == 1'; - break; - case 'WHOLE': - code = number_to_check + ' % 1 == 0'; - break; - case 'POSITIVE': - code = number_to_check + ' > 0'; - break; - case 'NEGATIVE': - code = number_to_check + ' < 0'; - break; - case 'DIVISIBLE_BY': - const divisor = - Dart.valueToCode(block, 'DIVISOR', Dart.ORDER_MULTIPLICATIVE); - if (!divisor) { - return ['false', Dart.ORDER_ATOMIC]; - } - code = number_to_check + ' % ' + divisor + ' == 0'; - break; - } - return [code, Dart.ORDER_EQUALITY]; + return [code, outputOrder]; }; Dart['math_change'] = function(block) { diff --git a/generators/javascript/math.js b/generators/javascript/math.js index 103d36a25..55ee3de82 100644 --- a/generators/javascript/math.js +++ b/generators/javascript/math.js @@ -149,11 +149,28 @@ JavaScript['math_constant'] = function(block) { JavaScript['math_number_property'] = function(block) { // Check if a number is even, odd, prime, whole, positive, or negative // or if it is divisible by certain number. Returns true or false. - const number_to_check = JavaScript.valueToCode(block, 'NUMBER_TO_CHECK', - JavaScript.ORDER_MODULUS) || '0'; - const dropdown_property = block.getFieldValue('PROPERTY'); + const PROPERTIES = { + 'EVEN': [' % 2 === 0', JavaScript.ORDER_MODULUS, + JavaScript.ORDER_EQUALITY], + 'ODD': [' % 2 === 1', JavaScript.ORDER_MODULUS, + JavaScript.ORDER_EQUALITY], + 'WHOLE': [' % 1 === 0', JavaScript.ORDER_MODULUS, + JavaScript.ORDER_EQUALITY], + 'POSITIVE': [' > 0', JavaScript.ORDER_RELATIONAL, + JavaScript.ORDER_RELATIONAL], + 'NEGATIVE': [' < 0', JavaScript.ORDER_RELATIONAL, + JavaScript.ORDER_RELATIONAL], + 'DIVISIBLE_BY': [null, JavaScript.ORDER_MODULUS, + JavaScript.ORDER_EQUALITY], + 'PRIME': [null, JavaScript.ORDER_NONE, + JavaScript.ORDER_FUNCTION_CALL] + }; + const dropdownProperty = block.getFieldValue('PROPERTY'); + const [suffix, inputOrder, outputOrder] = PROPERTIES[dropdownProperty]; + const numberToCheck = JavaScript.valueToCode(block, 'NUMBER_TO_CHECK', + inputOrder) || '0'; let code; - if (dropdown_property === 'PRIME') { + if (dropdownProperty === 'PRIME') { // Prime is a special case as it is not a one-liner test. const functionName = JavaScript.provideFunction_( 'mathIsPrime', @@ -176,33 +193,15 @@ JavaScript['math_number_property'] = function(block) { ' }', ' return true;', '}']); - code = functionName + '(' + number_to_check + ')'; - return [code, JavaScript.ORDER_FUNCTION_CALL]; + code = functionName + '(' + numberToCheck + ')'; + } else if (dropdownProperty === 'DIVISIBLE_BY') { + const divisor = JavaScript.valueToCode(block, 'DIVISOR', + JavaScript.ORDER_MODULUS) || '0'; + code = numberToCheck + ' % ' + divisor + ' === 0'; + } else { + code = numberToCheck + suffix; } - switch (dropdown_property) { - case 'EVEN': - code = number_to_check + ' % 2 === 0'; - break; - case 'ODD': - code = number_to_check + ' % 2 === 1'; - break; - case 'WHOLE': - code = number_to_check + ' % 1 === 0'; - break; - case 'POSITIVE': - code = number_to_check + ' > 0'; - break; - case 'NEGATIVE': - code = number_to_check + ' < 0'; - break; - case 'DIVISIBLE_BY': { - const divisor = JavaScript.valueToCode(block, 'DIVISOR', - JavaScript.ORDER_MODULUS) || '0'; - code = number_to_check + ' % ' + divisor + ' === 0'; - break; - } - } - return [code, JavaScript.ORDER_EQUALITY]; + return [code, outputOrder]; }; JavaScript['math_change'] = function(block) { diff --git a/generators/lua/math.js b/generators/lua/math.js index 7fdb50aa8..c51274830 100644 --- a/generators/lua/math.js +++ b/generators/lua/math.js @@ -126,61 +126,66 @@ Lua['math_constant'] = function(block) { Lua['math_number_property'] = function(block) { // Check if a number is even, odd, prime, whole, positive, or negative // or if it is divisible by certain number. Returns true or false. - const number_to_check = - Lua.valueToCode(block, 'NUMBER_TO_CHECK', Lua.ORDER_MULTIPLICATIVE) || - '0'; - const dropdown_property = block.getFieldValue('PROPERTY'); + const PROPERTIES = { + 'EVEN': [' % 2 == 0', Lua.ORDER_MULTIPLICATIVE, + Lua.ORDER_RELATIONAL], + 'ODD': [' % 2 == 1', Lua.ORDER_MULTIPLICATIVE, + Lua.ORDER_RELATIONAL], + 'WHOLE': [' % 1 == 0', Lua.ORDER_MULTIPLICATIVE, + Lua.ORDER_RELATIONAL], + 'POSITIVE': [' > 0', Lua.ORDER_RELATIONAL, + Lua.ORDER_RELATIONAL], + 'NEGATIVE': [' < 0', Lua.ORDER_RELATIONAL, + Lua.ORDER_RELATIONAL], + 'DIVISIBLE_BY': [null, Lua.ORDER_MULTIPLICATIVE, + Lua.ORDER_RELATIONAL], + 'PRIME': [null, Lua.ORDER_NONE, + Lua.ORDER_HIGH] + }; + const dropdownProperty = block.getFieldValue('PROPERTY'); + const [suffix, inputOrder, outputOrder] = PROPERTIES[dropdownProperty]; + const numberToCheck = Lua.valueToCode(block, 'NUMBER_TO_CHECK', + inputOrder) || '0'; let code; - if (dropdown_property === 'PRIME') { + if (dropdownProperty === 'PRIME') { // Prime is a special case as it is not a one-liner test. - const functionName = Lua.provideFunction_('math_isPrime', [ - 'function ' + Lua.FUNCTION_NAME_PLACEHOLDER_ + '(n)', - ' -- https://en.wikipedia.org/wiki/Primality_test#Naive_methods', - ' if n == 2 or n == 3 then', ' return true', ' end', - ' -- False if n is NaN, negative, is 1, or not whole.', - ' -- And false if n is divisible by 2 or 3.', - ' if not(n > 1) or n % 1 ~= 0 or n % 2 == 0 or n % 3 == 0 then', - ' return false', ' end', - ' -- Check all the numbers of form 6k +/- 1, up to sqrt(n).', - ' for x = 6, math.sqrt(n) + 1.5, 6 do', - ' if n % (x - 1) == 0 or n % (x + 1) == 0 then', ' return false', - ' end', ' end', ' return true', 'end' - ]); - code = functionName + '(' + number_to_check + ')'; - return [code, Lua.ORDER_HIGH]; - } - switch (dropdown_property) { - case 'EVEN': - code = number_to_check + ' % 2 == 0'; - break; - case 'ODD': - code = number_to_check + ' % 2 == 1'; - break; - case 'WHOLE': - code = number_to_check + ' % 1 == 0'; - break; - case 'POSITIVE': - code = number_to_check + ' > 0'; - break; - case 'NEGATIVE': - code = number_to_check + ' < 0'; - break; - case 'DIVISIBLE_BY': { - const divisor = - Lua.valueToCode(block, 'DIVISOR', Lua.ORDER_MULTIPLICATIVE); - // If 'divisor' is some code that evals to 0, Lua will produce a nan. - // Let's produce nil if we can determine this at compile-time. - if (!divisor || divisor === '0') { - return ['nil', Lua.ORDER_ATOMIC]; - } - // The normal trick to implement ?: with and/or doesn't work here: - // divisor == 0 and nil or number_to_check % divisor == 0 - // because nil is false, so allow a runtime failure. :-( - code = number_to_check + ' % ' + divisor + ' == 0'; - break; + const functionName = Lua.provideFunction_( + 'math_isPrime', + ['function ' + Lua.FUNCTION_NAME_PLACEHOLDER_ + '(n)', + ' -- https://en.wikipedia.org/wiki/Primality_test#Naive_methods', + ' if n == 2 or n == 3 then', + ' return true', + ' end', + ' -- False if n is NaN, negative, is 1, or not whole.', + ' -- And false if n is divisible by 2 or 3.', + ' if not(n > 1) or n % 1 ~= 0 or n % 2 == 0 or n % 3 == 0 then', + ' return false', + ' end', + ' -- Check all the numbers of form 6k +/- 1, up to sqrt(n).', + ' for x = 6, math.sqrt(n) + 1.5, 6 do', + ' if n % (x - 1) == 0 or n % (x + 1) == 0 then', + ' return false', + ' end', + ' end', + ' return true', + 'end']); + code = functionName + '(' + numberToCheck + ')'; + } else if (dropdownProperty === 'DIVISIBLE_BY') { + const divisor = Lua.valueToCode(block, 'DIVISOR', + Lua.ORDER_MULTIPLICATIVE) || '0'; + // If 'divisor' is some code that evals to 0, Lua will produce a nan. + // Let's produce nil if we can determine this at compile-time. + if (divisor === '0') { + return ['nil', Lua.ORDER_ATOMIC]; } + // The normal trick to implement ?: with and/or doesn't work here: + // divisor == 0 and nil or number_to_check % divisor == 0 + // because nil is false, so allow a runtime failure. :-( + code = numberToCheck + ' % ' + divisor + ' == 0'; + } else { + code = numberToCheck + suffix; } - return [code, Lua.ORDER_RELATIONAL]; + return [code, outputOrder]; }; Lua['math_change'] = function(block) { diff --git a/generators/php/math.js b/generators/php/math.js index d77f47806..1c1e3e621 100644 --- a/generators/php/math.js +++ b/generators/php/math.js @@ -142,53 +142,63 @@ PHP['math_constant'] = function(block) { PHP['math_number_property'] = function(block) { // Check if a number is even, odd, prime, whole, positive, or negative // or if it is divisible by certain number. Returns true or false. - const number_to_check = - PHP.valueToCode(block, 'NUMBER_TO_CHECK', PHP.ORDER_MODULUS) || '0'; - const dropdown_property = block.getFieldValue('PROPERTY'); + const PROPERTIES = { + 'EVEN': ['', ' % 2 == 0', PHP.ORDER_MODULUS, + PHP.ORDER_EQUALITY], + 'ODD': ['', ' % 2 == 1', PHP.ORDER_MODULUS, + PHP.ORDER_EQUALITY], + 'WHOLE': ['is_int(', ')', PHP.ORDER_NONE, + PHP.ORDER_FUNCTION_CALL], + 'POSITIVE': ['', ' > 0', PHP.ORDER_RELATIONAL, + PHP.ORDER_RELATIONAL], + 'NEGATIVE': ['', ' < 0', PHP.ORDER_RELATIONAL, + PHP.ORDER_RELATIONAL], + 'DIVISIBLE_BY': [null, null, PHP.ORDER_MODULUS, + PHP.ORDER_EQUALITY], + 'PRIME': [null, null, PHP.ORDER_NONE, + PHP.ORDER_FUNCTION_CALL] + }; + const dropdownProperty = block.getFieldValue('PROPERTY'); + const [prefix, suffix, inputOrder, outputOrder] = PROPERTIES[dropdownProperty]; + const numberToCheck = PHP.valueToCode(block, 'NUMBER_TO_CHECK', + inputOrder) || '0'; let code; - if (dropdown_property === 'PRIME') { + if (dropdownProperty === 'PRIME') { // Prime is a special case as it is not a one-liner test. - const functionName = PHP.provideFunction_('math_isPrime', [ - 'function ' + PHP.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 (!is_numeric($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 ($x = 6; $x <= sqrt($n) + 1; $x += 6) {', - ' if ($n % ($x - 1) == 0 || $n % ($x + 1) == 0) {', - ' return false;', ' }', ' }', ' return true;', '}' - ]); - code = functionName + '(' + number_to_check + ')'; - return [code, PHP.ORDER_FUNCTION_CALL]; - } - switch (dropdown_property) { - case 'EVEN': - code = number_to_check + ' % 2 == 0'; - break; - case 'ODD': - code = number_to_check + ' % 2 == 1'; - break; - case 'WHOLE': - code = 'is_int(' + number_to_check + ')'; - break; - case 'POSITIVE': - code = number_to_check + ' > 0'; - break; - case 'NEGATIVE': - code = number_to_check + ' < 0'; - break; - case 'DIVISIBLE_BY': { - const divisor = - PHP.valueToCode(block, 'DIVISOR', PHP.ORDER_MODULUS) || '0'; - code = number_to_check + ' % ' + divisor + ' == 0'; - break; + const functionName = PHP.provideFunction_( + 'math_isPrime', + ['function ' + PHP.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 (!is_numeric($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 ($x = 6; $x <= sqrt($n) + 1; $x += 6) {', + ' if ($n % ($x - 1) == 0 || $n % ($x + 1) == 0) {', + ' return false;', + ' }', + ' }', + ' return true;', + '}']); + code = functionName + '(' + numberToCheck + ')'; + } else if (dropdownProperty === 'DIVISIBLE_BY') { + const divisor = PHP.valueToCode(block, 'DIVISOR', + PHP.ORDER_MODULUS) || '0'; + if (divisor === '0') { + return ['false', PHP.ORDER_ATOMIC]; + } + code = numberToCheck + ' % ' + divisor + ' == 0'; + } else { + code = prefix + numberToCheck + suffix; } - return [code, PHP.ORDER_EQUALITY]; + return [code, outputOrder]; }; PHP['math_change'] = function(block) { diff --git a/generators/python/math.js b/generators/python/math.js index 9f4fdc983..93d4b8355 100644 --- a/generators/python/math.js +++ b/generators/python/math.js @@ -152,65 +152,68 @@ Python['math_constant'] = function(block) { }; Python['math_number_property'] = function(block) { - // Check if a number is even, odd, prime, whole, positive, or negative - // or if it is divisible by certain number. Returns true or false. - const number_to_check = - Python.valueToCode( - block, 'NUMBER_TO_CHECK', Python.ORDER_MULTIPLICATIVE) || - '0'; - const dropdown_property = block.getFieldValue('PROPERTY'); + // Check if a number is even, odd, prime, whole, positive, or negative + // or if it is divisible by certain number. Returns true or false. + const PROPERTIES = { + 'EVEN': [' % 2 == 0', Python.ORDER_MULTIPLICATIVE, + Python.ORDER_RELATIONAL], + 'ODD': [' % 2 == 1', Python.ORDER_MULTIPLICATIVE, + Python.ORDER_RELATIONAL], + 'WHOLE': [' % 1 == 0', Python.ORDER_MULTIPLICATIVE, + Python.ORDER_RELATIONAL], + 'POSITIVE': [' > 0', Python.ORDER_RELATIONAL, + Python.ORDER_RELATIONAL], + 'NEGATIVE': [' < 0', Python.ORDER_RELATIONAL, + Python.ORDER_RELATIONAL], + 'DIVISIBLE_BY': [null, Python.ORDER_MULTIPLICATIVE, + Python.ORDER_RELATIONAL], + 'PRIME': [null, Python.ORDER_NONE, + Python.ORDER_FUNCTION_CALL] + } + const dropdownProperty = block.getFieldValue('PROPERTY'); + const [suffix, inputOrder, outputOrder] = PROPERTIES[dropdownProperty]; + const numberToCheck = Python.valueToCode(block, 'NUMBER_TO_CHECK', + inputOrder) || '0'; let code; - if (dropdown_property === 'PRIME') { + if (dropdownProperty === 'PRIME') { + // Prime is a special case as it is not a one-liner test. Python.definitions_['import_math'] = 'import math'; Python.definitions_['from_numbers_import_Number'] = 'from numbers import Number'; - const functionName = Python.provideFunction_('math_isPrime', [ - 'def ' + Python.FUNCTION_NAME_PLACEHOLDER_ + '(n):', - ' # https://en.wikipedia.org/wiki/Primality_test#Naive_methods', - ' # If n is not a number but a string, try parsing it.', - ' if not isinstance(n, Number):', ' try:', ' n = float(n)', - ' except:', ' return False', - ' if n == 2 or n == 3:', ' return True', - ' # False if n is negative, is 1, or not whole,' + - ' or if n is divisible by 2 or 3.', - ' if n <= 1 or n % 1 != 0 or n % 2 == 0 or n % 3 == 0:', - ' return False', - ' # Check all the numbers of form 6k +/- 1, up to sqrt(n).', - ' for x in range(6, int(math.sqrt(n)) + 2, 6):', - ' if n % (x - 1) == 0 or n % (x + 1) == 0:', ' return False', - ' return True' - ]); - code = functionName + '(' + number_to_check + ')'; - return [code, Python.ORDER_FUNCTION_CALL]; - } - switch (dropdown_property) { - case 'EVEN': - code = number_to_check + ' % 2 == 0'; - break; - case 'ODD': - code = number_to_check + ' % 2 == 1'; - break; - case 'WHOLE': - code = number_to_check + ' % 1 == 0'; - break; - case 'POSITIVE': - code = number_to_check + ' > 0'; - break; - case 'NEGATIVE': - code = number_to_check + ' < 0'; - break; - case 'DIVISIBLE_BY': { - const divisor = - Python.valueToCode(block, 'DIVISOR', Python.ORDER_MULTIPLICATIVE); - // If 'divisor' is some code that evals to 0, Python will raise an error. - if (!divisor || divisor === '0') { - return ['False', Python.ORDER_ATOMIC]; - } - code = number_to_check + ' % ' + divisor + ' == 0'; - break; + const functionName = Python.provideFunction_( + 'math_isPrime', + ['def ' + Python.FUNCTION_NAME_PLACEHOLDER_ + '(n):', + ' # https://en.wikipedia.org/wiki/Primality_test#Naive_methods', + ' # If n is not a number but a string, try parsing it.', + ' if not isinstance(n, Number):', + ' try:', + ' n = float(n)', + ' except:', + ' return False', + ' if n == 2 or n == 3:', + ' return True', + ' # False if n is negative, is 1, or not whole,' + + ' or if n is divisible by 2 or 3.', + ' if n <= 1 or n % 1 != 0 or n % 2 == 0 or n % 3 == 0:', + ' return False', + ' # Check all the numbers of form 6k +/- 1, up to sqrt(n).', + ' for x in range(6, int(math.sqrt(n)) + 2, 6):', + ' if n % (x - 1) == 0 or n % (x + 1) == 0:', + ' return False', + ' return True']); + code = functionName + '(' + numberToCheck + ')'; + } else if (dropdownProperty === 'DIVISIBLE_BY') { + const divisor = Python.valueToCode(block, 'DIVISOR', + Python.ORDER_MULTIPLICATIVE) || '0'; + // If 'divisor' is some code that evals to 0, Python will raise an error. + if (divisor === '0') { + return ['False', Python.ORDER_ATOMIC]; } - } - return [code, Python.ORDER_RELATIONAL]; + code = numberToCheck + ' % ' + divisor + ' == 0'; + } else { + code = numberToCheck + suffix; + }; + return [code, outputOrder]; }; Python['math_change'] = function(block) { diff --git a/tests/generators/golden/generated.dart b/tests/generators/golden/generated.dart index 2c45db3b4..c067942e1 100644 --- a/tests/generators/golden/generated.dart +++ b/tests/generators/golden/generated.dart @@ -440,12 +440,16 @@ void test_number_properties() { unittest_assertequals(42 % 2 == 0, true, 'even'); unittest_assertequals(42.1 % 2 == 1, false, 'odd'); unittest_assertequals(math_isPrime(5), true, 'prime 5'); + unittest_assertequals(math_isPrime(5 + 2), true, 'prime 5 + 2 (extra parentheses)'); unittest_assertequals(math_isPrime(25), false, 'prime 25'); unittest_assertequals(math_isPrime(-31.1), false, 'prime negative'); unittest_assertequals(Math.pi % 1 == 0, false, 'whole'); unittest_assertequals(double.infinity > 0, true, 'positive'); + unittest_assertequals(5 + 2 > 0, true, '5 + 2 is positive (extra parentheses)'); unittest_assertequals(-42 < 0, true, 'negative'); + unittest_assertequals(3 + 2 < 0, false, '3 + 2 is negative (extra parentheses)'); unittest_assertequals(42 % 2 == 0, true, 'divisible'); + unittest_assertequals(!false, true, 'divisible by 0'); } /// Tests the "round" block. diff --git a/tests/generators/golden/generated.js b/tests/generators/golden/generated.js index 01e9bd311..019d51d19 100644 --- a/tests/generators/golden/generated.js +++ b/tests/generators/golden/generated.js @@ -449,12 +449,16 @@ function test_number_properties() { assertEquals(42 % 2 === 0, true, 'even'); assertEquals(42.1 % 2 === 1, false, 'odd'); assertEquals(mathIsPrime(5), true, 'prime 5'); + assertEquals(mathIsPrime(5 + 2), true, 'prime 5 + 2 (extra parentheses)'); assertEquals(mathIsPrime(25), false, 'prime 25'); assertEquals(mathIsPrime(-31.1), false, 'prime negative'); assertEquals(Math.PI % 1 === 0, false, 'whole'); assertEquals(Infinity > 0, true, 'positive'); + assertEquals(5 + 2 > 0, true, '5 + 2 is positive (extra parentheses)'); assertEquals(-42 < 0, true, 'negative'); + assertEquals(3 + 2 < 0, false, '3 + 2 is negative (extra parentheses)'); assertEquals(42 % 2 === 0, true, 'divisible'); + assertEquals(!(42 % 0 === 0), true, 'divisible by 0'); } // Tests the "round" block. diff --git a/tests/generators/golden/generated.lua b/tests/generators/golden/generated.lua index 2724c1d3b..ad71d3aca 100644 --- a/tests/generators/golden/generated.lua +++ b/tests/generators/golden/generated.lua @@ -450,12 +450,16 @@ function test_number_properties() assertEquals(42 % 2 == 0, true, 'even') assertEquals(42.1 % 2 == 1, false, 'odd') assertEquals(math_isPrime(5), true, 'prime 5') + assertEquals(math_isPrime(5 + 2), true, 'prime 5 + 2 (extra parentheses)') assertEquals(math_isPrime(25), false, 'prime 25') assertEquals(math_isPrime(-31.1), false, 'prime negative') assertEquals(math.pi % 1 == 0, false, 'whole') assertEquals(math.huge > 0, true, 'positive') + assertEquals(5 + 2 > 0, true, '5 + 2 is positive (extra parentheses)') assertEquals(-42 < 0, true, 'negative') + assertEquals(3 + 2 < 0, false, '3 + 2 is negative (extra parentheses)') assertEquals(42 % 2 == 0, true, 'divisible') + assertEquals(not nil, true, 'divisible by 0') end diff --git a/tests/generators/golden/generated.php b/tests/generators/golden/generated.php index 9d6436125..728273d52 100644 --- a/tests/generators/golden/generated.php +++ b/tests/generators/golden/generated.php @@ -444,12 +444,16 @@ function test_number_properties() { assertEquals(42 % 2 == 0, true, 'even'); assertEquals(42.1 % 2 == 1, false, 'odd'); assertEquals(math_isPrime(5), true, 'prime 5'); + assertEquals(math_isPrime(5 + 2), true, 'prime 5 + 2 (extra parentheses)'); assertEquals(math_isPrime(25), false, 'prime 25'); assertEquals(math_isPrime(-31.1), false, 'prime negative'); assertEquals(is_int(M_PI), false, 'whole'); assertEquals(INF > 0, true, 'positive'); + assertEquals(5 + 2 > 0, true, '5 + 2 is positive (extra parentheses)'); assertEquals(-42 < 0, true, 'negative'); + assertEquals(3 + 2 < 0, false, '3 + 2 is negative (extra parentheses)'); assertEquals(42 % 2 == 0, true, 'divisible'); + assertEquals(!false, true, 'divisible by 0'); } // Tests the "round" block. diff --git a/tests/generators/golden/generated.py b/tests/generators/golden/generated.py index 42764d368..12185286e 100644 --- a/tests/generators/golden/generated.py +++ b/tests/generators/golden/generated.py @@ -398,12 +398,16 @@ def test_number_properties(): assertEquals(42 % 2 == 0, True, 'even') assertEquals(42.1 % 2 == 1, False, 'odd') assertEquals(math_isPrime(5), True, 'prime 5') + assertEquals(math_isPrime(5 + 2), True, 'prime 5 + 2 (extra parentheses)') assertEquals(math_isPrime(25), False, 'prime 25') assertEquals(math_isPrime(-31.1), False, 'prime negative') assertEquals(math.pi % 1 == 0, False, 'whole') assertEquals(float('inf') > 0, True, 'positive') + assertEquals(5 + 2 > 0, True, '5 + 2 is positive (extra parentheses)') assertEquals(-42 < 0, True, 'negative') + assertEquals(3 + 2 < 0, False, '3 + 2 is negative (extra parentheses)') assertEquals(42 % 2 == 0, True, 'divisible') + assertEquals(not False, True, 'divisible by 0') # Tests the "round" block. def test_round(): diff --git a/tests/generators/math.xml b/tests/generators/math.xml index ff079d2e1..682d143ac 100644 --- a/tests/generators/math.xml +++ b/tests/generators/math.xml @@ -1,4 +1,8 @@ + + varToChange + rand + Math @@ -992,10 +996,10 @@ - FALSE + TRUE - prime 25 + prime 5 + 2 (extra parentheses) @@ -1003,8 +1007,18 @@ PRIME - - 25 + + ADD + + + 5 + + + + + 2 + + @@ -1014,7 +1028,7 @@ FALSE - prime negative + prime 25 @@ -1023,7 +1037,7 @@ PRIME - -31.1 + 25 @@ -1033,35 +1047,35 @@ FALSE - whole + prime negative - WHOLE + PRIME - - PI + + -31.1 - TRUE + FALSE - positive + whole - POSITIVE + WHOLE - INFINITY + PI @@ -1071,16 +1085,16 @@ TRUE - negative + positive - NEGATIVE + POSITIVE - - -42 + + INFINITY @@ -1090,25 +1104,138 @@ TRUE - divisible + 5 + 2 is positive (extra parentheses) - - DIVISIBLE_BY + + POSITIVE - - 42 - - - - - 2 + + ADD + + + 5 + + + + + 2 + + + + + TRUE + + + negative + + + + + + NEGATIVE + + + -42 + + + + + + + FALSE + + + 3 + 2 is negative (extra parentheses) + + + + + + NEGATIVE + + + ADD + + + 3 + + + + + 2 + + + + + + + + + TRUE + + + divisible + + + + + + DIVISIBLE_BY + + + 42 + + + + + 2 + + + + + + + TRUE + + + divisible by 0 + + + + + + + + DIVISIBLE_BY + + + 42 + + + + + 0 + + + + + + + + + + + + + + @@ -1128,7 +1255,7 @@ - + test round Tests the "round" block. @@ -1204,7 +1331,7 @@ - + test change Tests the "change" block. From 1f6a1bd8d9a5208a7da8c4fd0d55c1a3516ee7e7 Mon Sep 17 00:00:00 2001 From: Neil Fraser Date: Fri, 28 Jan 2022 17:58:43 -0800 Subject: [PATCH 049/128] chore: Use ES6 template strings in CSS and code generators (#5902) * Unindent CSS, save 3 kb of code. * Convert generator functions to template strings. This resolves #5761. --- core/comment.js | 20 +- core/css.js | 938 ++++++++++++------------- core/field_angle.js | 42 +- core/field_colour.js | 50 +- core/field_multilineinput.js | 20 +- core/flyout_button.js | 32 +- core/generator.js | 8 +- core/toolbox/category.js | 114 +-- core/toolbox/separator.js | 26 +- core/toolbox/toolbox.js | 52 +- core/workspace_comment_svg.js | 92 +-- core/zoom_controls.js | 18 +- generators/dart/colour.js | 120 ++-- generators/dart/lists.js | 111 +-- generators/dart/math.js | 275 ++++---- generators/dart/text.js | 144 ++-- generators/javascript/colour.js | 71 +- generators/javascript/lists.js | 93 +-- generators/javascript/math.js | 223 +++--- generators/javascript/text.js | 148 ++-- generators/lua/colour.js | 48 +- generators/lua/lists.js | 166 +++-- generators/lua/logic.js | 3 +- generators/lua/math.js | 289 ++++---- generators/lua/text.js | 215 +++--- generators/php/colour.js | 70 +- generators/php/lists.js | 198 +++--- generators/php/math.js | 147 ++-- generators/php/text.js | 124 ++-- generators/python/colour.js | 36 +- generators/python/lists.js | 68 +- generators/python/loops.js | 20 +- generators/python/math.js | 161 ++--- generators/python/text.js | 64 +- tests/generators/golden/generated.dart | 8 +- tests/generators/golden/generated.js | 12 +- tests/generators/golden/generated.lua | 15 +- tests/generators/golden/generated.php | 13 +- tests/generators/golden/generated.py | 2 +- 39 files changed, 2194 insertions(+), 2062 deletions(-) diff --git a/core/comment.js b/core/comment.js index 30f9aac36..d11e2b636 100644 --- a/core/comment.js +++ b/core/comment.js @@ -434,16 +434,16 @@ Comment.prototype.dispose = function() { * CSS for block comment. See css.js for use. */ Css.register(` - .blocklyCommentTextarea { - background-color: #fef49c; - border: 0; - display: block; - margin: 0; - outline: 0; - padding: 3px; - resize: none; - text-overflow: hidden; - } +.blocklyCommentTextarea { + background-color: #fef49c; + border: 0; + display: block; + margin: 0; + outline: 0; + padding: 3px; + resize: none; + text-overflow: hidden; +} `); exports.Comment = Comment; diff --git a/core/css.js b/core/css.js index 7cea9284f..e7ed4ec8c 100644 --- a/core/css.js +++ b/core/css.js @@ -89,480 +89,480 @@ exports.inject = inject; * @alias Blockly.Css.content */ let content = (` - .blocklySvg { - background-color: #fff; - outline: none; - overflow: hidden; /* IE overflows by default. */ - position: absolute; - display: block; - } +.blocklySvg { + background-color: #fff; + outline: none; + overflow: hidden; /* IE overflows by default. */ + position: absolute; + display: block; +} - .blocklyWidgetDiv { - display: none; - position: absolute; - z-index: 99999; /* big value for bootstrap3 compatibility */ - } +.blocklyWidgetDiv { + display: none; + position: absolute; + z-index: 99999; /* big value for bootstrap3 compatibility */ +} - .injectionDiv { - height: 100%; - position: relative; - overflow: hidden; /* So blocks in drag surface disappear at edges */ - touch-action: none; - } +.injectionDiv { + height: 100%; + position: relative; + overflow: hidden; /* So blocks in drag surface disappear at edges */ + touch-action: none; +} - .blocklyNonSelectable { - user-select: none; - -ms-user-select: none; - -webkit-user-select: none; - } +.blocklyNonSelectable { + user-select: none; + -ms-user-select: none; + -webkit-user-select: none; +} - .blocklyWsDragSurface { - display: none; - position: absolute; - top: 0; - left: 0; - } +.blocklyWsDragSurface { + display: none; + position: absolute; + top: 0; + left: 0; +} - /* Added as a separate rule with multiple classes to make it more specific - than a bootstrap rule that selects svg:root. See issue #1275 for context. +/* Added as a separate rule with multiple classes to make it more specific + than a bootstrap rule that selects svg:root. See issue #1275 for context. +*/ +.blocklyWsDragSurface.blocklyOverflowVisible { + overflow: visible; +} + +.blocklyBlockDragSurface { + display: none; + position: absolute; + top: 0; + left: 0; + right: 0; + bottom: 0; + overflow: visible !important; + z-index: 50; /* Display below toolbox, but above everything else. */ +} + +.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: 9pt sans-serif; + opacity: .9; + padding: 2px; + position: absolute; + z-index: 100000; /* big value for bootstrap3 compatibility */ +} + +.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: 0 0 3px 1px rgba(0,0,0,.3); +} + +.blocklyDropDownDiv.blocklyFocused { + box-shadow: 0 0 6px 1px rgba(0,0,0,.3); +} + +.blocklyDropDownContent { + max-height: 300px; // @todo: spec for maximum height. + overflow: auto; + overflow-x: hidden; + position: relative; +} + +.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 { + /* backup for browsers (e.g. IE11) that don't support grab */ + cursor: url("<<>>/handopen.cur"), auto; + cursor: grab; + cursor: -webkit-grab; +} + + /* backup for browsers (e.g. IE11) that don't support grabbing */ +.blocklyDragging { + /* backup for browsers (e.g. IE11) that don't support grabbing */ + cursor: url("<<>>/handclosed.cur"), auto; + cursor: grabbing; + cursor: -webkit-grabbing; +} + + /* Changes cursor on mouse down. Not effective in Firefox because of + https://bugzilla.mozilla.org/show_bug.cgi?id=771241 */ +.blocklyDraggable:active { + /* backup for browsers (e.g. IE11) that don't support grabbing */ + cursor: url("<<>>/handclosed.cur"), auto; + cursor: grabbing; + cursor: -webkit-grabbing; +} + +/* Change the cursor on the whole drag surface in case the mouse gets + ahead of block during a drag. This way the cursor is still a closed hand. */ - .blocklyWsDragSurface.blocklyOverflowVisible { - overflow: visible; - } - - .blocklyBlockDragSurface { - display: none; - position: absolute; - top: 0; - left: 0; - right: 0; - bottom: 0; - overflow: visible !important; - z-index: 50; /* Display below toolbox, but above everything else. */ - } - - .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: 9pt sans-serif; - opacity: .9; - padding: 2px; - position: absolute; - z-index: 100000; /* big value for bootstrap3 compatibility */ - } - - .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: 0 0 3px 1px rgba(0,0,0,.3); - } - - .blocklyDropDownDiv.blocklyFocused { - box-shadow: 0 0 6px 1px rgba(0,0,0,.3); - } - - .blocklyDropDownContent { - max-height: 300px; // @todo: spec for maximum height. - overflow: auto; - overflow-x: hidden; - position: relative; - } - - .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 { - /* backup for browsers (e.g. IE11) that don't support grab */ - cursor: url("<<>>/handopen.cur"), auto; - cursor: grab; - cursor: -webkit-grab; - } - - /* backup for browsers (e.g. IE11) that don't support grabbing */ - .blocklyDragging { - /* backup for browsers (e.g. IE11) that don't support grabbing */ - cursor: url("<<>>/handclosed.cur"), auto; - cursor: grabbing; - cursor: -webkit-grabbing; - } - - /* Changes cursor on mouse down. Not effective in Firefox because of - https://bugzilla.mozilla.org/show_bug.cgi?id=771241 */ - .blocklyDraggable:active { - /* backup for browsers (e.g. IE11) that don't support grabbing */ - cursor: url("<<>>/handclosed.cur"), auto; - cursor: grabbing; - cursor: -webkit-grabbing; - } - - /* Change the cursor on the whole drag surface in case the mouse gets - ahead of block during a drag. This way the cursor is still a closed hand. - */ - .blocklyBlockDragSurface .blocklyDraggable { - /* backup for browsers (e.g. IE11) that don't support grabbing */ - cursor: url("<<>>/handclosed.cur"), auto; - cursor: grabbing; - cursor: -webkit-grabbing; - } - - .blocklyDragging.blocklyDraggingDelete { - cursor: url("<<>>/handdelete.cur"), auto; - } - - .blocklyDragging>.blocklyPath, - .blocklyDragging>.blocklyPathLight { - fill-opacity: .8; - stroke-opacity: .8; - } - - .blocklyDragging>.blocklyPathDark { - display: none; - } - - .blocklyDisabled>.blocklyPath { - fill-opacity: .5; - stroke-opacity: .5; - } - - .blocklyDisabled>.blocklyPathLight, - .blocklyDisabled>.blocklyPathDark { - display: none; - } - - .blocklyInsertionMarker>.blocklyPath, - .blocklyInsertionMarker>.blocklyPathLight, - .blocklyInsertionMarker>.blocklyPathDark { - fill-opacity: .2; - stroke: none; - } - - .blocklyMultilineText { - font-family: monospace; - } - - .blocklyNonEditableText>text { - pointer-events: none; - } - - .blocklyFlyout { - position: absolute; - z-index: 20; - } - - .blocklyText text { - cursor: default; - } - - /* - Don't allow users to select text. It gets annoying when trying to - drag a block and selected text moves instead. - */ - .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; - } - - /* Edge and IE introduce a close icon when the input value is longer than a - certain length. This affects our sizing calculations of the text input. - Hiding the close icon to avoid that. */ - .blocklyHtmlInput::-ms-clear { - display: none; - } - - .blocklyMainBackground { - stroke-width: 1; - stroke: #c6c6c6; /* Equates to #ddd due to border being off-pixel. */ - } - - .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; - } - - /* Darken flyout scrollbars due to being on a grey background. */ - /* By contrast, workspace scrollbars are on a white background. */ - .blocklyFlyout .blocklyScrollbarHandle { - fill: #bbb; - } - - .blocklyFlyout .blocklyScrollbarBackground:hover+.blocklyScrollbarHandle, - .blocklyFlyout .blocklyScrollbarHandle:hover { - fill: #aaa; - } - - .blocklyInvalidInput { - background: #faa; - } - - .blocklyVerticalMarker { - stroke-width: 3px; - fill: rgba(255,255,255,.5); - pointer-events: none; - } - - .blocklyComputeCanvas { - position: absolute; - width: 0; - height: 0; - } - - .blocklyNoPointerEvents { - pointer-events: none; - } - - .blocklyContextMenu { - border-radius: 4px; - max-height: 100%; - } - - .blocklyDropdownMenu { - border-radius: 2px; - padding: 0 !important; - } - - .blocklyDropdownMenu .blocklyMenuItem { - /* 28px on the left for icon or checkbox. */ - padding-left: 28px; - } - - /* BiDi override for the resting state. */ - .blocklyDropdownMenu .blocklyMenuItemRtl { - /* Flip left/right padding for BiDi. */ - padding-left: 5px; - padding-right: 28px; - } - - .blocklyWidgetDiv .blocklyMenu { - background: #fff; - border: 1px solid transparent; - box-shadow: 0 0 3px 1px rgba(0,0,0,.3); - 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; /* Arbitrary, but some apps depend on it... */ - } - - .blocklyWidgetDiv .blocklyMenu.blocklyFocused { - box-shadow: 0 0 6px 1px rgba(0,0,0,.3); - } - - .blocklyDropDownDiv .blocklyMenu { - background: inherit; /* Compatibility with gapi, reset from goog-menu */ - border: inherit; /* Compatibility with gapi, reset from goog-menu */ - font: normal 13px "Helvetica Neue", Helvetica, sans-serif; - outline: none; - position: relative; /* Compatibility with gapi, reset from goog-menu */ - z-index: 20000; /* Arbitrary, but some apps depend on it... */ - } - - /* State: resting. */ - .blocklyMenuItem { - border: none; - color: #000; - cursor: pointer; - list-style: none; - margin: 0; - /* 7em on the right for shortcut. */ - min-width: 7em; - padding: 6px 15px; - white-space: nowrap; - } - - /* State: disabled. */ - .blocklyMenuItemDisabled { - color: #ccc; - cursor: inherit; - } - - /* State: hover. */ - .blocklyMenuItemHighlight { - background-color: rgba(0,0,0,.1); - } - - /* State: selected/checked. */ - .blocklyMenuItemCheckbox { - height: 16px; - position: absolute; - width: 16px; - } - - .blocklyMenuItemSelected .blocklyMenuItemCheckbox { - background: url(<<>>/sprites.png) no-repeat -48px -16px; - float: left; - margin-left: -24px; - position: static; /* Scroll with the menu. */ - } - - .blocklyMenuItemRtl .blocklyMenuItemCheckbox { - float: right; - margin-right: -24px; - } +.blocklyBlockDragSurface .blocklyDraggable { + /* backup for browsers (e.g. IE11) that don't support grabbing */ + cursor: url("<<>>/handclosed.cur"), auto; + cursor: grabbing; + cursor: -webkit-grabbing; +} + +.blocklyDragging.blocklyDraggingDelete { + cursor: url("<<>>/handdelete.cur"), auto; +} + +.blocklyDragging>.blocklyPath, +.blocklyDragging>.blocklyPathLight { + fill-opacity: .8; + stroke-opacity: .8; +} + +.blocklyDragging>.blocklyPathDark { + display: none; +} + +.blocklyDisabled>.blocklyPath { + fill-opacity: .5; + stroke-opacity: .5; +} + +.blocklyDisabled>.blocklyPathLight, +.blocklyDisabled>.blocklyPathDark { + display: none; +} + +.blocklyInsertionMarker>.blocklyPath, +.blocklyInsertionMarker>.blocklyPathLight, +.blocklyInsertionMarker>.blocklyPathDark { + fill-opacity: .2; + stroke: none; +} + +.blocklyMultilineText { + font-family: monospace; +} + +.blocklyNonEditableText>text { + pointer-events: none; +} + +.blocklyFlyout { + position: absolute; + z-index: 20; +} + +.blocklyText text { + cursor: default; +} + +/* + Don't allow users to select text. It gets annoying when trying to + drag a block and selected text moves instead. +*/ +.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; +} + +/* Edge and IE introduce a close icon when the input value is longer than a + certain length. This affects our sizing calculations of the text input. + Hiding the close icon to avoid that. */ +.blocklyHtmlInput::-ms-clear { + display: none; +} + +.blocklyMainBackground { + stroke-width: 1; + stroke: #c6c6c6; /* Equates to #ddd due to border being off-pixel. */ +} + +.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; +} + +/* Darken flyout scrollbars due to being on a grey background. */ +/* By contrast, workspace scrollbars are on a white background. */ +.blocklyFlyout .blocklyScrollbarHandle { + fill: #bbb; +} + +.blocklyFlyout .blocklyScrollbarBackground:hover+.blocklyScrollbarHandle, +.blocklyFlyout .blocklyScrollbarHandle:hover { + fill: #aaa; +} + +.blocklyInvalidInput { + background: #faa; +} + +.blocklyVerticalMarker { + stroke-width: 3px; + fill: rgba(255,255,255,.5); + pointer-events: none; +} + +.blocklyComputeCanvas { + position: absolute; + width: 0; + height: 0; +} + +.blocklyNoPointerEvents { + pointer-events: none; +} + +.blocklyContextMenu { + border-radius: 4px; + max-height: 100%; +} + +.blocklyDropdownMenu { + border-radius: 2px; + padding: 0 !important; +} + +.blocklyDropdownMenu .blocklyMenuItem { + /* 28px on the left for icon or checkbox. */ + padding-left: 28px; +} + +/* BiDi override for the resting state. */ +.blocklyDropdownMenu .blocklyMenuItemRtl { + /* Flip left/right padding for BiDi. */ + padding-left: 5px; + padding-right: 28px; +} + +.blocklyWidgetDiv .blocklyMenu { + background: #fff; + border: 1px solid transparent; + box-shadow: 0 0 3px 1px rgba(0,0,0,.3); + 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; /* Arbitrary, but some apps depend on it... */ +} + +.blocklyWidgetDiv .blocklyMenu.blocklyFocused { + box-shadow: 0 0 6px 1px rgba(0,0,0,.3); +} + +.blocklyDropDownDiv .blocklyMenu { + background: inherit; /* Compatibility with gapi, reset from goog-menu */ + border: inherit; /* Compatibility with gapi, reset from goog-menu */ + font: normal 13px "Helvetica Neue", Helvetica, sans-serif; + outline: none; + position: relative; /* Compatibility with gapi, reset from goog-menu */ + z-index: 20000; /* Arbitrary, but some apps depend on it... */ +} + +/* State: resting. */ +.blocklyMenuItem { + border: none; + color: #000; + cursor: pointer; + list-style: none; + margin: 0; + /* 7em on the right for shortcut. */ + min-width: 7em; + padding: 6px 15px; + white-space: nowrap; +} + +/* State: disabled. */ +.blocklyMenuItemDisabled { + color: #ccc; + cursor: inherit; +} + +/* State: hover. */ +.blocklyMenuItemHighlight { + background-color: rgba(0,0,0,.1); +} + +/* State: selected/checked. */ +.blocklyMenuItemCheckbox { + height: 16px; + position: absolute; + width: 16px; +} + +.blocklyMenuItemSelected .blocklyMenuItemCheckbox { + background: url(<<>>/sprites.png) no-repeat -48px -16px; + float: left; + margin-left: -24px; + position: static; /* Scroll with the menu. */ +} + +.blocklyMenuItemRtl .blocklyMenuItemCheckbox { + float: right; + margin-right: -24px; +} `); exports.content = content; diff --git a/core/field_angle.js b/core/field_angle.js index 8454f7900..bfc5843ea 100644 --- a/core/field_angle.js +++ b/core/field_angle.js @@ -540,30 +540,30 @@ FieldAngle.prototype.wrapValue_ = function(value) { * CSS for angle field. See css.js for use. */ Css.register(` - .blocklyAngleCircle { - stroke: #444; - stroke-width: 1; - fill: #ddd; - fill-opacity: .8; - } +.blocklyAngleCircle { + stroke: #444; + stroke-width: 1; + fill: #ddd; + fill-opacity: .8; +} - .blocklyAngleMarks { - stroke: #444; - stroke-width: 1; - } +.blocklyAngleMarks { + stroke: #444; + stroke-width: 1; +} - .blocklyAngleGauge { - fill: #f88; - fill-opacity: .8; - pointer-events: none; - } +.blocklyAngleGauge { + fill: #f88; + fill-opacity: .8; + pointer-events: none; +} - .blocklyAngleLine { - stroke: #f00; - stroke-width: 2; - stroke-linecap: round; - pointer-events: none; - } +.blocklyAngleLine { + stroke: #f00; + stroke-width: 2; + stroke-linecap: round; + pointer-events: none; +} `); fieldRegistry.register('field_angle', FieldAngle); diff --git a/core/field_colour.js b/core/field_colour.js index 4b4c037a9..a769844ef 100644 --- a/core/field_colour.js +++ b/core/field_colour.js @@ -668,34 +668,34 @@ FieldColour.prototype.dropdownDispose_ = function() { * CSS for colour picker. See css.js for use. */ Css.register(` - .blocklyColourTable { - border-collapse: collapse; - display: block; - outline: none; - padding: 1px; - } +.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 { + 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; - } +.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; - } +.blocklyColourSelected, .blocklyColourSelected:hover { + border-color: #eee !important; + outline: 1px solid #333; + position: relative; +} `); fieldRegistry.register('field_colour', FieldColour); diff --git a/core/field_multilineinput.js b/core/field_multilineinput.js index 5496bdef8..9f7899d6c 100644 --- a/core/field_multilineinput.js +++ b/core/field_multilineinput.js @@ -431,17 +431,17 @@ FieldMultilineInput.prototype.onHtmlInputKeyDown_ = function(e) { * CSS for multiline field. See css.js for use. */ Css.register(` - .blocklyHtmlTextAreaInput { - font-family: monospace; - resize: none; - overflow: hidden; - height: 100%; - text-align: left; - } +.blocklyHtmlTextAreaInput { + font-family: monospace; + resize: none; + overflow: hidden; + height: 100%; + text-align: left; +} - .blocklyHtmlTextAreaInputOverflowedY { - overflow-y: scroll; - } +.blocklyHtmlTextAreaInputOverflowedY { + overflow-y: scroll; +} `); fieldRegistry.register('field_multilinetext', FieldMultilineInput); diff --git a/core/flyout_button.js b/core/flyout_button.js index 427f2b694..e85a0b1ed 100644 --- a/core/flyout_button.js +++ b/core/flyout_button.js @@ -331,26 +331,26 @@ FlyoutButton.TEXT_MARGIN_Y = 2; * CSS for buttons and labels. See css.js for use. */ Css.register(` - .blocklyFlyoutButton { - fill: #888; - cursor: default; - } +.blocklyFlyoutButton { + fill: #888; + cursor: default; +} - .blocklyFlyoutButtonShadow { - fill: #666; - } +.blocklyFlyoutButtonShadow { + fill: #666; +} - .blocklyFlyoutButton:hover { - fill: #aaa; - } +.blocklyFlyoutButton:hover { + fill: #aaa; +} - .blocklyFlyoutLabel { - cursor: default; - } +.blocklyFlyoutLabel { + cursor: default; +} - .blocklyFlyoutLabelBackground { - opacity: 0; - } +.blocklyFlyoutLabelBackground { + opacity: 0; +} `); exports.FlyoutButton = FlyoutButton; diff --git a/core/generator.js b/core/generator.js index 55b7f9095..15be91bd4 100644 --- a/core/generator.js +++ b/core/generator.js @@ -459,7 +459,8 @@ Object.defineProperties(Generator.prototype, { * * @param {string} desiredName The desired name of the function * (e.g. mathIsPrime). - * @param {!Array} code A list of statements. Use ' ' for indents. + * @param {!Array|string} code A list of statements or one multi-line + * code string. Use ' ' for indents (they will be replaced). * @return {string} The actual name of the new function. This may differ * from desiredName if the former has already been taken by the user. * @protected @@ -469,7 +470,10 @@ Generator.prototype.provideFunction_ = function(desiredName, code) { const functionName = this.nameDB_.getDistinctName(desiredName, NameType.PROCEDURE); this.functionNames_[desiredName] = functionName; - let codeText = code.join('\n').replace( + if (Array.isArray(code)) { + code = code.join('\n'); + } + let codeText = code.trim().replace( this.FUNCTION_NAME_PLACEHOLDER_REGEXP_, functionName); // Change all ' ' indents into the desired indent. // To avoid an infinite loop of replacements, change all indents to '\0' diff --git a/core/toolbox/category.js b/core/toolbox/category.js index 286be4011..97df680f3 100644 --- a/core/toolbox/category.js +++ b/core/toolbox/category.js @@ -645,77 +645,77 @@ ToolboxCategory.prototype.dispose = function() { * CSS for Toolbox. See css.js for use. */ Css.register(` - .blocklyTreeRow:not(.blocklyTreeSelected):hover { - background-color: rgba(255, 255, 255, 0.2); - } +.blocklyTreeRow:not(.blocklyTreeSelected):hover { + background-color: rgba(255, 255, 255, .2); +} - .blocklyToolboxDiv[layout="h"] .blocklyToolboxCategory { - margin: 1px 5px 1px 0; - } +.blocklyToolboxDiv[layout="h"] .blocklyToolboxCategory { + margin: 1px 5px 1px 0; +} - .blocklyToolboxDiv[dir="RTL"][layout="h"] .blocklyToolboxCategory { - margin: 1px 0 1px 5px; - } +.blocklyToolboxDiv[dir="RTL"][layout="h"] .blocklyToolboxCategory { + margin: 1px 0 1px 5px; +} - .blocklyTreeRow { - height: 22px; - line-height: 22px; - margin-bottom: 3px; - padding-right: 8px; - white-space: nowrap; - } +.blocklyTreeRow { + height: 22px; + line-height: 22px; + margin-bottom: 3px; + padding-right: 8px; + white-space: nowrap; +} - .blocklyToolboxDiv[dir="RTL"] .blocklyTreeRow { - margin-left: 8px; - padding-right: 0; - } +.blocklyToolboxDiv[dir="RTL"] .blocklyTreeRow { + margin-left: 8px; + padding-right: 0; +} - .blocklyTreeIcon { - background-image: url(<<>>/sprites.png); - height: 16px; - vertical-align: middle; - visibility: hidden; - width: 16px; - } +.blocklyTreeIcon { + background-image: url(<<>>/sprites.png); + height: 16px; + vertical-align: middle; + visibility: hidden; + width: 16px; +} - .blocklyTreeIconClosed { - background-position: -32px -1px; - } +.blocklyTreeIconClosed { + background-position: -32px -1px; +} - .blocklyToolboxDiv[dir="RTL"] .blocklyTreeIconClosed { - background-position: 0 -1px; - } +.blocklyToolboxDiv[dir="RTL"] .blocklyTreeIconClosed { + background-position: 0 -1px; +} - .blocklyTreeSelected>.blocklyTreeIconClosed { - background-position: -32px -17px; - } +.blocklyTreeSelected>.blocklyTreeIconClosed { + background-position: -32px -17px; +} - .blocklyToolboxDiv[dir="RTL"] .blocklyTreeSelected>.blocklyTreeIconClosed { - background-position: 0 -17px; - } +.blocklyToolboxDiv[dir="RTL"] .blocklyTreeSelected>.blocklyTreeIconClosed { + background-position: 0 -17px; +} - .blocklyTreeIconOpen { - background-position: -16px -1px; - } +.blocklyTreeIconOpen { + background-position: -16px -1px; +} - .blocklyTreeSelected>.blocklyTreeIconOpen { - background-position: -16px -17px; - } +.blocklyTreeSelected>.blocklyTreeIconOpen { + background-position: -16px -17px; +} - .blocklyTreeLabel { - cursor: default; - font: 16px sans-serif; - padding: 0 3px; - vertical-align: middle; - } +.blocklyTreeLabel { + cursor: default; + font: 16px sans-serif; + padding: 0 3px; + vertical-align: middle; +} - .blocklyToolboxDelete .blocklyTreeLabel { - cursor: url("<<>>/handdelete.cur"), auto; - } +.blocklyToolboxDelete .blocklyTreeLabel { + cursor: url("<<>>/handdelete.cur"), auto; +} - .blocklyTreeSelected .blocklyTreeLabel { - color: #fff; - } +.blocklyTreeSelected .blocklyTreeLabel { + color: #fff; +} `); registry.register( diff --git a/core/toolbox/separator.js b/core/toolbox/separator.js index 9d82dc246..c9fb6f391 100644 --- a/core/toolbox/separator.js +++ b/core/toolbox/separator.js @@ -101,20 +101,20 @@ ToolboxSeparator.prototype.dispose = function() { * CSS for Toolbox. See css.js for use. */ Css.register(` - .blocklyTreeSeparator { - border-bottom: solid #e5e5e5 1px; - height: 0; - margin: 5px 0; - } +.blocklyTreeSeparator { + border-bottom: solid #e5e5e5 1px; + height: 0; + margin: 5px 0; +} - .blocklyToolboxDiv[layout="h"] .blocklyTreeSeparator { - border-right: solid #e5e5e5 1px; - border-bottom: none; - height: auto; - margin: 0 5px 0 5px; - padding: 5px 0; - width: 0; - } +.blocklyToolboxDiv[layout="h"] .blocklyTreeSeparator { + border-right: solid #e5e5e5 1px; + border-bottom: none; + height: auto; + margin: 0 5px 0 5px; + padding: 5px 0; + width: 0; +} `); registry.register( diff --git a/core/toolbox/toolbox.js b/core/toolbox/toolbox.js index 438a3b4a3..a31174d4a 100644 --- a/core/toolbox/toolbox.js +++ b/core/toolbox/toolbox.js @@ -1116,36 +1116,36 @@ Toolbox.prototype.dispose = function() { * CSS for Toolbox. See css.js for use. */ Css.register(` - .blocklyToolboxDelete { - cursor: url("<<>>/handdelete.cur"), auto; - } +.blocklyToolboxDelete { + cursor: url("<<>>/handdelete.cur"), auto; +} - .blocklyToolboxGrab { - cursor: url("<<>>/handclosed.cur"), auto; - cursor: grabbing; - cursor: -webkit-grabbing; - } +.blocklyToolboxGrab { + cursor: url("<<>>/handclosed.cur"), auto; + cursor: grabbing; + cursor: -webkit-grabbing; +} - /* Category tree in Toolbox. */ - .blocklyToolboxDiv { - background-color: #ddd; - overflow-x: visible; - overflow-y: auto; - padding: 4px 0 4px 0; - position: absolute; - z-index: 70; /* so blocks go under toolbox when dragging */ - -webkit-tap-highlight-color: transparent; /* issue #1345 */ - } +/* Category tree in Toolbox. */ +.blocklyToolboxDiv { + background-color: #ddd; + overflow-x: visible; + overflow-y: auto; + padding: 4px 0 4px 0; + position: absolute; + z-index: 70; /* so blocks go under toolbox when dragging */ + -webkit-tap-highlight-color: transparent; /* issue #1345 */ +} - .blocklyToolboxContents { - display: flex; - flex-wrap: wrap; - flex-direction: column; - } +.blocklyToolboxContents { + display: flex; + flex-wrap: wrap; + flex-direction: column; +} - .blocklyToolboxContents:focus { - outline: none; - } +.blocklyToolboxContents:focus { + outline: none; +} `); registry.register(registry.Type.TOOLBOX, registry.DEFAULT, Toolbox); diff --git a/core/workspace_comment_svg.js b/core/workspace_comment_svg.js index 24d0461bc..b06276c75 100644 --- a/core/workspace_comment_svg.js +++ b/core/workspace_comment_svg.js @@ -1084,63 +1084,63 @@ WorkspaceCommentSvg.prototype.blurFocus = function() { * CSS for workspace comment. See css.js for use. */ Css.register(` - .blocklyCommentForeignObject { - position: relative; - z-index: 0; - } +.blocklyCommentForeignObject { + position: relative; + z-index: 0; +} - .blocklyCommentRect { - fill: #E7DE8E; - stroke: #bcA903; - stroke-width: 1px; - } +.blocklyCommentRect { + fill: #E7DE8E; + stroke: #bcA903; + stroke-width: 1px; +} - .blocklyCommentTarget { - fill: transparent; - stroke: #bcA903; - } +.blocklyCommentTarget { + fill: transparent; + stroke: #bcA903; +} - .blocklyCommentTargetFocused { - fill: none; - } +.blocklyCommentTargetFocused { + fill: none; +} - .blocklyCommentHandleTarget { - fill: none; - } +.blocklyCommentHandleTarget { + fill: none; +} - .blocklyCommentHandleTargetFocused { - fill: transparent; - } +.blocklyCommentHandleTargetFocused { + fill: transparent; +} - .blocklyFocused>.blocklyCommentRect { - fill: #B9B272; - stroke: #B9B272; - } +.blocklyFocused>.blocklyCommentRect { + fill: #B9B272; + stroke: #B9B272; +} - .blocklySelected>.blocklyCommentTarget { - stroke: #fc3; - stroke-width: 3px; - } +.blocklySelected>.blocklyCommentTarget { + stroke: #fc3; + stroke-width: 3px; +} - .blocklyCommentDeleteIcon { - cursor: pointer; - fill: #000; - display: none; - } +.blocklyCommentDeleteIcon { + cursor: pointer; + fill: #000; + display: none; +} - .blocklySelected > .blocklyCommentDeleteIcon { - display: block; - } +.blocklySelected > .blocklyCommentDeleteIcon { + display: block; +} - .blocklyDeleteIconShape { - fill: #000; - stroke: #000; - stroke-width: 1px; - } +.blocklyDeleteIconShape { + fill: #000; + stroke: #000; + stroke-width: 1px; +} - .blocklyDeleteIconShape.blocklyDeleteIconHighlighted { - stroke: #fc3; - } +.blocklyDeleteIconShape.blocklyDeleteIconHighlighted { + stroke: #fc3; +} `); exports.WorkspaceCommentSvg = WorkspaceCommentSvg; diff --git a/core/zoom_controls.js b/core/zoom_controls.js index 3235a8e98..417d65181 100644 --- a/core/zoom_controls.js +++ b/core/zoom_controls.js @@ -491,17 +491,17 @@ class ZoomControls { * CSS for zoom controls. See css.js for use. */ Css.register(` - .blocklyZoom>image, .blocklyZoom>svg>image { - opacity: .4; - } +.blocklyZoom>image, .blocklyZoom>svg>image { + opacity: .4; +} - .blocklyZoom>image:hover, .blocklyZoom>svg>image:hover { - opacity: .6; - } +.blocklyZoom>image:hover, .blocklyZoom>svg>image:hover { + opacity: .6; +} - .blocklyZoom>image:active, .blocklyZoom>svg>image:active { - opacity: .8; - } +.blocklyZoom>image:active, .blocklyZoom>svg>image:active { + opacity: .8; +} `); exports.ZoomControls = ZoomControls; diff --git a/generators/dart/colour.js b/generators/dart/colour.js index 7f6f621ac..96aeaea51 100644 --- a/generators/dart/colour.js +++ b/generators/dart/colour.js @@ -24,17 +24,16 @@ Dart['colour_picker'] = function(block) { Dart['colour_random'] = function(block) { // Generate a random colour. - Dart.definitions_['import_dart_math'] = - 'import \'dart:math\' as Math;'; - const functionName = Dart.provideFunction_( - 'colour_random', - ['String ' + Dart.FUNCTION_NAME_PLACEHOLDER_ + '() {', - ' String hex = \'0123456789abcdef\';', - ' var rnd = new Math.Random();', - ' return \'#${hex[rnd.nextInt(16)]}${hex[rnd.nextInt(16)]}\'', - ' \'${hex[rnd.nextInt(16)]}${hex[rnd.nextInt(16)]}\'', - ' \'${hex[rnd.nextInt(16)]}${hex[rnd.nextInt(16)]}\';', - '}']); + Dart.definitions_['import_dart_math'] = "import 'dart:math' as Math;"; + const functionName = Dart.provideFunction_('colour_random', ` +String ${Dart.FUNCTION_NAME_PLACEHOLDER_}() { + String hex = '0123456789abcdef'; + var rnd = new Math.Random(); + return '#\${hex[rnd.nextInt(16)]}\${hex[rnd.nextInt(16)]}' + '\${hex[rnd.nextInt(16)]}\${hex[rnd.nextInt(16)]}' + '\${hex[rnd.nextInt(16)]}\${hex[rnd.nextInt(16)]}'; +} +`); const code = functionName + '()'; return [code, Dart.ORDER_UNARY_POSTFIX]; }; @@ -48,66 +47,59 @@ Dart['colour_rgb'] = function(block) { const blue = Dart.valueToCode(block, 'BLUE', Dart.ORDER_NONE) || 0; - Dart.definitions_['import_dart_math'] = - 'import \'dart:math\' as Math;'; - const functionName = Dart.provideFunction_( - 'colour_rgb', - ['String ' + Dart.FUNCTION_NAME_PLACEHOLDER_ + - '(num r, num g, num b) {', - ' num rn = (Math.max(Math.min(r, 100), 0) * 2.55).round();', - ' String rs = rn.toInt().toRadixString(16);', - ' rs = \'0$rs\';', - ' rs = rs.substring(rs.length - 2);', - ' num gn = (Math.max(Math.min(g, 100), 0) * 2.55).round();', - ' String gs = gn.toInt().toRadixString(16);', - ' gs = \'0$gs\';', - ' gs = gs.substring(gs.length - 2);', - ' num bn = (Math.max(Math.min(b, 100), 0) * 2.55).round();', - ' String bs = bn.toInt().toRadixString(16);', - ' bs = \'0$bs\';', - ' bs = bs.substring(bs.length - 2);', - ' return \'#$rs$gs$bs\';', - '}']); + Dart.definitions_['import_dart_math'] = "import 'dart:math' as Math;"; + const functionName = Dart.provideFunction_('colour_rgb', ` +String ${Dart.FUNCTION_NAME_PLACEHOLDER_}(num r, num g, num b) { + num rn = (Math.max(Math.min(r, 100), 0) * 2.55).round(); + String rs = rn.toInt().toRadixString(16); + rs = '0$rs'; + rs = rs.substring(rs.length - 2); + num gn = (Math.max(Math.min(g, 100), 0) * 2.55).round(); + String gs = gn.toInt().toRadixString(16); + gs = '0$gs'; + gs = gs.substring(gs.length - 2); + num bn = (Math.max(Math.min(b, 100), 0) * 2.55).round(); + String bs = bn.toInt().toRadixString(16); + bs = '0$bs'; + bs = bs.substring(bs.length - 2); + return '#$rs$gs$bs'; +} +`); const code = functionName + '(' + red + ', ' + green + ', ' + blue + ')'; return [code, Dart.ORDER_UNARY_POSTFIX]; }; Dart['colour_blend'] = function(block) { // Blend two colours together. - const c1 = Dart.valueToCode(block, 'COLOUR1', - Dart.ORDER_NONE) || '\'#000000\''; - const c2 = Dart.valueToCode(block, 'COLOUR2', - Dart.ORDER_NONE) || '\'#000000\''; - const ratio = Dart.valueToCode(block, 'RATIO', - Dart.ORDER_NONE) || 0.5; + const c1 = Dart.valueToCode(block, 'COLOUR1', Dart.ORDER_NONE) || "'#000000'"; + const c2 = Dart.valueToCode(block, 'COLOUR2', Dart.ORDER_NONE) || "'#000000'"; + const ratio = Dart.valueToCode(block, 'RATIO', Dart.ORDER_NONE) || 0.5; - Dart.definitions_['import_dart_math'] = - 'import \'dart:math\' as Math;'; - const functionName = Dart.provideFunction_( - 'colour_blend', - ['String ' + Dart.FUNCTION_NAME_PLACEHOLDER_ + - '(String c1, String c2, num ratio) {', - ' ratio = Math.max(Math.min(ratio, 1), 0);', - ' int r1 = int.parse(\'0x${c1.substring(1, 3)}\');', - ' int g1 = int.parse(\'0x${c1.substring(3, 5)}\');', - ' int b1 = int.parse(\'0x${c1.substring(5, 7)}\');', - ' int r2 = int.parse(\'0x${c2.substring(1, 3)}\');', - ' int g2 = int.parse(\'0x${c2.substring(3, 5)}\');', - ' int b2 = int.parse(\'0x${c2.substring(5, 7)}\');', - ' num rn = (r1 * (1 - ratio) + r2 * ratio).round();', - ' String rs = rn.toInt().toRadixString(16);', - ' num gn = (g1 * (1 - ratio) + g2 * ratio).round();', - ' String gs = gn.toInt().toRadixString(16);', - ' num bn = (b1 * (1 - ratio) + b2 * ratio).round();', - ' String bs = bn.toInt().toRadixString(16);', - ' rs = \'0$rs\';', - ' rs = rs.substring(rs.length - 2);', - ' gs = \'0$gs\';', - ' gs = gs.substring(gs.length - 2);', - ' bs = \'0$bs\';', - ' bs = bs.substring(bs.length - 2);', - ' return \'#$rs$gs$bs\';', - '}']); + Dart.definitions_['import_dart_math'] = "import 'dart:math' as Math;"; + const functionName = Dart.provideFunction_('colour_blend', ` +String ${Dart.FUNCTION_NAME_PLACEHOLDER_}(String c1, String c2, num ratio) { + ratio = Math.max(Math.min(ratio, 1), 0); + int r1 = int.parse('0x\${c1.substring(1, 3)}'); + int g1 = int.parse('0x\${c1.substring(3, 5)}'); + int b1 = int.parse('0x\${c1.substring(5, 7)}'); + int r2 = int.parse('0x\${c2.substring(1, 3)}'); + int g2 = int.parse('0x\${c2.substring(3, 5)}'); + int b2 = int.parse('0x\${c2.substring(5, 7)}'); + num rn = (r1 * (1 - ratio) + r2 * ratio).round(); + String rs = rn.toInt().toRadixString(16); + num gn = (g1 * (1 - ratio) + g2 * ratio).round(); + String gs = gn.toInt().toRadixString(16); + num bn = (b1 * (1 - ratio) + b2 * ratio).round(); + String bs = bn.toInt().toRadixString(16); + rs = '0$rs'; + rs = rs.substring(rs.length - 2); + gs = '0$gs'; + gs = gs.substring(gs.length - 2); + bs = '0$bs'; + bs = bs.substring(bs.length - 2); + return '#$rs$gs$bs'; +} +`); const code = functionName + '(' + c1 + ', ' + c2 + ', ' + ratio + ')'; return [code, Dart.ORDER_UNARY_POSTFIX]; }; diff --git a/generators/dart/lists.js b/generators/dart/lists.js index 5eefea91b..493cd7a83 100644 --- a/generators/dart/lists.js +++ b/generators/dart/lists.js @@ -58,7 +58,7 @@ Dart['lists_indexOf'] = function(block) { // Find an item in the list. const operator = block.getFieldValue('END') === 'FIRST' ? 'indexOf' : 'lastIndexOf'; - const item = Dart.valueToCode(block, 'FIND', Dart.ORDER_NONE) || '\'\''; + const item = Dart.valueToCode(block, 'FIND', Dart.ORDER_NONE) || "''"; const list = Dart.valueToCode(block, 'VALUE', Dart.ORDER_UNARY_POSTFIX) || '[]'; const code = list + '.' + operator + '(' + item + ')'; @@ -112,21 +112,23 @@ Dart['lists_getIndex'] = function(block) { } else if (mode === 'GET') { const at = Dart.getAdjusted(block, 'AT', 1); // We need to create a procedure to avoid reevaluating values. - const functionName = Dart.provideFunction_('lists_get_from_end', [ - 'dynamic ' + Dart.FUNCTION_NAME_PLACEHOLDER_ + - '(List my_list, num x) {', - ' x = my_list.length - x;', ' return my_list[x];', '}' - ]); + const functionName = Dart.provideFunction_('lists_get_from_end', ` +dynamic ${Dart.FUNCTION_NAME_PLACEHOLDER_}(List my_list, num x) { + x = my_list.length - x; + return my_list[x]; +} +`); const code = functionName + '(' + list + ', ' + at + ')'; return [code, Dart.ORDER_UNARY_POSTFIX]; } else if (mode === 'GET_REMOVE') { const at = Dart.getAdjusted(block, 'AT', 1); // We need to create a procedure to avoid reevaluating values. - const functionName = Dart.provideFunction_('lists_remove_from_end', [ - 'dynamic ' + Dart.FUNCTION_NAME_PLACEHOLDER_ + - '(List my_list, num x) {', - ' x = my_list.length - x;', ' return my_list.removeAt(x);', '}' - ]); + const functionName = Dart.provideFunction_('lists_remove_from_end', ` +dynamic ${Dart.FUNCTION_NAME_PLACEHOLDER_}(List my_list, num x) { + x = my_list.length - x; + return my_list.removeAt(x); +} +`); const code = functionName + '(' + list + ', ' + at + ')'; return [code, Dart.ORDER_UNARY_POSTFIX]; } @@ -195,21 +197,22 @@ Dart['lists_getIndex'] = function(block) { code += list + '.removeAt(' + xVar + ');\n'; return code; } else if (mode === 'GET') { - const functionName = Dart.provideFunction_('lists_get_random_item', [ - 'dynamic ' + Dart.FUNCTION_NAME_PLACEHOLDER_ + '(List my_list) {', - ' int x = new Math.Random().nextInt(my_list.length);', - ' return my_list[x];', '}' - ]); + const functionName = Dart.provideFunction_('lists_get_random_item', ` +dynamic ${Dart.FUNCTION_NAME_PLACEHOLDER_}(List my_list) { + int x = new Math.Random().nextInt(my_list.length); + return my_list[x]; +} +`); const code = functionName + '(' + list + ')'; return [code, Dart.ORDER_UNARY_POSTFIX]; } else if (mode === 'GET_REMOVE') { const functionName = - Dart.provideFunction_('lists_remove_random_item', [ - 'dynamic ' + Dart.FUNCTION_NAME_PLACEHOLDER_ + - '(List my_list) {', - ' int x = new Math.Random().nextInt(my_list.length);', - ' return my_list.removeAt(x);', '}' - ]); + Dart.provideFunction_('lists_remove_random_item', ` +dynamic ${Dart.FUNCTION_NAME_PLACEHOLDER_}(List my_list) { + int x = new Math.Random().nextInt(my_list.length); + return my_list.removeAt(x); +} +`); const code = functionName + '(' + list + ')'; return [code, Dart.ORDER_UNARY_POSTFIX]; } @@ -344,18 +347,25 @@ Dart['lists_getSublist'] = function(block) { } else { const at1 = Dart.getAdjusted(block, 'AT1'); const at2 = Dart.getAdjusted(block, 'AT2'); - const functionName = Dart.provideFunction_('lists_get_sublist', [ - 'List ' + Dart.FUNCTION_NAME_PLACEHOLDER_ + - '(List list, String where1, num at1, String where2, num at2) {', - ' int getAt(String where, num at) {', ' if (where == \'FROM_END\') {', - ' at = list.length - 1 - at;', - ' } else if (where == \'FIRST\') {', ' at = 0;', - ' } else if (where == \'LAST\') {', ' at = list.length - 1;', - ' } else if (where != \'FROM_START\') {', - ' throw \'Unhandled option (lists_getSublist).\';', ' }', - ' return at;', ' }', ' at1 = getAt(where1, at1);', - ' at2 = getAt(where2, at2) + 1;', ' return list.sublist(at1, at2);', '}' - ]); + const functionName = Dart.provideFunction_('lists_get_sublist', ` +List ${Dart.FUNCTION_NAME_PLACEHOLDER_}(List list, String where1, num at1, String where2, num at2) { + int getAt(String where, num at) { + if (where == 'FROM_END') { + at = list.length - 1 - at; + } else if (where == 'FIRST') { + at = 0; + } else if (where == 'LAST') { + at = list.length - 1; + } else if (where != 'FROM_START') { + throw 'Unhandled option (lists_getSublist).'; + } + return at; + } + at1 = getAt(where1, at1); + at2 = getAt(where2, at2) + 1; + return list.sublist(at1, at2); +} +`); code = functionName + '(' + list + ', \'' + where1 + '\', ' + at1 + ', \'' + where2 + '\', ' + at2 + ')'; } @@ -367,20 +377,21 @@ Dart['lists_sort'] = function(block) { const list = Dart.valueToCode(block, 'LIST', Dart.ORDER_NONE) || '[]'; const direction = block.getFieldValue('DIRECTION') === '1' ? 1 : -1; const type = block.getFieldValue('TYPE'); - const sortFunctionName = Dart.provideFunction_('lists_sort', [ - 'List ' + Dart.FUNCTION_NAME_PLACEHOLDER_ + - '(List list, String type, int direction) {', - ' var compareFuncs = {', - ' "NUMERIC": (a, b) => (direction * a.compareTo(b)).toInt(),', - ' "TEXT": (a, b) => direction * ' + - 'a.toString().compareTo(b.toString()),', - ' "IGNORE_CASE": ', ' (a, b) => direction * ', - ' a.toString().toLowerCase().compareTo(b.toString().toLowerCase())', - ' };', - ' list = new List.from(list);', // Clone the list. - ' var compare = compareFuncs[type];', ' list.sort(compare);', - ' return list;', '}' - ]); + const sortFunctionName = Dart.provideFunction_('lists_sort', ` +List ${Dart.FUNCTION_NAME_PLACEHOLDER_}(List list, String type, int direction) { + var compareFuncs = { + 'NUMERIC': (a, b) => (direction * a.compareTo(b)).toInt(), + 'TEXT': (a, b) => direction * a.toString().compareTo(b.toString()), + 'IGNORE_CASE': + (a, b) => direction * + a.toString().toLowerCase().compareTo(b.toString().toLowerCase()) + }; + list = new List.from(list); + var compare = compareFuncs[type]; + list.sort(compare); + return list; +} +`); return [ sortFunctionName + '(' + list + ', ' + '"' + type + '", ' + direction + ')', @@ -391,12 +402,12 @@ Dart['lists_sort'] = function(block) { Dart['lists_split'] = function(block) { // Block for splitting text into a list, or joining a list into text. let input = Dart.valueToCode(block, 'INPUT', Dart.ORDER_UNARY_POSTFIX); - const delimiter = Dart.valueToCode(block, 'DELIM', Dart.ORDER_NONE) || '\'\''; + const delimiter = Dart.valueToCode(block, 'DELIM', Dart.ORDER_NONE) || "''"; const mode = block.getFieldValue('MODE'); let functionName; if (mode === 'SPLIT') { if (!input) { - input = '\'\''; + input = "''"; } functionName = 'split'; } else if (mode === 'JOIN') { diff --git a/generators/dart/math.js b/generators/dart/math.js index ab2d0cc50..24c42c2ae 100644 --- a/generators/dart/math.js +++ b/generators/dart/math.js @@ -42,7 +42,7 @@ Dart['math_arithmetic'] = function(block) { 'MINUS': [' - ', Dart.ORDER_ADDITIVE], 'MULTIPLY': [' * ', Dart.ORDER_MULTIPLICATIVE], 'DIVIDE': [' / ', Dart.ORDER_MULTIPLICATIVE], - 'POWER': [null, Dart.ORDER_NONE] // Handle power separately. + 'POWER': [null, Dart.ORDER_NONE], // Handle power separately. }; const tuple = OPERATORS[block.getFieldValue('OP')]; const operator = tuple[0]; @@ -152,7 +152,7 @@ Dart['math_constant'] = function(block) { 'GOLDEN_RATIO': ['(1 + Math.sqrt(5)) / 2', Dart.ORDER_MULTIPLICATIVE], 'SQRT2': ['Math.sqrt2', Dart.ORDER_UNARY_POSTFIX], 'SQRT1_2': ['Math.sqrt1_2', Dart.ORDER_UNARY_POSTFIX], - 'INFINITY': ['double.infinity', Dart.ORDER_ATOMIC] + 'INFINITY': ['double.infinity', Dart.ORDER_ATOMIC], }; const constant = block.getFieldValue('CONSTANT'); if (constant !== 'INFINITY') { @@ -165,20 +165,13 @@ Dart['math_number_property'] = function(block) { // Check if a number is even, odd, prime, whole, positive, or negative // or if it is divisible by certain number. Returns true or false. const PROPERTIES = { - 'EVEN': [' % 2 == 0', Dart.ORDER_MULTIPLICATIVE, - Dart.ORDER_EQUALITY], - 'ODD': [' % 2 == 1', Dart.ORDER_MULTIPLICATIVE, - Dart.ORDER_EQUALITY], - 'WHOLE': [' % 1 == 0', Dart.ORDER_MULTIPLICATIVE, - Dart.ORDER_EQUALITY], - 'POSITIVE': [' > 0', Dart.ORDER_RELATIONAL, - Dart.ORDER_RELATIONAL], - 'NEGATIVE': [' < 0', Dart.ORDER_RELATIONAL, - Dart.ORDER_RELATIONAL], - 'DIVISIBLE_BY': [null, Dart.ORDER_MULTIPLICATIVE, - Dart.ORDER_EQUALITY], - 'PRIME': [null, Dart.ORDER_NONE, - Dart.ORDER_UNARY_POSTFIX] + 'EVEN': [' % 2 == 0', Dart.ORDER_MULTIPLICATIVE, Dart.ORDER_EQUALITY], + 'ODD': [' % 2 == 1', Dart.ORDER_MULTIPLICATIVE, Dart.ORDER_EQUALITY], + 'WHOLE': [' % 1 == 0', Dart.ORDER_MULTIPLICATIVE, Dart.ORDER_EQUALITY], + 'POSITIVE': [' > 0', Dart.ORDER_RELATIONAL, Dart.ORDER_RELATIONAL], + 'NEGATIVE': [' < 0', Dart.ORDER_RELATIONAL, Dart.ORDER_RELATIONAL], + 'DIVISIBLE_BY': [null, Dart.ORDER_MULTIPLICATIVE, Dart.ORDER_EQUALITY], + 'PRIME': [null, Dart.ORDER_NONE, Dart.ORDER_UNARY_POSTFIX], }; const dropdownProperty = block.getFieldValue('PROPERTY'); const [suffix, inputOrder, outputOrder] = PROPERTIES[dropdownProperty]; @@ -189,27 +182,26 @@ Dart['math_number_property'] = function(block) { // Prime is a special case as it is not a one-liner test. Dart.definitions_['import_dart_math'] = 'import \'dart:math\' as Math;'; - const functionName = Dart.provideFunction_( - 'math_isPrime', - ['bool ' + Dart.FUNCTION_NAME_PLACEHOLDER_ + '(n) {', - ' // https://en.wikipedia.org/wiki/Primality_test#Naive_methods', - ' if (n == 2 || n == 3) {', - ' return true;', - ' }', - ' // False if n is null, negative, is 1, or not whole.', - ' // And false if n is divisible by 2 or 3.', - ' if (n == null || 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;', - '}']); + const functionName = Dart.provideFunction_('math_isPrime', ` +bool ${Dart.FUNCTION_NAME_PLACEHOLDER_}(n) { + // https://en.wikipedia.org/wiki/Primality_test#Naive_methods + if (n == 2 || n == 3) { + return true; + } + // False if n is null, negative, is 1, or not whole. + // And false if n is divisible by 2 or 3. + if (n == null || 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; +} +`); code = functionName + '(' + numberToCheck + ')'; } else if (dropdownProperty === 'DIVISIBLE_BY') { const divisor = Dart.valueToCode(block, 'DIVISOR', @@ -246,70 +238,76 @@ Dart['math_on_list'] = function(block) { let code; switch (func) { case 'SUM': { - const functionName = Dart.provideFunction_('math_sum', [ - 'num ' + Dart.FUNCTION_NAME_PLACEHOLDER_ + '(List myList) {', - ' num sumVal = 0;', - ' myList.forEach((num entry) {sumVal += entry;});', ' return sumVal;', - '}' - ]); + const functionName = Dart.provideFunction_('math_sum', ` +num ${Dart.FUNCTION_NAME_PLACEHOLDER_}(List myList) { + num sumVal = 0; + myList.forEach((num entry) {sumVal += entry;}); + return sumVal; +} +`); code = functionName + '(' + list + ')'; break; } case 'MIN': { Dart.definitions_['import_dart_math'] = 'import \'dart:math\' as Math;'; - const functionName = Dart.provideFunction_('math_min', [ - 'num ' + Dart.FUNCTION_NAME_PLACEHOLDER_ + '(List myList) {', - ' if (myList.isEmpty) return null;', ' num minVal = myList[0];', - ' myList.forEach((num entry) ' + - '{minVal = Math.min(minVal, entry);});', - ' return minVal;', '}' - ]); + const functionName = Dart.provideFunction_('math_min', ` +num ${Dart.FUNCTION_NAME_PLACEHOLDER_}(List myList) { + if (myList.isEmpty) return null; + num minVal = myList[0]; + myList.forEach((num entry) {minVal = Math.min(minVal, entry);}); + return minVal; +} +`); code = functionName + '(' + list + ')'; break; } case 'MAX': { Dart.definitions_['import_dart_math'] = 'import \'dart:math\' as Math;'; - const functionName = Dart.provideFunction_('math_max', [ - 'num ' + Dart.FUNCTION_NAME_PLACEHOLDER_ + '(List myList) {', - ' if (myList.isEmpty) return null;', ' num maxVal = myList[0];', - ' myList.forEach((num entry) ' + - '{maxVal = Math.max(maxVal, entry);});', - ' return maxVal;', '}' - ]); + const functionName = Dart.provideFunction_('math_max', ` +num ${Dart.FUNCTION_NAME_PLACEHOLDER_}(List myList) { + if (myList.isEmpty) return null; + num maxVal = myList[0]; + myList.forEach((num entry) {maxVal = Math.max(maxVal, entry);}); + return maxVal; +} +`); code = functionName + '(' + list + ')'; break; } case 'AVERAGE': { // This operation exclude null and values that are not int or float: // math_mean([null,null,"aString",1,9]) -> 5.0 - const functionName = Dart.provideFunction_('math_mean', [ - 'num ' + Dart.FUNCTION_NAME_PLACEHOLDER_ + '(List myList) {', - ' // First filter list for numbers only.', - ' List localList = new List.from(myList);', - ' localList.removeWhere((a) => a is! num);', - ' if (localList.isEmpty) return null;', ' num sumVal = 0;', - ' localList.forEach((var entry) {sumVal += entry;});', - ' return sumVal / localList.length;', '}' - ]); + const functionName = Dart.provideFunction_('math_mean', ` +num ${Dart.FUNCTION_NAME_PLACEHOLDER_}(List myList) { + // First filter list for numbers only. + List localList = new List.from(myList); + localList.removeWhere((a) => a is! num); + if (localList.isEmpty) return null; + num sumVal = 0; + localList.forEach((var entry) {sumVal += entry;}); + return sumVal / localList.length; +} +`); code = functionName + '(' + list + ')'; break; } case 'MEDIAN': { - const functionName = Dart.provideFunction_('math_median', [ - 'num ' + Dart.FUNCTION_NAME_PLACEHOLDER_ + '(List myList) {', - ' // First filter list for numbers only, then sort, ' + - 'then return middle value', - ' // or the average of two middle values if list has an ' + - 'even number of elements.', - ' List localList = new List.from(myList);', - ' localList.removeWhere((a) => a is! num);', - ' if (localList.isEmpty) return null;', - ' localList.sort((a, b) => (a - b));', - ' int index = localList.length ~/ 2;', - ' if (localList.length % 2 == 1) {', ' return localList[index];', - ' } else {', - ' return (localList[index - 1] + localList[index]) / 2;', ' }', '}' - ]); + const functionName = Dart.provideFunction_('math_median', ` +num ${Dart.FUNCTION_NAME_PLACEHOLDER_}(List myList) { + // First filter list for numbers only, then sort, then return middle value + // or the average of two middle values if list has an even number of elements. + List localList = new List.from(myList); + localList.removeWhere((a) => a is! num); + if (localList.isEmpty) return null; + localList.sort((a, b) => (a - b)); + int index = localList.length ~/ 2; + if (localList.length % 2 == 1) { + return localList[index]; + } else { + return (localList[index - 1] + localList[index]) / 2; + } +} +`); code = functionName + '(' + list + ')'; break; } @@ -318,63 +316,67 @@ Dart['math_on_list'] = function(block) { // As a list of numbers can contain more than one mode, // the returned result is provided as an array. // Mode of [3, 'x', 'x', 1, 1, 2, '3'] -> ['x', 1] - const functionName = Dart.provideFunction_('math_modes', [ - 'List ' + Dart.FUNCTION_NAME_PLACEHOLDER_ + '(List values) {', - ' List modes = [];', - ' List counts = [];', - ' int maxCount = 0;', - ' for (int i = 0; i < values.length; i++) {', - ' var value = values[i];', - ' bool found = false;', - ' int thisCount;', - ' for (int j = 0; j < counts.length; j++) {', - ' if (counts[j][0] == value) {', - ' thisCount = ++counts[j][1];', - ' found = true;', - ' break;', - ' }', - ' }', - ' if (!found) {', - ' counts.add([value, 1]);', - ' thisCount = 1;', - ' }', - ' maxCount = Math.max(thisCount, maxCount);', - ' }', - ' for (int j = 0; j < counts.length; j++) {', - ' if (counts[j][1] == maxCount) {', - ' modes.add(counts[j][0]);', - ' }', - ' }', - ' return modes;', - '}' - ]); + const functionName = Dart.provideFunction_('math_modes', ` +List ${Dart.FUNCTION_NAME_PLACEHOLDER_}(List values) { + List modes = []; + List counts = []; + int maxCount = 0; + for (int i = 0; i < values.length; i++) { + var value = values[i]; + bool found = false; + int thisCount; + for (int j = 0; j < counts.length; j++) { + if (counts[j][0] == value) { + thisCount = ++counts[j][1]; + found = true; + break; + } + } + if (!found) { + counts.add([value, 1]); + thisCount = 1; + } + maxCount = Math.max(thisCount, maxCount); + } + for (int j = 0; j < counts.length; j++) { + if (counts[j][1] == maxCount) { + modes.add(counts[j][0]); + } + } + return modes; +} +`); code = functionName + '(' + list + ')'; break; } case 'STD_DEV': { Dart.definitions_['import_dart_math'] = 'import \'dart:math\' as Math;'; - const functionName = Dart.provideFunction_('math_standard_deviation', [ - 'num ' + Dart.FUNCTION_NAME_PLACEHOLDER_ + '(List myList) {', - ' // First filter list for numbers only.', - ' List numbers = new List.from(myList);', - ' numbers.removeWhere((a) => a is! num);', - ' if (numbers.isEmpty) return null;', ' num n = numbers.length;', - ' num sum = 0;', ' numbers.forEach((x) => sum += x);', - ' num mean = sum / n;', ' num sumSquare = 0;', - ' numbers.forEach((x) => sumSquare += ' + - 'Math.pow(x - mean, 2));', - ' return Math.sqrt(sumSquare / n);', '}' - ]); + const functionName = Dart.provideFunction_('math_standard_deviation', ` +num ${Dart.FUNCTION_NAME_PLACEHOLDER_}(List myList) { + // First filter list for numbers only. + List numbers = new List.from(myList); + numbers.removeWhere((a) => a is! num); + if (numbers.isEmpty) return null; + num n = numbers.length; + num sum = 0; + numbers.forEach((x) => sum += x); + num mean = sum / n; + num sumSquare = 0; + numbers.forEach((x) => sumSquare += Math.pow(x - mean, 2)); + return Math.sqrt(sumSquare / n); +} +`); code = functionName + '(' + list + ')'; break; } case 'RANDOM': { Dart.definitions_['import_dart_math'] = 'import \'dart:math\' as Math;'; - const functionName = Dart.provideFunction_('math_random_item', [ - 'dynamic ' + Dart.FUNCTION_NAME_PLACEHOLDER_ + '(List myList) {', - ' int x = new Math.Random().nextInt(myList.length);', - ' return myList[x];', '}' - ]); + const functionName = Dart.provideFunction_('math_random_item', ` +dynamic ${Dart.FUNCTION_NAME_PLACEHOLDER_}(List myList) { + int x = new Math.Random().nextInt(myList.length); + return myList[x]; +} +`); code = functionName + '(' + list + ')'; break; } @@ -411,12 +413,17 @@ Dart['math_random_int'] = function(block) { Dart.definitions_['import_dart_math'] = 'import \'dart:math\' as Math;'; const argument0 = Dart.valueToCode(block, 'FROM', Dart.ORDER_NONE) || '0'; const argument1 = Dart.valueToCode(block, 'TO', Dart.ORDER_NONE) || '0'; - const functionName = Dart.provideFunction_('math_random_int', [ - 'int ' + Dart.FUNCTION_NAME_PLACEHOLDER_ + '(num a, num b) {', - ' if (a > b) {', ' // Swap a and b to ensure a is smaller.', - ' num c = a;', ' a = b;', ' b = c;', ' }', - ' return new Math.Random().nextInt(b - a + 1) + a;', '}' - ]); + const functionName = Dart.provideFunction_('math_random_int', ` +int ${Dart.FUNCTION_NAME_PLACEHOLDER_}(num a, num b) { + if (a > b) { + // Swap a and b to ensure a is smaller. + num c = a; + a = b; + b = c; + } + return new Math.Random().nextInt(b - a + 1) + a; +} +`); const code = functionName + '(' + argument0 + ', ' + argument1 + ')'; return [code, Dart.ORDER_UNARY_POSTFIX]; }; diff --git a/generators/dart/text.js b/generators/dart/text.js index 7078815ec..5dfb372b0 100644 --- a/generators/dart/text.js +++ b/generators/dart/text.js @@ -35,10 +35,10 @@ Dart['text_join'] = function(block) { // Create a string made up of any number of elements of any type. switch (block.itemCount_) { case 0: - return ['\'\'', Dart.ORDER_ATOMIC]; + return ["''", Dart.ORDER_ATOMIC]; case 1: { const element = - Dart.valueToCode(block, 'ADD0', Dart.ORDER_UNARY_POSTFIX) || '\'\''; + Dart.valueToCode(block, 'ADD0', Dart.ORDER_UNARY_POSTFIX) || "''"; const code = element + '.toString()'; return [code, Dart.ORDER_UNARY_POSTFIX]; } @@ -46,7 +46,7 @@ Dart['text_join'] = function(block) { const elements = new Array(block.itemCount_); for (let i = 0; i < block.itemCount_; i++) { elements[i] = - Dart.valueToCode(block, 'ADD' + i, Dart.ORDER_NONE) || '\'\''; + Dart.valueToCode(block, 'ADD' + i, Dart.ORDER_NONE) || "''"; } const code = '[' + elements.join(',') + '].join()'; return [code, Dart.ORDER_UNARY_POSTFIX]; @@ -58,21 +58,21 @@ Dart['text_append'] = function(block) { // Append to a variable in place. const varName = Dart.nameDB_.getName(block.getFieldValue('VAR'), NameType.VARIABLE); - const value = Dart.valueToCode(block, 'TEXT', Dart.ORDER_NONE) || '\'\''; + const value = Dart.valueToCode(block, 'TEXT', Dart.ORDER_NONE) || "''"; return varName + ' = [' + varName + ', ' + value + '].join();\n'; }; Dart['text_length'] = function(block) { // String or array length. const text = - Dart.valueToCode(block, 'VALUE', Dart.ORDER_UNARY_POSTFIX) || '\'\''; + Dart.valueToCode(block, 'VALUE', Dart.ORDER_UNARY_POSTFIX) || "''"; return [text + '.length', Dart.ORDER_UNARY_POSTFIX]; }; Dart['text_isEmpty'] = function(block) { // Is the string null or array empty? const text = - Dart.valueToCode(block, 'VALUE', Dart.ORDER_UNARY_POSTFIX) || '\'\''; + Dart.valueToCode(block, 'VALUE', Dart.ORDER_UNARY_POSTFIX) || "''"; return [text + '.isEmpty', Dart.ORDER_UNARY_POSTFIX]; }; @@ -80,9 +80,9 @@ Dart['text_indexOf'] = function(block) { // Search the text for a substring. const operator = block.getFieldValue('END') === 'FIRST' ? 'indexOf' : 'lastIndexOf'; - const substring = Dart.valueToCode(block, 'FIND', Dart.ORDER_NONE) || '\'\''; + const substring = Dart.valueToCode(block, 'FIND', Dart.ORDER_NONE) || "''"; const text = - Dart.valueToCode(block, 'VALUE', Dart.ORDER_UNARY_POSTFIX) || '\'\''; + Dart.valueToCode(block, 'VALUE', Dart.ORDER_UNARY_POSTFIX) || "''"; const code = text + '.' + operator + '(' + substring + ')'; if (block.workspace.options.oneBasedIndex) { return [code + ' + 1', Dart.ORDER_ADDITIVE]; @@ -97,7 +97,7 @@ Dart['text_charAt'] = function(block) { const textOrder = (where === 'FIRST' || where === 'FROM_START') ? Dart.ORDER_UNARY_POSTFIX : Dart.ORDER_NONE; - const text = Dart.valueToCode(block, 'VALUE', textOrder) || '\'\''; + const text = Dart.valueToCode(block, 'VALUE', textOrder) || "''"; let at; switch (where) { case 'FIRST': { @@ -114,20 +114,22 @@ Dart['text_charAt'] = function(block) { // Fall through. case 'FROM_END': { at = Dart.getAdjusted(block, 'AT', 1); - const functionName = Dart.provideFunction_('text_get_from_end', [ - 'String ' + Dart.FUNCTION_NAME_PLACEHOLDER_ + '(String text, num x) {', - ' return text[text.length - x];', '}' - ]); + const functionName = Dart.provideFunction_('text_get_from_end', ` +String ${Dart.FUNCTION_NAME_PLACEHOLDER_}(String text, num x) { + return text[text.length - x]; +} +`); const code = functionName + '(' + text + ', ' + at + ')'; return [code, Dart.ORDER_UNARY_POSTFIX]; } case 'RANDOM': { Dart.definitions_['import_dart_math'] = 'import \'dart:math\' as Math;'; - const functionName = Dart.provideFunction_('text_random_letter', [ - 'String ' + Dart.FUNCTION_NAME_PLACEHOLDER_ + '(String text) {', - ' int x = new Math.Random().nextInt(text.length);', - ' return text[x];', '}' - ]); + const functionName = Dart.provideFunction_('text_random_letter', ` +String ${Dart.FUNCTION_NAME_PLACEHOLDER_}(String text) { + int x = new Math.Random().nextInt(text.length); + return text[x]; +} +`); const code = functionName + '(' + text + ')'; return [code, Dart.ORDER_UNARY_POSTFIX]; } @@ -142,7 +144,7 @@ Dart['text_getSubstring'] = function(block) { const requiresLengthCall = (where1 !== 'FROM_END' && where2 === 'FROM_START'); const textOrder = requiresLengthCall ? Dart.ORDER_UNARY_POSTFIX : Dart.ORDER_NONE; - const text = Dart.valueToCode(block, 'STRING', textOrder) || '\'\''; + const text = Dart.valueToCode(block, 'STRING', textOrder) || "''"; let code; if (where1 === 'FIRST' && where2 === 'LAST') { code = text; @@ -188,19 +190,25 @@ Dart['text_getSubstring'] = function(block) { } else { const at1 = Dart.getAdjusted(block, 'AT1'); const at2 = Dart.getAdjusted(block, 'AT2'); - const functionName = Dart.provideFunction_('text_get_substring', [ - 'String ' + Dart.FUNCTION_NAME_PLACEHOLDER_ + - '(String text, String where1, num at1, String where2, num at2) {', - ' int getAt(String where, num at) {', ' if (where == \'FROM_END\') {', - ' at = text.length - 1 - at;', - ' } else if (where == \'FIRST\') {', ' at = 0;', - ' } else if (where == \'LAST\') {', ' at = text.length - 1;', - ' } else if (where != \'FROM_START\') {', - ' throw \'Unhandled option (text_getSubstring).\';', ' }', - ' return at;', ' }', ' at1 = getAt(where1, at1);', - ' at2 = getAt(where2, at2) + 1;', ' return text.substring(at1, at2);', - '}' - ]); + const functionName = Dart.provideFunction_('text_get_substring', ` +String ${Dart.FUNCTION_NAME_PLACEHOLDER_}(String text, String where1, num at1, String where2, num at2) { + int getAt(String where, num at) { + if (where == 'FROM_END') { + at = text.length - 1 - at; + } else if (where == 'FIRST') { + at = 0; + } else if (where == 'LAST') { + at = text.length - 1; + } else if (where != 'FROM_START') { + throw 'Unhandled option (text_getSubstring).'; + } + return at; + } + at1 = getAt(where1, at1); + at2 = getAt(where2, at2) + 1; + return text.substring(at1, at2); +} +`); code = functionName + '(' + text + ', \'' + where1 + '\', ' + at1 + ', \'' + where2 + '\', ' + at2 + ')'; } @@ -216,23 +224,29 @@ Dart['text_changeCase'] = function(block) { }; const operator = OPERATORS[block.getFieldValue('CASE')]; const textOrder = operator ? Dart.ORDER_UNARY_POSTFIX : Dart.ORDER_NONE; - const text = Dart.valueToCode(block, 'TEXT', textOrder) || '\'\''; + const text = Dart.valueToCode(block, 'TEXT', textOrder) || "''"; let code; if (operator) { // Upper and lower case are functions built into Dart. code = text + operator; } else { // Title case is not a native Dart function. Define one. - const functionName = Dart.provideFunction_('text_toTitleCase', [ - 'String ' + Dart.FUNCTION_NAME_PLACEHOLDER_ + '(String str) {', - ' RegExp exp = new RegExp(r\'\\b\');', - ' List list = str.split(exp);', - ' final title = new StringBuffer();', ' for (String part in list) {', - ' if (part.length > 0) {', ' title.write(part[0].toUpperCase());', - ' if (part.length > 0) {', - ' title.write(part.substring(1).toLowerCase());', ' }', - ' }', ' }', ' return title.toString();', '}' - ]); + const functionName = Dart.provideFunction_('text_toTitleCase', ` +String ${Dart.FUNCTION_NAME_PLACEHOLDER_}(String str) { + RegExp exp = new RegExp(r'\\b'); + List list = str.split(exp); + final title = new StringBuffer(); + for (String part in list) { + if (part.length > 0) { + title.write(part[0].toUpperCase()); + if (part.length > 0) { + title.write(part.substring(1).toLowerCase()); + } + } + } + return title.toString(); +} +`); code = functionName + '(' + text + ')'; } return [code, Dart.ORDER_UNARY_POSTFIX]; @@ -247,13 +261,13 @@ Dart['text_trim'] = function(block) { }; const operator = OPERATORS[block.getFieldValue('MODE')]; const text = - Dart.valueToCode(block, 'TEXT', Dart.ORDER_UNARY_POSTFIX) || '\'\''; + Dart.valueToCode(block, 'TEXT', Dart.ORDER_UNARY_POSTFIX) || "''"; return [text + operator, Dart.ORDER_UNARY_POSTFIX]; }; Dart['text_print'] = function(block) { // Print statement. - const msg = Dart.valueToCode(block, 'TEXT', Dart.ORDER_NONE) || '\'\''; + const msg = Dart.valueToCode(block, 'TEXT', Dart.ORDER_NONE) || "''"; return 'print(' + msg + ');\n'; }; @@ -266,7 +280,7 @@ Dart['text_prompt_ext'] = function(block) { msg = Dart.quote_(block.getFieldValue('TEXT')); } else { // External message. - msg = Dart.valueToCode(block, 'TEXT', Dart.ORDER_NONE) || '\'\''; + msg = Dart.valueToCode(block, 'TEXT', Dart.ORDER_NONE) || "''"; } let code = 'Html.window.prompt(' + msg + ', \'\')'; const toNumber = block.getFieldValue('TYPE') === 'NUMBER'; @@ -280,27 +294,35 @@ Dart['text_prompt_ext'] = function(block) { Dart['text_prompt'] = Dart['text_prompt_ext']; Dart['text_count'] = function(block) { - const text = Dart.valueToCode(block, 'TEXT', Dart.ORDER_NONE) || '\'\''; - const sub = Dart.valueToCode(block, 'SUB', Dart.ORDER_NONE) || '\'\''; + const text = Dart.valueToCode(block, 'TEXT', Dart.ORDER_NONE) || "''"; + const sub = Dart.valueToCode(block, 'SUB', Dart.ORDER_NONE) || "''"; // Substring count is not a native Dart function. Define one. - const functionName = Dart.provideFunction_('text_count', [ - 'int ' + Dart.FUNCTION_NAME_PLACEHOLDER_ + - '(String haystack, String needle) {', - ' if (needle.length == 0) {', ' return haystack.length + 1;', ' }', - ' int index = 0;', ' int count = 0;', ' while (index != -1) {', - ' index = haystack.indexOf(needle, index);', ' if (index != -1) {', - ' count++;', ' index += needle.length;', ' }', ' }', - ' return count;', '}' - ]); + const functionName = Dart.provideFunction_('text_count', ` +int ${Dart.FUNCTION_NAME_PLACEHOLDER_}(String haystack, String needle) { + if (needle.length == 0) { + return haystack.length + 1; + } + int index = 0; + int count = 0; + while (index != -1) { + index = haystack.indexOf(needle, index); + if (index != -1) { + count++; + index += needle.length; + } + } + return count; +} +`); const code = functionName + '(' + text + ', ' + sub + ')'; return [code, Dart.ORDER_UNARY_POSTFIX]; }; Dart['text_replace'] = function(block) { const text = - Dart.valueToCode(block, 'TEXT', Dart.ORDER_UNARY_POSTFIX) || '\'\''; - const from = Dart.valueToCode(block, 'FROM', Dart.ORDER_NONE) || '\'\''; - const to = Dart.valueToCode(block, 'TO', Dart.ORDER_NONE) || '\'\''; + Dart.valueToCode(block, 'TEXT', Dart.ORDER_UNARY_POSTFIX) || "''"; + const from = Dart.valueToCode(block, 'FROM', Dart.ORDER_NONE) || "''"; + const to = Dart.valueToCode(block, 'TO', Dart.ORDER_NONE) || "''"; const code = text + '.replaceAll(' + from + ', ' + to + ')'; return [code, Dart.ORDER_UNARY_POSTFIX]; }; @@ -310,7 +332,7 @@ Dart['text_reverse'] = function(block) { // http://stackoverflow.com/a/21613700/3529104 // Implementing something is possibly better than not implementing anything? const text = - Dart.valueToCode(block, 'TEXT', Dart.ORDER_UNARY_POSTFIX) || '\'\''; + Dart.valueToCode(block, 'TEXT', Dart.ORDER_UNARY_POSTFIX) || "''"; const code = 'new String.fromCharCodes(' + text + '.runes.toList().reversed)'; return [code, Dart.ORDER_UNARY_PREFIX]; }; diff --git a/generators/javascript/colour.js b/generators/javascript/colour.js index 3b6632575..a2cc64a5a 100644 --- a/generators/javascript/colour.js +++ b/generators/javascript/colour.js @@ -22,11 +22,12 @@ JavaScript['colour_picker'] = function(block) { JavaScript['colour_random'] = function(block) { // Generate a random colour. - const functionName = JavaScript.provideFunction_('colourRandom', [ - 'function ' + JavaScript.FUNCTION_NAME_PLACEHOLDER_ + '() {', - ' var num = Math.floor(Math.random() * Math.pow(2, 24));', - ' return \'#\' + (\'00000\' + num.toString(16)).substr(-6);', '}' - ]); + const functionName = JavaScript.provideFunction_('colourRandom', ` +function ${JavaScript.FUNCTION_NAME_PLACEHOLDER_}() { + var num = Math.floor(Math.random() * Math.pow(2, 24)); + return '#' + ('00000' + num.toString(16)).substr(-6); +} +`); const code = functionName + '()'; return [code, JavaScript.ORDER_FUNCTION_CALL]; }; @@ -38,16 +39,17 @@ JavaScript['colour_rgb'] = function(block) { JavaScript.valueToCode(block, 'GREEN', JavaScript.ORDER_NONE) || 0; const blue = JavaScript.valueToCode(block, 'BLUE', JavaScript.ORDER_NONE) || 0; - const functionName = JavaScript.provideFunction_('colourRgb', [ - 'function ' + 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;', '}' - ]); + const functionName = JavaScript.provideFunction_('colourRgb', ` +function ${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; +} +`); const code = functionName + '(' + red + ', ' + green + ', ' + blue + ')'; return [code, JavaScript.ORDER_FUNCTION_CALL]; }; @@ -55,28 +57,29 @@ JavaScript['colour_rgb'] = function(block) { JavaScript['colour_blend'] = function(block) { // Blend two colours together. const c1 = JavaScript.valueToCode(block, 'COLOUR1', JavaScript.ORDER_NONE) || - '\'#000000\''; + "'#000000'"; const c2 = JavaScript.valueToCode(block, 'COLOUR2', JavaScript.ORDER_NONE) || - '\'#000000\''; + "'#000000'"; const ratio = JavaScript.valueToCode(block, 'RATIO', JavaScript.ORDER_NONE) || 0.5; - const functionName = JavaScript.provideFunction_('colourBlend', [ - 'function ' + 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;', '}' - ]); + const functionName = JavaScript.provideFunction_('colourBlend', ` +function ${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; +} +`); const code = functionName + '(' + c1 + ', ' + c2 + ', ' + ratio + ')'; return [code, JavaScript.ORDER_FUNCTION_CALL]; }; diff --git a/generators/javascript/lists.js b/generators/javascript/lists.js index a033710b8..e9fbc3598 100644 --- a/generators/javascript/lists.js +++ b/generators/javascript/lists.js @@ -35,11 +35,15 @@ JavaScript['lists_create_with'] = function(block) { JavaScript['lists_repeat'] = function(block) { // Create a list with one element repeated. - const functionName = JavaScript.provideFunction_('listsRepeat', [ - 'function ' + JavaScript.FUNCTION_NAME_PLACEHOLDER_ + '(value, n) {', - ' var array = [];', ' for (var i = 0; i < n; i++) {', - ' array[i] = value;', ' }', ' return array;', '}' - ]); + const functionName = JavaScript.provideFunction_('listsRepeat', ` +function ${JavaScript.FUNCTION_NAME_PLACEHOLDER_}(value, n) { + var array = []; + for (var i = 0; i < n; i++) { + array[i] = value; + } + return array; +} +`); const element = JavaScript.valueToCode(block, 'ITEM', JavaScript.ORDER_NONE) || 'null'; const repeatCount = @@ -67,7 +71,7 @@ JavaScript['lists_indexOf'] = function(block) { const operator = block.getFieldValue('END') === 'FIRST' ? 'indexOf' : 'lastIndexOf'; const item = - JavaScript.valueToCode(block, 'FIND', JavaScript.ORDER_NONE) || '\'\''; + JavaScript.valueToCode(block, 'FIND', JavaScript.ORDER_NONE) || "''"; const list = JavaScript.valueToCode(block, 'VALUE', JavaScript.ORDER_MEMBER) || '[]'; const code = list + '.' + operator + '(' + item + ')'; @@ -136,13 +140,16 @@ JavaScript['lists_getIndex'] = function(block) { break; } case ('RANDOM'): { - const functionName = JavaScript.provideFunction_('listsGetRandomItem', [ - 'function ' + 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];', - ' }', '}' - ]); + const functionName = JavaScript.provideFunction_('listsGetRandomItem', ` +function ${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]; + } +} +`); const code = functionName + '(' + list + ', ' + (mode !== 'GET') + ')'; if (mode === 'GET' || mode === 'GET_REMOVE') { return [code, JavaScript.ORDER_FUNCTION_CALL]; @@ -309,23 +316,22 @@ JavaScript['lists_getSublist'] = function(block) { 'FIRST': 'First', 'LAST': 'Last', 'FROM_START': 'FromStart', - 'FROM_END': 'FromEnd' + 'FROM_END': 'FromEnd', }; + // The value for 'FROM_END' and'FROM_START' depends on `at` so + // we add it as a parameter. + const at1Param = + (where1 === 'FROM_END' || where1 === 'FROM_START') ? ', at1' : ''; + const at2Param = + (where2 === 'FROM_END' || where2 === 'FROM_START') ? ', at2' : ''; const functionName = JavaScript.provideFunction_( - 'subsequence' + wherePascalCase[where1] + wherePascalCase[where2], [ - 'function ' + JavaScript.FUNCTION_NAME_PLACEHOLDER_ + '(sequence' + - // The value for 'FROM_END' and'FROM_START' depends on `at` so - // we add it as a parameter. - ((where1 === 'FROM_END' || where1 === 'FROM_START') ? ', at1' : - '') + - ((where2 === 'FROM_END' || where2 === 'FROM_START') ? ', at2' : - '') + - ') {', - getSubstringIndex('sequence', where1, 'at1') + ';', - ' var end = ' + getSubstringIndex('sequence', where2, 'at2') + - ' + 1;', - ' return sequence.slice(start, end);', '}' - ]); + 'subsequence' + wherePascalCase[where1] + wherePascalCase[where2], ` +function ${JavaScript.FUNCTION_NAME_PLACEHOLDER_}(sequence${at1Param}${at2Param}) { + var start = ${getSubstringIndex('sequence', where1, 'at1')}; + var end = ${getSubstringIndex('sequence', where2, 'at2')} + 1; + return sequence.slice(start, end); +} +`); code = functionName + '(' + list + // The value for 'FROM_END' and 'FROM_START' depends on `at` so we // pass it. @@ -344,19 +350,20 @@ JavaScript['lists_sort'] = function(block) { const direction = block.getFieldValue('DIRECTION') === '1' ? 1 : -1; const type = block.getFieldValue('TYPE'); const getCompareFunctionName = - JavaScript.provideFunction_('listsGetSortCompare', [ - 'function ' + 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; }', '}' - ]); + JavaScript.provideFunction_('listsGetSortCompare', ` +function ${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; }; +} + `); return [ list + '.slice().sort(' + getCompareFunctionName + '("' + type + '", ' + direction + '))', @@ -368,12 +375,12 @@ JavaScript['lists_split'] = function(block) { // Block for splitting text into a list, or joining a list into text. let input = JavaScript.valueToCode(block, 'INPUT', JavaScript.ORDER_MEMBER); const delimiter = - JavaScript.valueToCode(block, 'DELIM', JavaScript.ORDER_NONE) || '\'\''; + JavaScript.valueToCode(block, 'DELIM', JavaScript.ORDER_NONE) || "''"; const mode = block.getFieldValue('MODE'); let functionName; if (mode === 'SPLIT') { if (!input) { - input = '\'\''; + input = "''"; } functionName = 'split'; } else if (mode === 'JOIN') { diff --git a/generators/javascript/math.js b/generators/javascript/math.js index 55ee3de82..f370ba559 100644 --- a/generators/javascript/math.js +++ b/generators/javascript/math.js @@ -31,7 +31,7 @@ JavaScript['math_arithmetic'] = function(block) { 'MINUS': [' - ', JavaScript.ORDER_SUBTRACTION], 'MULTIPLY': [' * ', JavaScript.ORDER_MULTIPLICATION], 'DIVIDE': [' / ', JavaScript.ORDER_DIVISION], - 'POWER': [null, JavaScript.ORDER_NONE] // Handle power separately. + 'POWER': [null, JavaScript.ORDER_NONE], // Handle power separately. }; const tuple = OPERATORS[block.getFieldValue('OP')]; const operator = tuple[0]; @@ -137,11 +137,10 @@ JavaScript['math_constant'] = function(block) { const CONSTANTS = { 'PI': ['Math.PI', JavaScript.ORDER_MEMBER], 'E': ['Math.E', JavaScript.ORDER_MEMBER], - 'GOLDEN_RATIO': - ['(1 + Math.sqrt(5)) / 2', JavaScript.ORDER_DIVISION], + 'GOLDEN_RATIO': ['(1 + Math.sqrt(5)) / 2', JavaScript.ORDER_DIVISION], 'SQRT2': ['Math.SQRT2', JavaScript.ORDER_MEMBER], 'SQRT1_2': ['Math.SQRT1_2', JavaScript.ORDER_MEMBER], - 'INFINITY': ['Infinity', JavaScript.ORDER_ATOMIC] + 'INFINITY': ['Infinity', JavaScript.ORDER_ATOMIC], }; return CONSTANTS[block.getFieldValue('CONSTANT')]; }; @@ -150,20 +149,16 @@ JavaScript['math_number_property'] = function(block) { // Check if a number is even, odd, prime, whole, positive, or negative // or if it is divisible by certain number. Returns true or false. const PROPERTIES = { - 'EVEN': [' % 2 === 0', JavaScript.ORDER_MODULUS, - JavaScript.ORDER_EQUALITY], - 'ODD': [' % 2 === 1', JavaScript.ORDER_MODULUS, - JavaScript.ORDER_EQUALITY], + 'EVEN': [' % 2 === 0', JavaScript.ORDER_MODULUS, JavaScript.ORDER_EQUALITY], + 'ODD': [' % 2 === 1', JavaScript.ORDER_MODULUS, JavaScript.ORDER_EQUALITY], 'WHOLE': [' % 1 === 0', JavaScript.ORDER_MODULUS, JavaScript.ORDER_EQUALITY], 'POSITIVE': [' > 0', JavaScript.ORDER_RELATIONAL, JavaScript.ORDER_RELATIONAL], 'NEGATIVE': [' < 0', JavaScript.ORDER_RELATIONAL, JavaScript.ORDER_RELATIONAL], - 'DIVISIBLE_BY': [null, JavaScript.ORDER_MODULUS, - JavaScript.ORDER_EQUALITY], - 'PRIME': [null, JavaScript.ORDER_NONE, - JavaScript.ORDER_FUNCTION_CALL] + 'DIVISIBLE_BY': [null, JavaScript.ORDER_MODULUS, JavaScript.ORDER_EQUALITY], + 'PRIME': [null, JavaScript.ORDER_NONE, JavaScript.ORDER_FUNCTION_CALL], }; const dropdownProperty = block.getFieldValue('PROPERTY'); const [suffix, inputOrder, outputOrder] = PROPERTIES[dropdownProperty]; @@ -172,27 +167,26 @@ JavaScript['math_number_property'] = function(block) { let code; if (dropdownProperty === 'PRIME') { // Prime is a special case as it is not a one-liner test. - const functionName = JavaScript.provideFunction_( - 'mathIsPrime', - ['function ' + 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;', - '}']); + const functionName = JavaScript.provideFunction_('mathIsPrime', ` +function ${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; +} +`); code = functionName + '(' + numberToCheck + ')'; } else if (dropdownProperty === 'DIVISIBLE_BY') { const divisor = JavaScript.valueToCode(block, 'DIVISOR', @@ -242,13 +236,11 @@ JavaScript['math_on_list'] = function(block) { break; case 'AVERAGE': { // mathMean([null,null,1,3]) === 2.0. - const functionName = JavaScript.provideFunction_( - 'mathMean', - ['function ' + JavaScript.FUNCTION_NAME_PLACEHOLDER_ + - '(myList) {', - ' return myList.reduce(function(x, y) {return x + y;}) / ' + - 'myList.length;', - '}']); + const functionName = JavaScript.provideFunction_('mathMean', ` +function ${JavaScript.FUNCTION_NAME_PLACEHOLDER_}(myList) { + return myList.reduce(function(x, y) {return x + y;}) / myList.length; +} +`); list = JavaScript.valueToCode(block, 'LIST', JavaScript.ORDER_NONE) || '[]'; code = functionName + '(' + list + ')'; @@ -256,21 +248,18 @@ JavaScript['math_on_list'] = function(block) { } case 'MEDIAN': { // mathMedian([null,null,1,3]) === 2.0. - const functionName = JavaScript.provideFunction_( - 'mathMedian', - ['function ' + 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];', - ' }', - '}']); + const functionName = JavaScript.provideFunction_('mathMedian', ` +function ${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]; + } +} +`); list = JavaScript.valueToCode(block, 'LIST', JavaScript.ORDER_NONE) || '[]'; code = functionName + '(' + list + ')'; @@ -280,70 +269,67 @@ JavaScript['math_on_list'] = function(block) { // As a list of numbers can contain more than one mode, // the returned result is provided as an array. // Mode of [3, 'x', 'x', 1, 1, 2, '3'] -> ['x', 1]. - const functionName = JavaScript.provideFunction_( - 'mathModes', - ['function ' + 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;', - '}']); + const functionName = JavaScript.provideFunction_('mathModes', ` +function ${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; +} +`); list = JavaScript.valueToCode(block, 'LIST', JavaScript.ORDER_NONE) || '[]'; code = functionName + '(' + list + ')'; break; } case 'STD_DEV': { - const functionName = JavaScript.provideFunction_( - 'mathStandardDeviation', - ['function ' + 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);', - '}']); + const functionName = JavaScript.provideFunction_('mathStandardDeviation', ` +function ${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); +} +`); list = JavaScript.valueToCode(block, 'LIST', JavaScript.ORDER_NONE) || '[]'; code = functionName + '(' + list + ')'; break; } case 'RANDOM': { - const functionName = JavaScript.provideFunction_( - 'mathRandomList', - ['function ' + JavaScript.FUNCTION_NAME_PLACEHOLDER_ + - '(list) {', - ' var x = Math.floor(Math.random() * list.length);', - ' return list[x];', - '}']); + const functionName = JavaScript.provideFunction_('mathRandomList', ` +function ${JavaScript.FUNCTION_NAME_PLACEHOLDER_}(list) { + var x = Math.floor(Math.random() * list.length); + return list[x]; +} +`); list = JavaScript.valueToCode(block, 'LIST', JavaScript.ORDER_NONE) || '[]'; code = functionName + '(' + list + ')'; @@ -384,18 +370,17 @@ JavaScript['math_random_int'] = function(block) { JavaScript.ORDER_NONE) || '0'; const argument1 = JavaScript.valueToCode(block, 'TO', JavaScript.ORDER_NONE) || '0'; - const functionName = JavaScript.provideFunction_( - 'mathRandomInt', - ['function ' + 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);', - '}']); + const functionName = JavaScript.provideFunction_('mathRandomInt', ` +function ${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); +} +`); const code = functionName + '(' + argument0 + ', ' + argument1 + ')'; return [code, JavaScript.ORDER_FUNCTION_CALL]; }; diff --git a/generators/javascript/text.js b/generators/javascript/text.js index 419ffbfec..9c60bfa6c 100644 --- a/generators/javascript/text.js +++ b/generators/javascript/text.js @@ -71,18 +71,18 @@ JavaScript['text_join'] = function(block) { // Create a string made up of any number of elements of any type. switch (block.itemCount_) { case 0: - return ['\'\'', JavaScript.ORDER_ATOMIC]; + return ["''", JavaScript.ORDER_ATOMIC]; case 1: { const element = JavaScript.valueToCode(block, 'ADD0', - JavaScript.ORDER_NONE) || '\'\''; + JavaScript.ORDER_NONE) || "''"; const codeAndOrder = forceString(element); return codeAndOrder; } case 2: { const element0 = JavaScript.valueToCode(block, 'ADD0', - JavaScript.ORDER_NONE) || '\'\''; + JavaScript.ORDER_NONE) || "''"; const element1 = JavaScript.valueToCode(block, 'ADD1', - JavaScript.ORDER_NONE) || '\'\''; + JavaScript.ORDER_NONE) || "''"; const code = forceString(element0)[0] + ' + ' + forceString(element1)[0]; return [code, JavaScript.ORDER_ADDITION]; @@ -91,7 +91,7 @@ JavaScript['text_join'] = function(block) { const elements = new Array(block.itemCount_); for (let i = 0; i < block.itemCount_; i++) { elements[i] = JavaScript.valueToCode(block, 'ADD' + i, - JavaScript.ORDER_NONE) || '\'\''; + JavaScript.ORDER_NONE) || "''"; } const code = '[' + elements.join(',') + '].join(\'\')'; return [code, JavaScript.ORDER_FUNCTION_CALL]; @@ -104,7 +104,7 @@ JavaScript['text_append'] = function(block) { const varName = JavaScript.nameDB_.getName( block.getFieldValue('VAR'), NameType.VARIABLE); const value = JavaScript.valueToCode(block, 'TEXT', - JavaScript.ORDER_NONE) || '\'\''; + JavaScript.ORDER_NONE) || "''"; const code = varName + ' += ' + forceString(value)[0] + ';\n'; return code; @@ -113,14 +113,14 @@ JavaScript['text_append'] = function(block) { JavaScript['text_length'] = function(block) { // String or array length. const text = JavaScript.valueToCode(block, 'VALUE', - JavaScript.ORDER_MEMBER) || '\'\''; + JavaScript.ORDER_MEMBER) || "''"; return [text + '.length', JavaScript.ORDER_MEMBER]; }; JavaScript['text_isEmpty'] = function(block) { // Is the string null or array empty? const text = JavaScript.valueToCode(block, 'VALUE', - JavaScript.ORDER_MEMBER) || '\'\''; + JavaScript.ORDER_MEMBER) || "''"; return ['!' + text + '.length', JavaScript.ORDER_LOGICAL_NOT]; }; @@ -129,9 +129,9 @@ JavaScript['text_indexOf'] = function(block) { const operator = block.getFieldValue('END') === 'FIRST' ? 'indexOf' : 'lastIndexOf'; const substring = JavaScript.valueToCode(block, 'FIND', - JavaScript.ORDER_NONE) || '\'\''; + JavaScript.ORDER_NONE) || "''"; const text = JavaScript.valueToCode(block, 'VALUE', - JavaScript.ORDER_MEMBER) || '\'\''; + JavaScript.ORDER_MEMBER) || "''"; const code = text + '.' + operator + '(' + substring + ')'; // Adjust index if using one-based indices. if (block.workspace.options.oneBasedIndex) { @@ -146,8 +146,7 @@ JavaScript['text_charAt'] = function(block) { const where = block.getFieldValue('WHERE') || 'FROM_START'; const textOrder = (where === 'RANDOM') ? JavaScript.ORDER_NONE : JavaScript.ORDER_MEMBER; - const text = JavaScript.valueToCode(block, 'VALUE', - textOrder) || '\'\''; + const text = JavaScript.valueToCode(block, 'VALUE', textOrder) || "''"; switch (where) { case 'FIRST': { const code = text + '.charAt(0)'; @@ -169,13 +168,12 @@ JavaScript['text_charAt'] = function(block) { return [code, JavaScript.ORDER_FUNCTION_CALL]; } case 'RANDOM': { - const functionName = JavaScript.provideFunction_( - 'textRandomLetter', - ['function ' + JavaScript.FUNCTION_NAME_PLACEHOLDER_ + - '(text) {', - ' var x = Math.floor(Math.random() * text.length);', - ' return text[x];', - '}']); + const functionName = JavaScript.provideFunction_('textRandomLetter', ` +function ${JavaScript.FUNCTION_NAME_PLACEHOLDER_}(text) { + var x = Math.floor(Math.random() * text.length); + return text[x]; +} +`); const code = functionName + '(' + text + ')'; return [code, JavaScript.ORDER_FUNCTION_CALL]; } @@ -191,8 +189,7 @@ JavaScript['text_getSubstring'] = function(block) { where2 !== 'FROM_END' && where2 !== 'LAST'); const textOrder = requiresLengthCall ? JavaScript.ORDER_MEMBER : JavaScript.ORDER_NONE; - const text = JavaScript.valueToCode(block, 'STRING', - textOrder) || '\'\''; + const text = JavaScript.valueToCode(block, 'STRING', textOrder) || "''"; let code; if (where1 === 'FIRST' && where2 === 'LAST') { code = text; @@ -238,22 +235,20 @@ JavaScript['text_getSubstring'] = function(block) { const at2 = JavaScript.getAdjusted(block, 'AT2'); const wherePascalCase = {'FIRST': 'First', 'LAST': 'Last', 'FROM_START': 'FromStart', 'FROM_END': 'FromEnd'}; + // The value for 'FROM_END' and'FROM_START' depends on `at` so + // we add it as a parameter. + const at1Param = + (where1 === 'FROM_END' || where1 === 'FROM_START') ? ', at1' : ''; + const at2Param = + (where2 === 'FROM_END' || where2 === 'FROM_START') ? ', at2' : ''; const functionName = JavaScript.provideFunction_( - 'subsequence' + wherePascalCase[where1] + wherePascalCase[where2], [ - 'function ' + JavaScript.FUNCTION_NAME_PLACEHOLDER_ + - '(sequence' + - // The value for 'FROM_END' and'FROM_START' depends on `at` so - // we add it as a parameter. - ((where1 === 'FROM_END' || where1 === 'FROM_START') ? ', at1' : - '') + - ((where2 === 'FROM_END' || where2 === 'FROM_START') ? ', at2' : - '') + - ') {', - ' var start = ' + getSubstringIndex('sequence', where1, 'at1') + ';', - ' var end = ' + getSubstringIndex('sequence', where2, 'at2') + - ' + 1;', - ' return sequence.slice(start, end);', '}' - ]); + 'subsequence' + wherePascalCase[where1] + wherePascalCase[where2], ` +function ${JavaScript.FUNCTION_NAME_PLACEHOLDER_}(sequence${at1Param}${at2Param}) { + var start = ${getSubstringIndex('sequence', where1, 'at1')}; + var end = ${getSubstringIndex('sequence', where2, 'at2')} + 1; + return sequence.slice(start, end); +} +`); code = functionName + '(' + text + // The value for 'FROM_END' and 'FROM_START' depends on `at` so we // pass it. @@ -269,27 +264,23 @@ JavaScript['text_changeCase'] = function(block) { const OPERATORS = { 'UPPERCASE': '.toUpperCase()', 'LOWERCASE': '.toLowerCase()', - 'TITLECASE': null + 'TITLECASE': null, }; const operator = OPERATORS[block.getFieldValue('CASE')]; - const textOrder = operator ? JavaScript.ORDER_MEMBER : - JavaScript.ORDER_NONE; - const text = JavaScript.valueToCode(block, 'TEXT', - textOrder) || '\'\''; + const textOrder = operator ? JavaScript.ORDER_MEMBER : JavaScript.ORDER_NONE; + const text = JavaScript.valueToCode(block, 'TEXT', textOrder) || "''"; let code; if (operator) { // Upper and lower case are functions built into JavaScript. code = text + operator; } else { // Title case is not a native JavaScript function. Define one. - const functionName = JavaScript.provideFunction_( - 'textToTitleCase', - ['function ' + JavaScript.FUNCTION_NAME_PLACEHOLDER_ + - '(str) {', - ' return str.replace(/\\S+/g,', - ' function(txt) {return txt[0].toUpperCase() + ' + - 'txt.substring(1).toLowerCase();});', - '}']); + const functionName = JavaScript.provideFunction_('textToTitleCase', ` +function ${JavaScript.FUNCTION_NAME_PLACEHOLDER_}(str) { + return str.replace(/\\S+/g, + function(txt) {return txt[0].toUpperCase() + txt.substring(1).toLowerCase();}); +} +`); code = functionName + '(' + text + ')'; } return [code, JavaScript.ORDER_FUNCTION_CALL]; @@ -300,18 +291,18 @@ JavaScript['text_trim'] = function(block) { const OPERATORS = { 'LEFT': ".replace(/^[\\s\\xa0]+/, '')", 'RIGHT': ".replace(/[\\s\\xa0]+$/, '')", - 'BOTH': '.trim()' + 'BOTH': '.trim()', }; const operator = OPERATORS[block.getFieldValue('MODE')]; const text = JavaScript.valueToCode(block, 'TEXT', - JavaScript.ORDER_MEMBER) || '\'\''; + JavaScript.ORDER_MEMBER) || "''"; return [text + operator, JavaScript.ORDER_FUNCTION_CALL]; }; JavaScript['text_print'] = function(block) { // Print statement. const msg = JavaScript.valueToCode(block, 'TEXT', - JavaScript.ORDER_NONE) || '\'\''; + JavaScript.ORDER_NONE) || "''"; return 'window.alert(' + msg + ');\n'; }; @@ -323,8 +314,7 @@ JavaScript['text_prompt_ext'] = function(block) { msg = JavaScript.quote_(block.getFieldValue('TEXT')); } else { // External message. - msg = JavaScript.valueToCode(block, 'TEXT', - JavaScript.ORDER_NONE) || '\'\''; + msg = JavaScript.valueToCode(block, 'TEXT', JavaScript.ORDER_NONE) || "''"; } let code = 'window.prompt(' + msg + ')'; const toNumber = block.getFieldValue('TYPE') === 'NUMBER'; @@ -338,48 +328,44 @@ JavaScript['text_prompt'] = JavaScript['text_prompt_ext']; JavaScript['text_count'] = function(block) { const text = JavaScript.valueToCode(block, 'TEXT', - JavaScript.ORDER_NONE) || '\'\''; + JavaScript.ORDER_NONE) || "''"; const sub = JavaScript.valueToCode(block, 'SUB', - JavaScript.ORDER_NONE) || '\'\''; - const functionName = JavaScript.provideFunction_( - 'textCount', - ['function ' + JavaScript.FUNCTION_NAME_PLACEHOLDER_ + - '(haystack, needle) {', - ' if (needle.length === 0) {', - ' return haystack.length + 1;', - ' } else {', - ' return haystack.split(needle).length - 1;', - ' }', - '}']); + JavaScript.ORDER_NONE) || "''"; + const functionName = JavaScript.provideFunction_('textCount', ` +function ${JavaScript.FUNCTION_NAME_PLACEHOLDER_}(haystack, needle) { + if (needle.length === 0) { + return haystack.length + 1; + } else { + return haystack.split(needle).length - 1; + } +} +`); const code = functionName + '(' + text + ', ' + sub + ')'; return [code, JavaScript.ORDER_FUNCTION_CALL]; }; JavaScript['text_replace'] = function(block) { const text = JavaScript.valueToCode(block, 'TEXT', - JavaScript.ORDER_NONE) || '\'\''; + JavaScript.ORDER_NONE) || "''"; const from = JavaScript.valueToCode(block, 'FROM', - JavaScript.ORDER_NONE) || '\'\''; - const to = JavaScript.valueToCode(block, 'TO', - JavaScript.ORDER_NONE) || '\'\''; + JavaScript.ORDER_NONE) || "''"; + const to = JavaScript.valueToCode(block, 'TO', JavaScript.ORDER_NONE) || "''"; // The regex escaping code below is taken from the implementation of // goog.string.regExpEscape. - const functionName = JavaScript.provideFunction_( - 'textReplace', - ['function ' + JavaScript.FUNCTION_NAME_PLACEHOLDER_ + - '(haystack, needle, replacement) {', - ' needle = ' + - 'needle.replace(/([-()\\[\\]{}+?*.$\\^|,:# 0 ? 'else' : '') + 'if ' + conditionCode + ' then\n' + branchCode; diff --git a/generators/lua/math.js b/generators/lua/math.js index c51274830..b17821a33 100644 --- a/generators/lua/math.js +++ b/generators/lua/math.js @@ -25,11 +25,11 @@ Lua['math_number'] = function(block) { Lua['math_arithmetic'] = function(block) { // Basic arithmetic operators, and power. const OPERATORS = { - ADD: [' + ', Lua.ORDER_ADDITIVE], - MINUS: [' - ', Lua.ORDER_ADDITIVE], - MULTIPLY: [' * ', Lua.ORDER_MULTIPLICATIVE], - DIVIDE: [' / ', Lua.ORDER_MULTIPLICATIVE], - POWER: [' ^ ', Lua.ORDER_EXPONENTIATION] + 'ADD': [' + ', Lua.ORDER_ADDITIVE], + 'MINUS': [' - ', Lua.ORDER_ADDITIVE], + 'MULTIPLY': [' * ', Lua.ORDER_MULTIPLICATIVE], + 'DIVIDE': [' / ', Lua.ORDER_MULTIPLICATIVE], + 'POWER': [' ^ ', Lua.ORDER_EXPONENTIATION], }; const tuple = OPERATORS[block.getFieldValue('OP')]; const operator = tuple[0]; @@ -113,12 +113,12 @@ Lua['math_single'] = function(block) { Lua['math_constant'] = function(block) { // Constants: PI, E, the Golden Ratio, sqrt(2), 1/sqrt(2), INFINITY. const CONSTANTS = { - PI: ['math.pi', Lua.ORDER_HIGH], - E: ['math.exp(1)', Lua.ORDER_HIGH], - GOLDEN_RATIO: ['(1 + math.sqrt(5)) / 2', Lua.ORDER_MULTIPLICATIVE], - SQRT2: ['math.sqrt(2)', Lua.ORDER_HIGH], - SQRT1_2: ['math.sqrt(1 / 2)', Lua.ORDER_HIGH], - INFINITY: ['math.huge', Lua.ORDER_HIGH] + 'PI': ['math.pi', Lua.ORDER_HIGH], + 'E': ['math.exp(1)', Lua.ORDER_HIGH], + 'GOLDEN_RATIO': ['(1 + math.sqrt(5)) / 2', Lua.ORDER_MULTIPLICATIVE], + 'SQRT2': ['math.sqrt(2)', Lua.ORDER_HIGH], + 'SQRT1_2': ['math.sqrt(1 / 2)', Lua.ORDER_HIGH], + 'INFINITY': ['math.huge', Lua.ORDER_HIGH], }; return CONSTANTS[block.getFieldValue('CONSTANT')]; }; @@ -127,20 +127,13 @@ Lua['math_number_property'] = function(block) { // Check if a number is even, odd, prime, whole, positive, or negative // or if it is divisible by certain number. Returns true or false. const PROPERTIES = { - 'EVEN': [' % 2 == 0', Lua.ORDER_MULTIPLICATIVE, - Lua.ORDER_RELATIONAL], - 'ODD': [' % 2 == 1', Lua.ORDER_MULTIPLICATIVE, - Lua.ORDER_RELATIONAL], - 'WHOLE': [' % 1 == 0', Lua.ORDER_MULTIPLICATIVE, - Lua.ORDER_RELATIONAL], - 'POSITIVE': [' > 0', Lua.ORDER_RELATIONAL, - Lua.ORDER_RELATIONAL], - 'NEGATIVE': [' < 0', Lua.ORDER_RELATIONAL, - Lua.ORDER_RELATIONAL], - 'DIVISIBLE_BY': [null, Lua.ORDER_MULTIPLICATIVE, - Lua.ORDER_RELATIONAL], - 'PRIME': [null, Lua.ORDER_NONE, - Lua.ORDER_HIGH] + 'EVEN': [' % 2 == 0', Lua.ORDER_MULTIPLICATIVE, Lua.ORDER_RELATIONAL], + 'ODD': [' % 2 == 1', Lua.ORDER_MULTIPLICATIVE, Lua.ORDER_RELATIONAL], + 'WHOLE': [' % 1 == 0', Lua.ORDER_MULTIPLICATIVE, Lua.ORDER_RELATIONAL], + 'POSITIVE': [' > 0', Lua.ORDER_RELATIONAL, Lua.ORDER_RELATIONAL], + 'NEGATIVE': [' < 0', Lua.ORDER_RELATIONAL, Lua.ORDER_RELATIONAL], + 'DIVISIBLE_BY': [null, Lua.ORDER_MULTIPLICATIVE, Lua.ORDER_RELATIONAL], + 'PRIME': [null, Lua.ORDER_NONE, Lua.ORDER_HIGH], }; const dropdownProperty = block.getFieldValue('PROPERTY'); const [suffix, inputOrder, outputOrder] = PROPERTIES[dropdownProperty]; @@ -149,28 +142,28 @@ Lua['math_number_property'] = function(block) { let code; if (dropdownProperty === 'PRIME') { // Prime is a special case as it is not a one-liner test. - const functionName = Lua.provideFunction_( - 'math_isPrime', - ['function ' + Lua.FUNCTION_NAME_PLACEHOLDER_ + '(n)', - ' -- https://en.wikipedia.org/wiki/Primality_test#Naive_methods', - ' if n == 2 or n == 3 then', - ' return true', - ' end', - ' -- False if n is NaN, negative, is 1, or not whole.', - ' -- And false if n is divisible by 2 or 3.', - ' if not(n > 1) or n % 1 ~= 0 or n % 2 == 0 or n % 3 == 0 then', - ' return false', - ' end', - ' -- Check all the numbers of form 6k +/- 1, up to sqrt(n).', - ' for x = 6, math.sqrt(n) + 1.5, 6 do', - ' if n % (x - 1) == 0 or n % (x + 1) == 0 then', - ' return false', - ' end', - ' end', - ' return true', - 'end']); + const functionName = Lua.provideFunction_('math_isPrime', ` +function ${Lua.FUNCTION_NAME_PLACEHOLDER_}(n) + -- https://en.wikipedia.org/wiki/Primality_test#Naive_methods + if n == 2 or n == 3 then + return true + end + -- False if n is NaN, negative, is 1, or not whole. + -- And false if n is divisible by 2 or 3. + if not(n > 1) or n % 1 ~= 0 or n % 2 == 0 or n % 3 == 0 then + return false + end + -- Check all the numbers of form 6k +/- 1, up to sqrt(n). + for x = 6, math.sqrt(n) + 1.5, 6 do + if n % (x - 1) == 0 or n % (x + 1) == 0 then + return false + end + end + return true +end +`); code = functionName + '(' + numberToCheck + ')'; - } else if (dropdownProperty === 'DIVISIBLE_BY') { + } else if (dropdownProperty === 'DIVISIBLE_BY') { const divisor = Lua.valueToCode(block, 'DIVISOR', Lua.ORDER_MULTIPLICATIVE) || '0'; // If 'divisor' is some code that evals to 0, Lua will produce a nan. @@ -209,11 +202,15 @@ Lua['math_on_list'] = function(block) { // Functions needed in more than one case. function provideSum() { - return Lua.provideFunction_('math_sum', [ - 'function ' + Lua.FUNCTION_NAME_PLACEHOLDER_ + '(t)', - ' local result = 0', ' for _, v in ipairs(t) do', - ' result = result + v', ' end', ' return result', 'end' - ]); + return Lua.provideFunction_('math_sum', ` +function ${Lua.FUNCTION_NAME_PLACEHOLDER_}(t) + local result = 0 + for _, v in ipairs(t) do + result = result + v + end + return result +end +`); } switch (func) { @@ -223,103 +220,139 @@ Lua['math_on_list'] = function(block) { case 'MIN': // Returns 0 for the empty list. - functionName = Lua.provideFunction_('math_min', [ - 'function ' + Lua.FUNCTION_NAME_PLACEHOLDER_ + '(t)', - ' if #t == 0 then', ' return 0', ' end', - ' local result = math.huge', ' for _, v in ipairs(t) do', - ' if v < result then', ' result = v', ' end', ' end', - ' return result', 'end' - ]); + functionName = Lua.provideFunction_('math_min', ` +function ${Lua.FUNCTION_NAME_PLACEHOLDER_}(t) + if #t == 0 then + return 0 + end + local result = math.huge + for _, v in ipairs(t) do + if v < result then + result = v + end + end + return result +end +`); break; case 'AVERAGE': // Returns 0 for the empty list. - functionName = Lua.provideFunction_('math_average', [ - 'function ' + Lua.FUNCTION_NAME_PLACEHOLDER_ + '(t)', - ' if #t == 0 then', ' return 0', ' end', - ' return ' + provideSum() + '(t) / #t', 'end' - ]); + functionName = Lua.provideFunction_('math_average', ` +function ${Lua.FUNCTION_NAME_PLACEHOLDER_}(t) + if #t == 0 then + return 0 + end + return ${provideSum()}(t) / #t +end +`); break; case 'MAX': // Returns 0 for the empty list. - functionName = Lua.provideFunction_('math_max', [ - 'function ' + Lua.FUNCTION_NAME_PLACEHOLDER_ + '(t)', - ' if #t == 0 then', ' return 0', ' end', - ' local result = -math.huge', ' for _, v in ipairs(t) do', - ' if v > result then', ' result = v', ' end', ' end', - ' return result', 'end' - ]); + functionName = Lua.provideFunction_('math_max', ` +function ${Lua.FUNCTION_NAME_PLACEHOLDER_}(t) + if #t == 0 then + return 0 + end + local result = -math.huge + for _, v in ipairs(t) do + if v > result then + result = v + end + end + return result +end +`); break; case 'MEDIAN': - functionName = Lua.provideFunction_( - 'math_median', - // This operation excludes non-numbers. - [ - 'function ' + Lua.FUNCTION_NAME_PLACEHOLDER_ + '(t)', - ' -- Source: http://lua-users.org/wiki/SimpleStats', - ' if #t == 0 then', ' return 0', ' end', ' local temp={}', - ' for _, v in ipairs(t) do', ' if type(v) == "number" then', - ' table.insert(temp, v)', ' end', ' end', - ' table.sort(temp)', ' if #temp % 2 == 0 then', - ' return (temp[#temp/2] + temp[(#temp/2)+1]) / 2', ' else', - ' return temp[math.ceil(#temp/2)]', ' end', 'end' - ]); + // This operation excludes non-numbers. + functionName = Lua.provideFunction_('math_median', ` +function ${Lua.FUNCTION_NAME_PLACEHOLDER_}(t) + -- Source: http://lua-users.org/wiki/SimpleStats + if #t == 0 then + return 0 + end + local temp = {} + for _, v in ipairs(t) do + if type(v) == 'number' then + table.insert(temp, v) + end + end + table.sort(temp) + if #temp % 2 == 0 then + return (temp[#temp / 2] + temp[(#temp / 2) + 1]) / 2 + else + return temp[math.ceil(#temp / 2)] + end +end +`); break; case 'MODE': - functionName = Lua.provideFunction_( - 'math_modes', - // As a list of numbers can contain more than one mode, - // the returned result is provided as an array. - // The Lua version includes non-numbers. - [ - 'function ' + Lua.FUNCTION_NAME_PLACEHOLDER_ + '(t)', - ' -- Source: http://lua-users.org/wiki/SimpleStats', - ' local counts={}', - ' for _, v in ipairs(t) do', - ' if counts[v] == nil then', - ' counts[v] = 1', - ' else', - ' counts[v] = counts[v] + 1', - ' end', - ' end', - ' local biggestCount = 0', - ' for _, v in pairs(counts) do', - ' if v > biggestCount then', - ' biggestCount = v', - ' end', - ' end', - ' local temp={}', - ' for k, v in pairs(counts) do', - ' if v == biggestCount then', - ' table.insert(temp, k)', - ' end', - ' end', - ' return temp', - 'end' - ]); + // As a list of numbers can contain more than one mode, + // the returned result is provided as an array. + // The Lua version includes non-numbers. + functionName = Lua.provideFunction_('math_modes', ` +function ${Lua.FUNCTION_NAME_PLACEHOLDER_}(t) + -- Source: http://lua-users.org/wiki/SimpleStats + local counts = {} + for _, v in ipairs(t) do + if counts[v] == nil then + counts[v] = 1 + else + counts[v] = counts[v] + 1 + end + end + local biggestCount = 0 + for _, v in pairs(counts) do + if v > biggestCount then + biggestCount = v + end + end + local temp = {} + for k, v in pairs(counts) do + if v == biggestCount then + table.insert(temp, k) + end + end + return temp +end +`); break; case 'STD_DEV': - functionName = Lua.provideFunction_('math_standard_deviation', [ - 'function ' + Lua.FUNCTION_NAME_PLACEHOLDER_ + '(t)', ' local m', - ' local vm', ' local total = 0', ' local count = 0', - ' local result', ' m = #t == 0 and 0 or ' + provideSum() + '(t) / #t', - ' for _, v in ipairs(t) do', ' if type(v) == \'number\' then', - ' vm = v - m', ' total = total + (vm * vm)', - ' count = count + 1', ' end', ' end', - ' result = math.sqrt(total / (count-1))', ' return result', 'end' - ]); + functionName = Lua.provideFunction_('math_standard_deviation', ` +function ${Lua.FUNCTION_NAME_PLACEHOLDER_}(t) + local m + local vm + local total = 0 + local count = 0 + local result + m = #t == 0 and 0 or ${provideSum()}(t) / #t + for _, v in ipairs(t) do + if type(v) == 'number' then + vm = v - m + total = total + (vm * vm) + count = count + 1 + end + end + result = math.sqrt(total / (count-1)) + return result +end +`); break; case 'RANDOM': - functionName = Lua.provideFunction_('math_random_list', [ - 'function ' + Lua.FUNCTION_NAME_PLACEHOLDER_ + '(t)', - ' if #t == 0 then', ' return nil', ' end', - ' return t[math.random(#t)]', 'end' - ]); + functionName = Lua.provideFunction_('math_random_list', ` +function ${Lua.FUNCTION_NAME_PLACEHOLDER_}(t) + if #t == 0 then + return nil + end + return t[math.random(#t)] +end +`); break; default: diff --git a/generators/lua/text.js b/generators/lua/text.js index a8dae86c9..74fe842d8 100644 --- a/generators/lua/text.js +++ b/generators/lua/text.js @@ -32,22 +32,22 @@ Lua['text_multiline'] = function(block) { Lua['text_join'] = function(block) { // Create a string made up of any number of elements of any type. if (block.itemCount_ === 0) { - return ['\'\'', Lua.ORDER_ATOMIC]; + return ["''", Lua.ORDER_ATOMIC]; } else if (block.itemCount_ === 1) { - const element = Lua.valueToCode(block, 'ADD0', Lua.ORDER_NONE) || '\'\''; + const element = Lua.valueToCode(block, 'ADD0', Lua.ORDER_NONE) || "''"; const code = 'tostring(' + element + ')'; return [code, Lua.ORDER_HIGH]; } else if (block.itemCount_ === 2) { const element0 = - Lua.valueToCode(block, 'ADD0', Lua.ORDER_CONCATENATION) || '\'\''; + Lua.valueToCode(block, 'ADD0', Lua.ORDER_CONCATENATION) || "''"; const element1 = - Lua.valueToCode(block, 'ADD1', Lua.ORDER_CONCATENATION) || '\'\''; + Lua.valueToCode(block, 'ADD1', Lua.ORDER_CONCATENATION) || "''"; const code = element0 + ' .. ' + element1; return [code, Lua.ORDER_CONCATENATION]; } else { const elements = []; for (let i = 0; i < block.itemCount_; i++) { - elements[i] = Lua.valueToCode(block, 'ADD' + i, Lua.ORDER_NONE) || '\'\''; + elements[i] = Lua.valueToCode(block, 'ADD' + i, Lua.ORDER_NONE) || "''"; } const code = 'table.concat({' + elements.join(', ') + '})'; return [code, Lua.ORDER_HIGH]; @@ -59,41 +59,47 @@ Lua['text_append'] = function(block) { const varName = Lua.nameDB_.getName(block.getFieldValue('VAR'), NameType.VARIABLE); const value = - Lua.valueToCode(block, 'TEXT', Lua.ORDER_CONCATENATION) || '\'\''; + Lua.valueToCode(block, 'TEXT', Lua.ORDER_CONCATENATION) || "''"; return varName + ' = ' + varName + ' .. ' + value + '\n'; }; Lua['text_length'] = function(block) { // String or array length. - const text = Lua.valueToCode(block, 'VALUE', Lua.ORDER_UNARY) || '\'\''; + const text = Lua.valueToCode(block, 'VALUE', Lua.ORDER_UNARY) || "''"; return ['#' + text, Lua.ORDER_UNARY]; }; Lua['text_isEmpty'] = function(block) { // Is the string null or array empty? - const text = Lua.valueToCode(block, 'VALUE', Lua.ORDER_UNARY) || '\'\''; + const text = Lua.valueToCode(block, 'VALUE', Lua.ORDER_UNARY) || "''"; return ['#' + text + ' == 0', Lua.ORDER_RELATIONAL]; }; Lua['text_indexOf'] = function(block) { // Search the text for a substring. - const substring = Lua.valueToCode(block, 'FIND', Lua.ORDER_NONE) || '\'\''; - const text = Lua.valueToCode(block, 'VALUE', Lua.ORDER_NONE) || '\'\''; + const substring = Lua.valueToCode(block, 'FIND', Lua.ORDER_NONE) || "''"; + const text = Lua.valueToCode(block, 'VALUE', Lua.ORDER_NONE) || "''"; let functionName; if (block.getFieldValue('END') === 'FIRST') { - functionName = Lua.provideFunction_('firstIndexOf', [ - 'function ' + Lua.FUNCTION_NAME_PLACEHOLDER_ + '(str, substr) ', - ' local i = string.find(str, substr, 1, true)', ' if i == nil then', - ' return 0', ' else', ' return i', ' end', 'end' - ]); + functionName = Lua.provideFunction_('firstIndexOf', ` +function ${Lua.FUNCTION_NAME_PLACEHOLDER_}(str, substr) + local i = string.find(str, substr, 1, true) + if i == nil then + return 0 + end + return i +end +`); } else { - functionName = Lua.provideFunction_('lastIndexOf', [ - 'function ' + Lua.FUNCTION_NAME_PLACEHOLDER_ + '(str, substr)', - ' local i = string.find(string.reverse(str), ' + - 'string.reverse(substr), 1, true)', - ' if i then', ' return #str + 2 - i - #substr', ' end', ' return 0', - 'end' - ]); + functionName = Lua.provideFunction_('lastIndexOf', ` +function ${Lua.FUNCTION_NAME_PLACEHOLDER_}(str, substr) + local i = string.find(string.reverse(str), string.reverse(substr), 1, true) + if i then + return #str + 2 - i - #substr + end + return 0 +end +`); } const code = functionName + '(' + text + ', ' + substring + ')'; return [code, Lua.ORDER_HIGH]; @@ -105,14 +111,15 @@ Lua['text_charAt'] = function(block) { const where = block.getFieldValue('WHERE') || 'FROM_START'; const atOrder = (where === 'FROM_END') ? Lua.ORDER_UNARY : Lua.ORDER_NONE; const at = Lua.valueToCode(block, 'AT', atOrder) || '1'; - const text = Lua.valueToCode(block, 'VALUE', Lua.ORDER_NONE) || '\'\''; + const text = Lua.valueToCode(block, 'VALUE', Lua.ORDER_NONE) || "''"; let code; if (where === 'RANDOM') { - const functionName = Lua.provideFunction_('text_random_letter', [ - 'function ' + Lua.FUNCTION_NAME_PLACEHOLDER_ + '(str)', - ' local index = math.random(string.len(str))', - ' return string.sub(str, index, index)', 'end' - ]); + const functionName = Lua.provideFunction_('text_random_letter', ` +function ${Lua.FUNCTION_NAME_PLACEHOLDER_}(str) + local index = math.random(string.len(str)) + return string.sub(str, index, index) +end +`); code = functionName + '(' + text + ')'; } else { let start; @@ -133,10 +140,11 @@ Lua['text_charAt'] = function(block) { code = 'string.sub(' + text + ', ' + start + ', ' + start + ')'; } else { // use function to avoid reevaluation - const functionName = Lua.provideFunction_('text_char_at', [ - 'function ' + Lua.FUNCTION_NAME_PLACEHOLDER_ + '(str, index)', - ' return string.sub(str, index, index)', 'end' - ]); + const functionName = Lua.provideFunction_('text_char_at', ` +function ${Lua.FUNCTION_NAME_PLACEHOLDER_}(str, index) + return string.sub(str, index, index) +end +`); code = functionName + '(' + text + ', ' + start + ')'; } } @@ -145,7 +153,7 @@ Lua['text_charAt'] = function(block) { Lua['text_getSubstring'] = function(block) { // Get substring. - const text = Lua.valueToCode(block, 'STRING', Lua.ORDER_NONE) || '\'\''; + const text = Lua.valueToCode(block, 'STRING', Lua.ORDER_NONE) || "''"; // Get start index. const where1 = block.getFieldValue('WHERE1'); @@ -183,28 +191,35 @@ Lua['text_getSubstring'] = function(block) { Lua['text_changeCase'] = function(block) { // Change capitalization. const operator = block.getFieldValue('CASE'); - const text = Lua.valueToCode(block, 'TEXT', Lua.ORDER_NONE) || '\'\''; + const text = Lua.valueToCode(block, 'TEXT', Lua.ORDER_NONE) || "''"; let functionName; if (operator === 'UPPERCASE') { functionName = 'string.upper'; } else if (operator === 'LOWERCASE') { functionName = 'string.lower'; } else if (operator === 'TITLECASE') { - functionName = Lua.provideFunction_( - 'text_titlecase', - // There are shorter versions at - // http://lua-users.org/wiki/SciteTitleCase - // that do not preserve whitespace. - [ - 'function ' + Lua.FUNCTION_NAME_PLACEHOLDER_ + '(str)', - ' local buf = {}', ' local inWord = false', ' for i = 1, #str do', - ' local c = string.sub(str, i, i)', ' if inWord then', - ' table.insert(buf, string.lower(c))', - ' if string.find(c, "%s") then', ' inWord = false', - ' end', ' else', ' table.insert(buf, string.upper(c))', - ' inWord = true', ' end', ' end', - ' return table.concat(buf)', 'end' - ]); + // There are shorter versions at + // http://lua-users.org/wiki/SciteTitleCase + // that do not preserve whitespace. + functionName = Lua.provideFunction_('text_titlecase', ` +function ${Lua.FUNCTION_NAME_PLACEHOLDER_}(str) + local buf = {} + local inWord = false + for i = 1, #str do + local c = string.sub(str, i, i) + if inWord then + table.insert(buf, string.lower(c)) + if string.find(c, "%s") then + inWord = false + end + else + table.insert(buf, string.upper(c)) + inWord = true + end + end + return table.concat(buf) +end +`); } const code = functionName + '(' + text + ')'; return [code, Lua.ORDER_HIGH]; @@ -214,14 +229,14 @@ Lua['text_trim'] = function(block) { // Trim spaces. const OPERATORS = {LEFT: '^%s*(,-)', RIGHT: '(.-)%s*$', BOTH: '^%s*(.-)%s*$'}; const operator = OPERATORS[block.getFieldValue('MODE')]; - const text = Lua.valueToCode(block, 'TEXT', Lua.ORDER_NONE) || '\'\''; + const text = Lua.valueToCode(block, 'TEXT', Lua.ORDER_NONE) || "''"; const code = 'string.gsub(' + text + ', "' + operator + '", "%1")'; return [code, Lua.ORDER_HIGH]; }; Lua['text_print'] = function(block) { // Print statement. - const msg = Lua.valueToCode(block, 'TEXT', Lua.ORDER_NONE) || '\'\''; + const msg = Lua.valueToCode(block, 'TEXT', Lua.ORDER_NONE) || "''"; return 'print(' + msg + ')\n'; }; @@ -233,13 +248,16 @@ Lua['text_prompt_ext'] = function(block) { msg = Lua.quote_(block.getFieldValue('TEXT')); } else { // External message. - msg = Lua.valueToCode(block, 'TEXT', Lua.ORDER_NONE) || '\'\''; + msg = Lua.valueToCode(block, 'TEXT', Lua.ORDER_NONE) || "''"; } - const functionName = Lua.provideFunction_('text_prompt', [ - 'function ' + Lua.FUNCTION_NAME_PLACEHOLDER_ + '(msg)', ' io.write(msg)', - ' io.flush()', ' return io.read()', 'end' - ]); + const functionName = Lua.provideFunction_('text_prompt', ` +function ${Lua.FUNCTION_NAME_PLACEHOLDER_}(msg) + io.write(msg) + io.flush() + return io.read() +end +`); let code = functionName + '(' + msg + ')'; const toNumber = block.getFieldValue('TYPE') === 'NUMBER'; @@ -252,59 +270,58 @@ Lua['text_prompt_ext'] = function(block) { Lua['text_prompt'] = Lua['text_prompt_ext']; Lua['text_count'] = function(block) { - const text = Lua.valueToCode(block, 'TEXT', Lua.ORDER_NONE) || '\'\''; - const sub = Lua.valueToCode(block, 'SUB', Lua.ORDER_NONE) || '\'\''; - const functionName = Lua.provideFunction_('text_count', [ - 'function ' + Lua.FUNCTION_NAME_PLACEHOLDER_ + '(haystack, needle)', - ' if #needle == 0 then', - ' return #haystack + 1', - ' end', - ' local i = 1', - ' local count = 0', - ' while true do', - ' i = string.find(haystack, needle, i, true)', - ' if i == nil then', - ' break', - ' end', - ' count = count + 1', - ' i = i + #needle', - ' end', - ' return count', - 'end', - ]); + const text = Lua.valueToCode(block, 'TEXT', Lua.ORDER_NONE) || "''"; + const sub = Lua.valueToCode(block, 'SUB', Lua.ORDER_NONE) || "''"; + const functionName = Lua.provideFunction_('text_count', ` +function ${Lua.FUNCTION_NAME_PLACEHOLDER_}(haystack, needle) + if #needle == 0 then + return #haystack + 1 + end + local i = 1 + local count = 0 + while true do + i = string.find(haystack, needle, i, true) + if i == nil then + break + end + count = count + 1 + i = i + #needle + end + return count +end +`); const code = functionName + '(' + text + ', ' + sub + ')'; return [code, Lua.ORDER_HIGH]; }; Lua['text_replace'] = function(block) { - const text = Lua.valueToCode(block, 'TEXT', Lua.ORDER_NONE) || '\'\''; - const from = Lua.valueToCode(block, 'FROM', Lua.ORDER_NONE) || '\'\''; - const to = Lua.valueToCode(block, 'TO', Lua.ORDER_NONE) || '\'\''; - const functionName = Lua.provideFunction_('text_replace', [ - 'function ' + Lua.FUNCTION_NAME_PLACEHOLDER_ + - '(haystack, needle, replacement)', - ' local buf = {}', - ' local i = 1', - ' while i <= #haystack do', - ' if string.sub(haystack, i, i + #needle - 1) == needle then', - ' for j = 1, #replacement do', - ' table.insert(buf, string.sub(replacement, j, j))', - ' end', - ' i = i + #needle', - ' else', - ' table.insert(buf, string.sub(haystack, i, i))', - ' i = i + 1', - ' end', - ' end', - ' return table.concat(buf)', - 'end', - ]); + const text = Lua.valueToCode(block, 'TEXT', Lua.ORDER_NONE) || "''"; + const from = Lua.valueToCode(block, 'FROM', Lua.ORDER_NONE) || "''"; + const to = Lua.valueToCode(block, 'TO', Lua.ORDER_NONE) || "''"; + const functionName = Lua.provideFunction_('text_replace', ` +function ${Lua.FUNCTION_NAME_PLACEHOLDER_}(haystack, needle, replacement) + local buf = {} + local i = 1 + while i <= #haystack do + if string.sub(haystack, i, i + #needle - 1) == needle then + for j = 1, #replacement do + table.insert(buf, string.sub(replacement, j, j)) + end + i = i + #needle + else + table.insert(buf, string.sub(haystack, i, i)) + i = i + 1 + end + end + return table.concat(buf) +end +`); const code = functionName + '(' + text + ', ' + from + ', ' + to + ')'; return [code, Lua.ORDER_HIGH]; }; Lua['text_reverse'] = function(block) { - const text = Lua.valueToCode(block, 'TEXT', Lua.ORDER_NONE) || '\'\''; + const text = Lua.valueToCode(block, 'TEXT', Lua.ORDER_NONE) || "''"; const code = 'string.reverse(' + text + ')'; return [code, Lua.ORDER_HIGH]; }; diff --git a/generators/php/colour.js b/generators/php/colour.js index d50cbfb63..bbd2fd9d7 100644 --- a/generators/php/colour.js +++ b/generators/php/colour.js @@ -22,12 +22,11 @@ PHP['colour_picker'] = function(block) { PHP['colour_random'] = function(block) { // Generate a random colour. - const functionName = PHP.provideFunction_('colour_random', [ - 'function ' + PHP.FUNCTION_NAME_PLACEHOLDER_ + '() {', - ' return \'#\' . str_pad(dechex(mt_rand(0, 0xFFFFFF)), ' + - '6, \'0\', STR_PAD_LEFT);', - '}' - ]); + const functionName = PHP.provideFunction_('colour_random', ` +function ${PHP.FUNCTION_NAME_PLACEHOLDER_}() { + return '#' . str_pad(dechex(mt_rand(0, 0xFFFFFF)), 6, '0', STR_PAD_LEFT); +} +`); const code = functionName + '()'; return [code, PHP.ORDER_FUNCTION_CALL]; }; @@ -37,39 +36,46 @@ PHP['colour_rgb'] = function(block) { const red = PHP.valueToCode(block, 'RED', PHP.ORDER_NONE) || 0; const green = PHP.valueToCode(block, 'GREEN', PHP.ORDER_NONE) || 0; const blue = PHP.valueToCode(block, 'BLUE', PHP.ORDER_NONE) || 0; - const functionName = PHP.provideFunction_('colour_rgb', [ - 'function ' + PHP.FUNCTION_NAME_PLACEHOLDER_ + '($r, $g, $b) {', - ' $r = round(max(min($r, 100), 0) * 2.55);', - ' $g = round(max(min($g, 100), 0) * 2.55);', - ' $b = round(max(min($b, 100), 0) * 2.55);', ' $hex = \'#\';', - ' $hex .= str_pad(dechex($r), 2, \'0\', STR_PAD_LEFT);', - ' $hex .= str_pad(dechex($g), 2, \'0\', STR_PAD_LEFT);', - ' $hex .= str_pad(dechex($b), 2, \'0\', STR_PAD_LEFT);', ' return $hex;', - '}' - ]); + const functionName = PHP.provideFunction_('colour_rgb', ` +function ${PHP.FUNCTION_NAME_PLACEHOLDER_}($r, $g, $b) { + $r = round(max(min($r, 100), 0) * 2.55); + $g = round(max(min($g, 100), 0) * 2.55); + $b = round(max(min($b, 100), 0) * 2.55); + $hex = '#'; + $hex .= str_pad(dechex($r), 2, '0', STR_PAD_LEFT); + $hex .= str_pad(dechex($g), 2, '0', STR_PAD_LEFT); + $hex .= str_pad(dechex($b), 2, '0', STR_PAD_LEFT); + return $hex; +} +`); const code = functionName + '(' + red + ', ' + green + ', ' + blue + ')'; return [code, PHP.ORDER_FUNCTION_CALL]; }; PHP['colour_blend'] = function(block) { // Blend two colours together. - const c1 = PHP.valueToCode(block, 'COLOUR1', PHP.ORDER_NONE) || '\'#000000\''; - const c2 = PHP.valueToCode(block, 'COLOUR2', PHP.ORDER_NONE) || '\'#000000\''; + const c1 = PHP.valueToCode(block, 'COLOUR1', PHP.ORDER_NONE) || "'#000000'"; + const c2 = PHP.valueToCode(block, 'COLOUR2', PHP.ORDER_NONE) || "'#000000'"; const ratio = PHP.valueToCode(block, 'RATIO', PHP.ORDER_NONE) || 0.5; - const functionName = PHP.provideFunction_('colour_blend', [ - 'function ' + PHP.FUNCTION_NAME_PLACEHOLDER_ + '($c1, $c2, $ratio) {', - ' $ratio = max(min($ratio, 1), 0);', ' $r1 = hexdec(substr($c1, 1, 2));', - ' $g1 = hexdec(substr($c1, 3, 2));', ' $b1 = hexdec(substr($c1, 5, 2));', - ' $r2 = hexdec(substr($c2, 1, 2));', ' $g2 = hexdec(substr($c2, 3, 2));', - ' $b2 = hexdec(substr($c2, 5, 2));', - ' $r = round($r1 * (1 - $ratio) + $r2 * $ratio);', - ' $g = round($g1 * (1 - $ratio) + $g2 * $ratio);', - ' $b = round($b1 * (1 - $ratio) + $b2 * $ratio);', ' $hex = \'#\';', - ' $hex .= str_pad(dechex($r), 2, \'0\', STR_PAD_LEFT);', - ' $hex .= str_pad(dechex($g), 2, \'0\', STR_PAD_LEFT);', - ' $hex .= str_pad(dechex($b), 2, \'0\', STR_PAD_LEFT);', ' return $hex;', - '}' - ]); + const functionName = PHP.provideFunction_('colour_blend', ` +function ${PHP.FUNCTION_NAME_PLACEHOLDER_}($c1, $c2, $ratio) { + $ratio = max(min($ratio, 1), 0); + $r1 = hexdec(substr($c1, 1, 2)); + $g1 = hexdec(substr($c1, 3, 2)); + $b1 = hexdec(substr($c1, 5, 2)); + $r2 = hexdec(substr($c2, 1, 2)); + $g2 = hexdec(substr($c2, 3, 2)); + $b2 = hexdec(substr($c2, 5, 2)); + $r = round($r1 * (1 - $ratio) + $r2 * $ratio); + $g = round($g1 * (1 - $ratio) + $g2 * $ratio); + $b = round($b1 * (1 - $ratio) + $b2 * $ratio); + $hex = '#'; + $hex .= str_pad(dechex($r), 2, '0', STR_PAD_LEFT); + $hex .= str_pad(dechex($g), 2, '0', STR_PAD_LEFT); + $hex .= str_pad(dechex($b), 2, '0', STR_PAD_LEFT); + return $hex; +} +`); const code = functionName + '(' + c1 + ', ' + c2 + ', ' + ratio + ')'; return [code, PHP.ORDER_FUNCTION_CALL]; }; diff --git a/generators/php/lists.js b/generators/php/lists.js index efc237887..1c39a1ab6 100644 --- a/generators/php/lists.js +++ b/generators/php/lists.js @@ -44,11 +44,15 @@ PHP['lists_create_with'] = function(block) { PHP['lists_repeat'] = function(block) { // Create a list with one element repeated. - const functionName = PHP.provideFunction_('lists_repeat', [ - 'function ' + PHP.FUNCTION_NAME_PLACEHOLDER_ + '($value, $count) {', - ' $array = array();', ' for ($index = 0; $index < $count; $index++) {', - ' $array[] = $value;', ' }', ' return $array;', '}' - ]); + const functionName = PHP.provideFunction_('lists_repeat', ` +function ${PHP.FUNCTION_NAME_PLACEHOLDER_}($value, $count) { + $array = array(); + for ($index = 0; $index < $count; $index++) { + $array[] = $value; + } + return $array; +} +`); const element = PHP.valueToCode(block, 'ITEM', PHP.ORDER_NONE) || 'null'; const repeatCount = PHP.valueToCode(block, 'NUM', PHP.ORDER_NONE) || '0'; const code = functionName + '(' + element + ', ' + repeatCount + ')'; @@ -57,12 +61,16 @@ PHP['lists_repeat'] = function(block) { PHP['lists_length'] = function(block) { // String or array length. - const functionName = PHP.provideFunction_('length', [ - 'function ' + PHP.FUNCTION_NAME_PLACEHOLDER_ + '($value) {', - ' if (is_string($value)) {', ' return strlen($value);', ' } else {', - ' return count($value);', ' }', '}' - ]); - const list = PHP.valueToCode(block, 'VALUE', PHP.ORDER_NONE) || '\'\''; + const functionName = PHP.provideFunction_('length', ` +function ${PHP.FUNCTION_NAME_PLACEHOLDER_}($value) { + if (is_string($value)) { + return strlen($value); + } else { + return count($value); + } +} +`); + const list = PHP.valueToCode(block, 'VALUE', PHP.ORDER_NONE) || "''"; return [functionName + '(' + list + ')', PHP.ORDER_FUNCTION_CALL]; }; @@ -75,7 +83,7 @@ PHP['lists_isEmpty'] = function(block) { PHP['lists_indexOf'] = function(block) { // Find an item in the list. - const argument0 = PHP.valueToCode(block, 'FIND', PHP.ORDER_NONE) || '\'\''; + const argument0 = PHP.valueToCode(block, 'FIND', PHP.ORDER_NONE) || "''"; const argument1 = PHP.valueToCode(block, 'VALUE', PHP.ORDER_MEMBER) || '[]'; let errorIndex = ' -1'; let indexAdjustment = ''; @@ -86,23 +94,25 @@ PHP['lists_indexOf'] = function(block) { let functionName; if (block.getFieldValue('END') === 'FIRST') { // indexOf - functionName = PHP.provideFunction_('indexOf', [ - 'function ' + PHP.FUNCTION_NAME_PLACEHOLDER_ + '($haystack, $needle) {', - ' for ($index = 0; $index < count($haystack); $index++) {', - ' if ($haystack[$index] == $needle) return $index' + indexAdjustment + - ';', - ' }', ' return ' + errorIndex + ';', '}' - ]); + functionName = PHP.provideFunction_('indexOf', ` +function ${PHP.FUNCTION_NAME_PLACEHOLDER_}($haystack, $needle) { + for ($index = 0; $index < count($haystack); $index++) { + if ($haystack[$index] == $needle) return $index${indexAdjustment}; + } + return ${errorIndex}; +} +`); } else { // lastIndexOf - functionName = PHP.provideFunction_('lastIndexOf', [ - 'function ' + PHP.FUNCTION_NAME_PLACEHOLDER_ + '($haystack, $needle) {', - ' $last = ' + errorIndex + ';', - ' for ($index = 0; $index < count($haystack); $index++) {', - ' if ($haystack[$index] == $needle) $last = $index' + indexAdjustment + - ';', - ' }', ' return $last;', '}' - ]); + functionName = PHP.provideFunction_('lastIndexOf', ` +function ${PHP.FUNCTION_NAME_PLACEHOLDER_}($haystack, $needle) { + $last = ${errorIndex}; + for ($index = 0; $index < count($haystack); $index++) { + if ($haystack[$index] == $needle) $last = $index${indexAdjustment}; + } + return $last; +} +`); } const code = functionName + '(' + argument1 + ', ' + argument0 + ')'; @@ -191,26 +201,30 @@ PHP['lists_getIndex'] = function(block) { case 'RANDOM': { const list = PHP.valueToCode(block, 'VALUE', PHP.ORDER_NONE) || 'array()'; if (mode === 'GET') { - const functionName = PHP.provideFunction_('lists_get_random_item', [ - 'function ' + PHP.FUNCTION_NAME_PLACEHOLDER_ + '($list) {', - ' return $list[rand(0,count($list)-1)];', '}' - ]); + const functionName = PHP.provideFunction_('lists_get_random_item', ` +function ${PHP.FUNCTION_NAME_PLACEHOLDER_}($list) { + return $list[rand(0,count($list)-1)]; +} +`); const code = functionName + '(' + list + ')'; return [code, PHP.ORDER_FUNCTION_CALL]; } else if (mode === 'GET_REMOVE') { const functionName = - PHP.provideFunction_('lists_get_remove_random_item', [ - 'function ' + PHP.FUNCTION_NAME_PLACEHOLDER_ + '(&$list) {', - ' $x = rand(0,count($list)-1);', ' unset($list[$x]);', - ' return array_values($list);', '}' - ]); + PHP.provideFunction_('lists_get_remove_random_item', ` +function ${PHP.FUNCTION_NAME_PLACEHOLDER_}(&$list) { + $x = rand(0,count($list)-1); + unset($list[$x]); + return array_values($list); +} +`); const code = functionName + '(' + list + ')'; return [code, PHP.ORDER_FUNCTION_CALL]; } else if (mode === 'REMOVE') { - const functionName = PHP.provideFunction_('lists_remove_random_item', [ - 'function ' + PHP.FUNCTION_NAME_PLACEHOLDER_ + '(&$list) {', - ' unset($list[rand(0,count($list)-1)]);', '}' - ]); + const functionName = PHP.provideFunction_('lists_remove_random_item', ` +function ${PHP.FUNCTION_NAME_PLACEHOLDER_}(&$list) { + unset($list[rand(0,count($list)-1)]); +} +`); return functionName + '(' + list + ');\n'; } break; @@ -252,10 +266,11 @@ PHP['lists_setIndex'] = function(block) { case 'LAST': { const list = PHP.valueToCode(block, 'LIST', PHP.ORDER_NONE) || 'array()'; if (mode === 'SET') { - const functionName = PHP.provideFunction_('lists_set_last_item', [ - 'function ' + PHP.FUNCTION_NAME_PLACEHOLDER_ + '(&$list, $value) {', - ' $list[count($list) - 1] = $value;', '}' - ]); + const functionName = PHP.provideFunction_('lists_set_last_item', ` +function ${PHP.FUNCTION_NAME_PLACEHOLDER_}(&$list, $value) { + $list[count($list) - 1] = $value; +} +`); return functionName + '(' + list + ', ' + value + ');\n'; } else if (mode === 'INSERT') { return 'array_push(' + list + ', ' + value + ');\n'; @@ -279,18 +294,18 @@ PHP['lists_setIndex'] = function(block) { const list = PHP.valueToCode(block, 'LIST', PHP.ORDER_NONE) || 'array()'; const at = PHP.getAdjusted(block, 'AT', 1); if (mode === 'SET') { - const functionName = PHP.provideFunction_('lists_set_from_end', [ - 'function ' + PHP.FUNCTION_NAME_PLACEHOLDER_ + - '(&$list, $at, $value) {', - ' $list[count($list) - $at] = $value;', '}' - ]); + const functionName = PHP.provideFunction_('lists_set_from_end', ` +function ${PHP.FUNCTION_NAME_PLACEHOLDER_}(&$list, $at, $value) { + $list[count($list) - $at] = $value; +} +`); return functionName + '(' + list + ', ' + at + ', ' + value + ');\n'; } else if (mode === 'INSERT') { - const functionName = PHP.provideFunction_('lists_insert_from_end', [ - 'function ' + PHP.FUNCTION_NAME_PLACEHOLDER_ + - '(&$list, $at, $value) {', - ' return array_splice($list, count($list) - $at, 0, $value);', '}' - ]); + const functionName = PHP.provideFunction_('lists_insert_from_end', ` +function ${PHP.FUNCTION_NAME_PLACEHOLDER_}(&$list, $at, $value) { + return array_splice($list, count($list) - $at, 0, $value); +} +`); return functionName + '(' + list + ', ' + at + ', ' + value + ');\n'; } break; @@ -382,29 +397,28 @@ PHP['lists_getSublist'] = function(block) { } else { const at1 = PHP.getAdjusted(block, 'AT1'); const at2 = PHP.getAdjusted(block, 'AT2'); - const functionName = PHP.provideFunction_('lists_get_sublist', [ - 'function ' + PHP.FUNCTION_NAME_PLACEHOLDER_ + - '($list, $where1, $at1, $where2, $at2) {', - ' if ($where1 == \'FROM_END\') {', - ' $at1 = count($list) - 1 - $at1;', - ' } else if ($where1 == \'FIRST\') {', - ' $at1 = 0;', - ' } else if ($where1 != \'FROM_START\') {', - ' throw new Exception(\'Unhandled option (lists_get_sublist).\');', - ' }', - ' $length = 0;', - ' if ($where2 == \'FROM_START\') {', - ' $length = $at2 - $at1 + 1;', - ' } else if ($where2 == \'FROM_END\') {', - ' $length = count($list) - $at1 - $at2;', - ' } else if ($where2 == \'LAST\') {', - ' $length = count($list) - $at1;', - ' } else {', - ' throw new Exception(\'Unhandled option (lists_get_sublist).\');', - ' }', - ' return array_slice($list, $at1, $length);', - '}' - ]); + const functionName = PHP.provideFunction_('lists_get_sublist', ` +function ${PHP.FUNCTION_NAME_PLACEHOLDER_}($list, $where1, $at1, $where2, $at2) { + if ($where1 == 'FROM_END') { + $at1 = count($list) - 1 - $at1; + } else if ($where1 == 'FIRST') { + $at1 = 0; + } else if ($where1 != 'FROM_START') { + throw new Exception('Unhandled option (lists_get_sublist).'); + } + $length = 0; + if ($where2 == 'FROM_START') { + $length = $at2 - $at1 + 1; + } else if ($where2 == 'FROM_END') { + $length = count($list) - $at1 - $at2; + } else if ($where2 == 'LAST') { + $length = count($list) - $at1; + } else { + throw new Exception('Unhandled option (lists_get_sublist).'); + } + return array_slice($list, $at1, $length); +} +`); code = functionName + '(' + list + ', \'' + where1 + '\', ' + at1 + ', \'' + where2 + '\', ' + at2 + ')'; } @@ -416,16 +430,22 @@ PHP['lists_sort'] = function(block) { const listCode = PHP.valueToCode(block, 'LIST', PHP.ORDER_NONE) || 'array()'; const direction = block.getFieldValue('DIRECTION') === '1' ? 1 : -1; const type = block.getFieldValue('TYPE'); - const functionName = PHP.provideFunction_('lists_sort', [ - 'function ' + PHP.FUNCTION_NAME_PLACEHOLDER_ + - '($list, $type, $direction) {', - ' $sortCmpFuncs = array(', ' "NUMERIC" => "strnatcasecmp",', - ' "TEXT" => "strcmp",', ' "IGNORE_CASE" => "strcasecmp"', ' );', - ' $sortCmp = $sortCmpFuncs[$type];', - ' $list2 = $list;', // Clone list. - ' usort($list2, $sortCmp);', ' if ($direction == -1) {', - ' $list2 = array_reverse($list2);', ' }', ' return $list2;', '}' - ]); + const functionName = PHP.provideFunction_('lists_sort', ` +function ${PHP.FUNCTION_NAME_PLACEHOLDER_}($list, $type, $direction) { + $sortCmpFuncs = array( + 'NUMERIC' => 'strnatcasecmp', + 'TEXT' => 'strcmp', + 'IGNORE_CASE' => 'strcasecmp' + ); + $sortCmp = $sortCmpFuncs[$type]; + $list2 = $list; + usort($list2, $sortCmp); + if ($direction == -1) { + $list2 = array_reverse($list2); + } + return $list2; +} +`); const sortCode = functionName + '(' + listCode + ', "' + type + '", ' + direction + ')'; return [sortCode, PHP.ORDER_FUNCTION_CALL]; @@ -434,12 +454,12 @@ PHP['lists_sort'] = function(block) { PHP['lists_split'] = function(block) { // Block for splitting text into a list, or joining a list into text. let value_input = PHP.valueToCode(block, 'INPUT', PHP.ORDER_NONE); - const value_delim = PHP.valueToCode(block, 'DELIM', PHP.ORDER_NONE) || '\'\''; + const value_delim = PHP.valueToCode(block, 'DELIM', PHP.ORDER_NONE) || "''"; const mode = block.getFieldValue('MODE'); let functionName; if (mode === 'SPLIT') { if (!value_input) { - value_input = '\'\''; + value_input = "''"; } functionName = 'explode'; } else if (mode === 'JOIN') { diff --git a/generators/php/math.js b/generators/php/math.js index 1c1e3e621..6c8c5ffb4 100644 --- a/generators/php/math.js +++ b/generators/php/math.js @@ -34,7 +34,7 @@ PHP['math_arithmetic'] = function(block) { 'MINUS': [' - ', PHP.ORDER_SUBTRACTION], 'MULTIPLY': [' * ', PHP.ORDER_MULTIPLICATION], 'DIVIDE': [' / ', PHP.ORDER_DIVISION], - 'POWER': [' ** ', PHP.ORDER_POWER] + 'POWER': [' ** ', PHP.ORDER_POWER], }; const tuple = OPERATORS[block.getFieldValue('OP')]; const operator = tuple[0]; @@ -134,7 +134,7 @@ PHP['math_constant'] = function(block) { 'GOLDEN_RATIO': ['(1 + sqrt(5)) / 2', PHP.ORDER_DIVISION], 'SQRT2': ['M_SQRT2', PHP.ORDER_ATOMIC], 'SQRT1_2': ['M_SQRT1_2', PHP.ORDER_ATOMIC], - 'INFINITY': ['INF', PHP.ORDER_ATOMIC] + 'INFINITY': ['INF', PHP.ORDER_ATOMIC], }; return CONSTANTS[block.getFieldValue('CONSTANT')]; }; @@ -143,20 +143,13 @@ PHP['math_number_property'] = function(block) { // Check if a number is even, odd, prime, whole, positive, or negative // or if it is divisible by certain number. Returns true or false. const PROPERTIES = { - 'EVEN': ['', ' % 2 == 0', PHP.ORDER_MODULUS, - PHP.ORDER_EQUALITY], - 'ODD': ['', ' % 2 == 1', PHP.ORDER_MODULUS, - PHP.ORDER_EQUALITY], - 'WHOLE': ['is_int(', ')', PHP.ORDER_NONE, - PHP.ORDER_FUNCTION_CALL], - 'POSITIVE': ['', ' > 0', PHP.ORDER_RELATIONAL, - PHP.ORDER_RELATIONAL], - 'NEGATIVE': ['', ' < 0', PHP.ORDER_RELATIONAL, - PHP.ORDER_RELATIONAL], - 'DIVISIBLE_BY': [null, null, PHP.ORDER_MODULUS, - PHP.ORDER_EQUALITY], - 'PRIME': [null, null, PHP.ORDER_NONE, - PHP.ORDER_FUNCTION_CALL] + 'EVEN': ['', ' % 2 == 0', PHP.ORDER_MODULUS, PHP.ORDER_EQUALITY], + 'ODD': ['', ' % 2 == 1', PHP.ORDER_MODULUS, PHP.ORDER_EQUALITY], + 'WHOLE': ['is_int(', ')', PHP.ORDER_NONE, PHP.ORDER_FUNCTION_CALL], + 'POSITIVE': ['', ' > 0', PHP.ORDER_RELATIONAL, PHP.ORDER_RELATIONAL], + 'NEGATIVE': ['', ' < 0', PHP.ORDER_RELATIONAL, PHP.ORDER_RELATIONAL], + 'DIVISIBLE_BY': [null, null, PHP.ORDER_MODULUS, PHP.ORDER_EQUALITY], + 'PRIME': [null, null, PHP.ORDER_NONE, PHP.ORDER_FUNCTION_CALL], }; const dropdownProperty = block.getFieldValue('PROPERTY'); const [prefix, suffix, inputOrder, outputOrder] = PROPERTIES[dropdownProperty]; @@ -165,27 +158,26 @@ PHP['math_number_property'] = function(block) { let code; if (dropdownProperty === 'PRIME') { // Prime is a special case as it is not a one-liner test. - const functionName = PHP.provideFunction_( - 'math_isPrime', - ['function ' + PHP.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 (!is_numeric($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 ($x = 6; $x <= sqrt($n) + 1; $x += 6) {', - ' if ($n % ($x - 1) == 0 || $n % ($x + 1) == 0) {', - ' return false;', - ' }', - ' }', - ' return true;', - '}']); + const functionName = PHP.provideFunction_('math_isPrime', ` +function ${PHP.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 (!is_numeric($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 ($x = 6; $x <= sqrt($n) + 1; $x += 6) { + if ($n % ($x - 1) == 0 || $n % ($x + 1) == 0) { + return false; + } + } + return true; +} +`); code = functionName + '(' + numberToCheck + ')'; } else if (dropdownProperty === 'DIVISIBLE_BY') { const divisor = PHP.valueToCode(block, 'DIVISOR', @@ -236,23 +228,23 @@ PHP['math_on_list'] = function(block) { code = 'max(' + list + ')'; break; case 'AVERAGE': { - const functionName = PHP.provideFunction_('math_mean', [ - 'function ' + PHP.FUNCTION_NAME_PLACEHOLDER_ + '($myList) {', - ' return array_sum($myList) / count($myList);', '}' - ]); + const functionName = PHP.provideFunction_('math_mean', ` +function ${PHP.FUNCTION_NAME_PLACEHOLDER_}($myList) { + return array_sum($myList) / count($myList); +} +`); list = PHP.valueToCode(block, 'LIST', PHP.ORDER_NONE) || 'array()'; code = functionName + '(' + list + ')'; break; } case 'MEDIAN': { - const functionName = PHP.provideFunction_('math_median', [ - 'function ' + PHP.FUNCTION_NAME_PLACEHOLDER_ + '($arr) {', - ' sort($arr,SORT_NUMERIC);', - ' return (count($arr) % 2) ? $arr[floor(count($arr)/2)] : ', - ' ($arr[floor(count($arr)/2)] + $arr[floor(count($arr)/2)' + - ' - 1]) / 2;', - '}' - ]); + const functionName = PHP.provideFunction_('math_median', ` +function ${PHP.FUNCTION_NAME_PLACEHOLDER_}($arr) { + sort($arr,SORT_NUMERIC); + return (count($arr) % 2) ? $arr[floor(count($arr) / 2)] : + ($arr[floor(count($arr) / 2)] + $arr[floor(count($arr) / 2) - 1]) / 2; +} +`); list = PHP.valueToCode(block, 'LIST', PHP.ORDER_NONE) || '[]'; code = functionName + '(' + list + ')'; break; @@ -261,36 +253,40 @@ PHP['math_on_list'] = function(block) { // As a list of numbers can contain more than one mode, // the returned result is provided as an array. // Mode of [3, 'x', 'x', 1, 1, 2, '3'] -> ['x', 1]. - const functionName = PHP.provideFunction_('math_modes', [ - 'function ' + PHP.FUNCTION_NAME_PLACEHOLDER_ + '($values) {', - ' if (empty($values)) return array();', - ' $counts = array_count_values($values);', - ' arsort($counts); // Sort counts in descending order', - ' $modes = array_keys($counts, current($counts), true);', - ' return $modes;', '}' - ]); + const functionName = PHP.provideFunction_('math_modes', ` +function ${PHP.FUNCTION_NAME_PLACEHOLDER_}($values) { + if (empty($values)) return array(); + $counts = array_count_values($values); + arsort($counts); // Sort counts in descending order + $modes = array_keys($counts, current($counts), true); + return $modes; +} +`); list = PHP.valueToCode(block, 'LIST', PHP.ORDER_NONE) || '[]'; code = functionName + '(' + list + ')'; break; } case 'STD_DEV': { - const functionName = PHP.provideFunction_('math_standard_deviation', [ - 'function ' + PHP.FUNCTION_NAME_PLACEHOLDER_ + '($numbers) {', - ' $n = count($numbers);', ' if (!$n) return null;', - ' $mean = array_sum($numbers) / count($numbers);', - ' foreach($numbers as $key => $num) $devs[$key] = ' + - 'pow($num - $mean, 2);', - ' return sqrt(array_sum($devs) / (count($devs) - 1));', '}' - ]); + const functionName = PHP.provideFunction_('math_standard_deviation', ` +function ${PHP.FUNCTION_NAME_PLACEHOLDER_}($numbers) { + $n = count($numbers); + if (!$n) return null; + $mean = array_sum($numbers) / count($numbers); + foreach($numbers as $key => $num) $devs[$key] = pow($num - $mean, 2); + return sqrt(array_sum($devs) / (count($devs) - 1)); +} +`); list = PHP.valueToCode(block, 'LIST', PHP.ORDER_NONE) || '[]'; code = functionName + '(' + list + ')'; break; } case 'RANDOM': { - const functionName = PHP.provideFunction_('math_random_list', [ - 'function ' + PHP.FUNCTION_NAME_PLACEHOLDER_ + '($list) {', - ' $x = rand(0, count($list)-1);', ' return $list[$x];', '}' - ]); + const functionName = PHP.provideFunction_('math_random_list', ` +function ${PHP.FUNCTION_NAME_PLACEHOLDER_}($list) { + $x = rand(0, count($list)-1); + return $list[$x]; +} +`); list = PHP.valueToCode(block, 'LIST', PHP.ORDER_NONE) || '[]'; code = functionName + '(' + list + ')'; break; @@ -325,11 +321,14 @@ PHP['math_random_int'] = function(block) { // Random integer between [X] and [Y]. const argument0 = PHP.valueToCode(block, 'FROM', PHP.ORDER_NONE) || '0'; const argument1 = PHP.valueToCode(block, 'TO', PHP.ORDER_NONE) || '0'; - const functionName = PHP.provideFunction_('math_random_int', [ - 'function ' + PHP.FUNCTION_NAME_PLACEHOLDER_ + '($a, $b) {', - ' if ($a > $b) {', ' return rand($b, $a);', ' }', - ' return rand($a, $b);', '}' - ]); + const functionName = PHP.provideFunction_('math_random_int', ` +function ${PHP.FUNCTION_NAME_PLACEHOLDER_}($a, $b) { + if ($a > $b) { + return rand($b, $a); + } + return rand($a, $b); +} +`); const code = functionName + '(' + argument0 + ', ' + argument1 + ')'; return [code, PHP.ORDER_FUNCTION_CALL]; }; diff --git a/generators/php/text.js b/generators/php/text.js index eadf4cf5b..bc62a95cf 100644 --- a/generators/php/text.js +++ b/generators/php/text.js @@ -32,22 +32,22 @@ PHP['text_multiline'] = function(block) { PHP['text_join'] = function(block) { // Create a string made up of any number of elements of any type. if (block.itemCount_ === 0) { - return ['\'\'', PHP.ORDER_ATOMIC]; + return ["''", PHP.ORDER_ATOMIC]; } else if (block.itemCount_ === 1) { - const element = PHP.valueToCode(block, 'ADD0', PHP.ORDER_NONE) || '\'\''; + const element = PHP.valueToCode(block, 'ADD0', PHP.ORDER_NONE) || "''"; const code = element; return [code, PHP.ORDER_NONE]; } else if (block.itemCount_ === 2) { const element0 = - PHP.valueToCode(block, 'ADD0', PHP.ORDER_STRING_CONCAT) || '\'\''; + PHP.valueToCode(block, 'ADD0', PHP.ORDER_STRING_CONCAT) || "''"; const element1 = - PHP.valueToCode(block, 'ADD1', PHP.ORDER_STRING_CONCAT) || '\'\''; + PHP.valueToCode(block, 'ADD1', PHP.ORDER_STRING_CONCAT) || "''"; const code = element0 + ' . ' + element1; return [code, PHP.ORDER_STRING_CONCAT]; } else { const elements = new Array(block.itemCount_); for (let i = 0; i < block.itemCount_; i++) { - elements[i] = PHP.valueToCode(block, 'ADD' + i, PHP.ORDER_NONE) || '\'\''; + elements[i] = PHP.valueToCode(block, 'ADD' + i, PHP.ORDER_NONE) || "''"; } const code = 'implode(\'\', array(' + elements.join(',') + '))'; return [code, PHP.ORDER_FUNCTION_CALL]; @@ -58,24 +58,27 @@ PHP['text_append'] = function(block) { // Append to a variable in place. const varName = PHP.nameDB_.getName(block.getFieldValue('VAR'), NameType.VARIABLE); - const value = PHP.valueToCode(block, 'TEXT', PHP.ORDER_ASSIGNMENT) || '\'\''; + const value = PHP.valueToCode(block, 'TEXT', PHP.ORDER_ASSIGNMENT) || "''"; return varName + ' .= ' + value + ';\n'; }; PHP['text_length'] = function(block) { // String or array length. - const functionName = PHP.provideFunction_('length', [ - 'function ' + PHP.FUNCTION_NAME_PLACEHOLDER_ + '($value) {', - ' if (is_string($value)) {', ' return strlen($value);', ' } else {', - ' return count($value);', ' }', '}' - ]); - const text = PHP.valueToCode(block, 'VALUE', PHP.ORDER_NONE) || '\'\''; + const functionName = PHP.provideFunction_('length', ` +function ${PHP.FUNCTION_NAME_PLACEHOLDER_}($value) { + if (is_string($value)) { + return strlen($value); + } + return count($value); +} +`); + const text = PHP.valueToCode(block, 'VALUE', PHP.ORDER_NONE) || "''"; return [functionName + '(' + text + ')', PHP.ORDER_FUNCTION_CALL]; }; PHP['text_isEmpty'] = function(block) { // Is the string null or array empty? - const text = PHP.valueToCode(block, 'VALUE', PHP.ORDER_NONE) || '\'\''; + const text = PHP.valueToCode(block, 'VALUE', PHP.ORDER_NONE) || "''"; return ['empty(' + text + ')', PHP.ORDER_FUNCTION_CALL]; }; @@ -83,8 +86,8 @@ PHP['text_indexOf'] = function(block) { // Search the text for a substring. const operator = block.getFieldValue('END') === 'FIRST' ? 'strpos' : 'strrpos'; - const substring = PHP.valueToCode(block, 'FIND', PHP.ORDER_NONE) || '\'\''; - const text = PHP.valueToCode(block, 'VALUE', PHP.ORDER_NONE) || '\'\''; + const substring = PHP.valueToCode(block, 'FIND', PHP.ORDER_NONE) || "''"; + const text = PHP.valueToCode(block, 'VALUE', PHP.ORDER_NONE) || "''"; let errorIndex = ' -1'; let indexAdjustment = ''; if (block.workspace.options.oneBasedIndex) { @@ -94,13 +97,12 @@ PHP['text_indexOf'] = function(block) { const functionName = PHP.provideFunction_( block.getFieldValue('END') === 'FIRST' ? 'text_indexOf' : 'text_lastIndexOf', - [ - 'function ' + PHP.FUNCTION_NAME_PLACEHOLDER_ + '($text, $search) {', - ' $pos = ' + operator + '($text, $search);', - ' return $pos === false ? ' + errorIndex + ' : $pos' + - indexAdjustment + ';', - '}' - ]); + ` +function ${PHP.FUNCTION_NAME_PLACEHOLDER_}($text, $search) { + $pos = ${operator}($text, $search); + return $pos === false ? ${errorIndex} : $pos${indexAdjustment}; +} +`); const code = functionName + '(' + text + ', ' + substring + ')'; return [code, PHP.ORDER_FUNCTION_CALL]; }; @@ -109,7 +111,7 @@ PHP['text_charAt'] = function(block) { // Get letter at index. const where = block.getFieldValue('WHERE') || 'FROM_START'; const textOrder = (where === 'RANDOM') ? PHP.ORDER_NONE : PHP.ORDER_NONE; - const text = PHP.valueToCode(block, 'VALUE', textOrder) || '\'\''; + const text = PHP.valueToCode(block, 'VALUE', textOrder) || "''"; switch (where) { case 'FIRST': { const code = 'substr(' + text + ', 0, 1)'; @@ -130,10 +132,11 @@ PHP['text_charAt'] = function(block) { return [code, PHP.ORDER_FUNCTION_CALL]; } case 'RANDOM': { - const functionName = PHP.provideFunction_('text_random_letter', [ - 'function ' + PHP.FUNCTION_NAME_PLACEHOLDER_ + '($text) {', - ' return $text[rand(0, strlen($text) - 1)];', '}' - ]); + const functionName = PHP.provideFunction_('text_random_letter', ` +function ${PHP.FUNCTION_NAME_PLACEHOLDER_}($text) { + return $text[rand(0, strlen($text) - 1)]; +} +`); const code = functionName + '(' + text + ')'; return [code, PHP.ORDER_FUNCTION_CALL]; } @@ -145,36 +148,35 @@ PHP['text_getSubstring'] = function(block) { // Get substring. const where1 = block.getFieldValue('WHERE1'); const where2 = block.getFieldValue('WHERE2'); - const text = PHP.valueToCode(block, 'STRING', PHP.ORDER_NONE) || '\'\''; + const text = PHP.valueToCode(block, 'STRING', PHP.ORDER_NONE) || "''"; if (where1 === 'FIRST' && where2 === 'LAST') { const code = text; return [code, PHP.ORDER_NONE]; } else { const at1 = PHP.getAdjusted(block, 'AT1'); const at2 = PHP.getAdjusted(block, 'AT2'); - const functionName = PHP.provideFunction_('text_get_substring', [ - 'function ' + PHP.FUNCTION_NAME_PLACEHOLDER_ + - '($text, $where1, $at1, $where2, $at2) {', - ' if ($where1 == \'FROM_END\') {', - ' $at1 = strlen($text) - 1 - $at1;', - ' } else if ($where1 == \'FIRST\') {', - ' $at1 = 0;', - ' } else if ($where1 != \'FROM_START\') {', - ' throw new Exception(\'Unhandled option (text_get_substring).\');', - ' }', - ' $length = 0;', - ' if ($where2 == \'FROM_START\') {', - ' $length = $at2 - $at1 + 1;', - ' } else if ($where2 == \'FROM_END\') {', - ' $length = strlen($text) - $at1 - $at2;', - ' } else if ($where2 == \'LAST\') {', - ' $length = strlen($text) - $at1;', - ' } else {', - ' throw new Exception(\'Unhandled option (text_get_substring).\');', - ' }', - ' return substr($text, $at1, $length);', - '}' - ]); + const functionName = PHP.provideFunction_('text_get_substring', ` +function ${PHP.FUNCTION_NAME_PLACEHOLDER_}($text, $where1, $at1, $where2, $at2) { + if ($where1 == 'FROM_END') { + $at1 = strlen($text) - 1 - $at1; + } else if ($where1 == 'FIRST') { + $at1 = 0; + } else if ($where1 != 'FROM_START') { + throw new Exception('Unhandled option (text_get_substring).'); + } + $length = 0; + if ($where2 == 'FROM_START') { + $length = $at2 - $at1 + 1; + } else if ($where2 == 'FROM_END') { + $length = strlen($text) - $at1 - $at2; + } else if ($where2 == 'LAST') { + $length = strlen($text) - $at1; + } else { + throw new Exception('Unhandled option (text_get_substring).'); + } + return substr($text, $at1, $length); +} +`); const code = functionName + '(' + text + ', \'' + where1 + '\', ' + at1 + ', \'' + where2 + '\', ' + at2 + ')'; return [code, PHP.ORDER_FUNCTION_CALL]; @@ -183,7 +185,7 @@ PHP['text_getSubstring'] = function(block) { PHP['text_changeCase'] = function(block) { // Change capitalization. - const text = PHP.valueToCode(block, 'TEXT', PHP.ORDER_NONE) || '\'\''; + const text = PHP.valueToCode(block, 'TEXT', PHP.ORDER_NONE) || "''"; let code; if (block.getFieldValue('CASE') === 'UPPERCASE') { code = 'strtoupper(' + text + ')'; @@ -199,13 +201,13 @@ PHP['text_trim'] = function(block) { // Trim spaces. const OPERATORS = {'LEFT': 'ltrim', 'RIGHT': 'rtrim', 'BOTH': 'trim'}; const operator = OPERATORS[block.getFieldValue('MODE')]; - const text = PHP.valueToCode(block, 'TEXT', PHP.ORDER_NONE) || '\'\''; + const text = PHP.valueToCode(block, 'TEXT', PHP.ORDER_NONE) || "''"; return [operator + '(' + text + ')', PHP.ORDER_FUNCTION_CALL]; }; PHP['text_print'] = function(block) { // Print statement. - const msg = PHP.valueToCode(block, 'TEXT', PHP.ORDER_NONE) || '\'\''; + const msg = PHP.valueToCode(block, 'TEXT', PHP.ORDER_NONE) || "''"; return 'print(' + msg + ');\n'; }; @@ -217,7 +219,7 @@ PHP['text_prompt_ext'] = function(block) { msg = PHP.quote_(block.getFieldValue('TEXT')); } else { // External message. - msg = PHP.valueToCode(block, 'TEXT', PHP.ORDER_NONE) || '\'\''; + msg = PHP.valueToCode(block, 'TEXT', PHP.ORDER_NONE) || "''"; } let code = 'readline(' + msg + ')'; const toNumber = block.getFieldValue('TYPE') === 'NUMBER'; @@ -230,8 +232,8 @@ PHP['text_prompt_ext'] = function(block) { PHP['text_prompt'] = PHP['text_prompt_ext']; PHP['text_count'] = function(block) { - const text = PHP.valueToCode(block, 'TEXT', PHP.ORDER_NONE) || '\'\''; - const sub = PHP.valueToCode(block, 'SUB', PHP.ORDER_NONE) || '\'\''; + const text = PHP.valueToCode(block, 'TEXT', PHP.ORDER_NONE) || "''"; + const sub = PHP.valueToCode(block, 'SUB', PHP.ORDER_NONE) || "''"; const code = 'strlen(' + sub + ') === 0' + ' ? strlen(' + text + ') + 1' + ' : substr_count(' + text + ', ' + sub + ')'; @@ -239,15 +241,15 @@ PHP['text_count'] = function(block) { }; PHP['text_replace'] = function(block) { - const text = PHP.valueToCode(block, 'TEXT', PHP.ORDER_NONE) || '\'\''; - const from = PHP.valueToCode(block, 'FROM', PHP.ORDER_NONE) || '\'\''; - const to = PHP.valueToCode(block, 'TO', PHP.ORDER_NONE) || '\'\''; + const text = PHP.valueToCode(block, 'TEXT', PHP.ORDER_NONE) || "''"; + const from = PHP.valueToCode(block, 'FROM', PHP.ORDER_NONE) || "''"; + const to = PHP.valueToCode(block, 'TO', PHP.ORDER_NONE) || "''"; const code = 'str_replace(' + from + ', ' + to + ', ' + text + ')'; return [code, PHP.ORDER_FUNCTION_CALL]; }; PHP['text_reverse'] = function(block) { - const text = PHP.valueToCode(block, 'TEXT', PHP.ORDER_NONE) || '\'\''; + const text = PHP.valueToCode(block, 'TEXT', PHP.ORDER_NONE) || "''"; const code = 'strrev(' + text + ')'; return [code, PHP.ORDER_FUNCTION_CALL]; }; diff --git a/generators/python/colour.js b/generators/python/colour.js index 30cb6f463..1a24c2780 100644 --- a/generators/python/colour.js +++ b/generators/python/colour.js @@ -29,13 +29,13 @@ Python['colour_random'] = function(block) { Python['colour_rgb'] = function(block) { // Compose a colour from RGB components expressed as percentages. - const functionName = Python.provideFunction_('colour_rgb', [ - 'def ' + Python.FUNCTION_NAME_PLACEHOLDER_ + '(r, g, b):', - ' r = round(min(100, max(0, r)) * 2.55)', - ' g = round(min(100, max(0, g)) * 2.55)', - ' b = round(min(100, max(0, b)) * 2.55)', - ' return \'#%02x%02x%02x\' % (r, g, b)' - ]); + const functionName = Python.provideFunction_('colour_rgb', ` +def ${Python.FUNCTION_NAME_PLACEHOLDER_}(r, g, b): + r = round(min(100, max(0, r)) * 2.55) + g = round(min(100, max(0, g)) * 2.55) + b = round(min(100, max(0, b)) * 2.55) + return \'#%02x%02x%02x\' % (r, g, b) +`); const r = Python.valueToCode(block, 'RED', Python.ORDER_NONE) || 0; const g = Python.valueToCode(block, 'GREEN', Python.ORDER_NONE) || 0; const b = Python.valueToCode(block, 'BLUE', Python.ORDER_NONE) || 0; @@ -45,17 +45,17 @@ Python['colour_rgb'] = function(block) { Python['colour_blend'] = function(block) { // Blend two colours together. - const functionName = Python.provideFunction_('colour_blend', [ - 'def ' + Python.FUNCTION_NAME_PLACEHOLDER_ + '(colour1, colour2, ratio):', - ' r1, r2 = int(colour1[1:3], 16), int(colour2[1:3], 16)', - ' g1, g2 = int(colour1[3:5], 16), int(colour2[3:5], 16)', - ' b1, b2 = int(colour1[5:7], 16), int(colour2[5:7], 16)', - ' ratio = min(1, max(0, ratio))', - ' r = round(r1 * (1 - ratio) + r2 * ratio)', - ' g = round(g1 * (1 - ratio) + g2 * ratio)', - ' b = round(b1 * (1 - ratio) + b2 * ratio)', - ' return \'#%02x%02x%02x\' % (r, g, b)' - ]); + const functionName = Python.provideFunction_('colour_blend', ` +def ${Python.FUNCTION_NAME_PLACEHOLDER_}(colour1, colour2, ratio): + r1, r2 = int(colour1[1:3], 16), int(colour2[1:3], 16) + g1, g2 = int(colour1[3:5], 16), int(colour2[3:5], 16) + b1, b2 = int(colour1[5:7], 16), int(colour2[5:7], 16) + ratio = min(1, max(0, ratio)) + r = round(r1 * (1 - ratio) + r2 * ratio) + g = round(g1 * (1 - ratio) + g2 * ratio) + b = round(b1 * (1 - ratio) + b2 * ratio) + return \'#%02x%02x%02x\' % (r, g, b) +`); const colour1 = Python.valueToCode(block, 'COLOUR1', Python.ORDER_NONE) || '\'#000000\''; const colour2 = diff --git a/generators/python/lists.js b/generators/python/lists.js index 607f0671b..7026162ae 100644 --- a/generators/python/lists.js +++ b/generators/python/lists.js @@ -57,7 +57,7 @@ Python['lists_isEmpty'] = function(block) { Python['lists_indexOf'] = function(block) { // Find an item in the list. const item = Python.valueToCode(block, 'FIND', Python.ORDER_NONE) || '[]'; - const list = Python.valueToCode(block, 'VALUE', Python.ORDER_NONE) || '\'\''; + const list = Python.valueToCode(block, 'VALUE', Python.ORDER_NONE) || "''"; let errorIndex = ' -1'; let firstIndexAdjustment = ''; let lastIndexAdjustment = ' - 1'; @@ -68,21 +68,22 @@ Python['lists_indexOf'] = function(block) { lastIndexAdjustment = ''; } + let functionName; if (block.getFieldValue('END') === 'FIRST') { - const functionName = Python.provideFunction_('first_index', [ - 'def ' + Python.FUNCTION_NAME_PLACEHOLDER_ + '(my_list, elem):', - ' try: index = my_list.index(elem)' + firstIndexAdjustment, - ' except: index =' + errorIndex, ' return index' - ]); - const code = functionName + '(' + list + ', ' + item + ')'; - return [code, Python.ORDER_FUNCTION_CALL]; + functionName = Python.provideFunction_('first_index', ` +def ${Python.FUNCTION_NAME_PLACEHOLDER_}(my_list, elem): + try: index = my_list.index(elem)${firstIndexAdjustment} + except: index =${errorIndex} + return index +`); + } else { + functionName = Python.provideFunction_('last_index', ` +def ${Python.FUNCTION_NAME_PLACEHOLDER_}(my_list, elem): + try: index = len(my_list) - my_list[::-1].index(elem)${lastIndexAdjustment} + except: index =${errorIndex} + return index +`); } - const functionName = Python.provideFunction_('last_index', [ - 'def ' + Python.FUNCTION_NAME_PLACEHOLDER_ + '(my_list, elem):', - ' try: index = len(my_list) - my_list[::-1].index(elem)' + - lastIndexAdjustment, - ' except: index =' + errorIndex, ' return index' - ]); const code = functionName + '(' + list + ', ' + item + ')'; return [code, Python.ORDER_FUNCTION_CALL]; }; @@ -152,11 +153,11 @@ Python['lists_getIndex'] = function(block) { return [code, Python.ORDER_FUNCTION_CALL]; } else { const functionName = - Python.provideFunction_('lists_remove_random_item', [ - 'def ' + Python.FUNCTION_NAME_PLACEHOLDER_ + '(myList):', - ' x = int(random.random() * len(myList))', - ' return myList.pop(x)' - ]); + Python.provideFunction_('lists_remove_random_item', ` +def ${Python.FUNCTION_NAME_PLACEHOLDER_}(myList): + x = int(random.random() * len(myList)) + return myList.pop(x) +`); const code = functionName + '(' + list + ')'; if (mode === 'GET_REMOVE') { return [code, Python.ORDER_FUNCTION_CALL]; @@ -294,15 +295,22 @@ Python['lists_sort'] = function(block) { const list = (Python.valueToCode(block, 'LIST', Python.ORDER_NONE) || '[]'); const type = block.getFieldValue('TYPE'); const reverse = block.getFieldValue('DIRECTION') === '1' ? 'False' : 'True'; - const sortFunctionName = Python.provideFunction_('lists_sort', [ - 'def ' + Python.FUNCTION_NAME_PLACEHOLDER_ + '(my_list, type, reverse):', - ' def try_float(s):', ' try:', ' return float(s)', ' except:', - ' return 0', ' key_funcs = {', ' "NUMERIC": try_float,', - ' "TEXT": str,', ' "IGNORE_CASE": lambda s: str(s).lower()', ' }', - ' key_func = key_funcs[type]', - ' list_cpy = list(my_list)', // Clone the list. - ' return sorted(list_cpy, key=key_func, reverse=reverse)' - ]); + const sortFunctionName = Python.provideFunction_('lists_sort', ` +def ${Python.FUNCTION_NAME_PLACEHOLDER_}(my_list, type, reverse): + def try_float(s): + try: + return float(s) + except: + return 0 + key_funcs = { + "NUMERIC": try_float, + "TEXT": str, + "IGNORE_CASE": lambda s: str(s).lower() + } + key_func = key_funcs[type] + list_cpy = list(my_list) + return sorted(list_cpy, key=key_func, reverse=reverse) +`); const code = sortFunctionName + '(' + list + ', "' + type + '", ' + reverse + ')'; @@ -315,14 +323,14 @@ Python['lists_split'] = function(block) { let code; if (mode === 'SPLIT') { const value_input = - Python.valueToCode(block, 'INPUT', Python.ORDER_MEMBER) || '\'\''; + Python.valueToCode(block, 'INPUT', Python.ORDER_MEMBER) || "''"; const value_delim = Python.valueToCode(block, 'DELIM', Python.ORDER_NONE); code = value_input + '.split(' + value_delim + ')'; } else if (mode === 'JOIN') { const value_input = Python.valueToCode(block, 'INPUT', Python.ORDER_NONE) || '[]'; const value_delim = - Python.valueToCode(block, 'DELIM', Python.ORDER_MEMBER) || '\'\''; + Python.valueToCode(block, 'DELIM', Python.ORDER_MEMBER) || "''"; code = value_delim + '.join(' + value_input + ')'; } else { throw Error('Unknown mode: ' + mode); diff --git a/generators/python/loops.js b/generators/python/loops.js index aff791d21..b3c267f86 100644 --- a/generators/python/loops.js +++ b/generators/python/loops.js @@ -70,16 +70,20 @@ Python['controls_for'] = function(block) { // Helper functions. const defineUpRange = function() { - return Python.provideFunction_('upRange', [ - 'def ' + Python.FUNCTION_NAME_PLACEHOLDER_ + '(start, stop, step):', - ' while start <= stop:', ' yield start', ' start += abs(step)' - ]); + return Python.provideFunction_('upRange', ` +def ${Python.FUNCTION_NAME_PLACEHOLDER_}(start, stop, step): + while start <= stop: + yield start + start += abs(step) +`); }; const defineDownRange = function() { - return Python.provideFunction_('downRange', [ - 'def ' + Python.FUNCTION_NAME_PLACEHOLDER_ + '(start, stop, step):', - ' while start >= stop:', ' yield start', ' start -= abs(step)' - ]); + return Python.provideFunction_('downRange', ` +def ${Python.FUNCTION_NAME_PLACEHOLDER_}(start, stop, step): + while start >= stop: + yield start + start -= abs(step) +`); }; // Arguments are legal Python code (numbers or strings returned by scrub()). const generateUpDownRange = function(start, end, inc) { diff --git a/generators/python/math.js b/generators/python/math.js index 93d4b8355..ca23c1770 100644 --- a/generators/python/math.js +++ b/generators/python/math.js @@ -41,7 +41,7 @@ Python['math_arithmetic'] = function(block) { 'MINUS': [' - ', Python.ORDER_ADDITIVE], 'MULTIPLY': [' * ', Python.ORDER_MULTIPLICATIVE], 'DIVIDE': [' / ', Python.ORDER_MULTIPLICATIVE], - 'POWER': [' ** ', Python.ORDER_EXPONENTIATION] + 'POWER': [' ** ', Python.ORDER_EXPONENTIATION], }; const tuple = OPERATORS[block.getFieldValue('OP')]; const operator = tuple[0]; @@ -142,7 +142,7 @@ Python['math_constant'] = function(block) { 'GOLDEN_RATIO': ['(1 + math.sqrt(5)) / 2', Python.ORDER_MULTIPLICATIVE], 'SQRT2': ['math.sqrt(2)', Python.ORDER_MEMBER], 'SQRT1_2': ['math.sqrt(1.0 / 2)', Python.ORDER_MEMBER], - 'INFINITY': ['float(\'inf\')', Python.ORDER_ATOMIC] + 'INFINITY': ['float(\'inf\')', Python.ORDER_ATOMIC], }; const constant = block.getFieldValue('CONSTANT'); if (constant !== 'INFINITY') { @@ -155,20 +155,15 @@ Python['math_number_property'] = function(block) { // Check if a number is even, odd, prime, whole, positive, or negative // or if it is divisible by certain number. Returns true or false. const PROPERTIES = { - 'EVEN': [' % 2 == 0', Python.ORDER_MULTIPLICATIVE, - Python.ORDER_RELATIONAL], - 'ODD': [' % 2 == 1', Python.ORDER_MULTIPLICATIVE, - Python.ORDER_RELATIONAL], + 'EVEN': [' % 2 == 0', Python.ORDER_MULTIPLICATIVE, Python.ORDER_RELATIONAL], + 'ODD': [' % 2 == 1', Python.ORDER_MULTIPLICATIVE, Python.ORDER_RELATIONAL], 'WHOLE': [' % 1 == 0', Python.ORDER_MULTIPLICATIVE, Python.ORDER_RELATIONAL], - 'POSITIVE': [' > 0', Python.ORDER_RELATIONAL, - Python.ORDER_RELATIONAL], - 'NEGATIVE': [' < 0', Python.ORDER_RELATIONAL, - Python.ORDER_RELATIONAL], + 'POSITIVE': [' > 0', Python.ORDER_RELATIONAL, Python.ORDER_RELATIONAL], + 'NEGATIVE': [' < 0', Python.ORDER_RELATIONAL, Python.ORDER_RELATIONAL], 'DIVISIBLE_BY': [null, Python.ORDER_MULTIPLICATIVE, Python.ORDER_RELATIONAL], - 'PRIME': [null, Python.ORDER_NONE, - Python.ORDER_FUNCTION_CALL] + 'PRIME': [null, Python.ORDER_NONE, Python.ORDER_FUNCTION_CALL], } const dropdownProperty = block.getFieldValue('PROPERTY'); const [suffix, inputOrder, outputOrder] = PROPERTIES[dropdownProperty]; @@ -180,27 +175,26 @@ Python['math_number_property'] = function(block) { Python.definitions_['import_math'] = 'import math'; Python.definitions_['from_numbers_import_Number'] = 'from numbers import Number'; - const functionName = Python.provideFunction_( - 'math_isPrime', - ['def ' + Python.FUNCTION_NAME_PLACEHOLDER_ + '(n):', - ' # https://en.wikipedia.org/wiki/Primality_test#Naive_methods', - ' # If n is not a number but a string, try parsing it.', - ' if not isinstance(n, Number):', - ' try:', - ' n = float(n)', - ' except:', - ' return False', - ' if n == 2 or n == 3:', - ' return True', - ' # False if n is negative, is 1, or not whole,' + - ' or if n is divisible by 2 or 3.', - ' if n <= 1 or n % 1 != 0 or n % 2 == 0 or n % 3 == 0:', - ' return False', - ' # Check all the numbers of form 6k +/- 1, up to sqrt(n).', - ' for x in range(6, int(math.sqrt(n)) + 2, 6):', - ' if n % (x - 1) == 0 or n % (x + 1) == 0:', - ' return False', - ' return True']); + const functionName = Python.provideFunction_('math_isPrime', ` +def ${Python.FUNCTION_NAME_PLACEHOLDER_}(n): + # https://en.wikipedia.org/wiki/Primality_test#Naive_methods + # If n is not a number but a string, try parsing it. + if not isinstance(n, Number): + try: + n = float(n) + except: + return False + if n == 2 or n == 3: + return True + # False if n is negative, is 1, or not whole, or if n is divisible by 2 or 3. + if n <= 1 or n % 1 != 0 or n % 2 == 0 or n % 3 == 0: + return False + # Check all the numbers of form 6k +/- 1, up to sqrt(n). + for x in range(6, int(math.sqrt(n)) + 2, 6): + if n % (x - 1) == 0 or n % (x + 1) == 0: + return False + return True +`); code = functionName + '(' + numberToCheck + ')'; } else if (dropdownProperty === 'DIVISIBLE_BY') { const divisor = Python.valueToCode(block, 'DIVISOR', @@ -251,71 +245,72 @@ Python['math_on_list'] = function(block) { case 'AVERAGE': { Python.definitions_['from_numbers_import_Number'] = 'from numbers import Number'; - const functionName = Python.provideFunction_( - 'math_mean', - // This operation excludes null and values that aren't int or float: - // math_mean([null, null, "aString", 1, 9]) -> 5.0 - [ - 'def ' + Python.FUNCTION_NAME_PLACEHOLDER_ + '(myList):', - ' localList = [e for e in myList if isinstance(e, Number)]', - ' if not localList: return', - ' return float(sum(localList)) / len(localList)' - ]); + // This operation excludes null and values that aren't int or float: + // math_mean([null, null, "aString", 1, 9]) -> 5.0 + const functionName = Python.provideFunction_('math_mean', ` +def ${Python.FUNCTION_NAME_PLACEHOLDER_}(myList): + localList = [e for e in myList if isinstance(e, Number)] + if not localList: return + return float(sum(localList)) / len(localList) +`); code = functionName + '(' + list + ')'; break; } case 'MEDIAN': { Python.definitions_['from_numbers_import_Number'] = 'from numbers import Number'; - const functionName = Python.provideFunction_( - 'math_median', - // This operation excludes null values: - // math_median([null, null, 1, 3]) -> 2.0 - [ - 'def ' + Python.FUNCTION_NAME_PLACEHOLDER_ + '(myList):', - ' localList = sorted([e for e in myList if isinstance(e, Number)])', - ' if not localList: return', ' if len(localList) % 2 == 0:', - ' return (localList[len(localList) // 2 - 1] + ' + - 'localList[len(localList) // 2]) / 2.0', - ' else:', ' return localList[(len(localList) - 1) // 2]' - ]); + // This operation excludes null values: + // math_median([null, null, 1, 3]) -> 2.0 + const functionName = Python.provideFunction_( 'math_median', ` +def ${Python.FUNCTION_NAME_PLACEHOLDER_}(myList): + localList = sorted([e for e in myList if isinstance(e, Number)]) + if not localList: return + if len(localList) % 2 == 0: + return (localList[len(localList) // 2 - 1] + localList[len(localList) // 2]) / 2.0 + else: + return localList[(len(localList) - 1) // 2] +`); code = functionName + '(' + list + ')'; break; } case 'MODE': { - const functionName = Python.provideFunction_( - 'math_modes', - // As a list of numbers can contain more than one mode, - // the returned result is provided as an array. - // Mode of [3, 'x', 'x', 1, 1, 2, '3'] -> ['x', 1] - [ - 'def ' + Python.FUNCTION_NAME_PLACEHOLDER_ + '(some_list):', - ' modes = []', - ' # Using a lists of [item, count] to keep count rather than dict', - ' # to avoid "unhashable" errors when the counted item is ' + - 'itself a list or dict.', - ' counts = []', ' maxCount = 1', ' for item in some_list:', - ' found = False', ' for count in counts:', - ' if count[0] == item:', ' count[1] += 1', - ' maxCount = max(maxCount, count[1])', - ' found = True', - ' if not found:', ' counts.append([item, 1])', - ' for counted_item, item_count in counts:', - ' if item_count == maxCount:', - ' modes.append(counted_item)', ' return modes' - ]); + // As a list of numbers can contain more than one mode, + // the returned result is provided as an array. + // Mode of [3, 'x', 'x', 1, 1, 2, '3'] -> ['x', 1] + const functionName = Python.provideFunction_('math_modes', ` +def ${Python.FUNCTION_NAME_PLACEHOLDER_}(some_list): + modes = [] + # Using a lists of [item, count] to keep count rather than dict + # to avoid "unhashable" errors when the counted item is itself a list or dict. + counts = [] + maxCount = 1 + for item in some_list: + found = False + for count in counts: + if count[0] == item: + count[1] += 1 + maxCount = max(maxCount, count[1]) + found = True + if not found: + counts.append([item, 1]) + for counted_item, item_count in counts: + if item_count == maxCount: + modes.append(counted_item) + return modes +`); code = functionName + '(' + list + ')'; break; } case 'STD_DEV': { Python.definitions_['import_math'] = 'import math'; - const functionName = Python.provideFunction_('math_standard_deviation', [ - 'def ' + Python.FUNCTION_NAME_PLACEHOLDER_ + '(numbers):', - ' n = len(numbers)', ' if n == 0: return', - ' mean = float(sum(numbers)) / n', - ' variance = sum((x - mean) ** 2 for x in numbers) / n', - ' return math.sqrt(variance)' - ]); + const functionName = Python.provideFunction_('math_standard_deviation', ` +def ${Python.FUNCTION_NAME_PLACEHOLDER_}(numbers): + n = len(numbers) + if n == 0: return + mean = float(sum(numbers)) / n + variance = sum((x - mean) ** 2 for x in numbers) / n + return math.sqrt(variance) +`); code = functionName + '(' + list + ')'; break; } diff --git a/generators/python/text.js b/generators/python/text.js index 4edb5d3b2..a097cbee2 100644 --- a/generators/python/text.js +++ b/generators/python/text.js @@ -55,18 +55,18 @@ Python['text_join'] = function(block) { // Should we allow joining by '-' or ',' or any other characters? switch (block.itemCount_) { case 0: - return ['\'\'', Python.ORDER_ATOMIC]; + return ["''", Python.ORDER_ATOMIC]; case 1: { const element = - Python.valueToCode(block, 'ADD0', Python.ORDER_NONE) || '\'\''; + Python.valueToCode(block, 'ADD0', Python.ORDER_NONE) || "''"; const codeAndOrder = forceString(element); return codeAndOrder; } case 2: { const element0 = - Python.valueToCode(block, 'ADD0', Python.ORDER_NONE) || '\'\''; + Python.valueToCode(block, 'ADD0', Python.ORDER_NONE) || "''"; const element1 = - Python.valueToCode(block, 'ADD1', Python.ORDER_NONE) || '\'\''; + Python.valueToCode(block, 'ADD1', Python.ORDER_NONE) || "''"; const code = forceString(element0)[0] + ' + ' + forceString(element1)[0]; return [code, Python.ORDER_ADDITIVE]; } @@ -74,7 +74,7 @@ Python['text_join'] = function(block) { const elements = []; for (let i = 0; i < block.itemCount_; i++) { elements[i] = - Python.valueToCode(block, 'ADD' + i, Python.ORDER_NONE) || '\'\''; + Python.valueToCode(block, 'ADD' + i, Python.ORDER_NONE) || "''"; } const tempVar = Python.nameDB_.getDistinctName('x', NameType.VARIABLE); const code = '\'\'.join([str(' + tempVar + ') for ' + tempVar + ' in [' + @@ -88,19 +88,19 @@ Python['text_append'] = function(block) { // Append to a variable in place. const varName = Python.nameDB_.getName(block.getFieldValue('VAR'), NameType.VARIABLE); - const value = Python.valueToCode(block, 'TEXT', Python.ORDER_NONE) || '\'\''; + const value = Python.valueToCode(block, 'TEXT', Python.ORDER_NONE) || "''"; return varName + ' = str(' + varName + ') + ' + forceString(value)[0] + '\n'; }; Python['text_length'] = function(block) { // Is the string null or array empty? - const text = Python.valueToCode(block, 'VALUE', Python.ORDER_NONE) || '\'\''; + const text = Python.valueToCode(block, 'VALUE', Python.ORDER_NONE) || "''"; return ['len(' + text + ')', Python.ORDER_FUNCTION_CALL]; }; Python['text_isEmpty'] = function(block) { // Is the string null or array empty? - const text = Python.valueToCode(block, 'VALUE', Python.ORDER_NONE) || '\'\''; + const text = Python.valueToCode(block, 'VALUE', Python.ORDER_NONE) || "''"; const code = 'not len(' + text + ')'; return [code, Python.ORDER_LOGICAL_NOT]; }; @@ -110,9 +110,9 @@ Python['text_indexOf'] = function(block) { // Should we allow for non-case sensitive??? const operator = block.getFieldValue('END') === 'FIRST' ? 'find' : 'rfind'; const substring = - Python.valueToCode(block, 'FIND', Python.ORDER_NONE) || '\'\''; + Python.valueToCode(block, 'FIND', Python.ORDER_NONE) || "''"; const text = - Python.valueToCode(block, 'VALUE', Python.ORDER_MEMBER) || '\'\''; + Python.valueToCode(block, 'VALUE', Python.ORDER_MEMBER) || "''"; const code = text + '.' + operator + '(' + substring + ')'; if (block.workspace.options.oneBasedIndex) { return [code + ' + 1', Python.ORDER_ADDITIVE]; @@ -126,7 +126,7 @@ Python['text_charAt'] = function(block) { const where = block.getFieldValue('WHERE') || 'FROM_START'; const textOrder = (where === 'RANDOM') ? Python.ORDER_NONE : Python.ORDER_MEMBER; - const text = Python.valueToCode(block, 'VALUE', textOrder) || '\'\''; + const text = Python.valueToCode(block, 'VALUE', textOrder) || "''"; switch (where) { case 'FIRST': { const code = text + '[0]'; @@ -148,10 +148,11 @@ Python['text_charAt'] = function(block) { } case 'RANDOM': { Python.definitions_['import_random'] = 'import random'; - const functionName = Python.provideFunction_('text_random_letter', [ - 'def ' + Python.FUNCTION_NAME_PLACEHOLDER_ + '(text):', - ' x = int(random.random() * len(text))', ' return text[x];' - ]); + const functionName = Python.provideFunction_('text_random_letter', ` +def ${Python.FUNCTION_NAME_PLACEHOLDER_}(text): + x = int(random.random() * len(text)) + return text[x] +`); const code = functionName + '(' + text + ')'; return [code, Python.ORDER_FUNCTION_CALL]; } @@ -164,7 +165,7 @@ Python['text_getSubstring'] = function(block) { const where1 = block.getFieldValue('WHERE1'); const where2 = block.getFieldValue('WHERE2'); const text = - Python.valueToCode(block, 'STRING', Python.ORDER_MEMBER) || '\'\''; + Python.valueToCode(block, 'STRING', Python.ORDER_MEMBER) || "''"; let at1; switch (where1) { case 'FROM_START': @@ -217,7 +218,7 @@ Python['text_changeCase'] = function(block) { 'TITLECASE': '.title()' }; const operator = OPERATORS[block.getFieldValue('CASE')]; - const text = Python.valueToCode(block, 'TEXT', Python.ORDER_MEMBER) || '\'\''; + const text = Python.valueToCode(block, 'TEXT', Python.ORDER_MEMBER) || "''"; const code = text + operator; return [code, Python.ORDER_FUNCTION_CALL]; }; @@ -230,30 +231,33 @@ Python['text_trim'] = function(block) { 'BOTH': '.strip()' }; const operator = OPERATORS[block.getFieldValue('MODE')]; - const text = Python.valueToCode(block, 'TEXT', Python.ORDER_MEMBER) || '\'\''; + const text = Python.valueToCode(block, 'TEXT', Python.ORDER_MEMBER) || "''"; const code = text + operator; return [code, Python.ORDER_FUNCTION_CALL]; }; Python['text_print'] = function(block) { // Print statement. - const msg = Python.valueToCode(block, 'TEXT', Python.ORDER_NONE) || '\'\''; + const msg = Python.valueToCode(block, 'TEXT', Python.ORDER_NONE) || "''"; return 'print(' + msg + ')\n'; }; Python['text_prompt_ext'] = function(block) { // Prompt function. - const functionName = Python.provideFunction_('text_prompt', [ - 'def ' + Python.FUNCTION_NAME_PLACEHOLDER_ + '(msg):', ' try:', - ' return raw_input(msg)', ' except NameError:', ' return input(msg)' - ]); + const functionName = Python.provideFunction_('text_prompt', ` +def ${Python.FUNCTION_NAME_PLACEHOLDER_}(msg): + try: + return raw_input(msg) + except NameError: + return input(msg) +`); let msg; if (block.getField('TEXT')) { // Internal message. msg = Python.quote_(block.getFieldValue('TEXT')); } else { // External message. - msg = Python.valueToCode(block, 'TEXT', Python.ORDER_NONE) || '\'\''; + msg = Python.valueToCode(block, 'TEXT', Python.ORDER_NONE) || "''"; } let code = functionName + '(' + msg + ')'; const toNumber = block.getFieldValue('TYPE') === 'NUMBER'; @@ -266,22 +270,22 @@ Python['text_prompt_ext'] = function(block) { Python['text_prompt'] = Python['text_prompt_ext']; Python['text_count'] = function(block) { - const text = Python.valueToCode(block, 'TEXT', Python.ORDER_MEMBER) || '\'\''; - const sub = Python.valueToCode(block, 'SUB', Python.ORDER_NONE) || '\'\''; + const text = Python.valueToCode(block, 'TEXT', Python.ORDER_MEMBER) || "''"; + const sub = Python.valueToCode(block, 'SUB', Python.ORDER_NONE) || "''"; const code = text + '.count(' + sub + ')'; return [code, Python.ORDER_FUNCTION_CALL]; }; Python['text_replace'] = function(block) { - const text = Python.valueToCode(block, 'TEXT', Python.ORDER_MEMBER) || '\'\''; - const from = Python.valueToCode(block, 'FROM', Python.ORDER_NONE) || '\'\''; - const to = Python.valueToCode(block, 'TO', Python.ORDER_NONE) || '\'\''; + const text = Python.valueToCode(block, 'TEXT', Python.ORDER_MEMBER) || "''"; + const from = Python.valueToCode(block, 'FROM', Python.ORDER_NONE) || "''"; + const to = Python.valueToCode(block, 'TO', Python.ORDER_NONE) || "''"; const code = text + '.replace(' + from + ', ' + to + ')'; return [code, Python.ORDER_MEMBER]; }; Python['text_reverse'] = function(block) { - const text = Python.valueToCode(block, 'TEXT', Python.ORDER_MEMBER) || '\'\''; + const text = Python.valueToCode(block, 'TEXT', Python.ORDER_MEMBER) || "''"; const code = text + '[::-1]'; return [code, Python.ORDER_MEMBER]; }; diff --git a/tests/generators/golden/generated.dart b/tests/generators/golden/generated.dart index c067942e1..a47886588 100644 --- a/tests/generators/golden/generated.dart +++ b/tests/generators/golden/generated.dart @@ -1384,10 +1384,10 @@ void test_split() { List lists_sort(List list, String type, int direction) { var compareFuncs = { - "NUMERIC": (a, b) => (direction * a.compareTo(b)).toInt(), - "TEXT": (a, b) => direction * a.toString().compareTo(b.toString()), - "IGNORE_CASE": - (a, b) => direction * + 'NUMERIC': (a, b) => (direction * a.compareTo(b)).toInt(), + 'TEXT': (a, b) => direction * a.toString().compareTo(b.toString()), + 'IGNORE_CASE': + (a, b) => direction * a.toString().toLowerCase().compareTo(b.toString().toLowerCase()) }; list = new List.from(list); diff --git a/tests/generators/golden/generated.js b/tests/generators/golden/generated.js index 019d51d19..48a4e20ac 100644 --- a/tests/generators/golden/generated.js +++ b/tests/generators/golden/generated.js @@ -904,8 +904,8 @@ function test_text_reverse() { } function textReplace(haystack, needle, replacement) { - needle = needle.replace(/([-()\[\]{}+?*.$\^|,:# b.toString() ? 1 : -1; }, - "IGNORE_CASE": function(a, b) { + '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; } + return function(a, b) { return compare(a, b) * direction; }; } // Tests the "alphabetic sort" block. diff --git a/tests/generators/golden/generated.lua b/tests/generators/golden/generated.lua index ad71d3aca..085a76070 100644 --- a/tests/generators/golden/generated.lua +++ b/tests/generators/golden/generated.lua @@ -525,23 +525,23 @@ function math_median(t) if #t == 0 then return 0 end - local temp={} + local temp = {} for _, v in ipairs(t) do - if type(v) == "number" then + if type(v) == 'number' then table.insert(temp, v) end end table.sort(temp) if #temp % 2 == 0 then - return (temp[#temp/2] + temp[(#temp/2)+1]) / 2 + return (temp[#temp / 2] + temp[(#temp / 2) + 1]) / 2 else - return temp[math.ceil(#temp/2)] + return temp[math.ceil(#temp / 2)] end end function math_modes(t) -- Source: http://lua-users.org/wiki/SimpleStats - local counts={} + local counts = {} for _, v in ipairs(t) do if counts[v] == nil then counts[v] = 1 @@ -555,7 +555,7 @@ function math_modes(t) biggestCount = v end end - local temp={} + local temp = {} for k, v in pairs(counts) do if v == biggestCount then table.insert(temp, k) @@ -707,9 +707,8 @@ function firstIndexOf(str, substr) local i = string.find(str, substr, 1, true) if i == nil then return 0 - else - return i end + return i end function lastIndexOf(str, substr) diff --git a/tests/generators/golden/generated.php b/tests/generators/golden/generated.php index 728273d52..4a16b6f5c 100644 --- a/tests/generators/golden/generated.php +++ b/tests/generators/golden/generated.php @@ -478,8 +478,8 @@ function math_mean($myList) { function math_median($arr) { sort($arr,SORT_NUMERIC); - return (count($arr) % 2) ? $arr[floor(count($arr)/2)] : - ($arr[floor(count($arr)/2)] + $arr[floor(count($arr)/2) - 1]) / 2; + return (count($arr) % 2) ? $arr[floor(count($arr) / 2)] : + ($arr[floor(count($arr) / 2)] + $arr[floor(count($arr) / 2) - 1]) / 2; } function math_modes($values) { @@ -603,9 +603,8 @@ function test_empty_text() { function length($value) { if (is_string($value)) { return strlen($value); - } else { - return count($value); } + return count($value); } // Tests the "length" block. @@ -1384,9 +1383,9 @@ function test_split() { function lists_sort($list, $type, $direction) { $sortCmpFuncs = array( - "NUMERIC" => "strnatcasecmp", - "TEXT" => "strcmp", - "IGNORE_CASE" => "strcasecmp" + 'NUMERIC' => 'strnatcasecmp', + 'TEXT' => 'strcmp', + 'IGNORE_CASE' => 'strcasecmp' ); $sortCmp = $sortCmpFuncs[$type]; $list2 = $list; diff --git a/tests/generators/golden/generated.py b/tests/generators/golden/generated.py index 12185286e..28a673b74 100644 --- a/tests/generators/golden/generated.py +++ b/tests/generators/golden/generated.py @@ -599,7 +599,7 @@ def test_find_text_complex(): def text_random_letter(text): x = int(random.random() * len(text)) - return text[x]; + return text[x] # Tests the "get letter" block with a variable. def test_get_text_simple(): From 9b06fc88534d8425a2d39a9943964f77952b3daa Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 31 Jan 2022 12:35:23 +0000 Subject: [PATCH 050/128] chore(deps): bump eslint from 8.7.0 to 8.8.0 (#5905) Bumps [eslint](https://github.com/eslint/eslint) from 8.7.0 to 8.8.0. - [Release notes](https://github.com/eslint/eslint/releases) - [Changelog](https://github.com/eslint/eslint/blob/main/CHANGELOG.md) - [Commits](https://github.com/eslint/eslint/compare/v8.7.0...v8.8.0) --- updated-dependencies: - dependency-name: eslint dependency-type: direct:development update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- package-lock.json | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/package-lock.json b/package-lock.json index 2eaedc7ee..4e1118f63 100644 --- a/package-lock.json +++ b/package-lock.json @@ -3641,9 +3641,9 @@ } }, "node_modules/eslint": { - "version": "8.7.0", - "resolved": "https://registry.npmjs.org/eslint/-/eslint-8.7.0.tgz", - "integrity": "sha512-ifHYzkBGrzS2iDU7KjhCAVMGCvF6M3Xfs8X8b37cgrUlDt6bWRTpRh6T/gtSXv1HJ/BUGgmjvNvOEGu85Iif7w==", + "version": "8.8.0", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-8.8.0.tgz", + "integrity": "sha512-H3KXAzQGBH1plhYS3okDix2ZthuYJlQQEGE5k0IKuEqUSiyu4AmxxlJ2MtTYeJ3xB4jDhcYCwGOg2TXYdnDXlQ==", "dev": true, "dependencies": { "@eslint/eslintrc": "^1.0.5", @@ -15320,9 +15320,9 @@ } }, "eslint": { - "version": "8.7.0", - "resolved": "https://registry.npmjs.org/eslint/-/eslint-8.7.0.tgz", - "integrity": "sha512-ifHYzkBGrzS2iDU7KjhCAVMGCvF6M3Xfs8X8b37cgrUlDt6bWRTpRh6T/gtSXv1HJ/BUGgmjvNvOEGu85Iif7w==", + "version": "8.8.0", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-8.8.0.tgz", + "integrity": "sha512-H3KXAzQGBH1plhYS3okDix2ZthuYJlQQEGE5k0IKuEqUSiyu4AmxxlJ2MtTYeJ3xB4jDhcYCwGOg2TXYdnDXlQ==", "dev": true, "requires": { "@eslint/eslintrc": "^1.0.5", From 74ef1cbf521f7c6447ea9672ddbfe861d2292e5f Mon Sep 17 00:00:00 2001 From: Christopher Allen Date: Mon, 31 Jan 2022 18:36:10 +0000 Subject: [PATCH 051/128] fix!: Export loopTypes from Blockly.blocks.loops (#5900) * refactor(blocks): Make loopTypes a Set This is likely to slightly improve performance, especially if there are many entries. * refactor(blocks): Re-export individual block modules from Blockly.blocks.all * fix!(blocks): Have blocks_compressed.js export Blockly.blocks.all Previously the value obtained by const blocks = require('blockly/blocks'); // Node.js or import blocks from 'blockly/blocks.js'; // ES Modules would be the block definitions dictionary (Blockly.Blocks). Change this so that it is instead the export object from Blockly.blocks.all. This means you can now access loopTypes via: import blocks from 'blockly/blocks.js'; blocks.loops.loopTypes.add('my_loop_blocktype'); This is a breaking change for any code which depended on the value that was exported by blocks_compressed.js. BREAKING CHANGE: the exports provided by blocks_compressed.js (and therefore by `import ... from 'blockly/blocks'`) have changed; see above. --- blocks/all.js | 31 ++++++++++++++++++++++--------- blocks/loops.js | 12 ++++++------ scripts/gulpfiles/build_tasks.js | 6 +++--- tests/deps.js | 2 +- 4 files changed, 32 insertions(+), 19 deletions(-) diff --git a/blocks/all.js b/blocks/all.js index 17000f8c9..b145d4107 100644 --- a/blocks/all.js +++ b/blocks/all.js @@ -11,13 +11,26 @@ 'use strict'; goog.module('Blockly.blocks.all'); +goog.module.declareLegacyNamespace(); + +const colour = goog.require('Blockly.blocks.colour'); +const lists = goog.require('Blockly.blocks.lists'); +const logic = goog.require('Blockly.blocks.logic'); +const loops = goog.require('Blockly.blocks.loops'); +const math = goog.require('Blockly.blocks.math'); +const procedures = goog.require('Blockly.blocks.procedures'); +const texts = goog.require('Blockly.blocks.texts'); +const variables = goog.require('Blockly.blocks.variables'); +const variablesDynamic = goog.require('Blockly.blocks.variablesDynamic'); + + +exports.colour = colour; +exports.lists = lists; +exports.logic = logic; +exports.loops = loops; +exports.math = math; +exports.procedures = procedures; +exports.texts = texts; +exports.variables = variables; +exports.variablesDynamic = variablesDynamic; -goog.require('Blockly.blocks.colour'); -goog.require('Blockly.blocks.lists'); -goog.require('Blockly.blocks.logic'); -goog.require('Blockly.blocks.loops'); -goog.require('Blockly.blocks.math'); -goog.require('Blockly.blocks.procedures'); -goog.require('Blockly.blocks.texts'); -goog.require('Blockly.blocks.variables'); -goog.require('Blockly.blocks.variablesDynamic'); diff --git a/blocks/loops.js b/blocks/loops.js index cc3c27d37..21e66ece3 100644 --- a/blocks/loops.js +++ b/blocks/loops.js @@ -287,21 +287,21 @@ Extensions.register( * * // If using the Blockly npm package and es6 import syntax: * import {loopTypes} from 'blockly/blocks'; - * loopTypes.push('custom_loop'); + * loopTypes.add('custom_loop'); * * // Else if using Closure Compiler and goog.modules: * const {loopTypes} = goog.require('Blockly.blocks.loops'); - * loopTypes.push('custom_loop'); + * loopTypes.add('custom_loop'); * - * @type {!Array} + * @type {!Set} */ -const loopTypes = [ +const loopTypes = new Set([ 'controls_repeat', 'controls_repeat_ext', 'controls_forEach', 'controls_for', 'controls_whileUntil', -]; +]); exports.loopTypes = loopTypes; /** @@ -321,7 +321,7 @@ const CONTROL_FLOW_IN_LOOP_CHECK_MIXIN = { getSurroundLoop: function() { let block = this; do { - if (loopTypes.includes(block.type)) { + if (loopTypes.has(block.type)) { return block; } block = block.getSurroundParent(); diff --git a/scripts/gulpfiles/build_tasks.js b/scripts/gulpfiles/build_tasks.js index 0748ea118..aef2bf95b 100644 --- a/scripts/gulpfiles/build_tasks.js +++ b/scripts/gulpfiles/build_tasks.js @@ -108,7 +108,7 @@ const chunks = [ { name: 'blocks', entry: 'blocks/all.js', - exports: 'Blockly.Blocks', + exports: 'Blockly.blocks.all', importAs: 'BlocklyBlocks', }, { @@ -321,7 +321,7 @@ function chunkWrapper(chunk) { const cjsDeps = fileNames.map(f => `require(${f})`).join(', '); const browserDeps = chunk.dependencies.map(d => `root.${d.exports}`).join(', '); - const imports = chunk.dependencies.map(d => d.importAs).join(', '); + const factoryParams = chunk.dependencies.map(d => d.importAs).join(', '); return `// Do not edit this file; automatically generated. /* eslint-disable */ @@ -333,7 +333,7 @@ function chunkWrapper(chunk) { } else { // Browser root.${chunk.exports} = factory(${browserDeps}); } -}(this, function(${imports}) { +}(this, function(${factoryParams}) { ${chunk.factoryPreamble || FACTORY_PREAMBLE} %output% ${chunk.factoryPostamble || FACTORY_POSTAMBLE} diff --git a/tests/deps.js b/tests/deps.js index 1946968c4..601c79e77 100644 --- a/tests/deps.js +++ b/tests/deps.js @@ -1,4 +1,4 @@ -goog.addDependency('../../blocks/all.js', ['Blockly.blocks.all'], ['Blockly.blocks.colour', 'Blockly.blocks.lists', 'Blockly.blocks.logic', 'Blockly.blocks.loops', 'Blockly.blocks.math', 'Blockly.blocks.procedures', 'Blockly.blocks.texts', 'Blockly.blocks.variables', 'Blockly.blocks.variablesDynamic'], {'module': 'goog'}); +goog.addDependency('../../blocks/all.js', ['Blockly.blocks.all'], ['Blockly.blocks.colour', 'Blockly.blocks.lists', 'Blockly.blocks.logic', 'Blockly.blocks.loops', 'Blockly.blocks.math', 'Blockly.blocks.procedures', 'Blockly.blocks.texts', 'Blockly.blocks.variables', 'Blockly.blocks.variablesDynamic'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../blocks/colour.js', ['Blockly.blocks.colour'], ['Blockly.FieldColour', 'Blockly.common'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../blocks/lists.js', ['Blockly.blocks.lists'], ['Blockly.ConnectionType', 'Blockly.FieldDropdown', 'Blockly.FieldDropdown', 'Blockly.Input', 'Blockly.Msg', 'Blockly.Mutator', 'Blockly.blocks', 'Blockly.common', 'Blockly.utils.xml'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../blocks/logic.js', ['Blockly.blocks.logic'], ['Blockly.Events', 'Blockly.Extensions', 'Blockly.FieldDropdown', 'Blockly.FieldLabel', 'Blockly.Msg', 'Blockly.Mutator', 'Blockly.common', 'Blockly.utils.xml'], {'lang': 'es6', 'module': 'goog'}); From ffb8907db8d0f11609c1fe14b2a450d3e639a871 Mon Sep 17 00:00:00 2001 From: Christopher Allen Date: Mon, 31 Jan 2022 21:41:29 +0000 Subject: [PATCH 052/128] feature(blocks): Export block definitions (#5908) * refactor: Provide a BlockDefinition type * refactor: Split defineBlocksWithJsonArray Split defineBlocksWithJsonArray into: - createBlockDefinitionsFromJsonArray, which creates BlockDefinitions from a (possibly JSON-originated) POJsO array, having no side-effects except possibly issuing warnings to the console. - defineBlocks, which add any dictionary of BlockDefinitions to the Blocks dictionary. * feat(blocks): Export block definitions per-module - Define all blocks in a local blocks dictionary, often using createBlockDefinitionFromJsonArray, without registering them. - Separately, use defineBlocks to register the exported BlockDefinitions at the end of each Blockly.blocks.* module. - In Blockly.blocks.all, create a blocks export that combines all of the blocks exports from the individual blocks modules. * chore: have format script run clang-format on blocks/ too --- blocks/all.js | 11 ++++++ blocks/colour.js | 14 ++++++- blocks/lists.js | 33 ++++++++++------ blocks/logic.js | 14 ++++++- blocks/loops.js | 14 ++++++- blocks/math.js | 13 ++++++- blocks/procedures.js | 28 +++++++++---- blocks/text.js | 33 ++++++++++------ blocks/variables.js | 15 ++++++- blocks/variables_dynamic.js | 14 ++++++- core/block.js | 2 +- core/blocks.js | 11 +++++- core/common.js | 67 +++++++++++++++++++++++--------- scripts/gulpfiles/build_tasks.js | 2 +- scripts/gulpfiles/chunks.json | 2 +- tests/deps.js | 6 +-- 16 files changed, 208 insertions(+), 71 deletions(-) diff --git a/blocks/all.js b/blocks/all.js index b145d4107..b233bfcd8 100644 --- a/blocks/all.js +++ b/blocks/all.js @@ -22,6 +22,8 @@ const procedures = goog.require('Blockly.blocks.procedures'); const texts = goog.require('Blockly.blocks.texts'); const variables = goog.require('Blockly.blocks.variables'); const variablesDynamic = goog.require('Blockly.blocks.variablesDynamic'); +/* eslint-disable-next-line no-unused-vars */ +const {BlockDefinition} = goog.requireType('Blockly.blocks'); exports.colour = colour; @@ -34,3 +36,12 @@ exports.texts = texts; exports.variables = variables; exports.variablesDynamic = variablesDynamic; +/** + * A dictionary of the block definitions provided by all the + * Blockly.blocks.* modules. + * @type {!Object} + */ +const blocks = Object.assign( + {}, colour.blocks, lists.blocks, logic.blocks, loops.blocks, math.blocks, + procedures.blocks, variables.blocks, variablesDynamic.blocks); +exports.blocks = blocks; diff --git a/blocks/colour.js b/blocks/colour.js index c2a8b6b4b..abf7347e1 100644 --- a/blocks/colour.js +++ b/blocks/colour.js @@ -11,12 +11,18 @@ goog.module('Blockly.blocks.colour'); -const {defineBlocksWithJsonArray} = goog.require('Blockly.common'); +/* eslint-disable-next-line no-unused-vars */ +const {BlockDefinition} = goog.requireType('Blockly.blocks'); +const {createBlockDefinitionsFromJsonArray, defineBlocks} = goog.require('Blockly.common'); /** @suppress {extraRequire} */ goog.require('Blockly.FieldColour'); -defineBlocksWithJsonArray([ +/** + * A dictionary of the block definitions provided by this module. + * @type {!Object} + */ +const blocks = createBlockDefinitionsFromJsonArray([ // Block for colour picker. { 'type': 'colour_picker', @@ -107,3 +113,7 @@ defineBlocksWithJsonArray([ 'tooltip': '%{BKY_COLOUR_BLEND_TOOLTIP}', }, ]); +exports.blocks = blocks; + +// Register provided blocks. +defineBlocks(blocks); diff --git a/blocks/lists.js b/blocks/lists.js index 80400536d..dbb6b2aa4 100644 --- a/blocks/lists.js +++ b/blocks/lists.js @@ -16,19 +16,24 @@ const xmlUtils = goog.require('Blockly.utils.xml'); const {Align} = goog.require('Blockly.Input'); /* eslint-disable-next-line no-unused-vars */ const {Block} = goog.requireType('Blockly.Block'); -const {Blocks} = goog.require('Blockly.blocks'); +/* eslint-disable-next-line no-unused-vars */ +const {BlockDefinition} = goog.requireType('Blockly.blocks'); const {ConnectionType} = goog.require('Blockly.ConnectionType'); const {FieldDropdown} = goog.require('Blockly.FieldDropdown'); const {Msg} = goog.require('Blockly.Msg'); const {Mutator} = goog.require('Blockly.Mutator'); /* eslint-disable-next-line no-unused-vars */ const {Workspace} = goog.requireType('Blockly.Workspace'); -const {defineBlocksWithJsonArray} = goog.require('Blockly.common'); +const {createBlockDefinitionsFromJsonArray, defineBlocks} = goog.require('Blockly.common'); /** @suppress {extraRequire} */ goog.require('Blockly.FieldDropdown'); -defineBlocksWithJsonArray([ +/** + * A dictionary of the block definitions provided by this module. + * @type {!Object} + */ +const blocks = createBlockDefinitionsFromJsonArray([ // Block for creating an empty list // The 'list_create_with' block is preferred as it is more flexible. // @@ -112,8 +117,9 @@ defineBlocksWithJsonArray([ 'helpUrl': '%{BKY_LISTS_LENGTH_HELPURL}', }, ]); +exports.blocks = blocks; -Blocks['lists_create_with'] = { +blocks['lists_create_with'] = { /** * Block for creating a list with any number of elements of any type. * @this {Block} @@ -255,7 +261,7 @@ Blocks['lists_create_with'] = { }, }; -Blocks['lists_create_with_container'] = { +blocks['lists_create_with_container'] = { /** * Mutator block for list container. * @this {Block} @@ -270,7 +276,7 @@ Blocks['lists_create_with_container'] = { }, }; -Blocks['lists_create_with_item'] = { +blocks['lists_create_with_item'] = { /** * Mutator block for adding items. * @this {Block} @@ -285,7 +291,7 @@ Blocks['lists_create_with_item'] = { }, }; -Blocks['lists_indexOf'] = { +blocks['lists_indexOf'] = { /** * Block for finding an item in the list. * @this {Block} @@ -312,7 +318,7 @@ Blocks['lists_indexOf'] = { }, }; -Blocks['lists_getIndex'] = { +blocks['lists_getIndex'] = { /** * Block for getting element at index. * @this {Block} @@ -516,7 +522,7 @@ Blocks['lists_getIndex'] = { }, }; -Blocks['lists_setIndex'] = { +blocks['lists_setIndex'] = { /** * Block for setting the element at index. * @this {Block} @@ -668,7 +674,7 @@ Blocks['lists_setIndex'] = { }, }; -Blocks['lists_getSublist'] = { +blocks['lists_getSublist'] = { /** * Block for getting sublist. * @this {Block} @@ -786,7 +792,7 @@ Blocks['lists_getSublist'] = { }, }; -Blocks['lists_sort'] = { +blocks['lists_sort'] = { /** * Block for sorting a list. * @this {Block} @@ -826,7 +832,7 @@ Blocks['lists_sort'] = { }, }; -Blocks['lists_split'] = { +blocks['lists_split'] = { /** * Block for splitting text into a list, or joining a list into text. * @this {Block} @@ -913,3 +919,6 @@ Blocks['lists_split'] = { // dropdown values. // XML hooks are kept for backwards compatibility. }; + +// Register provided blocks. +defineBlocks(blocks); diff --git a/blocks/logic.js b/blocks/logic.js index 8a79d7f94..f7428ca19 100644 --- a/blocks/logic.js +++ b/blocks/logic.js @@ -19,20 +19,26 @@ const Extensions = goog.require('Blockly.Extensions'); const xmlUtils = goog.require('Blockly.utils.xml'); /* eslint-disable-next-line no-unused-vars */ const {Block} = goog.requireType('Blockly.Block'); +/* eslint-disable-next-line no-unused-vars */ +const {BlockDefinition} = goog.requireType('Blockly.blocks'); const {Msg} = goog.require('Blockly.Msg'); const {Mutator} = goog.require('Blockly.Mutator'); /* eslint-disable-next-line no-unused-vars */ const {RenderedConnection} = goog.requireType('Blockly.RenderedConnection'); /* eslint-disable-next-line no-unused-vars */ const {Workspace} = goog.requireType('Blockly.Workspace'); -const {defineBlocksWithJsonArray} = goog.require('Blockly.common'); +const {createBlockDefinitionsFromJsonArray, defineBlocks} = goog.require('Blockly.common'); /** @suppress {extraRequire} */ goog.require('Blockly.FieldDropdown'); /** @suppress {extraRequire} */ goog.require('Blockly.FieldLabel'); -defineBlocksWithJsonArray([ +/** + * A dictionary of the block definitions provided by this module. + * @type {!Object} + */ +const blocks = createBlockDefinitionsFromJsonArray([ // Block for boolean data type: true and false. { 'type': 'logic_boolean', @@ -258,6 +264,7 @@ defineBlocksWithJsonArray([ 'tooltip': '%{BKY_CONTROLS_IF_ELSE_TOOLTIP}', }, ]); +exports.blocks = blocks; /** * Tooltip text, keyed by block OP value. Used by logic_compare and @@ -645,3 +652,6 @@ const LOGIC_TERNARY_ONCHANGE_MIXIN = { }; Extensions.registerMixin('logic_ternary', LOGIC_TERNARY_ONCHANGE_MIXIN); + +// Register provided blocks. +defineBlocks(blocks); diff --git a/blocks/loops.js b/blocks/loops.js index 21e66ece3..7ac0228e2 100644 --- a/blocks/loops.js +++ b/blocks/loops.js @@ -18,11 +18,13 @@ const ContextMenu = goog.require('Blockly.ContextMenu'); const Events = goog.require('Blockly.Events'); const Extensions = goog.require('Blockly.Extensions'); const Variables = goog.require('Blockly.Variables'); -const common = goog.require('Blockly.common'); const xmlUtils = goog.require('Blockly.utils.xml'); /* eslint-disable-next-line no-unused-vars */ const {Block} = goog.requireType('Blockly.Block'); +/* eslint-disable-next-line no-unused-vars */ +const {BlockDefinition} = goog.requireType('Blockly.blocks'); const {Msg} = goog.require('Blockly.Msg'); +const {createBlockDefinitionsFromJsonArray, defineBlocks} = goog.require('Blockly.common'); /** @suppress {extraRequire} */ goog.require('Blockly.FieldDropdown'); /** @suppress {extraRequire} */ @@ -35,7 +37,11 @@ goog.require('Blockly.FieldVariable'); goog.require('Blockly.Warning'); -common.defineBlocksWithJsonArray([ +/** + * A dictionary of the block definitions provided by this module. + * @type {!Object} + */ +const blocks = createBlockDefinitionsFromJsonArray([ // Block for repeat n times (external number). { 'type': 'controls_repeat_ext', @@ -205,6 +211,7 @@ common.defineBlocksWithJsonArray([ ], }, ]); +exports.blocks = blocks; /** * Tooltips for the 'controls_whileUntil' block, keyed by MODE value. @@ -358,3 +365,6 @@ const CONTROL_FLOW_IN_LOOP_CHECK_MIXIN = { Extensions.registerMixin( 'controls_flow_in_loop_check', CONTROL_FLOW_IN_LOOP_CHECK_MIXIN); + +// Register provided blocks. +defineBlocks(blocks); diff --git a/blocks/math.js b/blocks/math.js index 003ff5bdc..a5143ba99 100644 --- a/blocks/math.js +++ b/blocks/math.js @@ -20,7 +20,8 @@ const xmlUtils = goog.require('Blockly.utils.xml'); /* eslint-disable-next-line no-unused-vars */ const {Block} = goog.requireType('Blockly.Block'); /* eslint-disable-next-line no-unused-vars */ -const {defineBlocksWithJsonArray} = goog.require('Blockly.common'); +const {BlockDefinition} = goog.requireType('Blockly.blocks'); +const {createBlockDefinitionsFromJsonArray, defineBlocks} = goog.require('Blockly.common'); /** @suppress {extraRequire} */ goog.require('Blockly.FieldLabel'); /** @suppress {extraRequire} */ @@ -29,7 +30,11 @@ goog.require('Blockly.FieldNumber'); goog.require('Blockly.FieldVariable'); -defineBlocksWithJsonArray([ +/** + * A dictionary of the block definitions provided by this module. + * @type {!Object} + */ +const blocks = createBlockDefinitionsFromJsonArray([ // Block for numeric value. { 'type': 'math_number', @@ -384,6 +389,7 @@ defineBlocksWithJsonArray([ 'helpUrl': '%{BKY_MATH_ATAN2_HELPURL}', }, ]); +exports.blocks = blocks; /** * Mapping of math block OP value to tooltip message for blocks @@ -581,3 +587,6 @@ const LIST_MODES_MUTATOR_EXTENSION = function() { Extensions.registerMutator( 'math_modes_of_list_mutator', LIST_MODES_MUTATOR_MIXIN, LIST_MODES_MUTATOR_EXTENSION); + +// Register provided blocks. +defineBlocks(blocks); diff --git a/blocks/procedures.js b/blocks/procedures.js index c41eb92db..49964f64f 100644 --- a/blocks/procedures.js +++ b/blocks/procedures.js @@ -24,7 +24,8 @@ const xmlUtils = goog.require('Blockly.utils.xml'); const {Align} = goog.require('Blockly.Input'); /* eslint-disable-next-line no-unused-vars */ const {Block} = goog.requireType('Blockly.Block'); -const {Blocks} = goog.require('Blockly.blocks'); +/* eslint-disable-next-line no-unused-vars */ +const {BlockDefinition} = goog.requireType('Blockly.blocks'); /* eslint-disable-next-line no-unused-vars */ const {FieldCheckbox} = goog.require('Blockly.FieldCheckbox'); const {FieldLabel} = goog.require('Blockly.FieldLabel'); @@ -36,12 +37,20 @@ const {Names} = goog.require('Blockly.Names'); const {VariableModel} = goog.requireType('Blockly.VariableModel'); /* eslint-disable-next-line no-unused-vars */ const {Workspace} = goog.requireType('Blockly.Workspace'); +const {defineBlocks} = goog.require('Blockly.common'); /** @suppress {extraRequire} */ goog.require('Blockly.Comment'); /** @suppress {extraRequire} */ goog.require('Blockly.Warning'); +/** + * A dictionary of the block definitions provided by this module. + * @type {!Object} + */ +const blocks = {}; +exports.blocks = blocks; + /** * Common properties for the procedure_defnoreturn and * procedure_defreturn blocks. @@ -437,7 +446,7 @@ const PROCEDURE_DEF_COMMON = { callType_: 'procedures_callnoreturn', }; -Blocks['procedures_defnoreturn'] = { +blocks['procedures_defnoreturn'] = { ...PROCEDURE_DEF_COMMON, /** * Block for defining a procedure with no return value. @@ -479,7 +488,7 @@ Blocks['procedures_defnoreturn'] = { }, }; -Blocks['procedures_defreturn'] = { +blocks['procedures_defreturn'] = { ...PROCEDURE_DEF_COMMON, /** * Block for defining a procedure with a return value. @@ -524,7 +533,7 @@ Blocks['procedures_defreturn'] = { }, }; -Blocks['procedures_mutatorcontainer'] = { +blocks['procedures_mutatorcontainer'] = { /** * Mutator block for procedure container. * @this {Block} @@ -542,7 +551,7 @@ Blocks['procedures_mutatorcontainer'] = { }, }; -Blocks['procedures_mutatorarg'] = { +blocks['procedures_mutatorarg'] = { /** * Mutator block for procedure argument. * @this {Block} @@ -1033,7 +1042,7 @@ const PROCEDURE_CALL_COMMON = { }, }; -Blocks['procedures_callnoreturn'] = { +blocks['procedures_callnoreturn'] = { ...PROCEDURE_CALL_COMMON, /** * Block for calling a procedure with no return value. @@ -1056,7 +1065,7 @@ Blocks['procedures_callnoreturn'] = { defType_: 'procedures_defnoreturn', }; -Blocks['procedures_callreturn'] = { +blocks['procedures_callreturn'] = { ...PROCEDURE_CALL_COMMON, /** * Block for calling a procedure with a return value. @@ -1078,7 +1087,7 @@ Blocks['procedures_callreturn'] = { defType_: 'procedures_defreturn', }; -Blocks['procedures_ifreturn'] = { +blocks['procedures_ifreturn'] = { /** * Block for conditionally returning a value from a procedure. * @this {Block} @@ -1179,3 +1188,6 @@ Blocks['procedures_ifreturn'] = { */ FUNCTION_TYPES: ['procedures_defnoreturn', 'procedures_defreturn'], }; + +// Register provided blocks. +defineBlocks(blocks); diff --git a/blocks/text.js b/blocks/text.js index 9072c7fa1..decefb53e 100644 --- a/blocks/text.js +++ b/blocks/text.js @@ -19,7 +19,8 @@ const xmlUtils = goog.require('Blockly.utils.xml'); const {Align} = goog.require('Blockly.Input'); /* eslint-disable-next-line no-unused-vars */ const {Block} = goog.requireType('Blockly.Block'); -const {Blocks} = goog.require('Blockly.blocks'); +/* eslint-disable-next-line no-unused-vars */ +const {BlockDefinition} = goog.requireType('Blockly.blocks'); const {ConnectionType} = goog.require('Blockly.ConnectionType'); const {FieldDropdown} = goog.require('Blockly.FieldDropdown'); const {FieldImage} = goog.require('Blockly.FieldImage'); @@ -27,14 +28,18 @@ const {FieldTextInput} = goog.require('Blockly.FieldTextInput'); const {Mutator} = goog.require('Blockly.Mutator'); /* eslint-disable-next-line no-unused-vars */ const {Workspace} = goog.requireType('Blockly.Workspace'); -const {defineBlocksWithJsonArray} = goog.require('Blockly.common'); +const {createBlockDefinitionsFromJsonArray, defineBlocks} = goog.require('Blockly.common'); /** @suppress {extraRequire} */ goog.require('Blockly.FieldMultilineInput'); /** @suppress {extraRequire} */ goog.require('Blockly.FieldVariable'); -defineBlocksWithJsonArray([ +/** + * A dictionary of the block definitions provided by this module. + * @type {!Object} + */ +const blocks = createBlockDefinitionsFromJsonArray([ // Block for text value { 'type': 'text', @@ -238,8 +243,9 @@ defineBlocksWithJsonArray([ 'mutator': 'text_charAt_mutator', }, ]); +exports.blocks = blocks; -Blocks['text_getSubstring'] = { +blocks['text_getSubstring'] = { /** * Block for getting substring. * @this {Block} @@ -363,7 +369,7 @@ Blocks['text_getSubstring'] = { }, }; -Blocks['text_changeCase'] = { +blocks['text_changeCase'] = { /** * Block for changing capitalization. * @this {Block} @@ -383,7 +389,7 @@ Blocks['text_changeCase'] = { }, }; -Blocks['text_trim'] = { +blocks['text_trim'] = { /** * Block for trimming spaces. * @this {Block} @@ -403,7 +409,7 @@ Blocks['text_trim'] = { }, }; -Blocks['text_print'] = { +blocks['text_print'] = { /** * Block for print statement. * @this {Block} @@ -463,7 +469,7 @@ const TEXT_PROMPT_COMMON = { }, }; -Blocks['text_prompt_ext'] = { +blocks['text_prompt_ext'] = { ...TEXT_PROMPT_COMMON, /** * Block for prompt function (external message). @@ -496,7 +502,7 @@ Blocks['text_prompt_ext'] = { // XML hooks are kept for backwards compatibility. }; -Blocks['text_prompt'] = { +blocks['text_prompt'] = { ...TEXT_PROMPT_COMMON, /** * Block for prompt function (internal message). @@ -531,7 +537,7 @@ Blocks['text_prompt'] = { }, }; -Blocks['text_count'] = { +blocks['text_count'] = { /** * Block for counting how many times one string appears within another string. * @this {Block} @@ -560,7 +566,7 @@ Blocks['text_count'] = { }, }; -Blocks['text_replace'] = { +blocks['text_replace'] = { /** * Block for replacing one string with another in the text. * @this {Block} @@ -594,7 +600,7 @@ Blocks['text_replace'] = { }, }; -Blocks['text_reverse'] = { +blocks['text_reverse'] = { /** * Block for reversing a string. * @this {Block} @@ -981,3 +987,6 @@ Extensions.registerMutator( Extensions.registerMutator( 'text_charAt_mutator', TEXT_CHARAT_MUTATOR_MIXIN, TEXT_CHARAT_EXTENSION); + +// Register provided blocks. +defineBlocks(blocks); diff --git a/blocks/variables.js b/blocks/variables.js index c9e4720fa..8875f287a 100644 --- a/blocks/variables.js +++ b/blocks/variables.js @@ -18,15 +18,21 @@ const Variables = goog.require('Blockly.Variables'); const xmlUtils = goog.require('Blockly.utils.xml'); /* eslint-disable-next-line no-unused-vars */ const {Block} = goog.requireType('Blockly.Block'); +/* eslint-disable-next-line no-unused-vars */ +const {BlockDefinition} = goog.requireType('Blockly.blocks'); const {Msg} = goog.require('Blockly.Msg'); -const {defineBlocksWithJsonArray} = goog.require('Blockly.common'); +const {createBlockDefinitionsFromJsonArray, defineBlocks} = goog.require('Blockly.common'); /** @suppress {extraRequire} */ goog.require('Blockly.FieldLabel'); /** @suppress {extraRequire} */ goog.require('Blockly.FieldVariable'); -defineBlocksWithJsonArray([ +/** + * A dictionary of the block definitions provided by this module. + * @type {!Object} + */ +const blocks = createBlockDefinitionsFromJsonArray([ // Block for variable getter. { 'type': 'variables_get', @@ -67,6 +73,8 @@ defineBlocksWithJsonArray([ 'extensions': ['contextMenu_variableSetterGetter'], }, ]); +exports.blocks = blocks; + /** * Mixin to add context menu items to create getter/setter blocks for this @@ -161,3 +169,6 @@ const deleteOptionCallbackFactory = function(block) { Extensions.registerMixin( 'contextMenu_variableSetterGetter', CUSTOM_CONTEXT_MENU_VARIABLE_GETTER_SETTER_MIXIN); + +// Register provided blocks. +defineBlocks(blocks); diff --git a/blocks/variables_dynamic.js b/blocks/variables_dynamic.js index 26a91af1e..3360d978e 100644 --- a/blocks/variables_dynamic.js +++ b/blocks/variables_dynamic.js @@ -20,15 +20,21 @@ const Variables = goog.require('Blockly.Variables'); const xml = goog.require('Blockly.utils.xml'); /* eslint-disable-next-line no-unused-vars */ const {Block} = goog.requireType('Blockly.Block'); +/* eslint-disable-next-line no-unused-vars */ +const {BlockDefinition} = goog.requireType('Blockly.blocks'); const {Msg} = goog.require('Blockly.Msg'); -const {defineBlocksWithJsonArray} = goog.require('Blockly.common'); +const {createBlockDefinitionsFromJsonArray, defineBlocks} = goog.require('Blockly.common'); /** @suppress {extraRequire} */ goog.require('Blockly.FieldLabel'); /** @suppress {extraRequire} */ goog.require('Blockly.FieldVariable'); -defineBlocksWithJsonArray([ +/** + * A dictionary of the block definitions provided by this module. + * @type {!Object} + */ +const blocks = createBlockDefinitionsFromJsonArray([ // Block for variable getter. { 'type': 'variables_get_dynamic', @@ -67,6 +73,7 @@ defineBlocksWithJsonArray([ 'extensions': ['contextMenu_variableDynamicSetterGetter'], }, ]); +exports.blocks = blocks; /** * Mixin to add context menu items to create getter/setter blocks for this @@ -178,3 +185,6 @@ const deleteOptionCallbackFactory = function(block) { Extensions.registerMixin( 'contextMenu_variableDynamicSetterGetter', CUSTOM_CONTEXT_MENU_VARIABLE_GETTER_SETTER_MIXIN); + +// Register provided blocks. +defineBlocks(blocks); diff --git a/core/block.js b/core/block.js index 082ca4296..2f8162154 100644 --- a/core/block.js +++ b/core/block.js @@ -316,7 +316,7 @@ const Block = function(workspace, prototypeName, opt_id) { this.type = prototypeName; const prototype = Blocks[prototypeName]; if (!prototype || typeof prototype !== 'object') { - throw TypeError('Unknown block type: ' + prototypeName); + throw TypeError('Invalid block definition for type: ' + prototypeName); } object.mixin(this, prototype); } diff --git a/core/blocks.js b/core/blocks.js index 0af6f6135..c29eaa96f 100644 --- a/core/blocks.js +++ b/core/blocks.js @@ -16,11 +16,18 @@ goog.module('Blockly.blocks'); +/** + * A block definition. For now this very lose, but it can potentially + * be refined e.g. by replacing this typedef with a class definition. + * @typedef {!Object} + */ +let BlockDefinition; +exports.BlockDefinition = BlockDefinition; + /** * A mapping of block type names to block prototype objects. - * @type {!Object} + * @type {!Object} * @alias Blockly.blocks.Blocks */ const Blocks = Object.create(null); - exports.Blocks = Blocks; diff --git a/core/common.js b/core/common.js index 59052b55d..29a4af214 100644 --- a/core/common.js +++ b/core/common.js @@ -17,7 +17,8 @@ */ goog.module('Blockly.common'); -const {Blocks} = goog.require('Blockly.blocks'); +/* eslint-disable-next-line no-unused-vars */ +const {BlockDefinition, Blocks} = goog.require('Blockly.blocks'); /* eslint-disable-next-line no-unused-vars */ const {Connection} = goog.requireType('Blockly.Connection'); /* eslint-disable-next-line no-unused-vars */ @@ -210,27 +211,55 @@ const jsonInitFactory = function(jsonDef) { * @alias Blockly.common.defineBlocksWithJsonArray */ const defineBlocksWithJsonArray = function(jsonArray) { + defineBlocks(createBlockDefinitionsFromJsonArray(jsonArray)); +}; +exports.defineBlocksWithJsonArray = defineBlocksWithJsonArray; + +/** + * Define blocks from an array of JSON block definitions, as might be generated + * by the Blockly Developer Tools. + * @param {!Array} jsonArray An array of JSON block definitions. + * @return {!Object} A map of the block + * definitions created. + * @alias Blockly.common.defineBlocksWithJsonArray + */ +const createBlockDefinitionsFromJsonArray = function(jsonArray) { + const /** @type {!Object} */ blocks = {}; for (let i = 0; i < jsonArray.length; i++) { const elem = jsonArray[i]; if (!elem) { - console.warn( - 'Block definition #' + i + ' in JSON array is ' + elem + '. ' + - 'Skipping.'); - } else { - const typename = elem.type; - if (!typename) { - console.warn( - 'Block definition #' + i + - ' in JSON array is missing a type attribute. Skipping.'); - } else { - if (Blocks[typename]) { - console.warn( - 'Block definition #' + i + ' in JSON array' + - ' overwrites prior definition of "' + typename + '".'); - } - Blocks[typename] = {init: jsonInitFactory(elem)}; - } + console.warn(`Block definition #${i} in JSON array is ${elem}. Skipping`); + continue; } + const type = elem.type; + if (!type) { + console.warn( + `Block definition #${i} in JSON array is missing a type attribute. ` + + 'Skipping.'); + continue; + } + blocks[type] = {init: jsonInitFactory(elem)}; + } + return blocks; +}; +exports.createBlockDefinitionsFromJsonArray = + createBlockDefinitionsFromJsonArray; + +/** + * Add the specified block definitions to the block definitions + * dictionary (Blockly.Blocks). + * @param {!Object} blocks A map of block + * type names to block definitions. + * @alias Blockly.common.defineBlocks + */ +const defineBlocks = function(blocks) { + // Iterate over own enumerable properties. + for (const type of Object.keys(blocks)) { + const definition = blocks[type]; + if (type in Blocks) { + console.warn(`Block definiton "${type}" overwrites previous definition.`); + } + Blocks[type] = definition; } }; -exports.defineBlocksWithJsonArray = defineBlocksWithJsonArray; +exports.defineBlocks = defineBlocks; diff --git a/scripts/gulpfiles/build_tasks.js b/scripts/gulpfiles/build_tasks.js index aef2bf95b..8b647b356 100644 --- a/scripts/gulpfiles/build_tasks.js +++ b/scripts/gulpfiles/build_tasks.js @@ -626,7 +626,7 @@ function cleanBuildDir(done) { * Runs clang format on all files in the core directory. */ function format() { - return gulp.src(['core/**/*.js'], {base: '.'}) + return gulp.src(['core/**/*.js', 'blocks/**/*.js'], {base: '.'}) .pipe(clangFormatter.format('file', clangFormat)) .pipe(gulp.dest('.')); }; diff --git a/scripts/gulpfiles/chunks.json b/scripts/gulpfiles/chunks.json index c3df5c612..4f9b94492 100644 --- a/scripts/gulpfiles/chunks.json +++ b/scripts/gulpfiles/chunks.json @@ -72,7 +72,6 @@ "./core/menuitem.js", "./core/menu.js", "./core/contextmenu.js", - "./core/blocks.js", "./core/utils/global.js", "./core/utils/useragent.js", "./core/utils/svg.js", @@ -264,6 +263,7 @@ "./core/xml.js", "./core/connection.js", "./core/common.js", + "./core/blocks.js", "./closure/goog/base_minimal.js", "./core/blockly.js", "./blocks/variables_dynamic.js", diff --git a/tests/deps.js b/tests/deps.js index 601c79e77..6c66f8850 100644 --- a/tests/deps.js +++ b/tests/deps.js @@ -1,11 +1,11 @@ goog.addDependency('../../blocks/all.js', ['Blockly.blocks.all'], ['Blockly.blocks.colour', 'Blockly.blocks.lists', 'Blockly.blocks.logic', 'Blockly.blocks.loops', 'Blockly.blocks.math', 'Blockly.blocks.procedures', 'Blockly.blocks.texts', 'Blockly.blocks.variables', 'Blockly.blocks.variablesDynamic'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../blocks/colour.js', ['Blockly.blocks.colour'], ['Blockly.FieldColour', 'Blockly.common'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../blocks/lists.js', ['Blockly.blocks.lists'], ['Blockly.ConnectionType', 'Blockly.FieldDropdown', 'Blockly.FieldDropdown', 'Blockly.Input', 'Blockly.Msg', 'Blockly.Mutator', 'Blockly.blocks', 'Blockly.common', 'Blockly.utils.xml'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../blocks/lists.js', ['Blockly.blocks.lists'], ['Blockly.ConnectionType', 'Blockly.FieldDropdown', 'Blockly.FieldDropdown', 'Blockly.Input', 'Blockly.Msg', 'Blockly.Mutator', 'Blockly.common', 'Blockly.utils.xml'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../blocks/logic.js', ['Blockly.blocks.logic'], ['Blockly.Events', 'Blockly.Extensions', 'Blockly.FieldDropdown', 'Blockly.FieldLabel', 'Blockly.Msg', 'Blockly.Mutator', 'Blockly.common', 'Blockly.utils.xml'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../blocks/loops.js', ['Blockly.blocks.loops'], ['Blockly.ContextMenu', 'Blockly.Events', 'Blockly.Extensions', 'Blockly.FieldDropdown', 'Blockly.FieldLabel', 'Blockly.FieldNumber', 'Blockly.FieldVariable', 'Blockly.Msg', 'Blockly.Variables', 'Blockly.Warning', 'Blockly.common', 'Blockly.utils.xml'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../blocks/math.js', ['Blockly.blocks.math'], ['Blockly.Extensions', 'Blockly.FieldDropdown', 'Blockly.FieldLabel', 'Blockly.FieldNumber', 'Blockly.FieldVariable', 'Blockly.common', 'Blockly.utils.xml'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../blocks/procedures.js', ['Blockly.blocks.procedures'], ['Blockly.Comment', 'Blockly.ContextMenu', 'Blockly.Events', 'Blockly.FieldCheckbox', 'Blockly.FieldLabel', 'Blockly.FieldTextInput', 'Blockly.Input', 'Blockly.Msg', 'Blockly.Mutator', 'Blockly.Names', 'Blockly.Procedures', 'Blockly.Variables', 'Blockly.Warning', 'Blockly.Xml', 'Blockly.blocks', 'Blockly.internalConstants', 'Blockly.utils.xml'], {'lang': 'es9', 'module': 'goog'}); -goog.addDependency('../../blocks/text.js', ['Blockly.blocks.texts'], ['Blockly.ConnectionType', 'Blockly.Extensions', 'Blockly.FieldDropdown', 'Blockly.FieldImage', 'Blockly.FieldMultilineInput', 'Blockly.FieldTextInput', 'Blockly.FieldVariable', 'Blockly.Input', 'Blockly.Msg', 'Blockly.Mutator', 'Blockly.blocks', 'Blockly.common', 'Blockly.utils.xml'], {'lang': 'es9', 'module': 'goog'}); +goog.addDependency('../../blocks/procedures.js', ['Blockly.blocks.procedures'], ['Blockly.Comment', 'Blockly.ContextMenu', 'Blockly.Events', 'Blockly.FieldCheckbox', 'Blockly.FieldLabel', 'Blockly.FieldTextInput', 'Blockly.Input', 'Blockly.Msg', 'Blockly.Mutator', 'Blockly.Names', 'Blockly.Procedures', 'Blockly.Variables', 'Blockly.Warning', 'Blockly.Xml', 'Blockly.common', 'Blockly.internalConstants', 'Blockly.utils.xml'], {'lang': 'es9', 'module': 'goog'}); +goog.addDependency('../../blocks/text.js', ['Blockly.blocks.texts'], ['Blockly.ConnectionType', 'Blockly.Extensions', 'Blockly.FieldDropdown', 'Blockly.FieldImage', 'Blockly.FieldMultilineInput', 'Blockly.FieldTextInput', 'Blockly.FieldVariable', 'Blockly.Input', 'Blockly.Msg', 'Blockly.Mutator', 'Blockly.common', 'Blockly.utils.xml'], {'lang': 'es9', 'module': 'goog'}); goog.addDependency('../../blocks/variables.js', ['Blockly.blocks.variables'], ['Blockly.ContextMenu', 'Blockly.Extensions', 'Blockly.FieldLabel', 'Blockly.FieldVariable', 'Blockly.Msg', 'Blockly.Variables', 'Blockly.common', 'Blockly.utils.xml'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../blocks/variables_dynamic.js', ['Blockly.blocks.variablesDynamic'], ['Blockly.ContextMenu', 'Blockly.Extensions', 'Blockly.FieldLabel', 'Blockly.FieldVariable', 'Blockly.Msg', 'Blockly.Variables', 'Blockly.common', 'Blockly.utils.xml'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/block.js', ['Blockly.Block'], ['Blockly.ASTNode', 'Blockly.Connection', 'Blockly.ConnectionType', 'Blockly.Events.BlockChange', 'Blockly.Events.BlockCreate', 'Blockly.Events.BlockDelete', 'Blockly.Events.BlockMove', 'Blockly.Events.utils', 'Blockly.Extensions', 'Blockly.IASTNodeLocation', 'Blockly.IDeletable', 'Blockly.Input', 'Blockly.Tooltip', 'Blockly.blocks', 'Blockly.common', 'Blockly.constants', 'Blockly.fieldRegistry', 'Blockly.inputTypes', 'Blockly.utils.Coordinate', 'Blockly.utils.Size', 'Blockly.utils.array', 'Blockly.utils.idGenerator', 'Blockly.utils.object', 'Blockly.utils.parsing'], {'lang': 'es6', 'module': 'goog'}); From 0690a1a8841f61580ed18f5302e7ed788c2ed8e9 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 1 Feb 2022 14:26:02 -0800 Subject: [PATCH 053/128] chore(deps): bump @blockly/theme-modern from 2.1.25 to 2.1.27 (#5906) Bumps [@blockly/theme-modern](https://github.com/google/blockly-samples/tree/HEAD/plugins/theme-modern) from 2.1.25 to 2.1.27. - [Release notes](https://github.com/google/blockly-samples/releases) - [Commits](https://github.com/google/blockly-samples/commits/@blockly/theme-modern@2.1.27/plugins/theme-modern) --- updated-dependencies: - dependency-name: "@blockly/theme-modern" dependency-type: direct:development update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- package-lock.json | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/package-lock.json b/package-lock.json index 4e1118f63..6c6d3b945 100644 --- a/package-lock.json +++ b/package-lock.json @@ -226,9 +226,9 @@ } }, "node_modules/@blockly/theme-modern": { - "version": "2.1.25", - "resolved": "https://registry.npmjs.org/@blockly/theme-modern/-/theme-modern-2.1.25.tgz", - "integrity": "sha512-CeImJoVh0Kv9O7GAlCzhrL5UDZRxe94H9ib1mGVi/eWweGA2ruU3pR/TLjg9d5oCuBbqaaGEsXEoZMiraE8pZQ==", + "version": "2.1.27", + "resolved": "https://registry.npmjs.org/@blockly/theme-modern/-/theme-modern-2.1.27.tgz", + "integrity": "sha512-i9jJJviaRwVO+FrllZp4NrwUGJJJ8RMZ2p0Fwtwsih0QpQ3K3RCNn/avMzB+nqo0X2/S/mk6ZNU/8z6OSYzmjg==", "dev": true, "engines": { "node": ">=8.17.0" @@ -12559,9 +12559,9 @@ "requires": {} }, "@blockly/theme-modern": { - "version": "2.1.25", - "resolved": "https://registry.npmjs.org/@blockly/theme-modern/-/theme-modern-2.1.25.tgz", - "integrity": "sha512-CeImJoVh0Kv9O7GAlCzhrL5UDZRxe94H9ib1mGVi/eWweGA2ruU3pR/TLjg9d5oCuBbqaaGEsXEoZMiraE8pZQ==", + "version": "2.1.27", + "resolved": "https://registry.npmjs.org/@blockly/theme-modern/-/theme-modern-2.1.27.tgz", + "integrity": "sha512-i9jJJviaRwVO+FrllZp4NrwUGJJJ8RMZ2p0Fwtwsih0QpQ3K3RCNn/avMzB+nqo0X2/S/mk6ZNU/8z6OSYzmjg==", "dev": true, "requires": {} }, From 75238ba26e4d551512de4713e99b4c13bbbc9e73 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 1 Feb 2022 14:26:40 -0800 Subject: [PATCH 054/128] chore(deps): bump @blockly/block-test from 2.0.1 to 2.0.3 (#5907) Bumps [@blockly/block-test](https://github.com/google/blockly-samples/tree/HEAD/plugins/block-test) from 2.0.1 to 2.0.3. - [Release notes](https://github.com/google/blockly-samples/releases) - [Commits](https://github.com/google/blockly-samples/commits/@blockly/block-test@2.0.3/plugins/block-test) --- updated-dependencies: - dependency-name: "@blockly/block-test" dependency-type: direct:development update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- package-lock.json | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/package-lock.json b/package-lock.json index 6c6d3b945..3fa971319 100644 --- a/package-lock.json +++ b/package-lock.json @@ -153,9 +153,9 @@ } }, "node_modules/@blockly/block-test": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/@blockly/block-test/-/block-test-2.0.1.tgz", - "integrity": "sha512-d8E109UEWTtFv1bfy5paQNk9HYdZDWH5S7qkCrlKTtSatPDt8f3SGCr/lu8JC086/LhjRafgX1RTa0uwJIDDdg==", + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/@blockly/block-test/-/block-test-2.0.3.tgz", + "integrity": "sha512-J5FETQwWFztWepduvA1H2z3D87AtSjHCk5nu+bV0YPFO93yrTJ0lHnZqERRfe8/AXvI6OCRHjiOEh5UWPOirrQ==", "dev": true, "engines": { "node": ">=8.17.0" @@ -12512,9 +12512,9 @@ } }, "@blockly/block-test": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/@blockly/block-test/-/block-test-2.0.1.tgz", - "integrity": "sha512-d8E109UEWTtFv1bfy5paQNk9HYdZDWH5S7qkCrlKTtSatPDt8f3SGCr/lu8JC086/LhjRafgX1RTa0uwJIDDdg==", + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/@blockly/block-test/-/block-test-2.0.3.tgz", + "integrity": "sha512-J5FETQwWFztWepduvA1H2z3D87AtSjHCk5nu+bV0YPFO93yrTJ0lHnZqERRfe8/AXvI6OCRHjiOEh5UWPOirrQ==", "dev": true, "requires": {} }, From 2b73dd550e23c9e4bd5cda49acd2cdfadd38508f Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 1 Feb 2022 14:27:43 -0800 Subject: [PATCH 055/128] chore(deps): bump selenium-standalone from 8.0.8 to 8.0.9 (#5885) Bumps [selenium-standalone](https://github.com/webdriverio/selenium-standalone) from 8.0.8 to 8.0.9. - [Release notes](https://github.com/webdriverio/selenium-standalone/releases) - [Changelog](https://github.com/webdriverio/selenium-standalone/blob/main/HISTORY.md) - [Commits](https://github.com/webdriverio/selenium-standalone/compare/v8.0.8...v8.0.9) --- updated-dependencies: - dependency-name: selenium-standalone dependency-type: direct:development update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- package-lock.json | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/package-lock.json b/package-lock.json index 3fa971319..c8a4fd368 100644 --- a/package-lock.json +++ b/package-lock.json @@ -10174,9 +10174,9 @@ "dev": true }, "node_modules/selenium-standalone": { - "version": "8.0.8", - "resolved": "https://registry.npmjs.org/selenium-standalone/-/selenium-standalone-8.0.8.tgz", - "integrity": "sha512-2NCHoK12dbLbtXPIdMe1ljiLAMflJDBezPhjJBwmnYz5/yGjCPv2R9ojHO6W1ctD9DOlqyi3AxoAvlT2nmB7Fw==", + "version": "8.0.9", + "resolved": "https://registry.npmjs.org/selenium-standalone/-/selenium-standalone-8.0.9.tgz", + "integrity": "sha512-Bl5Wbaeu5bKVmpLVATYeRcPsk9Bv3fr1aUvdC39UZjG6R/bem8j8Pj+dwB9F+PsS/owQnKh0BCg1KalZcAImbw==", "dev": true, "dependencies": { "commander": "^8.3.0", @@ -20549,9 +20549,9 @@ "dev": true }, "selenium-standalone": { - "version": "8.0.8", - "resolved": "https://registry.npmjs.org/selenium-standalone/-/selenium-standalone-8.0.8.tgz", - "integrity": "sha512-2NCHoK12dbLbtXPIdMe1ljiLAMflJDBezPhjJBwmnYz5/yGjCPv2R9ojHO6W1ctD9DOlqyi3AxoAvlT2nmB7Fw==", + "version": "8.0.9", + "resolved": "https://registry.npmjs.org/selenium-standalone/-/selenium-standalone-8.0.9.tgz", + "integrity": "sha512-Bl5Wbaeu5bKVmpLVATYeRcPsk9Bv3fr1aUvdC39UZjG6R/bem8j8Pj+dwB9F+PsS/owQnKh0BCg1KalZcAImbw==", "dev": true, "requires": { "commander": "^8.3.0", From 97c19be6125c73eb10c6e12e6e8f05e14caef2d6 Mon Sep 17 00:00:00 2001 From: Rachel Fenichel Date: Tue, 1 Feb 2022 15:43:11 -0800 Subject: [PATCH 056/128] refactor: convert renderer measurables to es6 classes (#5899) * chore: use casts to narrow types in renderers * chore: add @struct and type information on common measurables * refactor: update some renderer measurables to es6 classes * refactor: convert many measurables to es6 classes * chore: format * chore: rebuild --- core/renderers/common/drawer.js | 5 +- core/renderers/common/info.js | 15 +- core/renderers/geras/highlighter.js | 2 +- core/renderers/geras/info.js | 13 +- core/renderers/measurables/base.js | 9 + core/renderers/measurables/bottom_row.js | 165 +++++++++-------- core/renderers/measurables/connection.js | 39 ++-- .../measurables/external_value_input.js | 59 +++--- core/renderers/measurables/field.js | 55 ++++-- core/renderers/measurables/hat.js | 33 ++-- core/renderers/measurables/icon.js | 40 ++-- core/renderers/measurables/in_row_spacer.js | 30 +-- core/renderers/measurables/inline_input.js | 78 ++++---- .../renderers/measurables/input_connection.js | 67 ++++--- core/renderers/measurables/input_row.js | 92 ++++----- core/renderers/measurables/jagged_edge.js | 28 +-- core/renderers/measurables/next_connection.js | 32 ++-- .../measurables/output_connection.js | 44 +++-- .../measurables/previous_connection.js | 33 ++-- core/renderers/measurables/round_corner.js | 40 ++-- core/renderers/measurables/row.js | 3 + core/renderers/measurables/spacer_row.js | 63 ++++--- core/renderers/measurables/square_corner.js | 36 ++-- core/renderers/measurables/statement_input.js | 45 ++--- core/renderers/measurables/top_row.js | 174 +++++++++--------- core/renderers/thrasos/info.js | 13 +- core/renderers/zelos/drawer.js | 40 ++-- core/renderers/zelos/info.js | 16 +- tests/deps.js | 40 ++-- 29 files changed, 734 insertions(+), 575 deletions(-) diff --git a/core/renderers/common/drawer.js b/core/renderers/common/drawer.js index ad58c34e1..55f4f8054 100644 --- a/core/renderers/common/drawer.js +++ b/core/renderers/common/drawer.js @@ -22,6 +22,8 @@ const {BlockSvg} = goog.requireType('Blockly.BlockSvg'); /* eslint-disable-next-line no-unused-vars */ const {ConstantProvider} = goog.requireType('Blockly.blockRendering.ConstantProvider'); /* eslint-disable-next-line no-unused-vars */ +const {ExternalValueInput} = goog.requireType('Blockly.blockRendering.ExternalValueInput'); +/* eslint-disable-next-line no-unused-vars */ const {Field} = goog.requireType('Blockly.blockRendering.Field'); /* eslint-disable-next-line no-unused-vars */ const {Icon} = goog.requireType('Blockly.blockRendering.Icon'); @@ -175,7 +177,8 @@ Drawer.prototype.drawJaggedEdge_ = function(row) { * @protected */ Drawer.prototype.drawValueInput_ = function(row) { - const input = row.getLastInput(); + const input = + /** @type {ExternalValueInput|InlineInput} */ (row.getLastInput()); this.positionExternalValueConnection_(row); const pathDown = (typeof input.shape.pathDown === 'function') ? diff --git a/core/renderers/common/info.js b/core/renderers/common/info.js index 48e2d84b9..a5a06d4a1 100644 --- a/core/renderers/common/info.js +++ b/core/renderers/common/info.js @@ -90,7 +90,7 @@ const RenderInfo = function(renderer, block) { null : new OutputConnection( this.constants_, - /** @type {RenderedConnection} */ (block.outputConnection)); + /** @type {!RenderedConnection} */ (block.outputConnection)); /** * Whether the block should be rendered as a single line, either because it's @@ -285,7 +285,7 @@ RenderInfo.prototype.populateTopRow_ = function() { this.topRow.hasPreviousConnection = true; this.topRow.connection = new PreviousConnection( this.constants_, - /** @type {RenderedConnection} */ + /** @type {!RenderedConnection} */ (this.block_.previousConnection)); this.topRow.elements.push(this.topRow.connection); } @@ -338,7 +338,7 @@ RenderInfo.prototype.populateBottomRow_ = function() { if (this.bottomRow.hasNextConnection) { this.bottomRow.connection = new NextConnection( this.constants_, - /** @type {RenderedConnection} */ (this.block_.nextConnection)); + /** @type {!RenderedConnection} */ (this.block_.nextConnection)); this.bottomRow.elements.push(this.bottomRow.connection); } @@ -695,17 +695,20 @@ RenderInfo.prototype.getElemCenterline_ = function(row, elem) { return row.yPos + elem.height / 2; } if (Types.isBottomRow(row)) { - const baseline = row.yPos + row.height - row.descenderHeight; + const bottomRow = /** @type {!BottomRow} */ (row); + const baseline = + bottomRow.yPos + bottomRow.height - bottomRow.descenderHeight; if (Types.isNextConnection(elem)) { return baseline + elem.height / 2; } return baseline - elem.height / 2; } if (Types.isTopRow(row)) { + const topRow = /** @type {!TopRow} */ (row); if (Types.isHat(elem)) { - return row.capline - elem.height / 2; + return topRow.capline - elem.height / 2; } - return row.capline + elem.height / 2; + return topRow.capline + elem.height / 2; } return row.yPos + row.height / 2; }; diff --git a/core/renderers/geras/highlighter.js b/core/renderers/geras/highlighter.js index c81beb077..c10206c36 100644 --- a/core/renderers/geras/highlighter.js +++ b/core/renderers/geras/highlighter.js @@ -148,7 +148,7 @@ class Highlighter { * @package */ drawValueInput(row) { - const input = row.getLastInput(); + const input = /** @type {!InlineInput}} */ (row.getLastInput()); if (this.RTL_) { const belowTabHeight = row.height - input.connectionHeight; diff --git a/core/renderers/geras/info.js b/core/renderers/geras/info.js index d8e45c271..4824908a1 100644 --- a/core/renderers/geras/info.js +++ b/core/renderers/geras/info.js @@ -19,6 +19,8 @@ goog.module('Blockly.geras.RenderInfo'); /* eslint-disable-next-line no-unused-vars */ const {BlockSvg} = goog.requireType('Blockly.BlockSvg'); +/* eslint-disable-next-line no-unused-vars */ +const {BottomRow} = goog.requireType('Blockly.blockRendering.BottomRow'); const {ExternalValueInput} = goog.require('Blockly.blockRendering.ExternalValueInput'); /* eslint-disable-next-line no-unused-vars */ const {Field} = goog.requireType('Blockly.blockRendering.Field'); @@ -30,6 +32,8 @@ const {RenderInfo: BaseRenderInfo} = goog.require('Blockly.blockRendering.Render /* eslint-disable-next-line no-unused-vars */ const {Renderer} = goog.requireType('Blockly.geras.Renderer'); const {StatementInput} = goog.require('Blockly.geras.StatementInput'); +/* eslint-disable-next-line no-unused-vars */ +const {TopRow} = goog.requireType('Blockly.blockRendering.TopRow'); const {Types} = goog.require('Blockly.blockRendering.Types'); const {inputTypes} = goog.require('Blockly.inputTypes'); @@ -333,17 +337,20 @@ class RenderInfo extends BaseRenderInfo { return row.yPos + elem.height / 2; } if (Types.isBottomRow(row)) { - const baseline = row.yPos + row.height - row.descenderHeight; + const bottomRow = /** @type {!BottomRow} */ (row); + const baseline = + bottomRow.yPos + bottomRow.height - bottomRow.descenderHeight; if (Types.isNextConnection(elem)) { return baseline + elem.height / 2; } return baseline - elem.height / 2; } if (Types.isTopRow(row)) { + const topRow = /** @type {!TopRow} */ (row); if (Types.isHat(elem)) { - return row.capline - elem.height / 2; + return topRow.capline - elem.height / 2; } - return row.capline + elem.height / 2; + return topRow.capline + elem.height / 2; } let result = row.yPos; diff --git a/core/renderers/measurables/base.js b/core/renderers/measurables/base.js index c85f83306..f09039a4a 100644 --- a/core/renderers/measurables/base.js +++ b/core/renderers/measurables/base.js @@ -32,11 +32,19 @@ const {Types} = goog.require('Blockly.blockRendering.Types'); * @alias Blockly.blockRendering.Measurable */ const Measurable = function(constants) { + /** @type {number} */ this.width = 0; + + /** @type {number} */ this.height = 0; + + /** @type {number} */ this.type = Types.NONE; + /** @type {number} */ this.xPos = 0; + + /** @type {number} */ this.centerline = 0; /** @@ -46,6 +54,7 @@ const Measurable = function(constants) { */ this.constants_ = constants; + /** @type {number} */ this.notchOffset = this.constants_.NOTCH_OFFSET_LEFT; }; diff --git a/core/renderers/measurables/bottom_row.js b/core/renderers/measurables/bottom_row.js index 2103a92ba..a4c20e188 100644 --- a/core/renderers/measurables/bottom_row.js +++ b/core/renderers/measurables/bottom_row.js @@ -16,7 +16,6 @@ */ goog.module('Blockly.blockRendering.BottomRow'); -const object = goog.require('Blockly.utils.object'); /* eslint-disable-next-line no-unused-vars */ const {BlockSvg} = goog.requireType('Blockly.BlockSvg'); /* eslint-disable-next-line no-unused-vars */ @@ -32,104 +31,108 @@ const {Types} = goog.require('Blockly.blockRendering.Types'); * a block as well as spacing information for the bottom row. * Elements in a bottom row can consist of corners, spacers and next * connections. - * @param {!ConstantProvider} constants The rendering - * constants provider. - * @package - * @constructor * @extends {Row} - * @alias Blockly.blockRendering.BottomRow + * @struct */ -const BottomRow = function(constants) { - BottomRow.superClass_.constructor.call(this, constants); - this.type |= Types.BOTTOM_ROW; - +class BottomRow extends Row { /** - * Whether this row has a next connection. + * @param {!ConstantProvider} constants The rendering + * constants provider. * @package - * @type {boolean} + * @alias Blockly.blockRendering.BottomRow */ - this.hasNextConnection = false; + constructor(constants) { + super(constants); + this.type |= Types.BOTTOM_ROW; + + /** + * Whether this row has a next connection. + * @package + * @type {boolean} + */ + this.hasNextConnection = false; + + /** + * The next connection on the row, if any. + * @package + * @type {NextConnection} + */ + this.connection = null; + + /** + * The amount that the bottom of the block extends below the horizontal + * edge, e.g. because of a next connection. Must be non-negative (see + * #2820). + * @package + * @type {number} + */ + this.descenderHeight = 0; + + /** + * The Y position of the bottom edge of the block, relative to the origin + * of the block rendering. + * @type {number} + */ + this.baseline = 0; + } /** - * The next connection on the row, if any. - * @package - * @type {NextConnection} + * Returns whether or not the bottom row has a left square corner. + * @param {!BlockSvg} block The block whose bottom row this represents. + * @return {boolean} Whether or not the bottom row has a left square corner. */ - this.connection = null; + hasLeftSquareCorner(block) { + return !!block.outputConnection || !!block.getNextBlock(); + } /** - * The amount that the bottom of the block extends below the horizontal edge, - * e.g. because of a next connection. Must be non-negative (see #2820). - * @package - * @type {number} + * Returns whether or not the bottom row has a right square corner. + * @param {!BlockSvg} _block The block whose bottom row this represents. + * @return {boolean} Whether or not the bottom row has a right square corner. */ - this.descenderHeight = 0; + hasRightSquareCorner(_block) { + return true; + } /** - * The Y position of the bottom edge of the block, relative to the origin - * of the block rendering. - * @type {number} + * @override */ - this.baseline = 0; -}; -object.inherits(BottomRow, Row); - -/** - * Returns whether or not the bottom row has a left square corner. - * @param {!BlockSvg} block The block whose bottom row this represents. - * @return {boolean} Whether or not the bottom row has a left square corner. - */ -BottomRow.prototype.hasLeftSquareCorner = function(block) { - return !!block.outputConnection || !!block.getNextBlock(); -}; - -/** - * Returns whether or not the bottom row has a right square corner. - * @param {!BlockSvg} _block The block whose bottom row this represents. - * @return {boolean} Whether or not the bottom row has a right square corner. - */ -BottomRow.prototype.hasRightSquareCorner = function(_block) { - return true; -}; - -/** - * @override - */ -BottomRow.prototype.measure = function() { - let height = 0; - let width = 0; - let descenderHeight = 0; - for (let i = 0; i < this.elements.length; i++) { - const elem = this.elements[i]; - width += elem.width; - if (!(Types.isSpacer(elem))) { - // Note: this assumes that next connections have *only* descenderHeight, - // with no height above the baseline. - if (Types.isNextConnection(elem)) { - descenderHeight = Math.max(descenderHeight, elem.height); - } else { - height = Math.max(height, elem.height); + measure() { + let height = 0; + let width = 0; + let descenderHeight = 0; + for (let i = 0; i < this.elements.length; i++) { + const elem = this.elements[i]; + width += elem.width; + if (!(Types.isSpacer(elem))) { + // Note: this assumes that next connections have *only* descenderHeight, + // with no height above the baseline. + if (Types.isNextConnection(elem)) { + descenderHeight = Math.max(descenderHeight, elem.height); + } else { + height = Math.max(height, elem.height); + } } } + this.width = Math.max(this.minWidth, width); + this.height = Math.max(this.minHeight, height) + descenderHeight; + this.descenderHeight = descenderHeight; + this.widthWithConnectedBlocks = this.width; } - this.width = Math.max(this.minWidth, width); - this.height = Math.max(this.minHeight, height) + descenderHeight; - this.descenderHeight = descenderHeight; - this.widthWithConnectedBlocks = this.width; -}; -/** - * @override - */ -BottomRow.prototype.startsWithElemSpacer = function() { - return false; -}; + /** + * @override + */ + startsWithElemSpacer() { + return false; + } -/** - * @override - */ -BottomRow.prototype.endsWithElemSpacer = function() { - return false; -}; + /** + * @override + */ + endsWithElemSpacer() { + return false; + } +} exports.BottomRow = BottomRow; diff --git a/core/renderers/measurables/connection.js b/core/renderers/measurables/connection.js index fa13ace61..448c11e3c 100644 --- a/core/renderers/measurables/connection.js +++ b/core/renderers/measurables/connection.js @@ -16,7 +16,6 @@ */ goog.module('Blockly.blockRendering.Connection'); -const object = goog.require('Blockly.utils.object'); /* eslint-disable-next-line no-unused-vars */ const {ConstantProvider} = goog.requireType('Blockly.blockRendering.ConstantProvider'); const {Measurable} = goog.require('Blockly.blockRendering.Measurable'); @@ -28,22 +27,30 @@ const {Types} = goog.require('Blockly.blockRendering.Types'); /** * The base class to represent a connection and the space that it takes up on * the block. - * @param {!ConstantProvider} constants The rendering - * constants provider. - * @param {!RenderedConnection} connectionModel The connection object on - * the block that this represents. - * @package - * @constructor * @extends {Measurable} - * @alias Blockly.blockRendering.Connection */ -const Connection = function(constants, connectionModel) { - Connection.superClass_.constructor.call(this, constants); - this.connectionModel = connectionModel; - this.shape = this.constants_.shapeFor(connectionModel); - this.isDynamicShape = !!this.shape['isDynamic']; - this.type |= Types.CONNECTION; -}; -object.inherits(Connection, Measurable); +class Connection extends Measurable { + /** + * @param {!ConstantProvider} constants The rendering + * constants provider. + * @param {!RenderedConnection} connectionModel The connection object on + * the block that this represents. + * @package + * @alias Blockly.blockRendering.Connection + */ + constructor(constants, connectionModel) { + super(constants); + + /** @type {!RenderedConnection} */ + this.connectionModel = connectionModel; + + /** @type {!Object} */ + this.shape = this.constants_.shapeFor(connectionModel); + + /** @type {boolean} */ + this.isDynamicShape = !!this.shape['isDynamic']; + this.type |= Types.CONNECTION; + } +} exports.Connection = Connection; diff --git a/core/renderers/measurables/external_value_input.js b/core/renderers/measurables/external_value_input.js index 8fd8f9f3d..8aefc2b86 100644 --- a/core/renderers/measurables/external_value_input.js +++ b/core/renderers/measurables/external_value_input.js @@ -16,7 +16,6 @@ */ goog.module('Blockly.blockRendering.ExternalValueInput'); -const object = goog.require('Blockly.utils.object'); /* eslint-disable-next-line no-unused-vars */ const {ConstantProvider} = goog.requireType('Blockly.blockRendering.ConstantProvider'); const {InputConnection} = goog.require('Blockly.blockRendering.InputConnection'); @@ -28,30 +27,44 @@ const {Types} = goog.require('Blockly.blockRendering.Types'); /** * An object containing information about the space an external value input * takes up during rendering - * @param {!ConstantProvider} constants The rendering - * constants provider. - * @param {!Input} input The external value input to measure and store - * information for. - * @package - * @constructor + * @struct * @extends {InputConnection} - * @alias Blockly.blockRendering.ExternalValueInput */ -const ExternalValueInput = function(constants, input) { - ExternalValueInput.superClass_.constructor.call(this, constants, input); - this.type |= Types.EXTERNAL_VALUE_INPUT; - if (!this.connectedBlock) { - this.height = this.shape.height; - } else { - this.height = this.connectedBlockHeight - - this.constants_.TAB_OFFSET_FROM_TOP - this.constants_.MEDIUM_PADDING; - } - this.width = this.shape.width + this.constants_.EXTERNAL_VALUE_INPUT_PADDING; +class ExternalValueInput extends InputConnection { + /** + * @param {!ConstantProvider} constants The rendering + * constants provider. + * @param {!Input} input The external value input to measure and store + * information for. + * @package + * @alias Blockly.blockRendering.ExternalValueInput + */ + constructor(constants, input) { + super(constants, input); + this.type |= Types.EXTERNAL_VALUE_INPUT; - this.connectionOffsetY = this.constants_.TAB_OFFSET_FROM_TOP; - this.connectionHeight = this.shape.height; - this.connectionWidth = this.shape.width; -}; -object.inherits(ExternalValueInput, InputConnection); + /** @type {number} */ + this.height = 0; + if (!this.connectedBlock) { + this.height = this.shape.height; + } else { + this.height = this.connectedBlockHeight - + this.constants_.TAB_OFFSET_FROM_TOP - this.constants_.MEDIUM_PADDING; + } + + /** @type {number} */ + this.width = + this.shape.width + this.constants_.EXTERNAL_VALUE_INPUT_PADDING; + + /** @type {number} */ + this.connectionOffsetY = this.constants_.TAB_OFFSET_FROM_TOP; + + /** @type {number} */ + this.connectionHeight = this.shape.height; + + /** @type {number} */ + this.connectionWidth = this.shape.width; + } +} exports.ExternalValueInput = ExternalValueInput; diff --git a/core/renderers/measurables/field.js b/core/renderers/measurables/field.js index 52ff1b9a4..e7882c41e 100644 --- a/core/renderers/measurables/field.js +++ b/core/renderers/measurables/field.js @@ -16,7 +16,6 @@ */ goog.module('Blockly.blockRendering.Field'); -const object = goog.require('Blockly.utils.object'); /* eslint-disable-next-line no-unused-vars */ const {ConstantProvider} = goog.requireType('Blockly.blockRendering.ConstantProvider'); /* eslint-disable-next-line no-unused-vars */ @@ -30,27 +29,43 @@ const {Types} = goog.require('Blockly.blockRendering.Types'); /** * An object containing information about the space a field takes up during * rendering - * @param {!ConstantProvider} constants The rendering - * constants provider. - * @param {!BlocklyField} field The field to measure and store information for. - * @param {!Input} parentInput The parent input for the field. - * @package - * @constructor + * @struct * @extends {Measurable} - * @alias Blockly.blockRendering.Field */ -const Field = function(constants, field, parentInput) { - Field.superClass_.constructor.call(this, constants); - this.field = field; - this.isEditable = field.EDITABLE; - this.flipRtl = field.getFlipRtl(); - this.type |= Types.FIELD; +class Field extends Measurable { + /** + * @param {!ConstantProvider} constants The rendering + * constants provider. + * @param {!BlocklyField} field The field to measure and store information + * for. + * @param {!Input} parentInput The parent input for the field. + * @package + * @alias Blockly.blockRendering.Field + */ + constructor(constants, field, parentInput) { + super(constants); - const size = this.field.getSize(); - this.height = size.height; - this.width = size.width; - this.parentInput = parentInput; -}; -object.inherits(Field, Measurable); + /** @type {!BlocklyField} */ + this.field = field; + + /** @type {boolean} */ + this.isEditable = field.EDITABLE; + + /** @type {boolean} */ + this.flipRtl = field.getFlipRtl(); + this.type |= Types.FIELD; + + const size = this.field.getSize(); + + /** @type {number} */ + this.height = size.height; + + /** @type {number} */ + this.width = size.width; + + /** @type {!Input} */ + this.parentInput = parentInput; + } +} exports.Field = Field; diff --git a/core/renderers/measurables/hat.js b/core/renderers/measurables/hat.js index b0c2be23d..42c53d355 100644 --- a/core/renderers/measurables/hat.js +++ b/core/renderers/measurables/hat.js @@ -16,7 +16,6 @@ */ goog.module('Blockly.blockRendering.Hat'); -const object = goog.require('Blockly.utils.object'); /* eslint-disable-next-line no-unused-vars */ const {ConstantProvider} = goog.requireType('Blockly.blockRendering.ConstantProvider'); const {Measurable} = goog.require('Blockly.blockRendering.Measurable'); @@ -26,20 +25,26 @@ const {Types} = goog.require('Blockly.blockRendering.Types'); /** * An object containing information about the space a hat takes up during * rendering. - * @param {!ConstantProvider} constants The rendering - * constants provider. - * @package - * @constructor + * @struct * @extends {Measurable} - * @alias Blockly.blockRendering.Hat */ -const Hat = function(constants) { - Hat.superClass_.constructor.call(this, constants); - this.type |= Types.HAT; - this.height = this.constants_.START_HAT.height; - this.width = this.constants_.START_HAT.width; - this.ascenderHeight = this.height; -}; -object.inherits(Hat, Measurable); +class Hat extends Measurable { + /** + * @param {!ConstantProvider} constants The rendering + * constants provider. + * @package + * @alias Blockly.blockRendering.Hat + */ + constructor(constants) { + super(constants); + this.type |= Types.HAT; + + this.height = this.constants_.START_HAT.height; + this.width = this.constants_.START_HAT.width; + + /** @type {number} */ + this.ascenderHeight = this.height; + } +} exports.Hat = Hat; diff --git a/core/renderers/measurables/icon.js b/core/renderers/measurables/icon.js index 7b7efb552..072da2031 100644 --- a/core/renderers/measurables/icon.js +++ b/core/renderers/measurables/icon.js @@ -16,7 +16,6 @@ */ goog.module('Blockly.blockRendering.Icon'); -const object = goog.require('Blockly.utils.object'); /* eslint-disable-next-line no-unused-vars */ const {ConstantProvider} = goog.requireType('Blockly.blockRendering.ConstantProvider'); /* eslint-disable-next-line no-unused-vars */ @@ -28,24 +27,33 @@ const {Types} = goog.require('Blockly.blockRendering.Types'); /** * An object containing information about the space an icon takes up during * rendering - * @param {!ConstantProvider} constants The rendering - * constants provider. - * @param {!BlocklyIcon} icon The icon to measure and store information for. - * @package - * @constructor * @extends {Measurable} + * @struct * @alias Blockly.blockRendering.Icon */ -const Icon = function(constants, icon) { - Icon.superClass_.constructor.call(this, constants); - this.icon = icon; - this.isVisible = icon.isVisible(); - this.type |= Types.ICON; +class Icon extends Measurable { + /** + * An object containing information about the space an icon takes up during + * rendering + * @param {!ConstantProvider} constants The rendering + * constants provider. + * @param {!BlocklyIcon} icon The icon to measure and store information for. + * @package + * @alias Blockly.blockRendering.Icon + */ + constructor(constants, icon) { + super(constants); - const size = icon.getCorrectedSize(); - this.height = size.height; - this.width = size.width; -}; -object.inherits(Icon, Measurable); + /** @type {!BlocklyIcon} */ + this.icon = icon; + /** @type {boolean} */ + this.isVisible = icon.isVisible(); + this.type |= Types.ICON; + + const size = icon.getCorrectedSize(); + this.height = size.height; + this.width = size.width; + } +} exports.Icon = Icon; diff --git a/core/renderers/measurables/in_row_spacer.js b/core/renderers/measurables/in_row_spacer.js index 85e9251e4..0549e3f29 100644 --- a/core/renderers/measurables/in_row_spacer.js +++ b/core/renderers/measurables/in_row_spacer.js @@ -16,7 +16,6 @@ */ goog.module('Blockly.blockRendering.InRowSpacer'); -const object = goog.require('Blockly.utils.object'); /* eslint-disable-next-line no-unused-vars */ const {ConstantProvider} = goog.requireType('Blockly.blockRendering.ConstantProvider'); const {Measurable} = goog.require('Blockly.blockRendering.Measurable'); @@ -26,20 +25,23 @@ const {Types} = goog.require('Blockly.blockRendering.Types'); /** * An object containing information about a spacer between two elements on a * row. - * @param {!ConstantProvider} constants The rendering - * constants provider. - * @param {number} width The width of the spacer. - * @package - * @constructor * @extends {Measurable} - * @alias Blockly.blockRendering.InRowSpacer + * @struct */ -const InRowSpacer = function(constants, width) { - InRowSpacer.superClass_.constructor.call(this, constants); - this.type |= Types.SPACER | Types.IN_ROW_SPACER; - this.width = width; - this.height = this.constants_.SPACER_DEFAULT_HEIGHT; -}; -object.inherits(InRowSpacer, Measurable); +class InRowSpacer extends Measurable { + /** + * @param {!ConstantProvider} constants The rendering + * constants provider. + * @param {number} width The width of the spacer. + * @package + * @alias Blockly.blockRendering.InRowSpacer + */ + constructor(constants, width) { + super(constants); + this.type |= Types.SPACER | Types.IN_ROW_SPACER; + this.width = width; + this.height = this.constants_.SPACER_DEFAULT_HEIGHT; + } +} exports.InRowSpacer = InRowSpacer; diff --git a/core/renderers/measurables/inline_input.js b/core/renderers/measurables/inline_input.js index 1389d35a6..e5c256776 100644 --- a/core/renderers/measurables/inline_input.js +++ b/core/renderers/measurables/inline_input.js @@ -16,7 +16,6 @@ */ goog.module('Blockly.blockRendering.InlineInput'); -const object = goog.require('Blockly.utils.object'); /* eslint-disable-next-line no-unused-vars */ const {ConstantProvider} = goog.requireType('Blockly.blockRendering.ConstantProvider'); const {InputConnection} = goog.require('Blockly.blockRendering.InputConnection'); @@ -28,43 +27,54 @@ const {Types} = goog.require('Blockly.blockRendering.Types'); /** * An object containing information about the space an inline input takes up * during rendering - * @param {!ConstantProvider} constants The rendering - * constants provider. - * @param {!Input} input The inline input to measure and store - * information for. - * @package - * @constructor * @extends {InputConnection} - * @alias Blockly.blockRendering.InlineInput + * @struct */ -const InlineInput = function(constants, input) { - InlineInput.superClass_.constructor.call(this, constants, input); - this.type |= Types.INLINE_INPUT; +class InlineInput extends InputConnection { + /** + * @param {!ConstantProvider} constants The rendering + * constants provider. + * @param {!Input} input The inline input to measure and store + * information for. + * @package + * @alias Blockly.blockRendering.InlineInput + */ + constructor(constants, input) { + super(constants, input); + this.type |= Types.INLINE_INPUT; - if (!this.connectedBlock) { - this.height = this.constants_.EMPTY_INLINE_INPUT_HEIGHT; - this.width = this.constants_.EMPTY_INLINE_INPUT_PADDING; - } else { - // We allow the dark path to show on the parent block so that the child - // block looks embossed. This takes up an extra pixel in both x and y. - this.width = this.connectedBlockWidth; - this.height = this.connectedBlockHeight; - } + if (!this.connectedBlock) { + this.height = this.constants_.EMPTY_INLINE_INPUT_HEIGHT; + this.width = this.constants_.EMPTY_INLINE_INPUT_PADDING; + } else { + // We allow the dark path to show on the parent block so that the child + // block looks embossed. This takes up an extra pixel in both x and y. + this.width = this.connectedBlockWidth; + this.height = this.connectedBlockHeight; + } - this.connectionHeight = - !this.isDynamicShape ? this.shape.height : this.shape.height(this.height); - this.connectionWidth = - !this.isDynamicShape ? this.shape.width : this.shape.width(this.height); - if (!this.connectedBlock) { - this.width += this.connectionWidth * (this.isDynamicShape ? 2 : 1); + /** @type {number} */ + this.connectionHeight = !this.isDynamicShape ? + this.shape.height : + this.shape.height(this.height); + + /** @type {number} */ + this.connectionWidth = + !this.isDynamicShape ? this.shape.width : this.shape.width(this.height); + if (!this.connectedBlock) { + this.width += this.connectionWidth * (this.isDynamicShape ? 2 : 1); + } + + /** @type {number} */ + this.connectionOffsetY = this.isDynamicShape ? + this.shape.connectionOffsetY(this.connectionHeight) : + this.constants_.TAB_OFFSET_FROM_TOP; + + /** @type {number} */ + this.connectionOffsetX = this.isDynamicShape ? + this.shape.connectionOffsetX(this.connectionWidth) : + 0; } - 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; -}; -object.inherits(InlineInput, InputConnection); +} exports.InlineInput = InlineInput; diff --git a/core/renderers/measurables/input_connection.js b/core/renderers/measurables/input_connection.js index 39a3bfe43..b5b21c688 100644 --- a/core/renderers/measurables/input_connection.js +++ b/core/renderers/measurables/input_connection.js @@ -14,49 +14,62 @@ */ goog.module('Blockly.blockRendering.InputConnection'); -const object = goog.require('Blockly.utils.object'); +/* eslint-disable-next-line no-unused-vars */ +const {BlockSvg} = goog.requireType('Blockly.BlockSvg'); const {Connection} = goog.require('Blockly.blockRendering.Connection'); /* eslint-disable-next-line no-unused-vars */ const {ConstantProvider} = goog.requireType('Blockly.blockRendering.ConstantProvider'); /* eslint-disable-next-line no-unused-vars */ const {Input} = goog.requireType('Blockly.Input'); +/* eslint-disable-next-line no-unused-vars */ +const {RenderedConnection} = goog.requireType('Blockly.RenderedConnection'); const {Types} = goog.require('Blockly.blockRendering.Types'); /** * The base class to represent an input that takes up space on a block * during rendering - * @param {!ConstantProvider} constants The rendering - * constants provider. - * @param {!Input} input The input to measure and store information for. * @package - * @constructor * @extends {Connection} - * @alias Blockly.blockRendering.InputConnection */ -const InputConnection = function(constants, input) { - InputConnection.superClass_.constructor.call( - this, constants, input.connection); +class InputConnection extends Connection { + /** + * @param {!ConstantProvider} constants The rendering + * constants provider. + * @param {!Input} input The input to measure and store information for. + * @alias Blockly.blockRendering.InputConnection + */ + constructor(constants, input) { + super(constants, /** @type {!RenderedConnection} */ (input.connection)); - this.type |= Types.INPUT; - this.input = input; - this.align = input.align; - this.connectedBlock = input.connection && input.connection.targetBlock() ? - input.connection.targetBlock() : - null; + this.type |= Types.INPUT; - if (this.connectedBlock) { - const bBox = this.connectedBlock.getHeightWidth(); - this.connectedBlockWidth = bBox.width; - this.connectedBlockHeight = bBox.height; - } else { - this.connectedBlockWidth = 0; - this.connectedBlockHeight = 0; + /** @type {!Input} */ + this.input = input; + + /** @type {number} */ + this.align = input.align; + + /** @type {BlockSvg} */ + this.connectedBlock = input.connection && input.connection.targetBlock() ? + /** @type {BlockSvg} */ (input.connection.targetBlock()) : + null; + + if (this.connectedBlock) { + const bBox = this.connectedBlock.getHeightWidth(); + this.connectedBlockWidth = bBox.width; + this.connectedBlockHeight = bBox.height; + } else { + this.connectedBlockWidth = 0; + this.connectedBlockHeight = 0; + } + + /** @type {number} */ + this.connectionOffsetX = 0; + + /** @type {number} */ + this.connectionOffsetY = 0; } - - this.connectionOffsetX = 0; - this.connectionOffsetY = 0; -}; -object.inherits(InputConnection, Connection); +} exports.InputConnection = InputConnection; diff --git a/core/renderers/measurables/input_row.js b/core/renderers/measurables/input_row.js index 2f0e6011e..46eec63fe 100644 --- a/core/renderers/measurables/input_row.js +++ b/core/renderers/measurables/input_row.js @@ -16,7 +16,6 @@ */ goog.module('Blockly.blockRendering.InputRow'); -const object = goog.require('Blockly.utils.object'); /* eslint-disable-next-line no-unused-vars */ const {ConstantProvider} = goog.requireType('Blockly.blockRendering.ConstantProvider'); const {Row} = goog.require('Blockly.blockRendering.Row'); @@ -25,59 +24,62 @@ const {Types} = goog.require('Blockly.blockRendering.Types'); /** * An object containing information about a row that holds one or more inputs. - * @param {!ConstantProvider} constants The rendering - * constants provider. - * @package - * @constructor * @extends {Row} - * @alias Blockly.blockRendering.InputRow + * @struct */ -const InputRow = function(constants) { - InputRow.superClass_.constructor.call(this, constants); - this.type |= Types.INPUT_ROW; +class InputRow extends Row { + /** + * @param {!ConstantProvider} constants The rendering + * constants provider. + * @package + * @alias Blockly.blockRendering.InputRow + */ + constructor(constants) { + super(constants); + this.type |= Types.INPUT_ROW; + + /** + * The total width of all blocks connected to this row. + * @type {number} + * @package + */ + this.connectedBlockWidths = 0; + } /** - * The total width of all blocks connected to this row. - * @type {number} + * Inspect all subcomponents and populate all size properties on the row. * @package */ - this.connectedBlockWidths = 0; -}; -object.inherits(InputRow, Row); - -/** - * Inspect all subcomponents and populate all size properties on the row. - * @package - */ -InputRow.prototype.measure = function() { - this.width = this.minWidth; - this.height = this.minHeight; - let connectedBlockWidths = 0; - for (let i = 0; i < this.elements.length; i++) { - const elem = this.elements[i]; - this.width += elem.width; - if (Types.isInput(elem)) { - if (Types.isStatementInput(elem)) { - connectedBlockWidths += elem.connectedBlockWidth; - } else if ( - Types.isExternalInput(elem) && elem.connectedBlockWidth !== 0) { - connectedBlockWidths += - (elem.connectedBlockWidth - elem.connectionWidth); + measure() { + this.width = this.minWidth; + this.height = this.minHeight; + let connectedBlockWidths = 0; + for (let i = 0; i < this.elements.length; i++) { + const elem = this.elements[i]; + this.width += elem.width; + if (Types.isInput(elem)) { + if (Types.isStatementInput(elem)) { + connectedBlockWidths += elem.connectedBlockWidth; + } else if ( + Types.isExternalInput(elem) && elem.connectedBlockWidth !== 0) { + connectedBlockWidths += + (elem.connectedBlockWidth - elem.connectionWidth); + } + } + if (!(Types.isSpacer(elem))) { + this.height = Math.max(this.height, elem.height); } } - if (!(Types.isSpacer(elem))) { - this.height = Math.max(this.height, elem.height); - } + this.connectedBlockWidths = connectedBlockWidths; + this.widthWithConnectedBlocks = this.width + connectedBlockWidths; } - this.connectedBlockWidths = connectedBlockWidths; - this.widthWithConnectedBlocks = this.width + connectedBlockWidths; -}; -/** - * @override - */ -InputRow.prototype.endsWithElemSpacer = function() { - return !this.hasExternalInput && !this.hasStatement; -}; + /** + * @override + */ + endsWithElemSpacer() { + return !this.hasExternalInput && !this.hasStatement; + } +} exports.InputRow = InputRow; diff --git a/core/renderers/measurables/jagged_edge.js b/core/renderers/measurables/jagged_edge.js index 7c6a2930d..fbc103971 100644 --- a/core/renderers/measurables/jagged_edge.js +++ b/core/renderers/measurables/jagged_edge.js @@ -16,7 +16,6 @@ */ goog.module('Blockly.blockRendering.JaggedEdge'); -const object = goog.require('Blockly.utils.object'); /* eslint-disable-next-line no-unused-vars */ const {ConstantProvider} = goog.requireType('Blockly.blockRendering.ConstantProvider'); const {Measurable} = goog.require('Blockly.blockRendering.Measurable'); @@ -26,19 +25,22 @@ const {Types} = goog.require('Blockly.blockRendering.Types'); /** * An object containing information about the jagged edge of a collapsed block * takes up during rendering - * @param {!ConstantProvider} constants The rendering - * constants provider. - * @package - * @constructor * @extends {Measurable} - * @alias Blockly.blockRendering.JaggedEdge + * @struct */ -const JaggedEdge = function(constants) { - JaggedEdge.superClass_.constructor.call(this, constants); - this.type |= Types.JAGGED_EDGE; - this.height = this.constants_.JAGGED_TEETH.height; - this.width = this.constants_.JAGGED_TEETH.width; -}; -object.inherits(JaggedEdge, Measurable); +class JaggedEdge extends Measurable { + /** + * @param {!ConstantProvider} constants The rendering + * constants provider. + * @package + * @alias Blockly.blockRendering.JaggedEdge + */ + constructor(constants) { + super(constants); + this.type |= Types.JAGGED_EDGE; + this.height = this.constants_.JAGGED_TEETH.height; + this.width = this.constants_.JAGGED_TEETH.width; + } +} exports.JaggedEdge = JaggedEdge; diff --git a/core/renderers/measurables/next_connection.js b/core/renderers/measurables/next_connection.js index 387f2fb5b..f426bc121 100644 --- a/core/renderers/measurables/next_connection.js +++ b/core/renderers/measurables/next_connection.js @@ -16,7 +16,6 @@ */ goog.module('Blockly.blockRendering.NextConnection'); -const object = goog.require('Blockly.utils.object'); const {Connection} = goog.require('Blockly.blockRendering.Connection'); /* eslint-disable-next-line no-unused-vars */ const {ConstantProvider} = goog.requireType('Blockly.blockRendering.ConstantProvider'); @@ -28,21 +27,24 @@ const {Types} = goog.require('Blockly.blockRendering.Types'); /** * An object containing information about the space a next connection takes * up during rendering. - * @param {!ConstantProvider} constants The rendering - * constants provider. - * @param {RenderedConnection} connectionModel The connection object on - * the block that this represents. - * @package - * @constructor * @extends {Connection} - * @alias Blockly.blockRendering.NextConnection + * @struct */ -const NextConnection = function(constants, connectionModel) { - NextConnection.superClass_.constructor.call(this, constants, connectionModel); - this.type |= Types.NEXT_CONNECTION; - this.height = this.shape.height; - this.width = this.shape.width; -}; -object.inherits(NextConnection, Connection); +class NextConnection extends Connection { + /** + * @param {!ConstantProvider} constants The rendering + * constants provider. + * @param {!RenderedConnection} connectionModel The connection object on + * the block that this represents. + * @package + * @alias Blockly.blockRendering.NextConnection + */ + constructor(constants, connectionModel) { + super(constants, connectionModel); + this.type |= Types.NEXT_CONNECTION; + this.height = this.shape.height; + this.width = this.shape.width; + } +} exports.NextConnection = NextConnection; diff --git a/core/renderers/measurables/output_connection.js b/core/renderers/measurables/output_connection.js index 529a042bf..65c2fcb5a 100644 --- a/core/renderers/measurables/output_connection.js +++ b/core/renderers/measurables/output_connection.js @@ -17,7 +17,6 @@ */ goog.module('Blockly.blockRendering.OutputConnection'); -const object = goog.require('Blockly.utils.object'); const {Connection} = goog.require('Blockly.blockRendering.Connection'); /* eslint-disable-next-line no-unused-vars */ const {ConstantProvider} = goog.requireType('Blockly.blockRendering.ConstantProvider'); @@ -29,27 +28,34 @@ const {Types} = goog.require('Blockly.blockRendering.Types'); /** * An object containing information about the space an output connection takes * up during rendering. - * @param {!ConstantProvider} constants The rendering - * constants provider. - * @param {RenderedConnection} connectionModel The connection object on - * the block that this represents. - * @package - * @constructor * @extends {Connection} - * @alias Blockly.blockRendering.OutputConnection + * @struct */ -const OutputConnection = function(constants, connectionModel) { - OutputConnection.superClass_.constructor.call( - this, constants, connectionModel); - this.type |= Types.OUTPUT_CONNECTION; +class OutputConnection extends Connection { + /** + * @param {!ConstantProvider} constants The rendering + * constants provider. + * @param {!RenderedConnection} connectionModel The connection object on + * the block that this represents. + * @package + * @alias Blockly.blockRendering.OutputConnection + */ + constructor(constants, connectionModel) { + super(constants, connectionModel); + this.type |= Types.OUTPUT_CONNECTION; - this.height = !this.isDynamicShape ? this.shape.height : 0; - this.width = !this.isDynamicShape ? this.shape.width : 0; - this.startX = this.width; + this.height = !this.isDynamicShape ? this.shape.height : 0; + this.width = !this.isDynamicShape ? this.shape.width : 0; - this.connectionOffsetY = this.constants_.TAB_OFFSET_FROM_TOP; - this.connectionOffsetX = 0; -}; -object.inherits(OutputConnection, Connection); + /** @type {number} */ + this.startX = this.width; + + /** @type {number} */ + this.connectionOffsetY = this.constants_.TAB_OFFSET_FROM_TOP; + + /** @type {number} */ + this.connectionOffsetX = 0; + } +} exports.OutputConnection = OutputConnection; diff --git a/core/renderers/measurables/previous_connection.js b/core/renderers/measurables/previous_connection.js index 58c2e5081..e9ecc1145 100644 --- a/core/renderers/measurables/previous_connection.js +++ b/core/renderers/measurables/previous_connection.js @@ -16,7 +16,6 @@ */ goog.module('Blockly.blockRendering.PreviousConnection'); -const object = goog.require('Blockly.utils.object'); const {Connection} = goog.require('Blockly.blockRendering.Connection'); /* eslint-disable-next-line no-unused-vars */ const {ConstantProvider} = goog.requireType('Blockly.blockRendering.ConstantProvider'); @@ -28,22 +27,24 @@ const {Types} = goog.require('Blockly.blockRendering.Types'); /** * An object containing information about the space a previous connection takes * up during rendering. - * @param {!ConstantProvider} constants The rendering - * constants provider. - * @param {RenderedConnection} connectionModel The connection object on - * the block that this represents. - * @package - * @constructor * @extends {Connection} - * @alias Blockly.blockRendering.PreviousConnection + * @struct */ -const PreviousConnection = function(constants, connectionModel) { - PreviousConnection.superClass_.constructor.call( - this, constants, connectionModel); - this.type |= Types.PREVIOUS_CONNECTION; - this.height = this.shape.height; - this.width = this.shape.width; -}; -object.inherits(PreviousConnection, Connection); +class PreviousConnection extends Connection { + /** + * @param {!ConstantProvider} constants The rendering + * constants provider. + * @param {!RenderedConnection} connectionModel The connection object on + * the block that this represents. + * @package + * @alias Blockly.blockRendering.PreviousConnection + */ + constructor(constants, connectionModel) { + super(constants, connectionModel); + this.type |= Types.PREVIOUS_CONNECTION; + this.height = this.shape.height; + this.width = this.shape.width; + } +} exports.PreviousConnection = PreviousConnection; diff --git a/core/renderers/measurables/round_corner.js b/core/renderers/measurables/round_corner.js index fa153eedb..ccf15a6da 100644 --- a/core/renderers/measurables/round_corner.js +++ b/core/renderers/measurables/round_corner.js @@ -16,7 +16,6 @@ */ goog.module('Blockly.blockRendering.RoundCorner'); -const object = goog.require('Blockly.utils.object'); /* eslint-disable-next-line no-unused-vars */ const {ConstantProvider} = goog.requireType('Blockly.blockRendering.ConstantProvider'); const {Measurable} = goog.require('Blockly.blockRendering.Measurable'); @@ -26,25 +25,28 @@ const {Types} = goog.require('Blockly.blockRendering.Types'); /** * An object containing information about the space a rounded corner takes up * during rendering. - * @param {!ConstantProvider} constants The rendering - * constants provider. - * @param {string=} opt_position The position of this corner. - * @package - * @constructor * @extends {Measurable} - * @alias Blockly.blockRendering.RoundCorner + * @struct */ -const RoundCorner = function(constants, opt_position) { - RoundCorner.superClass_.constructor.call(this, constants); - this.type = - ((!opt_position || opt_position === 'left') ? Types.LEFT_ROUND_CORNER : - Types.RIGHT_ROUND_CORNER) | - Types.CORNER; - this.width = this.constants_.CORNER_RADIUS; - // The rounded corner extends into the next row by 4 so we only take the - // height that is aligned with this row. - this.height = this.constants_.CORNER_RADIUS / 2; -}; -object.inherits(RoundCorner, Measurable); +class RoundCorner extends Measurable { + /** + * @param {!ConstantProvider} constants The rendering + * constants provider. + * @param {string=} opt_position The position of this corner. + * @package + * @alias Blockly.blockRendering.RoundCorner + */ + constructor(constants, opt_position) { + super(constants); + this.type = ((!opt_position || opt_position === 'left') ? + Types.LEFT_ROUND_CORNER : + Types.RIGHT_ROUND_CORNER) | + Types.CORNER; + this.width = this.constants_.CORNER_RADIUS; + // The rounded corner extends into the next row by 4 so we only take the + // height that is aligned with this row. + this.height = this.constants_.CORNER_RADIUS / 2; + } +} exports.RoundCorner = RoundCorner; diff --git a/core/renderers/measurables/row.js b/core/renderers/measurables/row.js index 8b82e1aa2..40a592c7a 100644 --- a/core/renderers/measurables/row.js +++ b/core/renderers/measurables/row.js @@ -143,6 +143,9 @@ const Row = function(constants) { */ this.constants_ = constants; + /** + * @type {number} + */ this.notchOffset = this.constants_.NOTCH_OFFSET_LEFT; /** diff --git a/core/renderers/measurables/spacer_row.js b/core/renderers/measurables/spacer_row.js index 3f0eaa4f4..f0f860e4b 100644 --- a/core/renderers/measurables/spacer_row.js +++ b/core/renderers/measurables/spacer_row.js @@ -14,7 +14,6 @@ */ goog.module('Blockly.blockRendering.SpacerRow'); -const object = goog.require('Blockly.utils.object'); /* eslint-disable-next-line no-unused-vars */ const {ConstantProvider} = goog.requireType('Blockly.blockRendering.ConstantProvider'); const {InRowSpacer} = goog.require('Blockly.blockRendering.InRowSpacer'); @@ -24,31 +23,47 @@ const {Types} = goog.require('Blockly.blockRendering.Types'); /** * An object containing information about a spacer between two rows. - * @param {!ConstantProvider} constants The rendering - * constants provider. - * @param {number} height The height of the spacer. - * @param {number} width The width of the spacer. - * @package - * @constructor * @extends {Row} - * @alias Blockly.blockRendering.SpacerRow + * @struct */ -const SpacerRow = function(constants, height, width) { - SpacerRow.superClass_.constructor.call(this, constants); - this.type |= Types.SPACER | Types.BETWEEN_ROW_SPACER; - this.width = width; - this.height = height; - this.followsStatement = false; - this.widthWithConnectedBlocks = 0; - this.elements = [new InRowSpacer(this.constants_, width)]; -}; -object.inherits(SpacerRow, Row); +class SpacerRow extends Row { + /** + * @param {!ConstantProvider} constants The rendering + * constants provider. + * @param {number} height The height of the spacer. + * @param {number} width The width of the spacer. + * @package + * @alias Blockly.blockRendering.SpacerRow + */ + constructor(constants, height, width) { + super(constants); + this.type |= Types.SPACER | Types.BETWEEN_ROW_SPACER; -/** - * @override - */ -SpacerRow.prototype.measure = function() { - // NOP. Width and height were set at creation. -}; + /** @type {number} */ + this.width = width; + + /** @type {number} */ + this.height = height; + + /** @type {boolean} */ + this.followsStatement = false; + + /** @type {boolean} */ + this.precedesStatement = false; + + /** @type {number} */ + this.widthWithConnectedBlocks = 0; + + /** @type {!Array.} */ + this.elements = [new InRowSpacer(this.constants_, width)]; + } + + /** + * @override + */ + measure() { + // NOP. Width and height were set at creation. + } +} exports.SpacerRow = SpacerRow; diff --git a/core/renderers/measurables/square_corner.js b/core/renderers/measurables/square_corner.js index 347483e5c..b2de34794 100644 --- a/core/renderers/measurables/square_corner.js +++ b/core/renderers/measurables/square_corner.js @@ -16,7 +16,6 @@ */ goog.module('Blockly.blockRendering.SquareCorner'); -const object = goog.require('Blockly.utils.object'); /* eslint-disable-next-line no-unused-vars */ const {ConstantProvider} = goog.requireType('Blockly.blockRendering.ConstantProvider'); const {Measurable} = goog.require('Blockly.blockRendering.Measurable'); @@ -26,23 +25,26 @@ const {Types} = goog.require('Blockly.blockRendering.Types'); /** * An object containing information about the space a square corner takes up * during rendering. - * @param {!ConstantProvider} constants The rendering - * constants provider. - * @param {string=} opt_position The position of this corner. - * @package - * @constructor * @extends {Measurable} - * @alias Blockly.blockRendering.SquareCorner + * @struct */ -const SquareCorner = function(constants, opt_position) { - SquareCorner.superClass_.constructor.call(this, constants); - this.type = - ((!opt_position || opt_position === 'left') ? Types.LEFT_SQUARE_CORNER : - Types.RIGHT_SQUARE_CORNER) | - Types.CORNER; - this.height = this.constants_.NO_PADDING; - this.width = this.constants_.NO_PADDING; -}; -object.inherits(SquareCorner, Measurable); +class SquareCorner extends Measurable { + /** + * @param {!ConstantProvider} constants The rendering + * constants provider. + * @param {string=} opt_position The position of this corner. + * @package + * @alias Blockly.blockRendering.SquareCorner + */ + constructor(constants, opt_position) { + super(constants); + this.type = ((!opt_position || opt_position === 'left') ? + Types.LEFT_SQUARE_CORNER : + Types.RIGHT_SQUARE_CORNER) | + Types.CORNER; + this.height = this.constants_.NO_PADDING; + this.width = this.constants_.NO_PADDING; + } +} exports.SquareCorner = SquareCorner; diff --git a/core/renderers/measurables/statement_input.js b/core/renderers/measurables/statement_input.js index 5a45b9e91..5f989a72a 100644 --- a/core/renderers/measurables/statement_input.js +++ b/core/renderers/measurables/statement_input.js @@ -16,7 +16,6 @@ */ goog.module('Blockly.blockRendering.StatementInput'); -const object = goog.require('Blockly.utils.object'); /* eslint-disable-next-line no-unused-vars */ const {ConstantProvider} = goog.requireType('Blockly.blockRendering.ConstantProvider'); const {InputConnection} = goog.require('Blockly.blockRendering.InputConnection'); @@ -28,29 +27,33 @@ const {Types} = goog.require('Blockly.blockRendering.Types'); /** * An object containing information about the space a statement input takes up * during rendering - * @param {!ConstantProvider} constants The rendering - * constants provider. - * @param {!Input} input The statement input to measure and store - * information for. - * @package - * @constructor + * @struct * @extends {InputConnection} - * @alias Blockly.blockRendering.StatementInput */ -const StatementInput = function(constants, input) { - StatementInput.superClass_.constructor.call(this, constants, input); - this.type |= Types.STATEMENT_INPUT; +class StatementInput extends InputConnection { + /** + * @param {!ConstantProvider} constants The rendering + * constants provider. + * @param {!Input} input The statement input to measure and store + * information for. + * @package + * @alias Blockly.blockRendering.StatementInput + */ + constructor(constants, input) { + super(constants, input); + this.type |= Types.STATEMENT_INPUT; - if (!this.connectedBlock) { - this.height = this.constants_.EMPTY_STATEMENT_INPUT_HEIGHT; - } else { - // We allow the dark path to show on the parent block so that the child - // block looks embossed. This takes up an extra pixel in both x and y. - this.height = - this.connectedBlockHeight + this.constants_.STATEMENT_BOTTOM_SPACER; + if (!this.connectedBlock) { + this.height = this.constants_.EMPTY_STATEMENT_INPUT_HEIGHT; + } else { + // We allow the dark path to show on the parent block so that the child + // block looks embossed. This takes up an extra pixel in both x and y. + this.height = + this.connectedBlockHeight + this.constants_.STATEMENT_BOTTOM_SPACER; + } + this.width = + this.constants_.STATEMENT_INPUT_NOTCH_OFFSET + this.shape.width; } - this.width = this.constants_.STATEMENT_INPUT_NOTCH_OFFSET + this.shape.width; -}; -object.inherits(StatementInput, InputConnection); +} exports.StatementInput = StatementInput; diff --git a/core/renderers/measurables/top_row.js b/core/renderers/measurables/top_row.js index 756abd81d..b8f277826 100644 --- a/core/renderers/measurables/top_row.js +++ b/core/renderers/measurables/top_row.js @@ -14,7 +14,6 @@ */ goog.module('Blockly.blockRendering.TopRow'); -const object = goog.require('Blockly.utils.object'); /* eslint-disable-next-line no-unused-vars */ const {BlockSvg} = goog.requireType('Blockly.BlockSvg'); /* eslint-disable-next-line no-unused-vars */ @@ -32,109 +31,112 @@ const {Types} = goog.require('Blockly.blockRendering.Types'); * connections. * After this constructor is called, the row will contain all non-spacer * elements it needs. - * @param {!ConstantProvider} constants The rendering - * constants provider. - * @package - * @constructor * @extends {Row} - * @alias Blockly.blockRendering.TopRow + * @struct */ -const TopRow = function(constants) { - TopRow.superClass_.constructor.call(this, constants); - - this.type |= Types.TOP_ROW; - +class TopRow extends Row { /** - * The starting point for drawing the row, in the y direction. - * This allows us to draw hats and similar shapes that don't start at the - * origin. Must be non-negative (see #2820). + * @param {!ConstantProvider} constants The rendering + * constants provider. * @package - * @type {number} + * @alias Blockly.blockRendering.TopRow */ - this.capline = 0; + constructor(constants) { + super(constants); + + this.type |= Types.TOP_ROW; + + /** + * The starting point for drawing the row, in the y direction. + * This allows us to draw hats and similar shapes that don't start at the + * origin. Must be non-negative (see #2820). + * @package + * @type {number} + */ + this.capline = 0; + + /** + * How much the row extends up above its capline. + * @type {number} + */ + this.ascenderHeight = 0; + + /** + * Whether the block has a previous connection. + * @package + * @type {boolean} + */ + this.hasPreviousConnection = false; + + /** + * The previous connection on the block, if any. + * @type {PreviousConnection} + */ + this.connection = null; + } /** - * How much the row extends up above its capline. - * @type {number} + * Returns whether or not the top row has a left square corner. + * @param {!BlockSvg} block The block whose top row this represents. + * @return {boolean} Whether or not the top row has a left square corner. */ - this.ascenderHeight = 0; + hasLeftSquareCorner(block) { + const hasHat = + (block.hat ? block.hat === 'cap' : this.constants_.ADD_START_HATS) && + !block.outputConnection && !block.previousConnection; + const prevBlock = block.getPreviousBlock(); + + return !!block.outputConnection || hasHat || + (prevBlock ? prevBlock.getNextBlock() === block : false); + } /** - * Whether the block has a previous connection. - * @package - * @type {boolean} + * Returns whether or not the top row has a right square corner. + * @param {!BlockSvg} _block The block whose top row this represents. + * @return {boolean} Whether or not the top row has a right square corner. */ - this.hasPreviousConnection = false; + hasRightSquareCorner(_block) { + return true; + } /** - * The previous connection on the block, if any. - * @type {PreviousConnection} + * @override */ - this.connection = null; -}; -object.inherits(TopRow, Row); - -/** - * Returns whether or not the top row has a left square corner. - * @param {!BlockSvg} block The block whose top row this represents. - * @return {boolean} Whether or not the top row has a left square corner. - */ -TopRow.prototype.hasLeftSquareCorner = function(block) { - const hasHat = - (block.hat ? block.hat === 'cap' : this.constants_.ADD_START_HATS) && - !block.outputConnection && !block.previousConnection; - const prevBlock = block.getPreviousBlock(); - - return !!block.outputConnection || hasHat || - (prevBlock ? prevBlock.getNextBlock() === block : false); -}; - -/** - * Returns whether or not the top row has a right square corner. - * @param {!BlockSvg} _block The block whose top row this represents. - * @return {boolean} Whether or not the top row has a right square corner. - */ -TopRow.prototype.hasRightSquareCorner = function(_block) { - return true; -}; - -/** - * @override - */ -TopRow.prototype.measure = function() { - let height = 0; - let width = 0; - let ascenderHeight = 0; - for (let i = 0; i < this.elements.length; i++) { - const elem = this.elements[i]; - width += elem.width; - if (!(Types.isSpacer(elem))) { - if (Types.isHat(elem)) { - ascenderHeight = Math.max(ascenderHeight, elem.ascenderHeight); - } else { - height = Math.max(height, elem.height); + measure() { + let height = 0; + let width = 0; + let ascenderHeight = 0; + for (let i = 0; i < this.elements.length; i++) { + const elem = this.elements[i]; + width += elem.width; + if (!(Types.isSpacer(elem))) { + if (Types.isHat(elem)) { + ascenderHeight = Math.max(ascenderHeight, elem.ascenderHeight); + } else { + height = Math.max(height, elem.height); + } } } + this.width = Math.max(this.minWidth, width); + this.height = Math.max(this.minHeight, height) + ascenderHeight; + this.ascenderHeight = ascenderHeight; + this.capline = this.ascenderHeight; + this.widthWithConnectedBlocks = this.width; } - this.width = Math.max(this.minWidth, width); - this.height = Math.max(this.minHeight, height) + ascenderHeight; - this.ascenderHeight = ascenderHeight; - this.capline = this.ascenderHeight; - this.widthWithConnectedBlocks = this.width; -}; -/** - * @override - */ -TopRow.prototype.startsWithElemSpacer = function() { - return false; -}; + /** + * @override + */ + startsWithElemSpacer() { + return false; + } -/** - * @override - */ -TopRow.prototype.endsWithElemSpacer = function() { - return false; -}; + /** + * @override + */ + endsWithElemSpacer() { + return false; + } +} exports.TopRow = TopRow; diff --git a/core/renderers/thrasos/info.js b/core/renderers/thrasos/info.js index cf894842e..c3bd01d05 100644 --- a/core/renderers/thrasos/info.js +++ b/core/renderers/thrasos/info.js @@ -20,11 +20,15 @@ goog.module('Blockly.thrasos.RenderInfo'); /* eslint-disable-next-line no-unused-vars */ const {BlockSvg} = goog.requireType('Blockly.BlockSvg'); /* eslint-disable-next-line no-unused-vars */ +const {BottomRow} = goog.requireType('Blockly.blockRendering.BottomRow'); +/* eslint-disable-next-line no-unused-vars */ const {Field} = goog.requireType('Blockly.blockRendering.Field'); const {InRowSpacer} = goog.require('Blockly.blockRendering.InRowSpacer'); const {RenderInfo: BaseRenderInfo} = goog.require('Blockly.blockRendering.RenderInfo'); /* eslint-disable-next-line no-unused-vars */ const {Renderer} = goog.requireType('Blockly.thrasos.Renderer'); +/* eslint-disable-next-line no-unused-vars */ +const {TopRow} = goog.requireType('Blockly.blockRendering.TopRow'); const {Types} = goog.require('Blockly.blockRendering.Types'); @@ -261,17 +265,20 @@ class RenderInfo extends BaseRenderInfo { return row.yPos + elem.height / 2; } if (Types.isBottomRow(row)) { - const baseline = row.yPos + row.height - row.descenderHeight; + const bottomRow = /** @type {!BottomRow} */ (row); + const baseline = + bottomRow.yPos + bottomRow.height - bottomRow.descenderHeight; if (Types.isNextConnection(elem)) { return baseline + elem.height / 2; } return baseline - elem.height / 2; } if (Types.isTopRow(row)) { + const topRow = /** @type {!TopRow} */ (row); if (Types.isHat(elem)) { - return row.capline - elem.height / 2; + return topRow.capline - elem.height / 2; } - return row.capline + elem.height / 2; + return topRow.capline + elem.height / 2; } let result = row.yPos; diff --git a/core/renderers/zelos/drawer.js b/core/renderers/zelos/drawer.js index 9c9f7917e..deb8bf320 100644 --- a/core/renderers/zelos/drawer.js +++ b/core/renderers/zelos/drawer.js @@ -26,6 +26,11 @@ const {PathObject} = goog.requireType('Blockly.zelos.PathObject'); const {RenderInfo} = goog.requireType('Blockly.zelos.RenderInfo'); /* eslint-disable-next-line no-unused-vars */ const {Row} = goog.requireType('Blockly.blockRendering.Row'); +/* eslint-disable-next-line no-unused-vars */ +const {SpacerRow} = goog.requireType('Blockly.blockRendering.SpacerRow'); +/* eslint-disable-next-line no-unused-vars */ +const {StatementInput} = goog.requireType('Blockly.zelos.StatementInput'); +const {Types} = goog.require('Blockly.blockRendering.Types'); /** @@ -111,21 +116,26 @@ class Drawer extends BaseDrawer { if (row.height <= 0) { return; } - if (row.precedesStatement || row.followsStatement) { - const cornerHeight = this.constants_.INSIDE_CORNERS.rightHeight; - const remainingHeight = - row.height - (row.precedesStatement ? cornerHeight : 0); - this.outlinePath_ += (row.followsStatement ? - this.constants_.INSIDE_CORNERS.pathBottomRight : - '') + - (remainingHeight > 0 ? - svgPaths.lineOnAxis('V', row.yPos + remainingHeight) : - '') + - (row.precedesStatement ? this.constants_.INSIDE_CORNERS.pathTopRight : - ''); - } else { - this.outlinePath_ += svgPaths.lineOnAxis('V', row.yPos + row.height); + if (Types.isSpacer(row)) { + const spacerRow = /** @type {!SpacerRow} */ (row); + if (spacerRow.precedesStatement || spacerRow.followsStatement) { + const cornerHeight = this.constants_.INSIDE_CORNERS.rightHeight; + const remainingHeight = + spacerRow.height - (spacerRow.precedesStatement ? cornerHeight : 0); + this.outlinePath_ += + (spacerRow.followsStatement ? + this.constants_.INSIDE_CORNERS.pathBottomRight : + '') + + (remainingHeight > 0 ? + svgPaths.lineOnAxis('V', spacerRow.yPos + remainingHeight) : + '') + + (spacerRow.precedesStatement ? + this.constants_.INSIDE_CORNERS.pathTopRight : + ''); + return; + } } + this.outlinePath_ += svgPaths.lineOnAxis('V', row.yPos + row.height); } /** @@ -207,7 +217,7 @@ class Drawer extends BaseDrawer { * @override */ drawStatementInput_(row) { - const input = row.getLastInput(); + const input = /** @type {!StatementInput} */ (row.getLastInput()); // Where to start drawing the notch, which is on the right side in LTR. const x = input.xPos + input.notchOffset + input.shape.width; diff --git a/core/renderers/zelos/info.js b/core/renderers/zelos/info.js index 58802a909..96054308f 100644 --- a/core/renderers/zelos/info.js +++ b/core/renderers/zelos/info.js @@ -32,6 +32,8 @@ const {RenderInfo: BaseRenderInfo} = goog.require('Blockly.blockRendering.Render /* eslint-disable-next-line no-unused-vars */ const {Renderer} = goog.requireType('Blockly.zelos.Renderer'); const {RightConnectionShape} = goog.require('Blockly.zelos.RightConnectionShape'); +/* eslint-disable-next-line no-unused-vars */ +const {SpacerRow} = goog.requireType('Blockly.blockRendering.SpacerRow'); const {StatementInput} = goog.require('Blockly.zelos.StatementInput'); const {TopRow} = goog.require('Blockly.zelos.TopRow'); const {Types} = goog.require('Blockly.blockRendering.Types'); @@ -202,7 +204,8 @@ class RenderInfo extends BaseRenderInfo { } // Top and bottom rows act as a spacer so we don't need any extra padding. if (Types.isTopRow(prev)) { - if (!prev.hasPreviousConnection && + const topRow = /** @type {!TopRow} */ (prev); + if (!topRow.hasPreviousConnection && (!this.outputConnection || this.hasStatementInput)) { return Math.abs( this.constants_.NOTCH_HEIGHT - this.constants_.CORNER_RADIUS); @@ -210,6 +213,7 @@ class RenderInfo extends BaseRenderInfo { return this.constants_.NO_PADDING; } if (Types.isBottomRow(next)) { + const bottomRow = /** @type {!BottomRow} */ (next); if (!this.outputConnection) { const topHeight = Math.max( this.topRow.minHeight, @@ -218,7 +222,7 @@ class RenderInfo extends BaseRenderInfo { this.constants_.CORNER_RADIUS)) - this.constants_.CORNER_RADIUS; return topHeight; - } else if (!next.hasNextConnection && this.hasStatementInput) { + } else if (!bottomRow.hasNextConnection && this.hasStatementInput) { return Math.abs( this.constants_.NOTCH_HEIGHT - this.constants_.CORNER_RADIUS); } @@ -319,9 +323,9 @@ class RenderInfo extends BaseRenderInfo { // first input row (if the block has prev connection) and every input row // that has a prev and next notch. for (let i = 2; i < this.rows.length - 1; i += 2) { - const prevSpacer = this.rows[i - 1]; + const prevSpacer = /** @type {!SpacerRow} */ (this.rows[i - 1]); const row = this.rows[i]; - const nextSpacer = this.rows[i + 1]; + const nextSpacer = /** @type {!SpacerRow} */ (this.rows[i + 1]); const hasPrevNotch = i === 2 ? !!this.topRow.hasPreviousConnection : !!prevSpacer.followsStatement; @@ -536,9 +540,9 @@ class RenderInfo extends BaseRenderInfo { // Run through every input row on the block and only apply tight nesting // logic to input rows that have a prev and next notch. for (let i = 2; i < this.rows.length - 1; i += 2) { - const prevSpacer = this.rows[i - 1]; + const prevSpacer = /** @type {!SpacerRow} */ (this.rows[i - 1]); const row = this.rows[i]; - const nextSpacer = this.rows[i + 1]; + const nextSpacer = /** @type {!SpacerRow} */ (this.rows[i + 1]); const firstRow = i === 2; const hasPrevNotch = firstRow ? !!this.topRow.hasPreviousConnection : diff --git a/tests/deps.js b/tests/deps.js index 6c66f8850..c95ad8347 100644 --- a/tests/deps.js +++ b/tests/deps.js @@ -161,26 +161,26 @@ goog.addDependency('../../core/renderers/geras/measurables/statement_input.js', goog.addDependency('../../core/renderers/geras/path_object.js', ['Blockly.geras.PathObject'], ['Blockly.blockRendering.PathObject', 'Blockly.utils.Svg', 'Blockly.utils.colour', 'Blockly.utils.dom', 'Blockly.utils.object'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/renderers/geras/renderer.js', ['Blockly.geras.Renderer'], ['Blockly.blockRendering', 'Blockly.blockRendering.Renderer', 'Blockly.geras.ConstantProvider', 'Blockly.geras.Drawer', 'Blockly.geras.HighlightConstantProvider', 'Blockly.geras.PathObject', 'Blockly.geras.RenderInfo'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/renderers/measurables/base.js', ['Blockly.blockRendering.Measurable'], ['Blockly.blockRendering.Types'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/renderers/measurables/bottom_row.js', ['Blockly.blockRendering.BottomRow'], ['Blockly.blockRendering.Row', 'Blockly.blockRendering.Types', 'Blockly.utils.object'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/renderers/measurables/connection.js', ['Blockly.blockRendering.Connection'], ['Blockly.blockRendering.Measurable', 'Blockly.blockRendering.Types', 'Blockly.utils.object'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/renderers/measurables/external_value_input.js', ['Blockly.blockRendering.ExternalValueInput'], ['Blockly.blockRendering.InputConnection', 'Blockly.blockRendering.Types', 'Blockly.utils.object'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/renderers/measurables/field.js', ['Blockly.blockRendering.Field'], ['Blockly.blockRendering.Measurable', 'Blockly.blockRendering.Types', 'Blockly.utils.object'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/renderers/measurables/hat.js', ['Blockly.blockRendering.Hat'], ['Blockly.blockRendering.Measurable', 'Blockly.blockRendering.Types', 'Blockly.utils.object'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/renderers/measurables/icon.js', ['Blockly.blockRendering.Icon'], ['Blockly.blockRendering.Measurable', 'Blockly.blockRendering.Types', 'Blockly.utils.object'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/renderers/measurables/in_row_spacer.js', ['Blockly.blockRendering.InRowSpacer'], ['Blockly.blockRendering.Measurable', 'Blockly.blockRendering.Types', 'Blockly.utils.object'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/renderers/measurables/inline_input.js', ['Blockly.blockRendering.InlineInput'], ['Blockly.blockRendering.InputConnection', 'Blockly.blockRendering.Types', 'Blockly.utils.object'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/renderers/measurables/input_connection.js', ['Blockly.blockRendering.InputConnection'], ['Blockly.blockRendering.Connection', 'Blockly.blockRendering.Types', 'Blockly.utils.object'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/renderers/measurables/input_row.js', ['Blockly.blockRendering.InputRow'], ['Blockly.blockRendering.Row', 'Blockly.blockRendering.Types', 'Blockly.utils.object'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/renderers/measurables/jagged_edge.js', ['Blockly.blockRendering.JaggedEdge'], ['Blockly.blockRendering.Measurable', 'Blockly.blockRendering.Types', 'Blockly.utils.object'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/renderers/measurables/next_connection.js', ['Blockly.blockRendering.NextConnection'], ['Blockly.blockRendering.Connection', 'Blockly.blockRendering.Types', 'Blockly.utils.object'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/renderers/measurables/output_connection.js', ['Blockly.blockRendering.OutputConnection'], ['Blockly.blockRendering.Connection', 'Blockly.blockRendering.Types', 'Blockly.utils.object'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/renderers/measurables/previous_connection.js', ['Blockly.blockRendering.PreviousConnection'], ['Blockly.blockRendering.Connection', 'Blockly.blockRendering.Types', 'Blockly.utils.object'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/renderers/measurables/round_corner.js', ['Blockly.blockRendering.RoundCorner'], ['Blockly.blockRendering.Measurable', 'Blockly.blockRendering.Types', 'Blockly.utils.object'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/renderers/measurables/bottom_row.js', ['Blockly.blockRendering.BottomRow'], ['Blockly.blockRendering.Row', 'Blockly.blockRendering.Types'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/renderers/measurables/connection.js', ['Blockly.blockRendering.Connection'], ['Blockly.blockRendering.Measurable', 'Blockly.blockRendering.Types'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/renderers/measurables/external_value_input.js', ['Blockly.blockRendering.ExternalValueInput'], ['Blockly.blockRendering.InputConnection', 'Blockly.blockRendering.Types'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/renderers/measurables/field.js', ['Blockly.blockRendering.Field'], ['Blockly.blockRendering.Measurable', 'Blockly.blockRendering.Types'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/renderers/measurables/hat.js', ['Blockly.blockRendering.Hat'], ['Blockly.blockRendering.Measurable', 'Blockly.blockRendering.Types'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/renderers/measurables/icon.js', ['Blockly.blockRendering.Icon'], ['Blockly.blockRendering.Measurable', 'Blockly.blockRendering.Types'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/renderers/measurables/in_row_spacer.js', ['Blockly.blockRendering.InRowSpacer'], ['Blockly.blockRendering.Measurable', 'Blockly.blockRendering.Types'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/renderers/measurables/inline_input.js', ['Blockly.blockRendering.InlineInput'], ['Blockly.blockRendering.InputConnection', 'Blockly.blockRendering.Types'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/renderers/measurables/input_connection.js', ['Blockly.blockRendering.InputConnection'], ['Blockly.blockRendering.Connection', 'Blockly.blockRendering.Types'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/renderers/measurables/input_row.js', ['Blockly.blockRendering.InputRow'], ['Blockly.blockRendering.Row', 'Blockly.blockRendering.Types'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/renderers/measurables/jagged_edge.js', ['Blockly.blockRendering.JaggedEdge'], ['Blockly.blockRendering.Measurable', 'Blockly.blockRendering.Types'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/renderers/measurables/next_connection.js', ['Blockly.blockRendering.NextConnection'], ['Blockly.blockRendering.Connection', 'Blockly.blockRendering.Types'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/renderers/measurables/output_connection.js', ['Blockly.blockRendering.OutputConnection'], ['Blockly.blockRendering.Connection', 'Blockly.blockRendering.Types'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/renderers/measurables/previous_connection.js', ['Blockly.blockRendering.PreviousConnection'], ['Blockly.blockRendering.Connection', 'Blockly.blockRendering.Types'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/renderers/measurables/round_corner.js', ['Blockly.blockRendering.RoundCorner'], ['Blockly.blockRendering.Measurable', 'Blockly.blockRendering.Types'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/renderers/measurables/row.js', ['Blockly.blockRendering.Row'], ['Blockly.blockRendering.Types'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/renderers/measurables/spacer_row.js', ['Blockly.blockRendering.SpacerRow'], ['Blockly.blockRendering.InRowSpacer', 'Blockly.blockRendering.Row', 'Blockly.blockRendering.Types', 'Blockly.utils.object'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/renderers/measurables/square_corner.js', ['Blockly.blockRendering.SquareCorner'], ['Blockly.blockRendering.Measurable', 'Blockly.blockRendering.Types', 'Blockly.utils.object'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/renderers/measurables/statement_input.js', ['Blockly.blockRendering.StatementInput'], ['Blockly.blockRendering.InputConnection', 'Blockly.blockRendering.Types', 'Blockly.utils.object'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/renderers/measurables/top_row.js', ['Blockly.blockRendering.TopRow'], ['Blockly.blockRendering.Row', 'Blockly.blockRendering.Types', 'Blockly.utils.object'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/renderers/measurables/spacer_row.js', ['Blockly.blockRendering.SpacerRow'], ['Blockly.blockRendering.InRowSpacer', 'Blockly.blockRendering.Row', 'Blockly.blockRendering.Types'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/renderers/measurables/square_corner.js', ['Blockly.blockRendering.SquareCorner'], ['Blockly.blockRendering.Measurable', 'Blockly.blockRendering.Types'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/renderers/measurables/statement_input.js', ['Blockly.blockRendering.StatementInput'], ['Blockly.blockRendering.InputConnection', 'Blockly.blockRendering.Types'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/renderers/measurables/top_row.js', ['Blockly.blockRendering.TopRow'], ['Blockly.blockRendering.Row', 'Blockly.blockRendering.Types'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/renderers/measurables/types.js', ['Blockly.blockRendering.Types'], [], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/renderers/minimalist/constants.js', ['Blockly.minimalist.ConstantProvider'], ['Blockly.blockRendering.ConstantProvider'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/renderers/minimalist/drawer.js', ['Blockly.minimalist.Drawer'], ['Blockly.blockRendering.Drawer'], {'lang': 'es6', 'module': 'goog'}); @@ -191,7 +191,7 @@ goog.addDependency('../../core/renderers/thrasos/info.js', ['Blockly.thrasos.Ren goog.addDependency('../../core/renderers/thrasos/renderer.js', ['Blockly.thrasos.Renderer'], ['Blockly.blockRendering', 'Blockly.blockRendering.Renderer', 'Blockly.thrasos.RenderInfo'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/renderers/thrasos/thrasos.js', ['Blockly.thrasos'], ['Blockly.thrasos.RenderInfo', 'Blockly.thrasos.Renderer'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/renderers/zelos/constants.js', ['Blockly.zelos.ConstantProvider'], ['Blockly.ConnectionType', 'Blockly.blockRendering.ConstantProvider', 'Blockly.utils.Svg', 'Blockly.utils.colour', 'Blockly.utils.dom', 'Blockly.utils.svgPaths'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/renderers/zelos/drawer.js', ['Blockly.zelos.Drawer'], ['Blockly.blockRendering.Drawer', 'Blockly.blockRendering.debug', 'Blockly.utils.svgPaths'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/renderers/zelos/drawer.js', ['Blockly.zelos.Drawer'], ['Blockly.blockRendering.Drawer', 'Blockly.blockRendering.Types', 'Blockly.blockRendering.debug', 'Blockly.utils.svgPaths'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/renderers/zelos/info.js', ['Blockly.zelos.RenderInfo'], ['Blockly.FieldImage', 'Blockly.FieldLabel', 'Blockly.FieldTextInput', 'Blockly.Input', 'Blockly.blockRendering.InRowSpacer', 'Blockly.blockRendering.RenderInfo', 'Blockly.blockRendering.Types', 'Blockly.inputTypes', 'Blockly.zelos.BottomRow', 'Blockly.zelos.RightConnectionShape', 'Blockly.zelos.StatementInput', 'Blockly.zelos.TopRow'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/renderers/zelos/marker_svg.js', ['Blockly.zelos.MarkerSvg'], ['Blockly.blockRendering.MarkerSvg', 'Blockly.utils.Svg', 'Blockly.utils.dom'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/renderers/zelos/measurables/bottom_row.js', ['Blockly.zelos.BottomRow'], ['Blockly.blockRendering.BottomRow'], {'lang': 'es6', 'module': 'goog'}); From 7bbea824a51f1721c1966be9430c42e570e50749 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 1 Feb 2022 17:37:13 -0800 Subject: [PATCH 057/128] chore(deps): bump mocha from 9.1.4 to 9.2.0 (#5910) Bumps [mocha](https://github.com/mochajs/mocha) from 9.1.4 to 9.2.0. - [Release notes](https://github.com/mochajs/mocha/releases) - [Changelog](https://github.com/mochajs/mocha/blob/master/CHANGELOG.md) - [Commits](https://github.com/mochajs/mocha/compare/v9.1.4...v9.2.0) --- updated-dependencies: - dependency-name: mocha dependency-type: direct:development update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- package-lock.json | 148 +++++++++++++--------------------------------- 1 file changed, 40 insertions(+), 108 deletions(-) diff --git a/package-lock.json b/package-lock.json index c8a4fd368..52a99be01 100644 --- a/package-lock.json +++ b/package-lock.json @@ -2256,10 +2256,16 @@ } }, "node_modules/chokidar": { - "version": "3.5.2", - "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.5.2.tgz", - "integrity": "sha512-ekGhOnNVPgT77r4K/U3GDhu+FQ2S8TnK/s2KbIGXi0SZWuwkZ2QNyfWdZW+TVfn84DpEP7rLeCt2UI6bJ8GwbQ==", + "version": "3.5.3", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.5.3.tgz", + "integrity": "sha512-Dr3sfKRP6oTcjf2JmUmFJfeVMvXBdegxB0iVQ5eb2V10uFJUCAS8OByZdVAyVb8xXNz3GjjTgj9kLWsZTqE6kw==", "dev": true, + "funding": [ + { + "type": "individual", + "url": "https://paulmillr.com/funding/" + } + ], "dependencies": { "anymatch": "~3.1.2", "braces": "~3.0.2", @@ -7910,32 +7916,32 @@ "dev": true }, "node_modules/mocha": { - "version": "9.1.4", - "resolved": "https://registry.npmjs.org/mocha/-/mocha-9.1.4.tgz", - "integrity": "sha512-+q2aV5VlJZuLgCWoBvGI5zEwPF9eEI0kr/sAA9Jm4xMND7RfIEyF8JE7C0JIg8WXRG+P1sdIAb5ccoHPlXLzcw==", + "version": "9.2.0", + "resolved": "https://registry.npmjs.org/mocha/-/mocha-9.2.0.tgz", + "integrity": "sha512-kNn7E8g2SzVcq0a77dkphPsDSN7P+iYkqE0ZsGCYWRsoiKjOt+NvXfaagik8vuDa6W5Zw3qxe8Jfpt5qKf+6/Q==", "dev": true, "dependencies": { "@ungap/promise-all-settled": "1.1.2", "ansi-colors": "4.1.1", "browser-stdout": "1.3.1", - "chokidar": "3.5.2", - "debug": "4.3.2", + "chokidar": "3.5.3", + "debug": "4.3.3", "diff": "5.0.0", "escape-string-regexp": "4.0.0", "find-up": "5.0.0", - "glob": "7.1.7", + "glob": "7.2.0", "growl": "1.10.5", "he": "1.2.0", "js-yaml": "4.1.0", "log-symbols": "4.1.0", "minimatch": "3.0.4", "ms": "2.1.3", - "nanoid": "3.1.25", + "nanoid": "3.2.0", "serialize-javascript": "6.0.0", "strip-json-comments": "3.1.1", "supports-color": "8.1.1", "which": "2.0.2", - "workerpool": "6.1.5", + "workerpool": "6.2.0", "yargs": "16.2.0", "yargs-parser": "20.2.4", "yargs-unparser": "2.0.0" @@ -7952,29 +7958,6 @@ "url": "https://opencollective.com/mochajs" } }, - "node_modules/mocha/node_modules/debug": { - "version": "4.3.2", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.2.tgz", - "integrity": "sha512-mOp8wKcvj7XxC78zLgw/ZA+6TSgkoE2C/ienthhRD298T7UNwAg9diBpLRxC0mOezLl4B0xV7M0cCO6P/O0Xhw==", - "dev": true, - "dependencies": { - "ms": "2.1.2" - }, - "engines": { - "node": ">=6.0" - }, - "peerDependenciesMeta": { - "supports-color": { - "optional": true - } - } - }, - "node_modules/mocha/node_modules/debug/node_modules/ms": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", - "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==", - "dev": true - }, "node_modules/mocha/node_modules/diff": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/diff/-/diff-5.0.0.tgz", @@ -7984,26 +7967,6 @@ "node": ">=0.3.1" } }, - "node_modules/mocha/node_modules/glob": { - "version": "7.1.7", - "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.7.tgz", - "integrity": "sha512-OvD9ENzPLbegENnYP5UUfJIirTg4+XwMWGaQfQTY0JenxNvvIKP3U3/tAQSPIu/lHxXYSZmpXlUHeqAIdKzBLQ==", - "dev": true, - "dependencies": { - "fs.realpath": "^1.0.0", - "inflight": "^1.0.4", - "inherits": "2", - "minimatch": "^3.0.4", - "once": "^1.3.0", - "path-is-absolute": "^1.0.0" - }, - "engines": { - "node": "*" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, "node_modules/mocha/node_modules/ms": { "version": "2.1.3", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", @@ -8097,9 +8060,9 @@ "optional": true }, "node_modules/nanoid": { - "version": "3.1.25", - "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.1.25.tgz", - "integrity": "sha512-rdwtIXaXCLFAQbnfqDRnI6jaRHp9fTcYBjtFKE8eezcZ7LuLjhUaQGNeMXf1HmRoCH32CLz6XwX0TtxEOS/A3Q==", + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.2.0.tgz", + "integrity": "sha512-fmsZYa9lpn69Ad5eDn7FMcnnSR+8R34W9qJEijxYhTbfOWzr22n1QxCMzXLK+ODyW2973V3Fux959iQoUxzUIA==", "dev": true, "bin": { "nanoid": "bin/nanoid.cjs" @@ -12097,9 +12060,9 @@ } }, "node_modules/workerpool": { - "version": "6.1.5", - "resolved": "https://registry.npmjs.org/workerpool/-/workerpool-6.1.5.tgz", - "integrity": "sha512-XdKkCK0Zqc6w3iTxLckiuJ81tiD/o5rBE/m+nXpRCB+/Sq4DqkfXZ/x0jW02DG1tGsfUGXbTJyZDP+eu67haSw==", + "version": "6.2.0", + "resolved": "https://registry.npmjs.org/workerpool/-/workerpool-6.2.0.tgz", + "integrity": "sha512-Rsk5qQHJ9eowMH28Jwhe8HEbmdYDX4lwoMWshiCXugjtHqMD9ZbiqSDLxcsfdqsETPzVUtX5s1Z5kStiIM6l4A==", "dev": true }, "node_modules/wrap-ansi": { @@ -14191,9 +14154,9 @@ "dev": true }, "chokidar": { - "version": "3.5.2", - "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.5.2.tgz", - "integrity": "sha512-ekGhOnNVPgT77r4K/U3GDhu+FQ2S8TnK/s2KbIGXi0SZWuwkZ2QNyfWdZW+TVfn84DpEP7rLeCt2UI6bJ8GwbQ==", + "version": "3.5.3", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.5.3.tgz", + "integrity": "sha512-Dr3sfKRP6oTcjf2JmUmFJfeVMvXBdegxB0iVQ5eb2V10uFJUCAS8OByZdVAyVb8xXNz3GjjTgj9kLWsZTqE6kw==", "dev": true, "requires": { "anymatch": "~3.1.2", @@ -18757,74 +18720,43 @@ "dev": true }, "mocha": { - "version": "9.1.4", - "resolved": "https://registry.npmjs.org/mocha/-/mocha-9.1.4.tgz", - "integrity": "sha512-+q2aV5VlJZuLgCWoBvGI5zEwPF9eEI0kr/sAA9Jm4xMND7RfIEyF8JE7C0JIg8WXRG+P1sdIAb5ccoHPlXLzcw==", + "version": "9.2.0", + "resolved": "https://registry.npmjs.org/mocha/-/mocha-9.2.0.tgz", + "integrity": "sha512-kNn7E8g2SzVcq0a77dkphPsDSN7P+iYkqE0ZsGCYWRsoiKjOt+NvXfaagik8vuDa6W5Zw3qxe8Jfpt5qKf+6/Q==", "dev": true, "requires": { "@ungap/promise-all-settled": "1.1.2", "ansi-colors": "4.1.1", "browser-stdout": "1.3.1", - "chokidar": "3.5.2", - "debug": "4.3.2", + "chokidar": "3.5.3", + "debug": "4.3.3", "diff": "5.0.0", "escape-string-regexp": "4.0.0", "find-up": "5.0.0", - "glob": "7.1.7", + "glob": "7.2.0", "growl": "1.10.5", "he": "1.2.0", "js-yaml": "4.1.0", "log-symbols": "4.1.0", "minimatch": "3.0.4", "ms": "2.1.3", - "nanoid": "3.1.25", + "nanoid": "3.2.0", "serialize-javascript": "6.0.0", "strip-json-comments": "3.1.1", "supports-color": "8.1.1", "which": "2.0.2", - "workerpool": "6.1.5", + "workerpool": "6.2.0", "yargs": "16.2.0", "yargs-parser": "20.2.4", "yargs-unparser": "2.0.0" }, "dependencies": { - "debug": { - "version": "4.3.2", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.2.tgz", - "integrity": "sha512-mOp8wKcvj7XxC78zLgw/ZA+6TSgkoE2C/ienthhRD298T7UNwAg9diBpLRxC0mOezLl4B0xV7M0cCO6P/O0Xhw==", - "dev": true, - "requires": { - "ms": "2.1.2" - }, - "dependencies": { - "ms": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", - "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==", - "dev": true - } - } - }, "diff": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/diff/-/diff-5.0.0.tgz", "integrity": "sha512-/VTCrvm5Z0JGty/BWHljh+BAiw3IK+2j87NGMu8Nwc/f48WoDAC395uomO9ZD117ZOBaHmkX1oyLvkVM/aIT3w==", "dev": true }, - "glob": { - "version": "7.1.7", - "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.7.tgz", - "integrity": "sha512-OvD9ENzPLbegENnYP5UUfJIirTg4+XwMWGaQfQTY0JenxNvvIKP3U3/tAQSPIu/lHxXYSZmpXlUHeqAIdKzBLQ==", - "dev": true, - "requires": { - "fs.realpath": "^1.0.0", - "inflight": "^1.0.4", - "inherits": "2", - "minimatch": "^3.0.4", - "once": "^1.3.0", - "path-is-absolute": "^1.0.0" - } - }, "ms": { "version": "2.1.3", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", @@ -18905,9 +18837,9 @@ "optional": true }, "nanoid": { - "version": "3.1.25", - "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.1.25.tgz", - "integrity": "sha512-rdwtIXaXCLFAQbnfqDRnI6jaRHp9fTcYBjtFKE8eezcZ7LuLjhUaQGNeMXf1HmRoCH32CLz6XwX0TtxEOS/A3Q==", + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.2.0.tgz", + "integrity": "sha512-fmsZYa9lpn69Ad5eDn7FMcnnSR+8R34W9qJEijxYhTbfOWzr22n1QxCMzXLK+ODyW2973V3Fux959iQoUxzUIA==", "dev": true }, "nanomatch": { @@ -22155,9 +22087,9 @@ "integrity": "sha512-Hz/mrNwitNRh/HUAtM/VT/5VH+ygD6DV7mYKZAtHOrbs8U7lvPS6xf7EJKMF0uW1KJCl0H701g3ZGus+muE5vQ==" }, "workerpool": { - "version": "6.1.5", - "resolved": "https://registry.npmjs.org/workerpool/-/workerpool-6.1.5.tgz", - "integrity": "sha512-XdKkCK0Zqc6w3iTxLckiuJ81tiD/o5rBE/m+nXpRCB+/Sq4DqkfXZ/x0jW02DG1tGsfUGXbTJyZDP+eu67haSw==", + "version": "6.2.0", + "resolved": "https://registry.npmjs.org/workerpool/-/workerpool-6.2.0.tgz", + "integrity": "sha512-Rsk5qQHJ9eowMH28Jwhe8HEbmdYDX4lwoMWshiCXugjtHqMD9ZbiqSDLxcsfdqsETPzVUtX5s1Z5kStiIM6l4A==", "dev": true }, "wrap-ansi": { From b26a3f894982f633ccd833baaa7b1ea95de0f05f Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 4 Feb 2022 15:58:50 +0000 Subject: [PATCH 058/128] chore(deps): bump @blockly/dev-tools from 3.0.3 to 3.0.5 (#5911) Bumps [@blockly/dev-tools](https://github.com/google/blockly-samples/tree/HEAD/plugins/dev-tools) from 3.0.3 to 3.0.5. - [Release notes](https://github.com/google/blockly-samples/releases) - [Commits](https://github.com/google/blockly-samples/commits/@blockly/dev-tools@3.0.5/plugins/dev-tools) --- updated-dependencies: - dependency-name: "@blockly/dev-tools" dependency-type: direct:development update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- package-lock.json | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/package-lock.json b/package-lock.json index 52a99be01..c9eea8891 100644 --- a/package-lock.json +++ b/package-lock.json @@ -165,12 +165,12 @@ } }, "node_modules/@blockly/dev-tools": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/@blockly/dev-tools/-/dev-tools-3.0.3.tgz", - "integrity": "sha512-eg3j1vWapDgmsQY1DbEzWHJoEE5sK4IGyTOd+YKNwumtTR/GqjlCzM6ajcBAuAYwL9pBqD6rb6al/MfuwlbTtg==", + "version": "3.0.5", + "resolved": "https://registry.npmjs.org/@blockly/dev-tools/-/dev-tools-3.0.5.tgz", + "integrity": "sha512-k+LPWMbDK8FZg4iEgfFAWzAsnCwCybSnVnFBBSSZvBX77xuPBoCKq/BiqS9TM1fJRROBkiHYJZwXVPNs3bWMLA==", "dev": true, "dependencies": { - "@blockly/block-test": "^2.0.1", + "@blockly/block-test": "^2.0.3", "@blockly/theme-dark": "^2.0.7", "@blockly/theme-deuteranopia": "^1.0.8", "@blockly/theme-highcontrast": "^1.0.8", @@ -12482,12 +12482,12 @@ "requires": {} }, "@blockly/dev-tools": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/@blockly/dev-tools/-/dev-tools-3.0.3.tgz", - "integrity": "sha512-eg3j1vWapDgmsQY1DbEzWHJoEE5sK4IGyTOd+YKNwumtTR/GqjlCzM6ajcBAuAYwL9pBqD6rb6al/MfuwlbTtg==", + "version": "3.0.5", + "resolved": "https://registry.npmjs.org/@blockly/dev-tools/-/dev-tools-3.0.5.tgz", + "integrity": "sha512-k+LPWMbDK8FZg4iEgfFAWzAsnCwCybSnVnFBBSSZvBX77xuPBoCKq/BiqS9TM1fJRROBkiHYJZwXVPNs3bWMLA==", "dev": true, "requires": { - "@blockly/block-test": "^2.0.1", + "@blockly/block-test": "^2.0.3", "@blockly/theme-dark": "^2.0.7", "@blockly/theme-deuteranopia": "^1.0.8", "@blockly/theme-highcontrast": "^1.0.8", From 4cf1a5c886e1a4a32a55534a103482184c0943e4 Mon Sep 17 00:00:00 2001 From: Rachel Fenichel Date: Fri, 4 Feb 2022 10:58:22 -0800 Subject: [PATCH 059/128] refactor: convert some files to es classes (#5913) * refactor: update workspace_comment and _svg to es classes * refactor: update classes that extend icon to es classes * refactor: update icon to es6 class * refactor: update connection classes to es6 classes and add casts as needed * refactor: update scrollbar to es6 class and add casts as needed * refactor: update workspace_svg to es6 class * refactor: update several files to es6 classes * refactor: update several files to es6 classes * refactor: update renderers/common/info.js to es6 class * refactor: update several files to es6 classes * chore: rebuild deps.js * chore: run format --- core/block_svg.js | 36 +- core/comment.js | 736 +-- core/connection.js | 1188 ++-- core/connection_checker.js | 508 +- core/connection_db.js | 505 +- core/field_label_serializable.js | 87 +- core/field_multilineinput.js | 739 +-- core/icon.js | 332 +- core/marker_manager.js | 318 +- core/mutator.js | 948 ++-- core/rendered_connection.js | 1008 ++-- core/renderers/common/constants.js | 2234 ++++---- core/renderers/common/debugger.js | 753 +-- core/renderers/common/drawer.js | 797 +-- core/renderers/common/info.js | 1319 ++--- core/renderers/common/marker_svg.js | 1217 ++-- core/renderers/geras/drawer.js | 5 + core/renderers/geras/info.js | 5 + .../geras/measurables/inline_input.js | 9 +- .../geras/measurables/statement_input.js | 9 +- core/renderers/zelos/drawer.js | 5 + core/renderers/zelos/info.js | 3 + core/renderers/zelos/marker_svg.js | 16 +- core/scrollbar.js | 1590 +++--- core/theme_manager.js | 310 +- core/toolbox/separator.js | 104 +- core/warning.js | 254 +- core/workspace_comment.js | 661 +-- core/workspace_comment_svg.js | 2013 +++---- core/workspace_svg.js | 5002 +++++++++-------- core/xml.js | 2 +- tests/deps.js | 16 +- 32 files changed, 11523 insertions(+), 11206 deletions(-) diff --git a/core/block_svg.js b/core/block_svg.js index 5fd46d8a7..832659136 100644 --- a/core/block_svg.js +++ b/core/block_svg.js @@ -1423,14 +1423,17 @@ BlockSvg.prototype.appendInput_ = function(type, name) { */ BlockSvg.prototype.setConnectionTracking = function(track) { if (this.previousConnection) { - this.previousConnection.setTracking(track); + /** @type {!RenderedConnection} */ (this.previousConnection) + .setTracking(track); } if (this.outputConnection) { - this.outputConnection.setTracking(track); + /** @type {!RenderedConnection} */ (this.outputConnection) + .setTracking(track); } if (this.nextConnection) { - this.nextConnection.setTracking(track); - const child = this.nextConnection.targetBlock(); + /** @type {!RenderedConnection} */ (this.nextConnection).setTracking(track); + const child = + /** @type {!RenderedConnection} */ (this.nextConnection).targetBlock(); if (child) { child.setConnectionTracking(track); } @@ -1444,7 +1447,8 @@ BlockSvg.prototype.setConnectionTracking = function(track) { } for (let i = 0; i < this.inputList.length; i++) { - const conn = this.inputList[i].connection; + const conn = + /** @type {!RenderedConnection} */ (this.inputList[i].connection); if (conn) { conn.setTracking(track); @@ -1547,23 +1551,26 @@ BlockSvg.prototype.bumpNeighbours = function() { // Loop through every connection on this block. const myConnections = this.getConnections_(false); for (let i = 0, connection; (connection = myConnections[i]); i++) { + const renderedConn = /** @type {!RenderedConnection} */ (connection); // Spider down from this block bumping all sub-blocks. - if (connection.isConnected() && connection.isSuperior()) { - connection.targetBlock().bumpNeighbours(); + if (renderedConn.isConnected() && renderedConn.isSuperior()) { + renderedConn.targetBlock().bumpNeighbours(); } - const neighbours = connection.neighbours(internalConstants.SNAP_RADIUS); + const neighbours = renderedConn.neighbours(internalConstants.SNAP_RADIUS); for (let j = 0, otherConnection; (otherConnection = neighbours[j]); j++) { + const renderedOther = + /** @type {!RenderedConnection} */ (otherConnection); // If both connections are connected, that's probably fine. But if // either one of them is unconnected, then there could be confusion. - if (!connection.isConnected() || !otherConnection.isConnected()) { + if (!renderedConn.isConnected() || !renderedOther.isConnected()) { // Only bump blocks if they are from different tree structures. - if (otherConnection.getSourceBlock().getRootBlock() !== rootBlock) { + if (renderedOther.getSourceBlock().getRootBlock() !== rootBlock) { // Always bump the inferior block. - if (connection.isSuperior()) { - otherConnection.bumpAwayFrom(connection); + if (renderedConn.isSuperior()) { + renderedOther.bumpAwayFrom(renderedConn); } else { - connection.bumpAwayFrom(otherConnection); + renderedConn.bumpAwayFrom(renderedOther); } } } @@ -1706,7 +1713,8 @@ BlockSvg.prototype.updateConnectionLocations_ = function() { } for (let i = 0; i < this.inputList.length; i++) { - const conn = this.inputList[i].connection; + const conn = + /** @type {!RenderedConnection} */ (this.inputList[i].connection); if (conn) { conn.moveToOffset(blockTL); if (conn.isConnected()) { diff --git a/core/comment.js b/core/comment.js index d11e2b636..8f1efbe93 100644 --- a/core/comment.js +++ b/core/comment.js @@ -19,7 +19,6 @@ const Css = goog.require('Blockly.Css'); const browserEvents = goog.require('Blockly.browserEvents'); const dom = goog.require('Blockly.utils.dom'); const eventUtils = goog.require('Blockly.Events.utils'); -const object = goog.require('Blockly.utils.object'); const userAgent = goog.require('Blockly.utils.userAgent'); /* eslint-disable-next-line no-unused-vars */ const {BlockSvg} = goog.requireType('Blockly.BlockSvg'); @@ -44,391 +43,392 @@ goog.require('Blockly.Warning'); /** * Class for a comment. - * @param {!Block} block The block associated with this comment. * @extends {Icon} - * @constructor - * @alias Blockly.Comment */ -const Comment = function(block) { - Comment.superClass_.constructor.call(this, block); - +class Comment extends Icon { /** - * The model for this comment. - * @type {!Block.CommentModel} - * @private + * @param {!BlockSvg} block The block associated with this comment. + * @alias Blockly.Comment */ - this.model_ = block.commentModel; - // If someone creates the comment directly instead of calling - // block.setCommentText we want to make sure the text is non-null; - this.model_.text = this.model_.text || ''; + constructor(block) { + super(block); - /** - * The model's text value at the start of an edit. - * Used to tell if an event should be fired at the end of an edit. - * @type {?string} - * @private - */ - this.cachedText_ = ''; + /** + * The model for this comment. + * @type {!Block.CommentModel} + * @private + */ + this.model_ = block.commentModel; + // If someone creates the comment directly instead of calling + // block.setCommentText we want to make sure the text is non-null; + this.model_.text = this.model_.text || ''; - /** - * Mouse up event data. - * @type {?browserEvents.Data} - * @private - */ - this.onMouseUpWrapper_ = null; + /** + * The model's text value at the start of an edit. + * Used to tell if an event should be fired at the end of an edit. + * @type {?string} + * @private + */ + this.cachedText_ = ''; - /** - * Wheel event data. - * @type {?browserEvents.Data} - * @private - */ - this.onWheelWrapper_ = null; - - /** - * Change event data. - * @type {?browserEvents.Data} - * @private - */ - this.onChangeWrapper_ = null; - - /** - * Input event data. - * @type {?browserEvents.Data} - * @private - */ - this.onInputWrapper_ = null; - - /** - * The SVG element that contains the text edit area, or null if not created. - * @type {?SVGForeignObjectElement} - * @private - */ - this.foreignObject_ = null; - - /** - * The editable text area, or null if not created. - * @type {?Element} - * @private - */ - this.textarea_ = null; - - /** - * The top-level node of the comment text, or null if not created. - * @type {?SVGTextElement} - * @private - */ - this.paragraphElement_ = null; - - - this.createIcon(); -}; -object.inherits(Comment, Icon); - -/** - * Draw the comment icon. - * @param {!Element} group The icon group. - * @protected - */ -Comment.prototype.drawIcon_ = function(group) { - // Circle. - dom.createSvgElement( - Svg.CIRCLE, {'class': 'blocklyIconShape', 'r': '8', 'cx': '8', 'cy': '8'}, - group); - // Can't use a real '?' text character since different browsers and operating - // systems render it differently. - // Body of question mark. - dom.createSvgElement( - Svg.PATH, { - 'class': 'blocklyIconSymbol', - 'd': 'm6.8,10h2c0.003,-0.617 0.271,-0.962 0.633,-1.266 2.875,-2.405' + - '0.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', - }, - group); - // Dot of question mark. - dom.createSvgElement( - Svg.RECT, { - 'class': 'blocklyIconSymbol', - 'x': '6.8', - 'y': '10.78', - 'height': '2', - 'width': '2', - }, - group); -}; - -/** - * Create the editor for the comment's bubble. - * @return {!SVGElement} The top-level node of the editor. - * @private - */ -Comment.prototype.createEditor_ = function() { - /* Create the editor. Here's the markup that will be generated in - * editable mode: - - - - - - * For non-editable mode see Warning.textToDom_. - */ - - this.foreignObject_ = dom.createSvgElement( - Svg.FOREIGNOBJECT, {'x': Bubble.BORDER_WIDTH, 'y': Bubble.BORDER_WIDTH}, - null); - - const body = document.createElementNS(dom.HTML_NS, 'body'); - body.setAttribute('xmlns', dom.HTML_NS); - body.className = 'blocklyMinimalBody'; - - this.textarea_ = document.createElementNS(dom.HTML_NS, 'textarea'); - const textarea = this.textarea_; - textarea.className = 'blocklyCommentTextarea'; - textarea.setAttribute('dir', this.block_.RTL ? 'RTL' : 'LTR'); - textarea.value = this.model_.text; - this.resizeTextarea_(); - - body.appendChild(textarea); - this.foreignObject_.appendChild(body); - - // Ideally this would be hooked to the focus event for the comment. - // However doing so in Firefox swallows the cursor for unknown reasons. - // So this is hooked to mouseup instead. No big deal. - this.onMouseUpWrapper_ = browserEvents.conditionalBind( - textarea, 'mouseup', this, this.startEdit_, true, true); - // Don't zoom with mousewheel. - this.onWheelWrapper_ = - browserEvents.conditionalBind(textarea, 'wheel', this, function(e) { - e.stopPropagation(); - }); - this.onChangeWrapper_ = browserEvents.conditionalBind( - textarea, 'change', this, - /** - * @this {Comment} - * @param {Event} _e Unused event parameter. - */ - function(_e) { - if (this.cachedText_ !== this.model_.text) { - eventUtils.fire(new (eventUtils.get(eventUtils.BLOCK_CHANGE))( - this.block_, 'comment', null, this.cachedText_, - this.model_.text)); - } - }); - this.onInputWrapper_ = browserEvents.conditionalBind( - textarea, 'input', this, - /** - * @this {Comment} - * @param {Event} _e Unused event parameter. - */ - function(_e) { - this.model_.text = textarea.value; - }); - - setTimeout(textarea.focus.bind(textarea), 0); - - return this.foreignObject_; -}; - -/** - * Add or remove editability of the comment. - * @override - */ -Comment.prototype.updateEditable = function() { - Comment.superClass_.updateEditable.call(this); - if (this.isVisible()) { - // Recreate the bubble with the correct UI. - this.disposeBubble_(); - this.createBubble_(); - } -}; - -/** - * Callback function triggered when the bubble has resized. - * Resize the text area accordingly. - * @private - */ -Comment.prototype.onBubbleResize_ = function() { - if (!this.isVisible()) { - return; - } - this.model_.size = this.bubble_.getBubbleSize(); - this.resizeTextarea_(); -}; - -/** - * Resizes the text area to match the size defined on the model (which is - * the size of the bubble). - * @private - */ -Comment.prototype.resizeTextarea_ = function() { - const size = this.model_.size; - const doubleBorderWidth = 2 * Bubble.BORDER_WIDTH; - const widthMinusBorder = size.width - doubleBorderWidth; - const heightMinusBorder = size.height - doubleBorderWidth; - this.foreignObject_.setAttribute('width', widthMinusBorder); - this.foreignObject_.setAttribute('height', heightMinusBorder); - this.textarea_.style.width = (widthMinusBorder - 4) + 'px'; - this.textarea_.style.height = (heightMinusBorder - 4) + 'px'; -}; - -/** - * Show or hide the comment bubble. - * @param {boolean} visible True if the bubble should be visible. - */ -Comment.prototype.setVisible = function(visible) { - if (visible === this.isVisible()) { - return; - } - eventUtils.fire(new (eventUtils.get(eventUtils.BUBBLE_OPEN))( - this.block_, visible, 'comment')); - this.model_.pinned = visible; - if (visible) { - this.createBubble_(); - } else { - this.disposeBubble_(); - } -}; - -/** - * Show the bubble. Handles deciding if it should be editable or not. - * @private - */ -Comment.prototype.createBubble_ = function() { - if (!this.block_.isEditable() || userAgent.IE) { - // MSIE does not support foreignobject; textareas are impossible. - // https://docs.microsoft.com/en-us/openspecs/ie_standards/ms-svg/56e6e04c-7c8c-44dd-8100-bd745ee42034 - // Always treat comments in IE as uneditable. - this.createNonEditableBubble_(); - } else { - this.createEditableBubble_(); - } -}; - -/** - * Show an editable bubble. - * @private - */ -Comment.prototype.createEditableBubble_ = function() { - this.bubble_ = new Bubble( - /** @type {!WorkspaceSvg} */ (this.block_.workspace), - this.createEditor_(), this.block_.pathObject.svgPath, - /** @type {!Coordinate} */ (this.iconXY_), this.model_.size.width, - this.model_.size.height); - // Expose this comment's block's ID on its top-level SVG group. - this.bubble_.setSvgId(this.block_.id); - this.bubble_.registerResizeEvent(this.onBubbleResize_.bind(this)); - this.applyColour(); -}; - -/** - * Show a non-editable bubble. - * @private - * @suppress {checkTypes} Suppress `this` type mismatch. - */ -Comment.prototype.createNonEditableBubble_ = function() { - // TODO (#2917): It would be great if the comment could support line breaks. - this.paragraphElement_ = Bubble.textToDom(this.block_.getCommentText()); - this.bubble_ = Bubble.createNonEditableBubble( - this.paragraphElement_, /** @type {!BlockSvg} */ (this.block_), - /** @type {!Coordinate} */ (this.iconXY_)); - this.applyColour(); -}; - -/** - * Dispose of the bubble. - * @private - * @suppress {checkTypes} Suppress `this` type mismatch. - */ -Comment.prototype.disposeBubble_ = function() { - if (this.onMouseUpWrapper_) { - browserEvents.unbind(this.onMouseUpWrapper_); + /** + * Mouse up event data. + * @type {?browserEvents.Data} + * @private + */ this.onMouseUpWrapper_ = null; - } - if (this.onWheelWrapper_) { - browserEvents.unbind(this.onWheelWrapper_); + + /** + * Wheel event data. + * @type {?browserEvents.Data} + * @private + */ this.onWheelWrapper_ = null; - } - if (this.onChangeWrapper_) { - browserEvents.unbind(this.onChangeWrapper_); + + /** + * Change event data. + * @type {?browserEvents.Data} + * @private + */ this.onChangeWrapper_ = null; - } - if (this.onInputWrapper_) { - browserEvents.unbind(this.onInputWrapper_); + + /** + * Input event data. + * @type {?browserEvents.Data} + * @private + */ this.onInputWrapper_ = null; - } - this.bubble_.dispose(); - this.bubble_ = null; - this.textarea_ = null; - this.foreignObject_ = null; - this.paragraphElement_ = null; -}; -/** - * Callback fired when an edit starts. - * - * Bring the comment to the top of the stack when clicked on. Also cache the - * current text so it can be used to fire a change event. - * @param {!Event} _e Mouse up event. - * @private - */ -Comment.prototype.startEdit_ = function(_e) { - if (this.bubble_.promote()) { - // Since the act of moving this node within the DOM causes a loss of focus, - // we need to reapply the focus. - this.textarea_.focus(); + /** + * The SVG element that contains the text edit area, or null if not created. + * @type {?SVGForeignObjectElement} + * @private + */ + this.foreignObject_ = null; + + /** + * The editable text area, or null if not created. + * @type {?Element} + * @private + */ + this.textarea_ = null; + + /** + * The top-level node of the comment text, or null if not created. + * @type {?SVGTextElement} + * @private + */ + this.paragraphElement_ = null; + + + this.createIcon(); } - this.cachedText_ = this.model_.text; -}; - -/** - * Get the dimensions of this comment's bubble. - * @return {Size} Object with width and height properties. - */ -Comment.prototype.getBubbleSize = function() { - return this.model_.size; -}; - -/** - * Size this comment's bubble. - * @param {number} width Width of the bubble. - * @param {number} height Height of the bubble. - */ -Comment.prototype.setBubbleSize = function(width, height) { - if (this.bubble_) { - this.bubble_.setBubbleSize(width, height); - } else { - this.model_.size.width = width; - this.model_.size.height = height; + /** + * Draw the comment icon. + * @param {!Element} group The icon group. + * @protected + */ + drawIcon_(group) { + // Circle. + dom.createSvgElement( + Svg.CIRCLE, + {'class': 'blocklyIconShape', 'r': '8', 'cx': '8', 'cy': '8'}, group); + // Can't use a real '?' text character since different browsers and + // operating systems render it differently. Body of question mark. + dom.createSvgElement( + Svg.PATH, { + 'class': 'blocklyIconSymbol', + 'd': 'm6.8,10h2c0.003,-0.617 0.271,-0.962 0.633,-1.266 2.875,-2.405' + + '0.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', + }, + group); + // Dot of question mark. + dom.createSvgElement( + Svg.RECT, { + 'class': 'blocklyIconSymbol', + 'x': '6.8', + 'y': '10.78', + 'height': '2', + 'width': '2', + }, + group); } -}; -/** - * Update the comment's view to match the model. - * @package - */ -Comment.prototype.updateText = function() { - if (this.textarea_) { - this.textarea_.value = this.model_.text; - } else if (this.paragraphElement_) { - // Non-Editable mode. - // TODO (#2917): If 2917 gets added this will probably need to be updated. - this.paragraphElement_.firstChild.textContent = this.model_.text; + /** + * Create the editor for the comment's bubble. + * @return {!SVGElement} The top-level node of the editor. + * @private + */ + createEditor_() { + /* Create the editor. Here's the markup that will be generated in + * editable mode: + + + + + + * For non-editable mode see Warning.textToDom_. + */ + + this.foreignObject_ = dom.createSvgElement( + Svg.FOREIGNOBJECT, {'x': Bubble.BORDER_WIDTH, 'y': Bubble.BORDER_WIDTH}, + null); + + const body = document.createElementNS(dom.HTML_NS, 'body'); + body.setAttribute('xmlns', dom.HTML_NS); + body.className = 'blocklyMinimalBody'; + + this.textarea_ = document.createElementNS(dom.HTML_NS, 'textarea'); + const textarea = this.textarea_; + textarea.className = 'blocklyCommentTextarea'; + textarea.setAttribute('dir', this.block_.RTL ? 'RTL' : 'LTR'); + textarea.value = this.model_.text; + this.resizeTextarea_(); + + body.appendChild(textarea); + this.foreignObject_.appendChild(body); + + // Ideally this would be hooked to the focus event for the comment. + // However doing so in Firefox swallows the cursor for unknown reasons. + // So this is hooked to mouseup instead. No big deal. + this.onMouseUpWrapper_ = browserEvents.conditionalBind( + textarea, 'mouseup', this, this.startEdit_, true, true); + // Don't zoom with mousewheel. + this.onWheelWrapper_ = + browserEvents.conditionalBind(textarea, 'wheel', this, function(e) { + e.stopPropagation(); + }); + this.onChangeWrapper_ = browserEvents.conditionalBind( + textarea, 'change', this, + /** + * @this {Comment} + * @param {Event} _e Unused event parameter. + */ + function(_e) { + if (this.cachedText_ !== this.model_.text) { + eventUtils.fire(new (eventUtils.get(eventUtils.BLOCK_CHANGE))( + this.block_, 'comment', null, this.cachedText_, + this.model_.text)); + } + }); + this.onInputWrapper_ = browserEvents.conditionalBind( + textarea, 'input', this, + /** + * @this {Comment} + * @param {Event} _e Unused event parameter. + */ + function(_e) { + this.model_.text = textarea.value; + }); + + setTimeout(textarea.focus.bind(textarea), 0); + + return this.foreignObject_; } -}; -/** - * Dispose of this comment. - * - * If you want to receive a comment "delete" event (newValue: null), then this - * should not be called directly. Instead call block.setCommentText(null); - */ -Comment.prototype.dispose = function() { - this.block_.comment = null; - Icon.prototype.dispose.call(this); -}; + /** + * Add or remove editability of the comment. + * @override + */ + updateEditable() { + super.updateEditable(); + if (this.isVisible()) { + // Recreate the bubble with the correct UI. + this.disposeBubble_(); + this.createBubble_(); + } + } + + /** + * Callback function triggered when the bubble has resized. + * Resize the text area accordingly. + * @private + */ + onBubbleResize_() { + if (!this.isVisible()) { + return; + } + this.model_.size = this.bubble_.getBubbleSize(); + this.resizeTextarea_(); + } + + /** + * Resizes the text area to match the size defined on the model (which is + * the size of the bubble). + * @private + */ + resizeTextarea_() { + const size = this.model_.size; + const doubleBorderWidth = 2 * Bubble.BORDER_WIDTH; + const widthMinusBorder = size.width - doubleBorderWidth; + const heightMinusBorder = size.height - doubleBorderWidth; + this.foreignObject_.setAttribute('width', widthMinusBorder); + this.foreignObject_.setAttribute('height', heightMinusBorder); + this.textarea_.style.width = (widthMinusBorder - 4) + 'px'; + this.textarea_.style.height = (heightMinusBorder - 4) + 'px'; + } + + /** + * Show or hide the comment bubble. + * @param {boolean} visible True if the bubble should be visible. + */ + setVisible(visible) { + if (visible === this.isVisible()) { + return; + } + eventUtils.fire(new (eventUtils.get(eventUtils.BUBBLE_OPEN))( + this.block_, visible, 'comment')); + this.model_.pinned = visible; + if (visible) { + this.createBubble_(); + } else { + this.disposeBubble_(); + } + } + + /** + * Show the bubble. Handles deciding if it should be editable or not. + * @private + */ + createBubble_() { + if (!this.block_.isEditable() || userAgent.IE) { + // MSIE does not support foreignobject; textareas are impossible. + // https://docs.microsoft.com/en-us/openspecs/ie_standards/ms-svg/56e6e04c-7c8c-44dd-8100-bd745ee42034 + // Always treat comments in IE as uneditable. + this.createNonEditableBubble_(); + } else { + this.createEditableBubble_(); + } + } + + /** + * Show an editable bubble. + * @private + */ + createEditableBubble_() { + this.bubble_ = new Bubble( + /** @type {!WorkspaceSvg} */ (this.block_.workspace), + this.createEditor_(), this.block_.pathObject.svgPath, + /** @type {!Coordinate} */ (this.iconXY_), this.model_.size.width, + this.model_.size.height); + // Expose this comment's block's ID on its top-level SVG group. + this.bubble_.setSvgId(this.block_.id); + this.bubble_.registerResizeEvent(this.onBubbleResize_.bind(this)); + this.applyColour(); + } + + /** + * Show a non-editable bubble. + * @private + * @suppress {checkTypes} Suppress `this` type mismatch. + */ + createNonEditableBubble_() { + // TODO (#2917): It would be great if the comment could support line breaks. + this.paragraphElement_ = Bubble.textToDom(this.block_.getCommentText()); + this.bubble_ = Bubble.createNonEditableBubble( + this.paragraphElement_, /** @type {!BlockSvg} */ (this.block_), + /** @type {!Coordinate} */ (this.iconXY_)); + this.applyColour(); + } + + /** + * Dispose of the bubble. + * @private + * @suppress {checkTypes} Suppress `this` type mismatch. + */ + disposeBubble_() { + if (this.onMouseUpWrapper_) { + browserEvents.unbind(this.onMouseUpWrapper_); + this.onMouseUpWrapper_ = null; + } + if (this.onWheelWrapper_) { + browserEvents.unbind(this.onWheelWrapper_); + this.onWheelWrapper_ = null; + } + if (this.onChangeWrapper_) { + browserEvents.unbind(this.onChangeWrapper_); + this.onChangeWrapper_ = null; + } + if (this.onInputWrapper_) { + browserEvents.unbind(this.onInputWrapper_); + this.onInputWrapper_ = null; + } + this.bubble_.dispose(); + this.bubble_ = null; + this.textarea_ = null; + this.foreignObject_ = null; + this.paragraphElement_ = null; + } + + /** + * Callback fired when an edit starts. + * + * Bring the comment to the top of the stack when clicked on. Also cache the + * current text so it can be used to fire a change event. + * @param {!Event} _e Mouse up event. + * @private + */ + startEdit_(_e) { + if (this.bubble_.promote()) { + // Since the act of moving this node within the DOM causes a loss of + // focus, we need to reapply the focus. + this.textarea_.focus(); + } + + this.cachedText_ = this.model_.text; + } + + /** + * Get the dimensions of this comment's bubble. + * @return {Size} Object with width and height properties. + */ + getBubbleSize() { + return this.model_.size; + } + + /** + * Size this comment's bubble. + * @param {number} width Width of the bubble. + * @param {number} height Height of the bubble. + */ + setBubbleSize(width, height) { + if (this.bubble_) { + this.bubble_.setBubbleSize(width, height); + } else { + this.model_.size.width = width; + this.model_.size.height = height; + } + } + + /** + * Update the comment's view to match the model. + * @package + */ + updateText() { + if (this.textarea_) { + this.textarea_.value = this.model_.text; + } else if (this.paragraphElement_) { + // Non-Editable mode. + // TODO (#2917): If 2917 gets added this will probably need to be updated. + this.paragraphElement_.firstChild.textContent = this.model_.text; + } + } + + /** + * Dispose of this comment. + * + * If you want to receive a comment "delete" event (newValue: null), then this + * should not be called directly. Instead call block.setCommentText(null); + */ + dispose() { + this.block_.comment = null; + Icon.prototype.dispose.call(this); + } +} /** * CSS for block comment. See css.js for use. diff --git a/core/connection.js b/core/connection.js index 3273ab100..962b884ca 100644 --- a/core/connection.js +++ b/core/connection.js @@ -35,62 +35,627 @@ goog.require('Blockly.constants'); /** * Class for a connection between blocks. - * @param {!Block} source The block establishing this connection. - * @param {number} type The type of the connection. - * @constructor * @implements {IASTNodeLocationWithBlock} - * @alias Blockly.Connection */ -const Connection = function(source, type) { +class Connection { /** - * @type {!Block} + * @param {!Block} source The block establishing this connection. + * @param {number} type The type of the connection. + * @alias Blockly.Connection + */ + constructor(source, type) { + /** + * @type {!Block} + * @protected + */ + this.sourceBlock_ = source; + /** @type {number} */ + this.type = type; + + /** + * Connection this connection connects to. Null if not connected. + * @type {Connection} + */ + this.targetConnection = null; + + /** + * Has this connection been disposed of? + * @type {boolean} + * @package + */ + this.disposed = false; + + /** + * List of compatible value types. Null if all types are compatible. + * @type {Array} + * @private + */ + this.check_ = null; + + /** + * DOM representation of a shadow block, or null if none. + * @type {Element} + * @private + */ + this.shadowDom_ = null; + + /** + * Horizontal location of this connection. + * @type {number} + * @package + */ + this.x = 0; + + /** + * Vertical location of this connection. + * @type {number} + * @package + */ + this.y = 0; + + /** + * @type {?blocks.State} + * @private + */ + this.shadowState_ = null; + } + + /** + * Connect two connections together. This is the connection on the superior + * block. + * @param {!Connection} childConnection Connection on inferior block. * @protected */ - this.sourceBlock_ = source; - /** @type {number} */ - this.type = type; + connect_(childConnection) { + const INPUT = ConnectionType.INPUT_VALUE; + const parentConnection = this; + const parentBlock = parentConnection.getSourceBlock(); + const childBlock = childConnection.getSourceBlock(); + + // Make sure the childConnection is available. + if (childConnection.isConnected()) { + childConnection.disconnect(); + } + + // Make sure the parentConnection is available. + let orphan; + if (parentConnection.isConnected()) { + const shadowState = parentConnection.stashShadowState_(); + const target = parentConnection.targetBlock(); + if (target.isShadow()) { + target.dispose(false); + } else { + parentConnection.disconnect(); + orphan = target; + } + parentConnection.applyShadowState_(shadowState); + } + + // Connect the new connection to the parent. + let event; + if (eventUtils.isEnabled()) { + event = new (eventUtils.get(eventUtils.BLOCK_MOVE))(childBlock); + } + connectReciprocally(parentConnection, childConnection); + childBlock.setParent(parentBlock); + if (event) { + event.recordNew(); + eventUtils.fire(event); + } + + // Deal with the orphan if it exists. + if (orphan) { + const orphanConnection = parentConnection.type === INPUT ? + orphan.outputConnection : + orphan.previousConnection; + const connection = Connection.getConnectionForOrphanedConnection( + childBlock, /** @type {!Connection} */ (orphanConnection)); + if (connection) { + orphanConnection.connect(connection); + } else { + orphanConnection.onFailedConnect(parentConnection); + } + } + } /** - * Connection this connection connects to. Null if not connected. - * @type {Connection} - */ - this.targetConnection = null; - - /** - * Has this connection been disposed of? - * @type {boolean} + * Dispose of this connection and deal with connected blocks. * @package */ - this.disposed = false; + dispose() { + // isConnected returns true for shadows and non-shadows. + if (this.isConnected()) { + // Destroy the attached shadow block & its children (if it exists). + this.setShadowStateInternal_(); + + const targetBlock = this.targetBlock(); + if (targetBlock) { + // Disconnect the attached normal block. + targetBlock.unplug(); + } + } + + this.disposed = true; + } /** - * List of compatible value types. Null if all types are compatible. - * @type {Array} + * Get the source block for this connection. + * @return {!Block} The source block. + */ + getSourceBlock() { + return this.sourceBlock_; + } + + /** + * Does the connection belong to a superior block (higher in the source + * stack)? + * @return {boolean} True if connection faces down or right. + */ + isSuperior() { + return this.type === ConnectionType.INPUT_VALUE || + this.type === ConnectionType.NEXT_STATEMENT; + } + + /** + * Is the connection connected? + * @return {boolean} True if connection is connected to another connection. + */ + isConnected() { + return !!this.targetConnection; + } + + /** + * Get the workspace's connection type checker object. + * @return {!IConnectionChecker} The connection type checker for the + * source block's workspace. + * @package + */ + getConnectionChecker() { + return this.sourceBlock_.workspace.connectionChecker; + } + + /** + * Called when an attempted connection fails. NOP by default (i.e. for + * headless workspaces). + * @param {!Connection} _otherConnection Connection that this connection + * failed to connect to. + * @package + */ + onFailedConnect(_otherConnection) { + // NOP + } + + /** + * Connect this connection to another connection. + * @param {!Connection} otherConnection Connection to connect to. + * @return {boolean} Whether the the blocks are now connected or not. + */ + connect(otherConnection) { + if (this.targetConnection === otherConnection) { + // Already connected together. NOP. + return true; + } + + const checker = this.getConnectionChecker(); + if (checker.canConnect(this, otherConnection, false)) { + const eventGroup = eventUtils.getGroup(); + if (!eventGroup) { + eventUtils.setGroup(true); + } + // Determine which block is superior (higher in the source stack). + if (this.isSuperior()) { + // Superior block. + this.connect_(otherConnection); + } else { + // Inferior block. + otherConnection.connect_(this); + } + if (!eventGroup) { + eventUtils.setGroup(false); + } + } + + return this.isConnected(); + } + + /** + * Disconnect this connection. + */ + disconnect() { + const otherConnection = this.targetConnection; + if (!otherConnection) { + throw Error('Source connection not connected.'); + } + if (otherConnection.targetConnection !== this) { + throw Error('Target connection not connected to source connection.'); + } + let parentBlock; + let childBlock; + let parentConnection; + if (this.isSuperior()) { + // Superior block. + parentBlock = this.sourceBlock_; + childBlock = otherConnection.getSourceBlock(); + parentConnection = this; + } else { + // Inferior block. + parentBlock = otherConnection.getSourceBlock(); + childBlock = this.sourceBlock_; + parentConnection = otherConnection; + } + + const eventGroup = eventUtils.getGroup(); + if (!eventGroup) { + eventUtils.setGroup(true); + } + this.disconnectInternal_(parentBlock, childBlock); + if (!childBlock.isShadow()) { + // If we were disconnecting a shadow, no need to spawn a new one. + parentConnection.respawnShadow_(); + } + if (!eventGroup) { + eventUtils.setGroup(false); + } + } + + /** + * Disconnect two blocks that are connected by this connection. + * @param {!Block} parentBlock The superior block. + * @param {!Block} childBlock The inferior block. + * @protected + */ + disconnectInternal_(parentBlock, childBlock) { + let event; + if (eventUtils.isEnabled()) { + event = new (eventUtils.get(eventUtils.BLOCK_MOVE))(childBlock); + } + const otherConnection = this.targetConnection; + otherConnection.targetConnection = null; + this.targetConnection = null; + childBlock.setParent(null); + if (event) { + event.recordNew(); + eventUtils.fire(event); + } + } + + /** + * Respawn the shadow block if there was one connected to the this connection. + * @protected + */ + respawnShadow_() { + // Have to keep respawnShadow_ for backwards compatibility. + this.createShadowBlock_(true); + } + + /** + * Returns the block that this connection connects to. + * @return {?Block} The connected block or null if none is connected. + */ + targetBlock() { + if (this.isConnected()) { + return this.targetConnection.getSourceBlock(); + } + return null; + } + + /** + * Function to be called when this connection's compatible types have changed. + * @protected + */ + onCheckChanged_() { + // The new value type may not be compatible with the existing connection. + if (this.isConnected() && + (!this.targetConnection || + !this.getConnectionChecker().canConnect( + this, this.targetConnection, false))) { + const child = this.isSuperior() ? this.targetBlock() : this.sourceBlock_; + child.unplug(); + } + } + + /** + * Change a connection's compatibility. + * @param {?(string|!Array)} check Compatible value type or list of + * value types. Null if all types are compatible. + * @return {!Connection} The connection being modified + * (to allow chaining). + */ + setCheck(check) { + if (check) { + // Ensure that check is in an array. + if (!Array.isArray(check)) { + check = [check]; + } + this.check_ = check; + this.onCheckChanged_(); + } else { + this.check_ = null; + } + return this; + } + + /** + * Get a connection's compatibility. + * @return {?Array} List of compatible value types. + * Null if all types are compatible. + * @public + */ + getCheck() { + return this.check_; + } + + /** + * Changes the connection's shadow block. + * @param {?Element} shadowDom DOM representation of a block or null. + */ + setShadowDom(shadowDom) { + this.setShadowStateInternal_({shadowDom: shadowDom}); + } + + /** + * Returns the xml representation of the connection's shadow block. + * @param {boolean=} returnCurrent If true, and the shadow block is currently + * attached to this connection, this serializes the state of that block + * and returns it (so that field values are correct). Otherwise the saved + * shadowDom is just returned. + * @return {?Element} Shadow DOM representation of a block or null. + */ + getShadowDom(returnCurrent) { + return (returnCurrent && this.targetBlock().isShadow()) ? + /** @type {!Element} */ (Xml.blockToDom( + /** @type {!Block} */ (this.targetBlock()))) : + this.shadowDom_; + } + + /** + * Changes the connection's shadow block. + * @param {?blocks.State} shadowState An state represetation of the block or + * null. + */ + setShadowState(shadowState) { + this.setShadowStateInternal_({shadowState: shadowState}); + } + + /** + * Returns the serialized object representation of the connection's shadow + * block. + * @param {boolean=} returnCurrent If true, and the shadow block is currently + * attached to this connection, this serializes the state of that block + * and returns it (so that field values are correct). Otherwise the saved + * state is just returned. + * @return {?blocks.State} Serialized object representation of the block, or + * null. + */ + getShadowState(returnCurrent) { + if (returnCurrent && this.targetBlock() && this.targetBlock().isShadow()) { + return blocks.save(/** @type {!Block} */ (this.targetBlock())); + } + return this.shadowState_; + } + + /** + * Find all nearby compatible connections to this connection. + * Type checking does not apply, since this function is used for bumping. + * + * Headless configurations (the default) do not have neighboring connection, + * and always return an empty list (the default). + * {@link Blockly.RenderedConnection} overrides this behavior with a list + * computed from the rendered positioning. + * @param {number} _maxLimit The maximum radius to another connection. + * @return {!Array} List of connections. + * @package + */ + neighbours(_maxLimit) { + return []; + } + + /** + * Get the parent input of a connection. + * @return {?Input} The input that the connection belongs to or null if + * no parent exists. + * @package + */ + getParentInput() { + let parentInput = null; + const inputs = this.sourceBlock_.inputList; + for (let i = 0; i < inputs.length; i++) { + if (inputs[i].connection === this) { + parentInput = inputs[i]; + break; + } + } + return parentInput; + } + + /** + * This method returns a string describing this Connection in developer terms + * (English only). Intended to on be used in console logs and errors. + * @return {string} The description. + */ + toString() { + const block = this.sourceBlock_; + if (!block) { + return 'Orphan Connection'; + } + let msg; + if (block.outputConnection === this) { + msg = 'Output Connection of '; + } else if (block.previousConnection === this) { + msg = 'Previous Connection of '; + } else if (block.nextConnection === this) { + msg = 'Next Connection of '; + } else { + let parentInput = null; + for (let i = 0, input; (input = block.inputList[i]); i++) { + if (input.connection === this) { + parentInput = input; + break; + } + } + if (parentInput) { + msg = 'Input "' + parentInput.name + '" connection on '; + } else { + console.warn('Connection not actually connected to sourceBlock_'); + return 'Orphan Connection'; + } + } + return msg + block.toDevString(); + } + + /** + * Returns the state of the shadowDom_ and shadowState_ properties, then + * temporarily sets those properties to null so no shadow respawns. + * @return {{shadowDom: ?Element, shadowState: ?blocks.State}} The state of + * both the shadowDom_ and shadowState_ properties. * @private */ - this.check_ = null; + stashShadowState_() { + const shadowDom = this.getShadowDom(true); + const shadowState = this.getShadowState(true); + // Set to null so it doesn't respawn. + this.shadowDom_ = null; + this.shadowState_ = null; + return {shadowDom, shadowState}; + } /** - * DOM representation of a shadow block, or null if none. - * @type {Element} + * Reapplies the stashed state of the shadowDom_ and shadowState_ properties. + * @param {{shadowDom: ?Element, shadowState: ?blocks.State}} param0 The state + * to reapply to the shadowDom_ and shadowState_ properties. * @private */ - this.shadowDom_ = null; + applyShadowState_({shadowDom, shadowState}) { + this.shadowDom_ = shadowDom; + this.shadowState_ = shadowState; + } /** - * Horizontal location of this connection. - * @type {number} - * @package + * Sets the state of the shadow of this connection. + * @param {{shadowDom: (?Element|undefined), shadowState: + * (?blocks.State|undefined)}=} param0 The state to set the shadow of this + * connection to. + * @private */ - this.x = 0; + setShadowStateInternal_({shadowDom = null, shadowState = null} = {}) { + // One or both of these should always be null. + // If neither is null, the shadowState will get priority. + this.shadowDom_ = shadowDom; + this.shadowState_ = shadowState; + + const target = this.targetBlock(); + if (!target) { + this.respawnShadow_(); + if (this.targetBlock() && this.targetBlock().isShadow()) { + this.serializeShadow_(this.targetBlock()); + } + } else if (target.isShadow()) { + target.dispose(false); + this.respawnShadow_(); + if (this.targetBlock() && this.targetBlock().isShadow()) { + this.serializeShadow_(this.targetBlock()); + } + } else { + const shadow = this.createShadowBlock_(false); + this.serializeShadow_(shadow); + if (shadow) { + shadow.dispose(false); + } + } + } /** - * Vertical location of this connection. - * @type {number} - * @package + * Creates a shadow block based on the current shadowState_ or shadowDom_. + * shadowState_ gets priority. + * @param {boolean} attemptToConnect Whether to try to connect the shadow + * block to this connection or not. + * @return {?Block} The shadow block that was created, or null if both the + * shadowState_ and shadowDom_ are null. + * @private */ - this.y = 0; -}; + createShadowBlock_(attemptToConnect) { + const parentBlock = this.getSourceBlock(); + const shadowState = this.getShadowState(); + const shadowDom = this.getShadowDom(); + if (!parentBlock.workspace || (!shadowState && !shadowDom)) { + return null; + } + + let blockShadow; + if (shadowState) { + blockShadow = blocks.appendInternal(shadowState, parentBlock.workspace, { + parentConnection: attemptToConnect ? this : undefined, + isShadow: true, + recordUndo: false, + }); + return blockShadow; + } + + if (shadowDom) { + blockShadow = Xml.domToBlock(shadowDom, parentBlock.workspace); + if (attemptToConnect) { + if (this.type === ConnectionType.INPUT_VALUE) { + if (!blockShadow.outputConnection) { + throw new Error('Shadow block is missing an output connection'); + } + if (!this.connect(blockShadow.outputConnection)) { + throw new Error('Could not connect shadow block to connection'); + } + } else if (this.type === ConnectionType.NEXT_STATEMENT) { + if (!blockShadow.previousConnection) { + throw new Error('Shadow block is missing previous connection'); + } + if (!this.connect(blockShadow.previousConnection)) { + throw new Error('Could not connect shadow block to connection'); + } + } else { + throw new Error( + 'Cannot connect a shadow block to a previous/output connection'); + } + } + return blockShadow; + } + return null; + } + + /** + * Saves the given shadow block to both the shadowDom_ and shadowState_ + * properties, in their respective serialized forms. + * @param {?Block} shadow The shadow to serialize, or null. + * @private + */ + serializeShadow_(shadow) { + if (!shadow) { + return; + } + this.shadowDom_ = /** @type {!Element} */ (Xml.blockToDom(shadow)); + this.shadowState_ = blocks.save(shadow); + } + + /** + * Returns the connection (starting at the startBlock) which will accept + * the given connection. This includes compatible connection types and + * connection checks. + * @param {!Block} startBlock The block on which to start the search. + * @param {!Connection} orphanConnection The connection that is looking + * for a home. + * @return {?Connection} The suitable connection point on the chain of + * blocks, or null. + */ + static getConnectionForOrphanedConnection(startBlock, orphanConnection) { + if (orphanConnection.type === ConnectionType.OUTPUT_VALUE) { + return getConnectionForOrphanedOutput( + startBlock, orphanConnection.getSourceBlock()); + } + // Otherwise we're dealing with a stack. + const connection = startBlock.lastConnectionInStack(true); + const checker = orphanConnection.getConnectionChecker(); + if (connection && checker.canConnect(orphanConnection, connection, false)) { + return connection; + } + return null; + } +} /** * Constants for checking whether two connections are compatible. @@ -105,163 +670,6 @@ Connection.REASON_SHADOW_PARENT = 6; Connection.REASON_DRAG_CHECKS_FAILED = 7; Connection.REASON_PREVIOUS_AND_OUTPUT = 8; -/** - * Connect two connections together. This is the connection on the superior - * block. - * @param {!Connection} childConnection Connection on inferior block. - * @protected - */ -Connection.prototype.connect_ = function(childConnection) { - const INPUT = ConnectionType.INPUT_VALUE; - const parentConnection = this; - const parentBlock = parentConnection.getSourceBlock(); - const childBlock = childConnection.getSourceBlock(); - - // Make sure the childConnection is available. - if (childConnection.isConnected()) { - childConnection.disconnect(); - } - - // Make sure the parentConnection is available. - let orphan; - if (parentConnection.isConnected()) { - const shadowState = parentConnection.stashShadowState_(); - const target = parentConnection.targetBlock(); - if (target.isShadow()) { - target.dispose(false); - } else { - parentConnection.disconnect(); - orphan = target; - } - parentConnection.applyShadowState_(shadowState); - } - - // Connect the new connection to the parent. - let event; - if (eventUtils.isEnabled()) { - event = new (eventUtils.get(eventUtils.BLOCK_MOVE))(childBlock); - } - connectReciprocally(parentConnection, childConnection); - childBlock.setParent(parentBlock); - if (event) { - event.recordNew(); - eventUtils.fire(event); - } - - // Deal with the orphan if it exists. - if (orphan) { - const orphanConnection = parentConnection.type === INPUT ? - orphan.outputConnection : - orphan.previousConnection; - const connection = Connection.getConnectionForOrphanedConnection( - childBlock, /** @type {!Connection} */ (orphanConnection)); - if (connection) { - orphanConnection.connect(connection); - } else { - orphanConnection.onFailedConnect(parentConnection); - } - } -}; - -/** - * Dispose of this connection and deal with connected blocks. - * @package - */ -Connection.prototype.dispose = function() { - // isConnected returns true for shadows and non-shadows. - if (this.isConnected()) { - // Destroy the attached shadow block & its children (if it exists). - this.setShadowStateInternal_(); - - const targetBlock = this.targetBlock(); - if (targetBlock) { - // Disconnect the attached normal block. - targetBlock.unplug(); - } - } - - this.disposed = true; -}; - -/** - * Get the source block for this connection. - * @return {!Block} The source block. - */ -Connection.prototype.getSourceBlock = function() { - return this.sourceBlock_; -}; - -/** - * Does the connection belong to a superior block (higher in the source stack)? - * @return {boolean} True if connection faces down or right. - */ -Connection.prototype.isSuperior = function() { - return this.type === ConnectionType.INPUT_VALUE || - this.type === ConnectionType.NEXT_STATEMENT; -}; - -/** - * Is the connection connected? - * @return {boolean} True if connection is connected to another connection. - */ -Connection.prototype.isConnected = function() { - return !!this.targetConnection; -}; - -/** - * Get the workspace's connection type checker object. - * @return {!IConnectionChecker} The connection type checker for the - * source block's workspace. - * @package - */ -Connection.prototype.getConnectionChecker = function() { - return this.sourceBlock_.workspace.connectionChecker; -}; - -/** - * Called when an attempted connection fails. NOP by default (i.e. for headless - * workspaces). - * @param {!Connection} _otherConnection Connection that this connection - * failed to connect to. - * @package - */ -Connection.prototype.onFailedConnect = function(_otherConnection) { - // NOP -}; - -/** - * Connect this connection to another connection. - * @param {!Connection} otherConnection Connection to connect to. - * @return {boolean} Whether the the blocks are now connected or not. - */ -Connection.prototype.connect = function(otherConnection) { - if (this.targetConnection === otherConnection) { - // Already connected together. NOP. - return true; - } - - const checker = this.getConnectionChecker(); - if (checker.canConnect(this, otherConnection, false)) { - const eventGroup = eventUtils.getGroup(); - if (!eventGroup) { - eventUtils.setGroup(true); - } - // Determine which block is superior (higher in the source stack). - if (this.isSuperior()) { - // Superior block. - this.connect_(otherConnection); - } else { - // Inferior block. - otherConnection.connect_(this); - } - if (!eventGroup) { - eventUtils.setGroup(false); - } - } - - return this.isConnected(); -}; - /** * Update two connections to target each other. * @param {Connection} first The first connection to update. @@ -327,404 +735,4 @@ const getConnectionForOrphanedOutput = function(startBlock, orphanBlock) { return null; }; -/** - * Returns the connection (starting at the startBlock) which will accept - * the given connection. This includes compatible connection types and - * connection checks. - * @param {!Block} startBlock The block on which to start the search. - * @param {!Connection} orphanConnection The connection that is looking - * for a home. - * @return {?Connection} The suitable connection point on the chain of - * blocks, or null. - */ -Connection.getConnectionForOrphanedConnection = function( - startBlock, orphanConnection) { - if (orphanConnection.type === ConnectionType.OUTPUT_VALUE) { - return getConnectionForOrphanedOutput( - startBlock, orphanConnection.getSourceBlock()); - } - // Otherwise we're dealing with a stack. - const connection = startBlock.lastConnectionInStack(true); - const checker = orphanConnection.getConnectionChecker(); - if (connection && checker.canConnect(orphanConnection, connection, false)) { - return connection; - } - return null; -}; - -/** - * Disconnect this connection. - */ -Connection.prototype.disconnect = function() { - const otherConnection = this.targetConnection; - if (!otherConnection) { - throw Error('Source connection not connected.'); - } - if (otherConnection.targetConnection !== this) { - throw Error('Target connection not connected to source connection.'); - } - let parentBlock; - let childBlock; - let parentConnection; - if (this.isSuperior()) { - // Superior block. - parentBlock = this.sourceBlock_; - childBlock = otherConnection.getSourceBlock(); - parentConnection = this; - } else { - // Inferior block. - parentBlock = otherConnection.getSourceBlock(); - childBlock = this.sourceBlock_; - parentConnection = otherConnection; - } - - const eventGroup = eventUtils.getGroup(); - if (!eventGroup) { - eventUtils.setGroup(true); - } - this.disconnectInternal_(parentBlock, childBlock); - if (!childBlock.isShadow()) { - // If we were disconnecting a shadow, no need to spawn a new one. - parentConnection.respawnShadow_(); - } - if (!eventGroup) { - eventUtils.setGroup(false); - } -}; - -/** - * Disconnect two blocks that are connected by this connection. - * @param {!Block} parentBlock The superior block. - * @param {!Block} childBlock The inferior block. - * @protected - */ -Connection.prototype.disconnectInternal_ = function(parentBlock, childBlock) { - let event; - if (eventUtils.isEnabled()) { - event = new (eventUtils.get(eventUtils.BLOCK_MOVE))(childBlock); - } - const otherConnection = this.targetConnection; - otherConnection.targetConnection = null; - this.targetConnection = null; - childBlock.setParent(null); - if (event) { - event.recordNew(); - eventUtils.fire(event); - } -}; - -/** - * Respawn the shadow block if there was one connected to the this connection. - * @protected - */ -Connection.prototype.respawnShadow_ = function() { - // Have to keep respawnShadow_ for backwards compatibility. - this.createShadowBlock_(true); -}; - -/** - * Returns the block that this connection connects to. - * @return {?Block} The connected block or null if none is connected. - */ -Connection.prototype.targetBlock = function() { - if (this.isConnected()) { - return this.targetConnection.getSourceBlock(); - } - return null; -}; - -/** - * Function to be called when this connection's compatible types have changed. - * @protected - */ -Connection.prototype.onCheckChanged_ = function() { - // The new value type may not be compatible with the existing connection. - if (this.isConnected() && - (!this.targetConnection || - !this.getConnectionChecker().canConnect( - this, this.targetConnection, false))) { - const child = this.isSuperior() ? this.targetBlock() : this.sourceBlock_; - child.unplug(); - } -}; - -/** - * Change a connection's compatibility. - * @param {?(string|!Array)} check Compatible value type or list of - * value types. Null if all types are compatible. - * @return {!Connection} The connection being modified - * (to allow chaining). - */ -Connection.prototype.setCheck = function(check) { - if (check) { - // Ensure that check is in an array. - if (!Array.isArray(check)) { - check = [check]; - } - this.check_ = check; - this.onCheckChanged_(); - } else { - this.check_ = null; - } - return this; -}; - -/** - * Get a connection's compatibility. - * @return {?Array} List of compatible value types. - * Null if all types are compatible. - * @public - */ -Connection.prototype.getCheck = function() { - return this.check_; -}; - -/** - * Changes the connection's shadow block. - * @param {?Element} shadowDom DOM representation of a block or null. - */ -Connection.prototype.setShadowDom = function(shadowDom) { - this.setShadowStateInternal_({shadowDom: shadowDom}); -}; - -/** - * Returns the xml representation of the connection's shadow block. - * @param {boolean=} returnCurrent If true, and the shadow block is currently - * attached to this connection, this serializes the state of that block - * and returns it (so that field values are correct). Otherwise the saved - * shadowDom is just returned. - * @return {?Element} Shadow DOM representation of a block or null. - */ -Connection.prototype.getShadowDom = function(returnCurrent) { - return (returnCurrent && this.targetBlock().isShadow()) ? - /** @type {!Element} */ (Xml.blockToDom( - /** @type {!Block} */ (this.targetBlock()))) : - this.shadowDom_; -}; - -/** - * Changes the connection's shadow block. - * @param {?blocks.State} shadowState An state represetation of the block or - * null. - */ -Connection.prototype.setShadowState = function(shadowState) { - this.setShadowStateInternal_({shadowState: shadowState}); -}; - -/** - * Returns the serialized object representation of the connection's shadow - * block. - * @param {boolean=} returnCurrent If true, and the shadow block is currently - * attached to this connection, this serializes the state of that block - * and returns it (so that field values are correct). Otherwise the saved - * state is just returned. - * @return {?blocks.State} Serialized object representation of the block, or - * null. - */ -Connection.prototype.getShadowState = function(returnCurrent) { - if (returnCurrent && this.targetBlock() && this.targetBlock().isShadow()) { - return blocks.save(/** @type {!Block} */ (this.targetBlock())); - } - return this.shadowState_; -}; - -/** - * Find all nearby compatible connections to this connection. - * Type checking does not apply, since this function is used for bumping. - * - * Headless configurations (the default) do not have neighboring connection, - * and always return an empty list (the default). - * {@link Blockly.RenderedConnection} overrides this behavior with a list - * computed from the rendered positioning. - * @param {number} _maxLimit The maximum radius to another connection. - * @return {!Array} List of connections. - * @package - */ -Connection.prototype.neighbours = function(_maxLimit) { - return []; -}; - -/** - * Get the parent input of a connection. - * @return {?Input} The input that the connection belongs to or null if - * no parent exists. - * @package - */ -Connection.prototype.getParentInput = function() { - let parentInput = null; - const inputs = this.sourceBlock_.inputList; - for (let i = 0; i < inputs.length; i++) { - if (inputs[i].connection === this) { - parentInput = inputs[i]; - break; - } - } - return parentInput; -}; - -/** - * This method returns a string describing this Connection in developer terms - * (English only). Intended to on be used in console logs and errors. - * @return {string} The description. - */ -Connection.prototype.toString = function() { - const block = this.sourceBlock_; - if (!block) { - return 'Orphan Connection'; - } - let msg; - if (block.outputConnection === this) { - msg = 'Output Connection of '; - } else if (block.previousConnection === this) { - msg = 'Previous Connection of '; - } else if (block.nextConnection === this) { - msg = 'Next Connection of '; - } else { - let parentInput = null; - for (let i = 0, input; (input = block.inputList[i]); i++) { - if (input.connection === this) { - parentInput = input; - break; - } - } - if (parentInput) { - msg = 'Input "' + parentInput.name + '" connection on '; - } else { - console.warn('Connection not actually connected to sourceBlock_'); - return 'Orphan Connection'; - } - } - return msg + block.toDevString(); -}; - -/** - * Returns the state of the shadowDom_ and shadowState_ properties, then - * temporarily sets those properties to null so no shadow respawns. - * @return {{shadowDom: ?Element, shadowState: ?blocks.State}} The state of both - * the shadowDom_ and shadowState_ properties. - * @private - */ -Connection.prototype.stashShadowState_ = function() { - const shadowDom = this.getShadowDom(true); - const shadowState = this.getShadowState(true); - // Set to null so it doesn't respawn. - this.shadowDom_ = null; - this.shadowState_ = null; - return {shadowDom, shadowState}; -}; - -/** - * Reapplies the stashed state of the shadowDom_ and shadowState_ properties. - * @param {{shadowDom: ?Element, shadowState: ?blocks.State}} param0 The state - * to reapply to the shadowDom_ and shadowState_ properties. - * @private - */ -Connection.prototype.applyShadowState_ = function({shadowDom, shadowState}) { - this.shadowDom_ = shadowDom; - this.shadowState_ = shadowState; -}; - -/** - * Sets the state of the shadow of this connection. - * @param {{shadowDom: (?Element|undefined), shadowState: - * (?blocks.State|undefined)}=} param0 The state to set the shadow of this - * connection to. - * @private - */ -Connection.prototype.setShadowStateInternal_ = function( - {shadowDom = null, shadowState = null} = {}) { - // One or both of these should always be null. - // If neither is null, the shadowState will get priority. - this.shadowDom_ = shadowDom; - this.shadowState_ = shadowState; - - const target = this.targetBlock(); - if (!target) { - this.respawnShadow_(); - if (this.targetBlock() && this.targetBlock().isShadow()) { - this.serializeShadow_(this.targetBlock()); - } - } else if (target.isShadow()) { - target.dispose(false); - this.respawnShadow_(); - if (this.targetBlock() && this.targetBlock().isShadow()) { - this.serializeShadow_(this.targetBlock()); - } - } else { - const shadow = this.createShadowBlock_(false); - this.serializeShadow_(shadow); - if (shadow) { - shadow.dispose(false); - } - } -}; - -/** - * Creates a shadow block based on the current shadowState_ or shadowDom_. - * shadowState_ gets priority. - * @param {boolean} attemptToConnect Whether to try to connect the shadow block - * to this connection or not. - * @return {?Block} The shadow block that was created, or null if both the - * shadowState_ and shadowDom_ are null. - * @private - */ -Connection.prototype.createShadowBlock_ = function(attemptToConnect) { - const parentBlock = this.getSourceBlock(); - const shadowState = this.getShadowState(); - const shadowDom = this.getShadowDom(); - if (!parentBlock.workspace || (!shadowState && !shadowDom)) { - return null; - } - - let blockShadow; - if (shadowState) { - blockShadow = blocks.appendInternal(shadowState, parentBlock.workspace, { - parentConnection: attemptToConnect ? this : undefined, - isShadow: true, - recordUndo: false, - }); - return blockShadow; - } - - if (shadowDom) { - blockShadow = Xml.domToBlock(shadowDom, parentBlock.workspace); - if (attemptToConnect) { - if (this.type === ConnectionType.INPUT_VALUE) { - if (!blockShadow.outputConnection) { - throw new Error('Shadow block is missing an output connection'); - } - if (!this.connect(blockShadow.outputConnection)) { - throw new Error('Could not connect shadow block to connection'); - } - } else if (this.type === ConnectionType.NEXT_STATEMENT) { - if (!blockShadow.previousConnection) { - throw new Error('Shadow block is missing previous connection'); - } - if (!this.connect(blockShadow.previousConnection)) { - throw new Error('Could not connect shadow block to connection'); - } - } else { - throw new Error( - 'Cannot connect a shadow block to a previous/output connection'); - } - } - return blockShadow; - } - return null; -}; - -/** - * Saves the given shadow block to both the shadowDom_ and shadowState_ - * properties, in their respective serialized forms. - * @param {?Block} shadow The shadow to serialize, or null. - * @private - */ -Connection.prototype.serializeShadow_ = function(shadow) { - if (!shadow) { - return; - } - this.shadowDom_ = /** @type {!Element} */ (Xml.blockToDom(shadow)); - this.shadowState_ = blocks.save(shadow); -}; - exports.Connection = Connection; diff --git a/core/connection_checker.js b/core/connection_checker.js index d512488ef..5ad5e36f5 100644 --- a/core/connection_checker.js +++ b/core/connection_checker.js @@ -31,282 +31,284 @@ const {RenderedConnection} = goog.requireType('Blockly.RenderedConnection'); /** * Class for connection type checking logic. * @implements {IConnectionChecker} - * @constructor - * @alias Blockly.ConnectionChecker */ -const ConnectionChecker = function() {}; +class ConnectionChecker { + /** + * @alias Blockly.ConnectionChecker + */ + constructor() {} -/** - * Check whether the current connection can connect with the target - * connection. - * @param {Connection} a Connection to check compatibility with. - * @param {Connection} b Connection to check compatibility with. - * @param {boolean} isDragging True if the connection is being made by dragging - * a block. - * @param {number=} opt_distance The max allowable distance between the - * connections for drag checks. - * @return {boolean} Whether the connection is legal. - * @public - */ -ConnectionChecker.prototype.canConnect = function( - a, b, isDragging, opt_distance) { - return this.canConnectWithReason(a, b, isDragging, opt_distance) === - Connection.CAN_CONNECT; -}; - -/** - * Checks whether the current connection can connect with the target - * connection, and return an error code if there are problems. - * @param {Connection} a Connection to check compatibility with. - * @param {Connection} b Connection to check compatibility with. - * @param {boolean} isDragging True if the connection is being made by dragging - * a block. - * @param {number=} opt_distance The max allowable distance between the - * connections for drag checks. - * @return {number} Connection.CAN_CONNECT if the connection is legal, - * an error code otherwise. - * @public - */ -ConnectionChecker.prototype.canConnectWithReason = function( - a, b, isDragging, opt_distance) { - const safety = this.doSafetyChecks(a, b); - if (safety !== Connection.CAN_CONNECT) { - return safety; + /** + * Check whether the current connection can connect with the target + * connection. + * @param {Connection} a Connection to check compatibility with. + * @param {Connection} b Connection to check compatibility with. + * @param {boolean} isDragging True if the connection is being made by + * dragging a block. + * @param {number=} opt_distance The max allowable distance between the + * connections for drag checks. + * @return {boolean} Whether the connection is legal. + * @public + */ + canConnect(a, b, isDragging, opt_distance) { + return this.canConnectWithReason(a, b, isDragging, opt_distance) === + Connection.CAN_CONNECT; } - // If the safety checks passed, both connections are non-null. - const connOne = /** @type {!Connection} **/ (a); - const connTwo = /** @type {!Connection} **/ (b); - if (!this.doTypeChecks(connOne, connTwo)) { - return Connection.REASON_CHECKS_FAILED; - } - - if (isDragging && - !this.doDragChecks( - /** @type {!RenderedConnection} **/ (a), - /** @type {!RenderedConnection} **/ (b), opt_distance || 0)) { - return Connection.REASON_DRAG_CHECKS_FAILED; - } - - return Connection.CAN_CONNECT; -}; - -/** - * Helper method that translates a connection error code into a string. - * @param {number} errorCode The error code. - * @param {Connection} a One of the two connections being checked. - * @param {Connection} b The second of the two connections being - * checked. - * @return {string} A developer-readable error string. - * @public - */ -ConnectionChecker.prototype.getErrorMessage = function(errorCode, a, b) { - switch (errorCode) { - case Connection.REASON_SELF_CONNECTION: - return 'Attempted to connect a block to itself.'; - case Connection.REASON_DIFFERENT_WORKSPACES: - // Usually this means one block has been deleted. - return 'Blocks not on same workspace.'; - case Connection.REASON_WRONG_TYPE: - return 'Attempt to connect incompatible types.'; - case Connection.REASON_TARGET_NULL: - return 'Target connection is null.'; - case Connection.REASON_CHECKS_FAILED: { - const connOne = /** @type {!Connection} **/ (a); - const connTwo = /** @type {!Connection} **/ (b); - let msg = 'Connection checks failed. '; - msg += connOne + ' expected ' + connOne.getCheck() + ', found ' + - connTwo.getCheck(); - return msg; + /** + * Checks whether the current connection can connect with the target + * connection, and return an error code if there are problems. + * @param {Connection} a Connection to check compatibility with. + * @param {Connection} b Connection to check compatibility with. + * @param {boolean} isDragging True if the connection is being made by + * dragging a block. + * @param {number=} opt_distance The max allowable distance between the + * connections for drag checks. + * @return {number} Connection.CAN_CONNECT if the connection is legal, + * an error code otherwise. + * @public + */ + canConnectWithReason(a, b, isDragging, opt_distance) { + const safety = this.doSafetyChecks(a, b); + if (safety !== Connection.CAN_CONNECT) { + return safety; } - case Connection.REASON_SHADOW_PARENT: - return 'Connecting non-shadow to shadow block.'; - case Connection.REASON_DRAG_CHECKS_FAILED: - return 'Drag checks failed.'; - case Connection.REASON_PREVIOUS_AND_OUTPUT: - return 'Block would have an output and a previous connection.'; - default: - return 'Unknown connection failure: this should never happen!'; - } -}; -/** - * Check that connecting the given connections is safe, meaning that it would - * not break any of Blockly's basic assumptions (e.g. no self connections). - * @param {Connection} a The first of the connections to check. - * @param {Connection} b The second of the connections to check. - * @return {number} An enum with the reason this connection is safe or unsafe. - * @public - */ -ConnectionChecker.prototype.doSafetyChecks = function(a, b) { - if (!a || !b) { - return Connection.REASON_TARGET_NULL; - } - let superiorBlock; - let inferiorBlock; - let superiorConnection; - let inferiorConnection; - if (a.isSuperior()) { - superiorBlock = a.getSourceBlock(); - inferiorBlock = b.getSourceBlock(); - superiorConnection = a; - inferiorConnection = b; - } else { - inferiorBlock = a.getSourceBlock(); - superiorBlock = b.getSourceBlock(); - inferiorConnection = a; - superiorConnection = b; - } - if (superiorBlock === inferiorBlock) { - return Connection.REASON_SELF_CONNECTION; - } else if ( - inferiorConnection.type !== - internalConstants.OPPOSITE_TYPE[superiorConnection.type]) { - return Connection.REASON_WRONG_TYPE; - } else if (superiorBlock.workspace !== inferiorBlock.workspace) { - return Connection.REASON_DIFFERENT_WORKSPACES; - } else if (superiorBlock.isShadow() && !inferiorBlock.isShadow()) { - return Connection.REASON_SHADOW_PARENT; - } else if ( - inferiorConnection.type === ConnectionType.OUTPUT_VALUE && - inferiorBlock.previousConnection && - inferiorBlock.previousConnection.isConnected()) { - return Connection.REASON_PREVIOUS_AND_OUTPUT; - } else if ( - inferiorConnection.type === ConnectionType.PREVIOUS_STATEMENT && - inferiorBlock.outputConnection && - inferiorBlock.outputConnection.isConnected()) { - return Connection.REASON_PREVIOUS_AND_OUTPUT; - } - return Connection.CAN_CONNECT; -}; + // If the safety checks passed, both connections are non-null. + const connOne = /** @type {!Connection} **/ (a); + const connTwo = /** @type {!Connection} **/ (b); + if (!this.doTypeChecks(connOne, connTwo)) { + return Connection.REASON_CHECKS_FAILED; + } -/** - * Check whether this connection is compatible with another connection with - * respect to the value type system. E.g. square_root("Hello") is not - * compatible. - * @param {!Connection} a Connection to compare. - * @param {!Connection} b Connection to compare against. - * @return {boolean} True if the connections share a type. - * @public - */ -ConnectionChecker.prototype.doTypeChecks = function(a, b) { - const checkArrayOne = a.getCheck(); - const checkArrayTwo = b.getCheck(); + if (isDragging && + !this.doDragChecks( + /** @type {!RenderedConnection} **/ (a), + /** @type {!RenderedConnection} **/ (b), opt_distance || 0)) { + return Connection.REASON_DRAG_CHECKS_FAILED; + } - if (!checkArrayOne || !checkArrayTwo) { - // One or both sides are promiscuous enough that anything will fit. - return true; + return Connection.CAN_CONNECT; } - // Find any intersection in the check lists. - for (let i = 0; i < checkArrayOne.length; i++) { - if (checkArrayTwo.indexOf(checkArrayOne[i]) !== -1) { + + /** + * Helper method that translates a connection error code into a string. + * @param {number} errorCode The error code. + * @param {Connection} a One of the two connections being checked. + * @param {Connection} b The second of the two connections being + * checked. + * @return {string} A developer-readable error string. + * @public + */ + getErrorMessage(errorCode, a, b) { + switch (errorCode) { + case Connection.REASON_SELF_CONNECTION: + return 'Attempted to connect a block to itself.'; + case Connection.REASON_DIFFERENT_WORKSPACES: + // Usually this means one block has been deleted. + return 'Blocks not on same workspace.'; + case Connection.REASON_WRONG_TYPE: + return 'Attempt to connect incompatible types.'; + case Connection.REASON_TARGET_NULL: + return 'Target connection is null.'; + case Connection.REASON_CHECKS_FAILED: { + const connOne = /** @type {!Connection} **/ (a); + const connTwo = /** @type {!Connection} **/ (b); + let msg = 'Connection checks failed. '; + msg += connOne + ' expected ' + connOne.getCheck() + ', found ' + + connTwo.getCheck(); + return msg; + } + case Connection.REASON_SHADOW_PARENT: + return 'Connecting non-shadow to shadow block.'; + case Connection.REASON_DRAG_CHECKS_FAILED: + return 'Drag checks failed.'; + case Connection.REASON_PREVIOUS_AND_OUTPUT: + return 'Block would have an output and a previous connection.'; + default: + return 'Unknown connection failure: this should never happen!'; + } + } + + /** + * Check that connecting the given connections is safe, meaning that it would + * not break any of Blockly's basic assumptions (e.g. no self connections). + * @param {Connection} a The first of the connections to check. + * @param {Connection} b The second of the connections to check. + * @return {number} An enum with the reason this connection is safe or unsafe. + * @public + */ + doSafetyChecks(a, b) { + if (!a || !b) { + return Connection.REASON_TARGET_NULL; + } + let superiorBlock; + let inferiorBlock; + let superiorConnection; + let inferiorConnection; + if (a.isSuperior()) { + superiorBlock = a.getSourceBlock(); + inferiorBlock = b.getSourceBlock(); + superiorConnection = a; + inferiorConnection = b; + } else { + inferiorBlock = a.getSourceBlock(); + superiorBlock = b.getSourceBlock(); + inferiorConnection = a; + superiorConnection = b; + } + if (superiorBlock === inferiorBlock) { + return Connection.REASON_SELF_CONNECTION; + } else if ( + inferiorConnection.type !== + internalConstants.OPPOSITE_TYPE[superiorConnection.type]) { + return Connection.REASON_WRONG_TYPE; + } else if (superiorBlock.workspace !== inferiorBlock.workspace) { + return Connection.REASON_DIFFERENT_WORKSPACES; + } else if (superiorBlock.isShadow() && !inferiorBlock.isShadow()) { + return Connection.REASON_SHADOW_PARENT; + } else if ( + inferiorConnection.type === ConnectionType.OUTPUT_VALUE && + inferiorBlock.previousConnection && + inferiorBlock.previousConnection.isConnected()) { + return Connection.REASON_PREVIOUS_AND_OUTPUT; + } else if ( + inferiorConnection.type === ConnectionType.PREVIOUS_STATEMENT && + inferiorBlock.outputConnection && + inferiorBlock.outputConnection.isConnected()) { + return Connection.REASON_PREVIOUS_AND_OUTPUT; + } + return Connection.CAN_CONNECT; + } + + /** + * Check whether this connection is compatible with another connection with + * respect to the value type system. E.g. square_root("Hello") is not + * compatible. + * @param {!Connection} a Connection to compare. + * @param {!Connection} b Connection to compare against. + * @return {boolean} True if the connections share a type. + * @public + */ + doTypeChecks(a, b) { + const checkArrayOne = a.getCheck(); + const checkArrayTwo = b.getCheck(); + + if (!checkArrayOne || !checkArrayTwo) { + // One or both sides are promiscuous enough that anything will fit. return true; } - } - // No intersection. - return false; -}; - -/** - * Check whether this connection can be made by dragging. - * @param {!RenderedConnection} a Connection to compare. - * @param {!RenderedConnection} b Connection to compare against. - * @param {number} distance The maximum allowable distance between connections. - * @return {boolean} True if the connection is allowed during a drag. - * @public - */ -ConnectionChecker.prototype.doDragChecks = function(a, b, distance) { - if (a.distanceFrom(b) > distance) { + // Find any intersection in the check lists. + for (let i = 0; i < checkArrayOne.length; i++) { + if (checkArrayTwo.indexOf(checkArrayOne[i]) !== -1) { + return true; + } + } + // No intersection. return false; } - // Don't consider insertion markers. - if (b.getSourceBlock().isInsertionMarker()) { - return false; - } - - switch (b.type) { - case ConnectionType.PREVIOUS_STATEMENT: - return this.canConnectToPrevious_(a, b); - case ConnectionType.OUTPUT_VALUE: { - // Don't offer to connect an already connected left (male) value plug to - // an available right (female) value plug. - if ((b.isConnected() && !b.targetBlock().isInsertionMarker()) || - a.isConnected()) { - return false; - } - break; - } - case ConnectionType.INPUT_VALUE: { - // Offering to connect the left (male) of a value block to an already - // connected value pair is ok, we'll splice it in. - // However, don't offer to splice into an immovable block. - if (b.isConnected() && !b.targetBlock().isMovable() && - !b.targetBlock().isShadow()) { - return false; - } - break; - } - case ConnectionType.NEXT_STATEMENT: { - // Don't let a block with no next connection bump other blocks out of the - // stack. But covering up a shadow block or stack of shadow blocks is - // fine. Similarly, replacing a terminal statement with another terminal - // statement is allowed. - if (b.isConnected() && !a.getSourceBlock().nextConnection && - !b.targetBlock().isShadow() && b.targetBlock().nextConnection) { - return false; - } - break; - } - default: - // Unexpected connection type. + /** + * Check whether this connection can be made by dragging. + * @param {!RenderedConnection} a Connection to compare. + * @param {!RenderedConnection} b Connection to compare against. + * @param {number} distance The maximum allowable distance between + * connections. + * @return {boolean} True if the connection is allowed during a drag. + * @public + */ + doDragChecks(a, b, distance) { + if (a.distanceFrom(b) > distance) { return false; - } + } - // Don't let blocks try to connect to themselves or ones they nest. - if (common.draggingConnections.indexOf(b) !== -1) { - return false; - } + // Don't consider insertion markers. + if (b.getSourceBlock().isInsertionMarker()) { + return false; + } - return true; -}; + switch (b.type) { + case ConnectionType.PREVIOUS_STATEMENT: + return this.canConnectToPrevious_(a, b); + case ConnectionType.OUTPUT_VALUE: { + // Don't offer to connect an already connected left (male) value plug to + // an available right (female) value plug. + if ((b.isConnected() && !b.targetBlock().isInsertionMarker()) || + a.isConnected()) { + return false; + } + break; + } + case ConnectionType.INPUT_VALUE: { + // Offering to connect the left (male) of a value block to an already + // connected value pair is ok, we'll splice it in. + // However, don't offer to splice into an immovable block. + if (b.isConnected() && !b.targetBlock().isMovable() && + !b.targetBlock().isShadow()) { + return false; + } + break; + } + case ConnectionType.NEXT_STATEMENT: { + // Don't let a block with no next connection bump other blocks out of + // the stack. But covering up a shadow block or stack of shadow blocks + // is fine. Similarly, replacing a terminal statement with another + // terminal statement is allowed. + if (b.isConnected() && !a.getSourceBlock().nextConnection && + !b.targetBlock().isShadow() && b.targetBlock().nextConnection) { + return false; + } + break; + } + default: + // Unexpected connection type. + return false; + } -/** - * Helper function for drag checking. - * @param {!Connection} a The connection to check, which must be a - * statement input or next connection. - * @param {!Connection} b A nearby connection to check, which - * must be a previous connection. - * @return {boolean} True if the connection is allowed, false otherwise. - * @protected - */ -ConnectionChecker.prototype.canConnectToPrevious_ = function(a, b) { - if (a.targetConnection) { - // This connection is already occupied. - // A next connection will never disconnect itself mid-drag. - return false; - } + // Don't let blocks try to connect to themselves or ones they nest. + if (common.draggingConnections.indexOf(b) !== -1) { + return false; + } - // Don't let blocks try to connect to themselves or ones they nest. - if (common.draggingConnections.indexOf(b) !== -1) { - return false; - } - - if (!b.targetConnection) { return true; } - const targetBlock = b.targetBlock(); - // If it is connected to a real block, game over. - if (!targetBlock.isInsertionMarker()) { - return false; + /** + * Helper function for drag checking. + * @param {!Connection} a The connection to check, which must be a + * statement input or next connection. + * @param {!Connection} b A nearby connection to check, which + * must be a previous connection. + * @return {boolean} True if the connection is allowed, false otherwise. + * @protected + */ + canConnectToPrevious_(a, b) { + if (a.targetConnection) { + // This connection is already occupied. + // A next connection will never disconnect itself mid-drag. + return false; + } + + // Don't let blocks try to connect to themselves or ones they nest. + if (common.draggingConnections.indexOf(b) !== -1) { + return false; + } + + if (!b.targetConnection) { + return true; + } + + const targetBlock = b.targetBlock(); + // If it is connected to a real block, game over. + if (!targetBlock.isInsertionMarker()) { + return false; + } + // If it's connected to an insertion marker but that insertion marker + // is the first block in a stack, it's still fine. If that insertion + // marker is in the middle of a stack, it won't work. + return !targetBlock.getPreviousBlock(); } - // If it's connected to an insertion marker but that insertion marker - // is the first block in a stack, it's still fine. If that insertion - // marker is in the middle of a stack, it won't work. - return !targetBlock.getPreviousBlock(); -}; +} registry.register( registry.Type.CONNECTION_CHECKER, registry.DEFAULT, ConnectionChecker); diff --git a/core/connection_db.js b/core/connection_db.js index 35c1363a1..1979b68f7 100644 --- a/core/connection_db.js +++ b/core/connection_db.js @@ -34,276 +34,281 @@ goog.require('Blockly.constants'); * Database of connections. * Connections are stored in order of their vertical component. This way * connections in an area may be looked up quickly using a binary search. - * @param {!IConnectionChecker} checker The workspace's - * connection type checker, used to decide if connections are valid during a - * drag. - * @constructor - * @alias Blockly.ConnectionDB */ -const ConnectionDB = function(checker) { +class ConnectionDB { /** - * Array of connections sorted by y position in workspace units. - * @type {!Array} + * @param {!IConnectionChecker} checker The workspace's + * connection type checker, used to decide if connections are valid during + * a drag. + * @alias Blockly.ConnectionDB + */ + constructor(checker) { + /** + * Array of connections sorted by y position in workspace units. + * @type {!Array} + * @private + */ + this.connections_ = []; + /** + * The workspace's connection type checker, used to decide if connections + * are valid during a drag. + * @type {!IConnectionChecker} + * @private + */ + this.connectionChecker_ = checker; + } + + /** + * Add a connection to the database. Should not already exist in the database. + * @param {!RenderedConnection} connection The connection to be added. + * @param {number} yPos The y position used to decide where to insert the + * connection. + * @package + */ + addConnection(connection, yPos) { + const index = this.calculateIndexForYPos_(yPos); + this.connections_.splice(index, 0, connection); + } + + /** + * Finds the index of the given connection. + * + * Starts by doing a binary search to find the approximate location, then + * linearly searches nearby for the exact connection. + * @param {!RenderedConnection} conn The connection to find. + * @param {number} yPos The y position used to find the index of the + * connection. + * @return {number} The index of the connection, or -1 if the connection was + * not found. * @private */ - this.connections_ = []; - /** - * The workspace's connection type checker, used to decide if connections are - * valid during a drag. - * @type {!IConnectionChecker} - * @private - */ - this.connectionChecker_ = checker; -}; + findIndexOfConnection_(conn, yPos) { + if (!this.connections_.length) { + return -1; + } -/** - * Add a connection to the database. Should not already exist in the database. - * @param {!RenderedConnection} connection The connection to be added. - * @param {number} yPos The y position used to decide where to insert the - * connection. - * @package - */ -ConnectionDB.prototype.addConnection = function(connection, yPos) { - const index = this.calculateIndexForYPos_(yPos); - this.connections_.splice(index, 0, connection); -}; + const bestGuess = this.calculateIndexForYPos_(yPos); + if (bestGuess >= this.connections_.length) { + // Not in list + return -1; + } -/** - * Finds the index of the given connection. - * - * Starts by doing a binary search to find the approximate location, then - * linearly searches nearby for the exact connection. - * @param {!RenderedConnection} conn The connection to find. - * @param {number} yPos The y position used to find the index of the connection. - * @return {number} The index of the connection, or -1 if the connection was - * not found. - * @private - */ -ConnectionDB.prototype.findIndexOfConnection_ = function(conn, yPos) { - if (!this.connections_.length) { + yPos = conn.y; + // Walk forward and back on the y axis looking for the connection. + let pointer = bestGuess; + while (pointer >= 0 && this.connections_[pointer].y === yPos) { + if (this.connections_[pointer] === conn) { + return pointer; + } + pointer--; + } + + pointer = bestGuess; + while (pointer < this.connections_.length && + this.connections_[pointer].y === yPos) { + if (this.connections_[pointer] === conn) { + return pointer; + } + pointer++; + } return -1; } - const bestGuess = this.calculateIndexForYPos_(yPos); - if (bestGuess >= this.connections_.length) { - // Not in list - return -1; - } - - yPos = conn.y; - // Walk forward and back on the y axis looking for the connection. - let pointer = bestGuess; - while (pointer >= 0 && this.connections_[pointer].y === yPos) { - if (this.connections_[pointer] === conn) { - return pointer; - } - pointer--; - } - - pointer = bestGuess; - while (pointer < this.connections_.length && - this.connections_[pointer].y === yPos) { - if (this.connections_[pointer] === conn) { - return pointer; - } - pointer++; - } - return -1; -}; - -/** - * Finds the correct index for the given y position. - * @param {number} yPos The y position used to decide where to - * insert the connection. - * @return {number} The candidate index. - * @private - */ -ConnectionDB.prototype.calculateIndexForYPos_ = function(yPos) { - if (!this.connections_.length) { - return 0; - } - let pointerMin = 0; - let pointerMax = this.connections_.length; - while (pointerMin < pointerMax) { - const pointerMid = Math.floor((pointerMin + pointerMax) / 2); - if (this.connections_[pointerMid].y < yPos) { - pointerMin = pointerMid + 1; - } else if (this.connections_[pointerMid].y > yPos) { - pointerMax = pointerMid; - } else { - pointerMin = pointerMid; - break; - } - } - return pointerMin; -}; - -/** - * Remove a connection from the database. Must already exist in DB. - * @param {!RenderedConnection} connection The connection to be removed. - * @param {number} yPos The y position used to find the index of the connection. - * @throws {Error} If the connection cannot be found in the database. - */ -ConnectionDB.prototype.removeConnection = function(connection, yPos) { - const index = this.findIndexOfConnection_(connection, yPos); - if (index === -1) { - throw Error('Unable to find connection in connectionDB.'); - } - this.connections_.splice(index, 1); -}; - -/** - * Find all nearby connections to the given connection. - * Type checking does not apply, since this function is used for bumping. - * @param {!RenderedConnection} connection The connection whose - * neighbours should be returned. - * @param {number} maxRadius The maximum radius to another connection. - * @return {!Array} List of connections. - */ -ConnectionDB.prototype.getNeighbours = function(connection, maxRadius) { - const db = this.connections_; - const currentX = connection.x; - const currentY = connection.y; - - // Binary search to find the closest y location. - let pointerMin = 0; - let pointerMax = db.length - 2; - let pointerMid = pointerMax; - while (pointerMin < pointerMid) { - if (db[pointerMid].y < currentY) { - pointerMin = pointerMid; - } else { - pointerMax = pointerMid; - } - pointerMid = Math.floor((pointerMin + pointerMax) / 2); - } - - const neighbours = []; /** - * Computes if the current connection is within the allowed radius of another - * connection. - * This function is a closure and has access to outside variables. - * @param {number} yIndex The other connection's index in the database. - * @return {boolean} True if the current connection's vertical distance from - * the other connection is less than the allowed radius. + * Finds the correct index for the given y position. + * @param {number} yPos The y position used to decide where to + * insert the connection. + * @return {number} The candidate index. + * @private */ - function checkConnection_(yIndex) { - const dx = currentX - db[yIndex].x; - const dy = currentY - db[yIndex].y; - const r = Math.sqrt(dx * dx + dy * dy); - if (r <= maxRadius) { - neighbours.push(db[yIndex]); + calculateIndexForYPos_(yPos) { + if (!this.connections_.length) { + return 0; } - return dy < maxRadius; + let pointerMin = 0; + let pointerMax = this.connections_.length; + while (pointerMin < pointerMax) { + const pointerMid = Math.floor((pointerMin + pointerMax) / 2); + if (this.connections_[pointerMid].y < yPos) { + pointerMin = pointerMid + 1; + } else if (this.connections_[pointerMid].y > yPos) { + pointerMax = pointerMid; + } else { + pointerMin = pointerMid; + break; + } + } + return pointerMin; } - // Walk forward and back on the y axis looking for the closest x,y point. - pointerMin = pointerMid; - pointerMax = pointerMid; - if (db.length) { - while (pointerMin >= 0 && checkConnection_(pointerMin)) { + /** + * Remove a connection from the database. Must already exist in DB. + * @param {!RenderedConnection} connection The connection to be removed. + * @param {number} yPos The y position used to find the index of the + * connection. + * @throws {Error} If the connection cannot be found in the database. + */ + removeConnection(connection, yPos) { + const index = this.findIndexOfConnection_(connection, yPos); + if (index === -1) { + throw Error('Unable to find connection in connectionDB.'); + } + this.connections_.splice(index, 1); + } + + /** + * Find all nearby connections to the given connection. + * Type checking does not apply, since this function is used for bumping. + * @param {!RenderedConnection} connection The connection whose + * neighbours should be returned. + * @param {number} maxRadius The maximum radius to another connection. + * @return {!Array} List of connections. + */ + getNeighbours(connection, maxRadius) { + const db = this.connections_; + const currentX = connection.x; + const currentY = connection.y; + + // Binary search to find the closest y location. + let pointerMin = 0; + let pointerMax = db.length - 2; + let pointerMid = pointerMax; + while (pointerMin < pointerMid) { + if (db[pointerMid].y < currentY) { + pointerMin = pointerMid; + } else { + pointerMax = pointerMid; + } + pointerMid = Math.floor((pointerMin + pointerMax) / 2); + } + + const neighbours = []; + /** + * Computes if the current connection is within the allowed radius of + * another connection. This function is a closure and has access to outside + * variables. + * @param {number} yIndex The other connection's index in the database. + * @return {boolean} True if the current connection's vertical distance from + * the other connection is less than the allowed radius. + */ + function checkConnection_(yIndex) { + const dx = currentX - db[yIndex].x; + const dy = currentY - db[yIndex].y; + const r = Math.sqrt(dx * dx + dy * dy); + if (r <= maxRadius) { + neighbours.push(db[yIndex]); + } + return dy < maxRadius; + } + + // Walk forward and back on the y axis looking for the closest x,y point. + pointerMin = pointerMid; + pointerMax = pointerMid; + if (db.length) { + while (pointerMin >= 0 && checkConnection_(pointerMin)) { + pointerMin--; + } + do { + pointerMax++; + } while (pointerMax < db.length && checkConnection_(pointerMax)); + } + + return neighbours; + } + + /** + * Is the candidate connection close to the reference connection. + * Extremely fast; only looks at Y distance. + * @param {number} index Index in database of candidate connection. + * @param {number} baseY Reference connection's Y value. + * @param {number} maxRadius The maximum radius to another connection. + * @return {boolean} True if connection is in range. + * @private + */ + isInYRange_(index, baseY, maxRadius) { + return (Math.abs(this.connections_[index].y - baseY) <= maxRadius); + } + + /** + * Find the closest compatible connection to this connection. + * @param {!RenderedConnection} conn The connection searching for a compatible + * mate. + * @param {number} maxRadius The maximum radius to another connection. + * @param {!Coordinate} dxy Offset between this connection's + * location in the database and the current location (as a result of + * dragging). + * @return {!{connection: RenderedConnection, radius: number}} + * Contains two properties: 'connection' which is either another + * connection or null, and 'radius' which is the distance. + */ + searchForClosest(conn, maxRadius, dxy) { + if (!this.connections_.length) { + // Don't bother. + return {connection: null, radius: maxRadius}; + } + + // Stash the values of x and y from before the drag. + const baseY = conn.y; + const baseX = conn.x; + + conn.x = baseX + dxy.x; + conn.y = baseY + dxy.y; + + // calculateIndexForYPos_ finds an index for insertion, which is always + // after any block with the same y index. We want to search both forward + // and back, so search on both sides of the index. + const closestIndex = this.calculateIndexForYPos_(conn.y); + + let bestConnection = null; + let bestRadius = maxRadius; + let temp; + + // Walk forward and back on the y axis looking for the closest x,y point. + let pointerMin = closestIndex - 1; + while (pointerMin >= 0 && this.isInYRange_(pointerMin, conn.y, maxRadius)) { + temp = this.connections_[pointerMin]; + if (this.connectionChecker_.canConnect(conn, temp, true, bestRadius)) { + bestConnection = temp; + bestRadius = temp.distanceFrom(conn); + } pointerMin--; } - do { + + let pointerMax = closestIndex; + while (pointerMax < this.connections_.length && + this.isInYRange_(pointerMax, conn.y, maxRadius)) { + temp = this.connections_[pointerMax]; + if (this.connectionChecker_.canConnect(conn, temp, true, bestRadius)) { + bestConnection = temp; + bestRadius = temp.distanceFrom(conn); + } pointerMax++; - } while (pointerMax < db.length && checkConnection_(pointerMax)); - } - - return neighbours; -}; - -/** - * Is the candidate connection close to the reference connection. - * Extremely fast; only looks at Y distance. - * @param {number} index Index in database of candidate connection. - * @param {number} baseY Reference connection's Y value. - * @param {number} maxRadius The maximum radius to another connection. - * @return {boolean} True if connection is in range. - * @private - */ -ConnectionDB.prototype.isInYRange_ = function(index, baseY, maxRadius) { - return (Math.abs(this.connections_[index].y - baseY) <= maxRadius); -}; - -/** - * Find the closest compatible connection to this connection. - * @param {!RenderedConnection} conn The connection searching for a compatible - * mate. - * @param {number} maxRadius The maximum radius to another connection. - * @param {!Coordinate} dxy Offset between this connection's - * location in the database and the current location (as a result of - * dragging). - * @return {!{connection: RenderedConnection, radius: number}} - * Contains two properties: 'connection' which is either another - * connection or null, and 'radius' which is the distance. - */ -ConnectionDB.prototype.searchForClosest = function(conn, maxRadius, dxy) { - if (!this.connections_.length) { - // Don't bother. - return {connection: null, radius: maxRadius}; - } - - // Stash the values of x and y from before the drag. - const baseY = conn.y; - const baseX = conn.x; - - conn.x = baseX + dxy.x; - conn.y = baseY + dxy.y; - - // calculateIndexForYPos_ finds an index for insertion, which is always - // after any block with the same y index. We want to search both forward - // and back, so search on both sides of the index. - const closestIndex = this.calculateIndexForYPos_(conn.y); - - let bestConnection = null; - let bestRadius = maxRadius; - let temp; - - // Walk forward and back on the y axis looking for the closest x,y point. - let pointerMin = closestIndex - 1; - while (pointerMin >= 0 && this.isInYRange_(pointerMin, conn.y, maxRadius)) { - temp = this.connections_[pointerMin]; - if (this.connectionChecker_.canConnect(conn, temp, true, bestRadius)) { - bestConnection = temp; - bestRadius = temp.distanceFrom(conn); } - pointerMin--; + + // Reset the values of x and y. + conn.x = baseX; + conn.y = baseY; + + // If there were no valid connections, bestConnection will be null. + return {connection: bestConnection, radius: bestRadius}; } - let pointerMax = closestIndex; - while (pointerMax < this.connections_.length && - this.isInYRange_(pointerMax, conn.y, maxRadius)) { - temp = this.connections_[pointerMax]; - if (this.connectionChecker_.canConnect(conn, temp, true, bestRadius)) { - bestConnection = temp; - bestRadius = temp.distanceFrom(conn); - } - pointerMax++; + /** + * Initialize a set of connection DBs for a workspace. + * @param {!IConnectionChecker} checker The workspace's + * connection checker, used to decide if connections are valid during a + * drag. + * @return {!Array} Array of databases. + */ + static init(checker) { + // Create four databases, one for each connection type. + const dbList = []; + dbList[ConnectionType.INPUT_VALUE] = new ConnectionDB(checker); + dbList[ConnectionType.OUTPUT_VALUE] = new ConnectionDB(checker); + dbList[ConnectionType.NEXT_STATEMENT] = new ConnectionDB(checker); + dbList[ConnectionType.PREVIOUS_STATEMENT] = new ConnectionDB(checker); + return dbList; } - - // Reset the values of x and y. - conn.x = baseX; - conn.y = baseY; - - // If there were no valid connections, bestConnection will be null. - return {connection: bestConnection, radius: bestRadius}; -}; - -/** - * Initialize a set of connection DBs for a workspace. - * @param {!IConnectionChecker} checker The workspace's - * connection checker, used to decide if connections are valid during a - * drag. - * @return {!Array} Array of databases. - */ -ConnectionDB.init = function(checker) { - // Create four databases, one for each connection type. - const dbList = []; - dbList[ConnectionType.INPUT_VALUE] = new ConnectionDB(checker); - dbList[ConnectionType.OUTPUT_VALUE] = new ConnectionDB(checker); - dbList[ConnectionType.NEXT_STATEMENT] = new ConnectionDB(checker); - dbList[ConnectionType.PREVIOUS_STATEMENT] = new ConnectionDB(checker); - return dbList; -}; +} exports.ConnectionDB = ConnectionDB; diff --git a/core/field_label_serializable.js b/core/field_label_serializable.js index 4c4990f03..b8d3e027a 100644 --- a/core/field_label_serializable.js +++ b/core/field_label_serializable.js @@ -20,59 +20,62 @@ goog.module('Blockly.FieldLabelSerializable'); const fieldRegistry = goog.require('Blockly.fieldRegistry'); -const object = goog.require('Blockly.utils.object'); const parsing = goog.require('Blockly.utils.parsing'); const {FieldLabel} = goog.require('Blockly.FieldLabel'); /** * Class for a non-editable, serializable text field. - * @param {*} opt_value The initial value of the field. Should cast to a - * string. Defaults to an empty string if null or undefined. - * @param {string=} opt_class Optional CSS class for the field's text. - * @param {Object=} opt_config A map of options used to configure the field. - * See the [field creation documentation]{@link - * https://developers.google.com/blockly/guides/create-custom-blocks/fields/built-in-fields/label-serializable#creation} - * for a list of properties this parameter supports. * @extends {FieldLabel} - * @constructor - * - * @alias Blockly.FieldLabelSerializable */ -const FieldLabelSerializable = function(opt_value, opt_class, opt_config) { - FieldLabelSerializable.superClass_.constructor.call( - this, opt_value, opt_class, opt_config); -}; -object.inherits(FieldLabelSerializable, FieldLabel); +class FieldLabelSerializable extends FieldLabel { + /** + * @param {*} opt_value The initial value of the field. Should cast to a + * string. Defaults to an empty string if null or undefined. + * @param {string=} opt_class Optional CSS class for the field's text. + * @param {Object=} opt_config A map of options used to configure the field. + * See the [field creation documentation]{@link + * https://developers.google.com/blockly/guides/create-custom-blocks/fields/built-in-fields/label-serializable#creation} + * for a list of properties this parameter supports. + * + * @alias Blockly.FieldLabelSerializable + */ + constructor(opt_value, opt_class, opt_config) { + const stringValue = opt_value == undefined ? '' : String(opt_value); + super(stringValue, opt_class, opt_config); -/** - * Construct a FieldLabelSerializable from a JSON arg object, - * dereferencing any string table references. - * @param {!Object} options A JSON object with options (text, and class). - * @return {!FieldLabelSerializable} The new field instance. - * @package - * @nocollapse - */ -FieldLabelSerializable.fromJson = function(options) { - const text = parsing.replaceMessageReferences(options['text']); - // `this` might be a subclass of FieldLabelSerializable if that class doesn't - // override the static fromJson method. - return new this(text, undefined, options); -}; + /** + * Editable fields usually show some sort of UI indicating they are + * editable. This field should not. + * @type {boolean} + */ + this.EDITABLE = false; -/** - * Editable fields usually show some sort of UI indicating they are - * editable. This field should not. - * @type {boolean} - */ -FieldLabelSerializable.prototype.EDITABLE = false; + /** + * Serializable fields are saved by the XML renderer, non-serializable + * fields are not. This field should be serialized, but only edited + * programmatically. + * @type {boolean} + */ + this.SERIALIZABLE = true; + } -/** - * Serializable fields are saved by the XML renderer, non-serializable fields - * are not. This field should be serialized, but only edited programmatically. - * @type {boolean} - */ -FieldLabelSerializable.prototype.SERIALIZABLE = true; + /** + * Construct a FieldLabelSerializable from a JSON arg object, + * dereferencing any string table references. + * @param {!Object} options A JSON object with options (text, and class). + * @return {!FieldLabelSerializable} The new field instance. + * @package + * @nocollapse + * @override + */ + static fromJson(options) { + const text = parsing.replaceMessageReferences(options['text']); + // `this` might be a subclass of FieldLabelSerializable if that class + // doesn't override the static fromJson method. + return new this(text, undefined, options); + } +} fieldRegistry.register('field_label_serializable', FieldLabelSerializable); diff --git a/core/field_multilineinput.js b/core/field_multilineinput.js index 9f7899d6c..b03dc2d2b 100644 --- a/core/field_multilineinput.js +++ b/core/field_multilineinput.js @@ -20,7 +20,6 @@ const WidgetDiv = goog.require('Blockly.WidgetDiv'); const aria = goog.require('Blockly.utils.aria'); const dom = goog.require('Blockly.utils.dom'); const fieldRegistry = goog.require('Blockly.fieldRegistry'); -const object = goog.require('Blockly.utils.object'); const parsing = goog.require('Blockly.utils.parsing'); const userAgent = goog.require('Blockly.utils.userAgent'); const {FieldTextInput} = goog.require('Blockly.FieldTextInput'); @@ -31,401 +30,419 @@ const {Svg} = goog.require('Blockly.utils.Svg'); /** * Class for an editable text area field. - * @param {string=} opt_value The initial content of the field. Should cast to a - * string. Defaults to an empty string if null or undefined. - * @param {Function=} opt_validator An optional function that is called - * to validate any constraints on what the user entered. Takes the new - * text as an argument and returns either the accepted text, a replacement - * text, or null to abort the change. - * @param {Object=} opt_config A map of options used to configure the field. - * See the [field creation documentation]{@link - * https://developers.google.com/blockly/guides/create-custom-blocks/fields/built-in-fields/multiline-text-input#creation} - * for a list of properties this parameter supports. * @extends {FieldTextInput} - * @constructor - * @alias Blockly.FieldMultilineInput */ -const FieldMultilineInput = function(opt_value, opt_validator, opt_config) { - FieldMultilineInput.superClass_.constructor.call( - this, opt_value, opt_validator, opt_config); - +class FieldMultilineInput extends FieldTextInput { /** - * The SVG group element that will contain a text element for each text row - * when initialized. - * @type {SVGGElement} + * @param {string=} opt_value The initial content of the field. Should cast to + * a + * string. Defaults to an empty string if null or undefined. + * @param {Function=} opt_validator An optional function that is called + * to validate any constraints on what the user entered. Takes the new + * text as an argument and returns either the accepted text, a replacement + * text, or null to abort the change. + * @param {Object=} opt_config A map of options used to configure the field. + * See the [field creation documentation]{@link + * https://developers.google.com/blockly/guides/create-custom-blocks/fields/built-in-fields/multiline-text-input#creation} + * for a list of properties this parameter supports. + * @alias Blockly.FieldMultilineInput */ - this.textGroup_ = null; + constructor(opt_value, opt_validator, opt_config) { + const stringValue = opt_value == undefined ? '' : String(opt_value); + super(stringValue, opt_validator, opt_config); + + /** + * The SVG group element that will contain a text element for each text row + * when initialized. + * @type {SVGGElement} + */ + this.textGroup_ = null; + + /** + * Defines the maximum number of lines of field. + * If exceeded, scrolling functionality is enabled. + * @type {number} + * @protected + */ + this.maxLines_ = Infinity; + + /** + * Whether Y overflow is currently occurring. + * @type {boolean} + * @protected + */ + this.isOverflowedY_ = false; + + /** + * @type {boolean} + * @private + */ + this.isBeingEdited_ = false; + + /** + * @type {boolean} + * @private + */ + this.isTextValid_ = false; + } /** - * Defines the maximum number of lines of field. - * If exceeded, scrolling functionality is enabled. - * @type {number} + * @override + */ + configure_(config) { + super.configure_(config); + config.maxLines && this.setMaxLines(config.maxLines); + } + + /** + * Serializes this field's value to XML. Should only be called by Blockly.Xml. + * @param {!Element} fieldElement The element to populate with info about the + * field's state. + * @return {!Element} The element containing info about the field's state. + * @package + */ + toXml(fieldElement) { + // Replace '\n' characters with HTML-escaped equivalent ' '. This is + // needed so the plain-text representation of the XML produced by + // `Blockly.Xml.domToText` will appear on a single line (this is a + // limitation of the plain-text format). + fieldElement.textContent = this.getValue().replace(/\n/g, ' '); + return fieldElement; + } + + /** + * Sets the field's value based on the given XML element. Should only be + * called by Blockly.Xml. + * @param {!Element} fieldElement The element containing info about the + * field's state. + * @package + */ + fromXml(fieldElement) { + this.setValue(fieldElement.textContent.replace(/ /g, '\n')); + } + + /** + * Saves this field's value. + * @return {*} The state of this field. + * @package + */ + saveState() { + const legacyState = this.saveLegacyState(FieldMultilineInput); + if (legacyState !== null) { + return legacyState; + } + return this.getValue(); + } + + /** + * Sets the field's value based on the given state. + * @param {*} state The state of the variable to assign to this variable + * field. + * @override + * @package + */ + loadState(state) { + if (this.loadLegacyState(Field, state)) { + return; + } + this.setValue(state); + } + + /** + * Create the block UI for this field. + * @package + */ + initView() { + this.createBorderRect_(); + this.textGroup_ = dom.createSvgElement( + Svg.G, { + 'class': 'blocklyEditableText', + }, + this.fieldGroup_); + } + + /** + * Get the text from this field as displayed on screen. May differ from + * getText due to ellipsis, and other formatting. + * @return {string} Currently displayed text. + * @protected + * @override + */ + getDisplayText_() { + let textLines = this.getText(); + if (!textLines) { + // Prevent the field from disappearing if empty. + return Field.NBSP; + } + const lines = textLines.split('\n'); + textLines = ''; + const displayLinesNumber = + this.isOverflowedY_ ? this.maxLines_ : lines.length; + for (let i = 0; i < displayLinesNumber; i++) { + let text = lines[i]; + if (text.length > this.maxDisplayLength) { + // Truncate displayed string and add an ellipsis ('...'). + text = text.substring(0, this.maxDisplayLength - 4) + '...'; + } else if (this.isOverflowedY_ && i === displayLinesNumber - 1) { + text = text.substring(0, text.length - 3) + '...'; + } + // Replace whitespace with non-breaking spaces so the text doesn't + // collapse. + text = text.replace(/\s/g, Field.NBSP); + + textLines += text; + if (i !== displayLinesNumber - 1) { + textLines += '\n'; + } + } + if (this.sourceBlock_.RTL) { + // The SVG is LTR, force value to be RTL. + textLines += '\u200F'; + } + return textLines; + } + + /** + * Called by setValue if the text input is valid. Updates the value of the + * field, and updates the text of the field if it is not currently being + * edited (i.e. handled by the htmlInput_). Is being redefined here to update + * overflow state of the field. + * @param {*} newValue The value to be saved. The default validator guarantees + * that this is a string. * @protected */ - this.maxLines_ = Infinity; + doValueUpdate_(newValue) { + super.doValueUpdate_(newValue); + this.isOverflowedY_ = this.value_.split('\n').length > this.maxLines_; + } /** - * Whether Y overflow is currently occurring. - * @type {boolean} + * Updates the text of the textElement. * @protected */ - this.isOverflowedY_ = false; -}; -object.inherits(FieldMultilineInput, FieldTextInput); - -/** - * @override - */ -FieldMultilineInput.prototype.configure_ = function(config) { - FieldMultilineInput.superClass_.configure_.call(this, config); - config.maxLines && this.setMaxLines(config.maxLines); -}; - -/** - * Construct a FieldMultilineInput from a JSON arg object, - * dereferencing any string table references. - * @param {!Object} options A JSON object with options (text, and spellcheck). - * @return {!FieldMultilineInput} The new field instance. - * @package - * @nocollapse - */ -FieldMultilineInput.fromJson = function(options) { - const text = parsing.replaceMessageReferences(options['text']); - // `this` might be a subclass of FieldMultilineInput if that class doesn't - // override the static fromJson method. - return new this(text, undefined, options); -}; - -/** - * Serializes this field's value to XML. Should only be called by Blockly.Xml. - * @param {!Element} fieldElement The element to populate with info about the - * field's state. - * @return {!Element} The element containing info about the field's state. - * @package - */ -FieldMultilineInput.prototype.toXml = function(fieldElement) { - // Replace '\n' characters with HTML-escaped equivalent ' '. This is - // needed so the plain-text representation of the XML produced by - // `Blockly.Xml.domToText` will appear on a single line (this is a limitation - // of the plain-text format). - fieldElement.textContent = this.getValue().replace(/\n/g, ' '); - return fieldElement; -}; - -/** - * Sets the field's value based on the given XML element. Should only be - * called by Blockly.Xml. - * @param {!Element} fieldElement The element containing info about the - * field's state. - * @package - */ -FieldMultilineInput.prototype.fromXml = function(fieldElement) { - this.setValue(fieldElement.textContent.replace(/ /g, '\n')); -}; - -/** - * Saves this field's value. - * @return {*} The state of this field. - * @package - */ -FieldMultilineInput.prototype.saveState = function() { - const legacyState = this.saveLegacyState(FieldMultilineInput); - if (legacyState !== null) { - return legacyState; - } - return this.getValue(); -}; - -/** - * Sets the field's value based on the given state. - * @param {*} state The state of the variable to assign to this variable field. - * @override - * @package - */ -FieldMultilineInput.prototype.loadState = function(state) { - if (this.loadLegacyState(Field, state)) { - return; - } - this.setValue(state); -}; - -/** - * Create the block UI for this field. - * @package - */ -FieldMultilineInput.prototype.initView = function() { - this.createBorderRect_(); - this.textGroup_ = dom.createSvgElement( - Svg.G, { - 'class': 'blocklyEditableText', - }, - this.fieldGroup_); -}; - -/** - * Get the text from this field as displayed on screen. May differ from getText - * due to ellipsis, and other formatting. - * @return {string} Currently displayed text. - * @protected - * @override - */ -FieldMultilineInput.prototype.getDisplayText_ = function() { - let textLines = this.getText(); - if (!textLines) { - // Prevent the field from disappearing if empty. - return Field.NBSP; - } - const lines = textLines.split('\n'); - textLines = ''; - const displayLinesNumber = - this.isOverflowedY_ ? this.maxLines_ : lines.length; - for (let i = 0; i < displayLinesNumber; i++) { - let text = lines[i]; - if (text.length > this.maxDisplayLength) { - // Truncate displayed string and add an ellipsis ('...'). - text = text.substring(0, this.maxDisplayLength - 4) + '...'; - } else if (this.isOverflowedY_ && i === displayLinesNumber - 1) { - text = text.substring(0, text.length - 3) + '...'; + render_() { + // Remove all text group children. + let currentChild; + while ((currentChild = this.textGroup_.firstChild)) { + this.textGroup_.removeChild(currentChild); } - // Replace whitespace with non-breaking spaces so the text doesn't collapse. - text = text.replace(/\s/g, Field.NBSP); - textLines += text; - if (i !== displayLinesNumber - 1) { - textLines += '\n'; + // Add in text elements into the group. + const lines = this.getDisplayText_().split('\n'); + let y = 0; + for (let i = 0; i < lines.length; i++) { + const lineHeight = this.getConstants().FIELD_TEXT_HEIGHT + + this.getConstants().FIELD_BORDER_RECT_Y_PADDING; + const span = dom.createSvgElement( + Svg.TEXT, { + 'class': 'blocklyText blocklyMultilineText', + 'x': this.getConstants().FIELD_BORDER_RECT_X_PADDING, + 'y': y + this.getConstants().FIELD_BORDER_RECT_Y_PADDING, + 'dy': this.getConstants().FIELD_TEXT_BASELINE, + }, + this.textGroup_); + span.appendChild(document.createTextNode(lines[i])); + y += lineHeight; + } + + if (this.isBeingEdited_) { + const htmlInput = /** @type {!HTMLElement} */ (this.htmlInput_); + if (this.isOverflowedY_) { + dom.addClass(htmlInput, 'blocklyHtmlTextAreaInputOverflowedY'); + } else { + dom.removeClass(htmlInput, 'blocklyHtmlTextAreaInputOverflowedY'); + } + } + + this.updateSize_(); + + if (this.isBeingEdited_) { + if (this.sourceBlock_.RTL) { + // in RTL, we need to let the browser reflow before resizing + // in order to get the correct bounding box of the borderRect + // avoiding issue #2777. + setTimeout(this.resizeEditor_.bind(this), 0); + } else { + this.resizeEditor_(); + } + const htmlInput = /** @type {!HTMLElement} */ (this.htmlInput_); + if (!this.isTextValid_) { + dom.addClass(htmlInput, 'blocklyInvalidInput'); + aria.setState(htmlInput, aria.State.INVALID, true); + } else { + dom.removeClass(htmlInput, 'blocklyInvalidInput'); + aria.setState(htmlInput, aria.State.INVALID, false); + } } } - if (this.sourceBlock_.RTL) { - // The SVG is LTR, force value to be RTL. - textLines += '\u200F'; - } - return textLines; -}; -/** - * Called by setValue if the text input is valid. Updates the value of the - * field, and updates the text of the field if it is not currently being - * edited (i.e. handled by the htmlInput_). Is being redefined here to update - * overflow state of the field. - * @param {*} newValue The value to be saved. The default validator guarantees - * that this is a string. - * @protected - */ -FieldMultilineInput.prototype.doValueUpdate_ = function(newValue) { - FieldMultilineInput.superClass_.doValueUpdate_.call(this, newValue); - this.isOverflowedY_ = this.value_.split('\n').length > this.maxLines_; -}; + /** + * Updates the size of the field based on the text. + * @protected + */ + updateSize_() { + const nodes = this.textGroup_.childNodes; + let totalWidth = 0; + let totalHeight = 0; + for (let i = 0; i < nodes.length; i++) { + const tspan = /** @type {!Element} */ (nodes[i]); + const textWidth = dom.getTextWidth(tspan); + if (textWidth > totalWidth) { + totalWidth = textWidth; + } + totalHeight += this.getConstants().FIELD_TEXT_HEIGHT + + (i > 0 ? this.getConstants().FIELD_BORDER_RECT_Y_PADDING : 0); + } + if (this.isBeingEdited_) { + // The default width is based on the longest line in the display text, + // but when it's being edited, width should be calculated based on the + // absolute longest line, even if it would be truncated after editing. + // Otherwise we would get wrong editor width when there are more + // lines than this.maxLines_. + const actualEditorLines = this.value_.split('\n'); + const dummyTextElement = dom.createSvgElement( + Svg.TEXT, {'class': 'blocklyText blocklyMultilineText'}); + const fontSize = this.getConstants().FIELD_TEXT_FONTSIZE; + const fontWeight = this.getConstants().FIELD_TEXT_FONTWEIGHT; + const fontFamily = this.getConstants().FIELD_TEXT_FONTFAMILY; -/** - * Updates the text of the textElement. - * @protected - */ -FieldMultilineInput.prototype.render_ = function() { - // Remove all text group children. - let currentChild; - while ((currentChild = this.textGroup_.firstChild)) { - this.textGroup_.removeChild(currentChild); + for (let i = 0; i < actualEditorLines.length; i++) { + if (actualEditorLines[i].length > this.maxDisplayLength) { + actualEditorLines[i] = + actualEditorLines[i].substring(0, this.maxDisplayLength); + } + dummyTextElement.textContent = actualEditorLines[i]; + const lineWidth = dom.getFastTextWidth( + dummyTextElement, fontSize, fontWeight, fontFamily); + if (lineWidth > totalWidth) { + totalWidth = lineWidth; + } + } + + const scrollbarWidth = + this.htmlInput_.offsetWidth - this.htmlInput_.clientWidth; + totalWidth += scrollbarWidth; + } + if (this.borderRect_) { + totalHeight += this.getConstants().FIELD_BORDER_RECT_Y_PADDING * 2; + totalWidth += this.getConstants().FIELD_BORDER_RECT_X_PADDING * 2; + this.borderRect_.setAttribute('width', totalWidth); + this.borderRect_.setAttribute('height', totalHeight); + } + this.size_.width = totalWidth; + this.size_.height = totalHeight; + + this.positionBorderRect_(); } - // Add in text elements into the group. - const lines = this.getDisplayText_().split('\n'); - let y = 0; - for (let i = 0; i < lines.length; i++) { + /** + * Show the inline free-text editor on top of the text. + * Overrides the default behaviour to force rerender in order to + * correct block size, based on editor text. + * @param {Event=} _opt_e Optional mouse event that triggered the field to + * open, or undefined if triggered programmatically. + * @param {boolean=} opt_quietInput True if editor should be created without + * focus. Defaults to false. + * @override + */ + showEditor_(_opt_e, opt_quietInput) { + super.showEditor_(_opt_e, opt_quietInput); + this.forceRerender(); + } + + /** + * Create the text input editor widget. + * @return {!HTMLTextAreaElement} The newly created text input editor. + * @protected + */ + widgetCreate_() { + const div = WidgetDiv.getDiv(); + const scale = this.workspace_.getScale(); + + const htmlInput = + /** @type {HTMLTextAreaElement} */ (document.createElement('textarea')); + htmlInput.className = 'blocklyHtmlInput blocklyHtmlTextAreaInput'; + htmlInput.setAttribute('spellcheck', this.spellcheck_); + const fontSize = (this.getConstants().FIELD_TEXT_FONTSIZE * scale) + 'pt'; + div.style.fontSize = fontSize; + htmlInput.style.fontSize = fontSize; + const borderRadius = (FieldTextInput.BORDERRADIUS * scale) + 'px'; + htmlInput.style.borderRadius = borderRadius; + const paddingX = this.getConstants().FIELD_BORDER_RECT_X_PADDING * scale; + const paddingY = + this.getConstants().FIELD_BORDER_RECT_Y_PADDING * scale / 2; + htmlInput.style.padding = paddingY + 'px ' + paddingX + 'px ' + paddingY + + 'px ' + paddingX + 'px'; const lineHeight = this.getConstants().FIELD_TEXT_HEIGHT + this.getConstants().FIELD_BORDER_RECT_Y_PADDING; - const span = dom.createSvgElement( - Svg.TEXT, { - 'class': 'blocklyText blocklyMultilineText', - 'x': this.getConstants().FIELD_BORDER_RECT_X_PADDING, - 'y': y + this.getConstants().FIELD_BORDER_RECT_Y_PADDING, - 'dy': this.getConstants().FIELD_TEXT_BASELINE, - }, - this.textGroup_); - span.appendChild(document.createTextNode(lines[i])); - y += lineHeight; - } + htmlInput.style.lineHeight = (lineHeight * scale) + 'px'; - if (this.isBeingEdited_) { - const htmlInput = /** @type {!HTMLElement} */ (this.htmlInput_); - if (this.isOverflowedY_) { - dom.addClass(htmlInput, 'blocklyHtmlTextAreaInputOverflowedY'); - } else { - dom.removeClass(htmlInput, 'blocklyHtmlTextAreaInputOverflowedY'); - } - } + div.appendChild(htmlInput); - this.updateSize_(); - - if (this.isBeingEdited_) { - if (this.sourceBlock_.RTL) { - // in RTL, we need to let the browser reflow before resizing - // in order to get the correct bounding box of the borderRect - // avoiding issue #2777. + htmlInput.value = htmlInput.defaultValue = this.getEditorText_(this.value_); + htmlInput.untypedDefaultValue_ = this.value_; + htmlInput.oldValue_ = null; + if (userAgent.GECKO) { + // In FF, ensure the browser reflows before resizing to avoid issue #2777. setTimeout(this.resizeEditor_.bind(this), 0); } else { this.resizeEditor_(); } - const htmlInput = /** @type {!HTMLElement} */ (this.htmlInput_); - if (!this.isTextValid_) { - dom.addClass(htmlInput, 'blocklyInvalidInput'); - aria.setState(htmlInput, aria.State.INVALID, true); - } else { - dom.removeClass(htmlInput, 'blocklyInvalidInput'); - aria.setState(htmlInput, aria.State.INVALID, false); + + this.bindInputEvents_(htmlInput); + + return htmlInput; + } + + /** + * Sets the maxLines config for this field. + * @param {number} maxLines Defines the maximum number of lines allowed, + * before scrolling functionality is enabled. + */ + setMaxLines(maxLines) { + if (typeof maxLines === 'number' && maxLines > 0 && + maxLines !== this.maxLines_) { + this.maxLines_ = maxLines; + this.forceRerender(); } } -}; -/** - * Updates the size of the field based on the text. - * @protected - */ -FieldMultilineInput.prototype.updateSize_ = function() { - const nodes = this.textGroup_.childNodes; - let totalWidth = 0; - let totalHeight = 0; - for (let i = 0; i < nodes.length; i++) { - const tspan = /** @type {!Element} */ (nodes[i]); - const textWidth = dom.getTextWidth(tspan); - if (textWidth > totalWidth) { - totalWidth = textWidth; + /** + * Returns the maxLines config of this field. + * @return {number} The maxLines config value. + */ + getMaxLines() { + return this.maxLines_; + } + + /** + * Handle key down to the editor. Override the text input definition of this + * so as to not close the editor when enter is typed in. + * @param {!Event} e Keyboard event. + * @protected + */ + onHtmlInputKeyDown_(e) { + if (e.keyCode !== KeyCodes.ENTER) { + super.onHtmlInputKeyDown_(e); } - totalHeight += this.getConstants().FIELD_TEXT_HEIGHT + - (i > 0 ? this.getConstants().FIELD_BORDER_RECT_Y_PADDING : 0); - } - if (this.isBeingEdited_) { - // The default width is based on the longest line in the display text, - // but when it's being edited, width should be calculated based on the - // absolute longest line, even if it would be truncated after editing. - // Otherwise we would get wrong editor width when there are more - // lines than this.maxLines_. - const actualEditorLines = this.value_.split('\n'); - const dummyTextElement = dom.createSvgElement( - Svg.TEXT, {'class': 'blocklyText blocklyMultilineText'}); - const fontSize = this.getConstants().FIELD_TEXT_FONTSIZE; - const fontWeight = this.getConstants().FIELD_TEXT_FONTWEIGHT; - const fontFamily = this.getConstants().FIELD_TEXT_FONTFAMILY; - - for (let i = 0; i < actualEditorLines.length; i++) { - if (actualEditorLines[i].length > this.maxDisplayLength) { - actualEditorLines[i] = - actualEditorLines[i].substring(0, this.maxDisplayLength); - } - dummyTextElement.textContent = actualEditorLines[i]; - const lineWidth = dom.getFastTextWidth( - dummyTextElement, fontSize, fontWeight, fontFamily); - if (lineWidth > totalWidth) { - totalWidth = lineWidth; - } - } - - const scrollbarWidth = - this.htmlInput_.offsetWidth - this.htmlInput_.clientWidth; - totalWidth += scrollbarWidth; - } - if (this.borderRect_) { - totalHeight += this.getConstants().FIELD_BORDER_RECT_Y_PADDING * 2; - totalWidth += this.getConstants().FIELD_BORDER_RECT_X_PADDING * 2; - this.borderRect_.setAttribute('width', totalWidth); - this.borderRect_.setAttribute('height', totalHeight); - } - this.size_.width = totalWidth; - this.size_.height = totalHeight; - - this.positionBorderRect_(); -}; - -/** - * Show the inline free-text editor on top of the text. - * Overrides the default behaviour to force rerender in order to - * correct block size, based on editor text. - * @param {Event=} _opt_e Optional mouse event that triggered the field to open, - * or undefined if triggered programmatically. - * @param {boolean=} opt_quietInput True if editor should be created without - * focus. Defaults to false. - * @override - */ -FieldMultilineInput.prototype.showEditor_ = function(_opt_e, opt_quietInput) { - FieldMultilineInput.superClass_.showEditor_.call( - this, _opt_e, opt_quietInput); - this.forceRerender(); -}; - -/** - * Create the text input editor widget. - * @return {!HTMLTextAreaElement} The newly created text input editor. - * @protected - */ -FieldMultilineInput.prototype.widgetCreate_ = function() { - const div = WidgetDiv.getDiv(); - const scale = this.workspace_.getScale(); - - const htmlInput = - /** @type {HTMLTextAreaElement} */ (document.createElement('textarea')); - htmlInput.className = 'blocklyHtmlInput blocklyHtmlTextAreaInput'; - htmlInput.setAttribute('spellcheck', this.spellcheck_); - const fontSize = (this.getConstants().FIELD_TEXT_FONTSIZE * scale) + 'pt'; - div.style.fontSize = fontSize; - htmlInput.style.fontSize = fontSize; - const borderRadius = (FieldTextInput.BORDERRADIUS * scale) + 'px'; - htmlInput.style.borderRadius = borderRadius; - const paddingX = this.getConstants().FIELD_BORDER_RECT_X_PADDING * scale; - const paddingY = this.getConstants().FIELD_BORDER_RECT_Y_PADDING * scale / 2; - htmlInput.style.padding = - paddingY + 'px ' + paddingX + 'px ' + paddingY + 'px ' + paddingX + 'px'; - const lineHeight = this.getConstants().FIELD_TEXT_HEIGHT + - this.getConstants().FIELD_BORDER_RECT_Y_PADDING; - htmlInput.style.lineHeight = (lineHeight * scale) + 'px'; - - div.appendChild(htmlInput); - - htmlInput.value = htmlInput.defaultValue = this.getEditorText_(this.value_); - htmlInput.untypedDefaultValue_ = this.value_; - htmlInput.oldValue_ = null; - if (userAgent.GECKO) { - // In FF, ensure the browser reflows before resizing to avoid issue #2777. - setTimeout(this.resizeEditor_.bind(this), 0); - } else { - this.resizeEditor_(); } - this.bindInputEvents_(htmlInput); - - return htmlInput; -}; - -/** - * Sets the maxLines config for this field. - * @param {number} maxLines Defines the maximum number of lines allowed, - * before scrolling functionality is enabled. - */ -FieldMultilineInput.prototype.setMaxLines = function(maxLines) { - if (typeof maxLines === 'number' && maxLines > 0 && - maxLines !== this.maxLines_) { - this.maxLines_ = maxLines; - this.forceRerender(); + /** + * Construct a FieldMultilineInput from a JSON arg object, + * dereferencing any string table references. + * @param {!Object} options A JSON object with options (text, and spellcheck). + * @return {!FieldMultilineInput} The new field instance. + * @package + * @nocollapse + * @override + */ + static fromJson(options) { + const text = parsing.replaceMessageReferences(options['text']); + // `this` might be a subclass of FieldMultilineInput if that class doesn't + // override the static fromJson method. + return new this(text, undefined, options); } -}; - -/** - * Returns the maxLines config of this field. - * @return {number} The maxLines config value. - */ -FieldMultilineInput.prototype.getMaxLines = function() { - return this.maxLines_; -}; - -/** - * Handle key down to the editor. Override the text input definition of this - * so as to not close the editor when enter is typed in. - * @param {!Event} e Keyboard event. - * @protected - */ -FieldMultilineInput.prototype.onHtmlInputKeyDown_ = function(e) { - if (e.keyCode !== KeyCodes.ENTER) { - FieldMultilineInput.superClass_.onHtmlInputKeyDown_.call(this, e); - } -}; +} /** * CSS for multiline field. See css.js for use. diff --git a/core/icon.js b/core/icon.js index 3f81e9795..66a4a7299 100644 --- a/core/icon.js +++ b/core/icon.js @@ -29,189 +29,197 @@ const {Svg} = goog.require('Blockly.utils.Svg'); /** * Class for an icon. - * @param {BlockSvg} block The block associated with this icon. - * @constructor * @abstract - * @alias Blockly.Icon */ -const Icon = function(block) { +class Icon { /** - * The block this icon is attached to. - * @type {BlockSvg} + * @param {BlockSvg} block The block associated with this icon. + * @alias Blockly.Icon + */ + constructor(block) { + /** + * The block this icon is attached to. + * @type {BlockSvg} + * @protected + */ + this.block_ = block; + + /** + * The icon SVG group. + * @type {?SVGGElement} + */ + this.iconGroup_ = null; + + /** + * Whether this icon gets hidden when the block is collapsed. + * @type {boolean} + */ + this.collapseHidden = true; + + /** + * Height and width of icons. + * @const + */ + this.SIZE = 17; + + /** + * Bubble UI (if visible). + * @type {?Bubble} + * @protected + */ + this.bubble_ = null; + + /** + * Absolute coordinate of icon's center. + * @type {?Coordinate} + * @protected + */ + this.iconXY_ = null; + } + + /** + * Create the icon on the block. + */ + createIcon() { + if (this.iconGroup_) { + // Icon already exists. + return; + } + /* Here's the markup that will be generated: + + ... + + */ + this.iconGroup_ = + dom.createSvgElement(Svg.G, {'class': 'blocklyIconGroup'}, null); + if (this.block_.isInFlyout) { + dom.addClass( + /** @type {!Element} */ (this.iconGroup_), + 'blocklyIconGroupReadonly'); + } + this.drawIcon_(this.iconGroup_); + + this.block_.getSvgRoot().appendChild(this.iconGroup_); + browserEvents.conditionalBind( + this.iconGroup_, 'mouseup', this, this.iconClick_); + this.updateEditable(); + } + + /** + * Dispose of this icon. + */ + dispose() { + // Dispose of and unlink the icon. + dom.removeNode(this.iconGroup_); + this.iconGroup_ = null; + // Dispose of and unlink the bubble. + this.setVisible(false); + this.block_ = null; + } + + /** + * Add or remove the UI indicating if this icon may be clicked or not. + */ + updateEditable() { + // No-op on the base class. + } + + /** + * Is the associated bubble visible? + * @return {boolean} True if the bubble is visible. + */ + isVisible() { + return !!this.bubble_; + } + + /** + * Clicking on the icon toggles if the bubble is visible. + * @param {!Event} e Mouse click event. * @protected */ - this.block_ = block; + iconClick_(e) { + if (this.block_.workspace.isDragging()) { + // Drag operation is concluding. Don't open the editor. + return; + } + if (!this.block_.isInFlyout && !browserEvents.isRightButton(e)) { + this.setVisible(!this.isVisible()); + } + } /** - * The icon SVG group. - * @type {?SVGGElement} + * Change the colour of the associated bubble to match its block. */ - this.iconGroup_ = null; + applyColour() { + if (this.isVisible()) { + this.bubble_.setColour(this.block_.style.colourPrimary); + } + } /** - * Whether this icon gets hidden when the block is collapsed. - * @type {boolean} + * Notification that the icon has moved. Update the arrow accordingly. + * @param {!Coordinate} xy Absolute location in workspace coordinates. */ - this.collapseHidden = true; + setIconLocation(xy) { + this.iconXY_ = xy; + if (this.isVisible()) { + this.bubble_.setAnchorLocation(xy); + } + } /** - * Height and width of icons. - * @const + * Notification that the icon has moved, but we don't really know where. + * Recompute the icon's location from scratch. */ - this.SIZE = 17; + computeIconLocation() { + // Find coordinates for the centre of the icon and update the arrow. + const blockXY = this.block_.getRelativeToSurfaceXY(); + const iconXY = svgMath.getRelativeXY( + /** @type {!SVGElement} */ (this.iconGroup_)); + const newXY = new Coordinate( + blockXY.x + iconXY.x + this.SIZE / 2, + blockXY.y + iconXY.y + this.SIZE / 2); + if (!Coordinate.equals(this.getIconLocation(), newXY)) { + this.setIconLocation(newXY); + } + } /** - * Bubble UI (if visible). - * @type {?Bubble} + * Returns the center of the block's icon relative to the surface. + * @return {?Coordinate} Object with x and y properties in + * workspace coordinates. + */ + getIconLocation() { + return this.iconXY_; + } + + /** + * Get the size of the icon as used for rendering. + * This differs from the actual size of the icon, because it bulges slightly + * out of its row rather than increasing the height of its row. + * @return {!Size} Height and width. + */ + getCorrectedSize() { + // TODO (#2562): Remove getCorrectedSize. + return new Size(this.SIZE, this.SIZE - 2); + } + + /** + * Draw the icon. + * @param {!Element} _group The icon group. * @protected */ - this.bubble_ = null; + drawIcon_(_group) { + // No-op on base class. + } /** - * Absolute coordinate of icon's center. - * @type {?Coordinate} - * @protected + * Show or hide the icon. + * @param {boolean} _visible True if the icon should be visible. */ - this.iconXY_ = null; -}; - -/** - * Create the icon on the block. - */ -Icon.prototype.createIcon = function() { - if (this.iconGroup_) { - // Icon already exists. - return; + setVisible(_visible) { + // No-op on base class } - /* Here's the markup that will be generated: - - ... - - */ - this.iconGroup_ = - dom.createSvgElement(Svg.G, {'class': 'blocklyIconGroup'}, null); - if (this.block_.isInFlyout) { - dom.addClass( - /** @type {!Element} */ (this.iconGroup_), 'blocklyIconGroupReadonly'); - } - this.drawIcon_(this.iconGroup_); - - this.block_.getSvgRoot().appendChild(this.iconGroup_); - browserEvents.conditionalBind( - this.iconGroup_, 'mouseup', this, this.iconClick_); - this.updateEditable(); -}; - -/** - * Dispose of this icon. - */ -Icon.prototype.dispose = function() { - // Dispose of and unlink the icon. - dom.removeNode(this.iconGroup_); - this.iconGroup_ = null; - // Dispose of and unlink the bubble. - this.setVisible(false); - this.block_ = null; -}; - -/** - * Add or remove the UI indicating if this icon may be clicked or not. - */ -Icon.prototype.updateEditable = function() { - // No-op on the base class. -}; - -/** - * Is the associated bubble visible? - * @return {boolean} True if the bubble is visible. - */ -Icon.prototype.isVisible = function() { - return !!this.bubble_; -}; - -/** - * Clicking on the icon toggles if the bubble is visible. - * @param {!Event} e Mouse click event. - * @protected - */ -Icon.prototype.iconClick_ = function(e) { - if (this.block_.workspace.isDragging()) { - // Drag operation is concluding. Don't open the editor. - return; - } - if (!this.block_.isInFlyout && !browserEvents.isRightButton(e)) { - this.setVisible(!this.isVisible()); - } -}; - -/** - * Change the colour of the associated bubble to match its block. - */ -Icon.prototype.applyColour = function() { - if (this.isVisible()) { - this.bubble_.setColour(this.block_.style.colourPrimary); - } -}; - -/** - * Notification that the icon has moved. Update the arrow accordingly. - * @param {!Coordinate} xy Absolute location in workspace coordinates. - */ -Icon.prototype.setIconLocation = function(xy) { - this.iconXY_ = xy; - if (this.isVisible()) { - this.bubble_.setAnchorLocation(xy); - } -}; - -/** - * Notification that the icon has moved, but we don't really know where. - * Recompute the icon's location from scratch. - */ -Icon.prototype.computeIconLocation = function() { - // Find coordinates for the centre of the icon and update the arrow. - const blockXY = this.block_.getRelativeToSurfaceXY(); - const iconXY = svgMath.getRelativeXY( - /** @type {!SVGElement} */ (this.iconGroup_)); - const newXY = new Coordinate( - blockXY.x + iconXY.x + this.SIZE / 2, - blockXY.y + iconXY.y + this.SIZE / 2); - if (!Coordinate.equals(this.getIconLocation(), newXY)) { - this.setIconLocation(newXY); - } -}; - -/** - * Returns the center of the block's icon relative to the surface. - * @return {?Coordinate} Object with x and y properties in - * workspace coordinates. - */ -Icon.prototype.getIconLocation = function() { - return this.iconXY_; -}; - -/** - * Get the size of the icon as used for rendering. - * This differs from the actual size of the icon, because it bulges slightly - * out of its row rather than increasing the height of its row. - * @return {!Size} Height and width. - */ -// TODO (#2562): Remove getCorrectedSize. -Icon.prototype.getCorrectedSize = function() { - return new Size(this.SIZE, this.SIZE - 2); -}; - -/** - * Draw the icon. - * @param {!Element} group The icon group. - * @protected - */ -Icon.prototype.drawIcon_; - -/** - * Show or hide the icon. - * @param {boolean} visible True if the icon should be visible. - */ -Icon.prototype.setVisible; +} exports.Icon = Icon; diff --git a/core/marker_manager.js b/core/marker_manager.js index 035f6a4c4..79bc384ea 100644 --- a/core/marker_manager.js +++ b/core/marker_manager.js @@ -25,40 +25,183 @@ const {WorkspaceSvg} = goog.requireType('Blockly.WorkspaceSvg'); /** * Class to manage the multiple markers and the cursor on a workspace. - * @param {!WorkspaceSvg} workspace The workspace for the marker manager. - * @constructor - * @alias Blockly.MarkerManager - * @package */ -const MarkerManager = function(workspace) { +class MarkerManager { /** - * The cursor. - * @type {?Cursor} - * @private + * @param {!WorkspaceSvg} workspace The workspace for the marker manager. + * @alias Blockly.MarkerManager + * @package */ - this.cursor_ = null; + constructor(workspace) { + /** + * The cursor. + * @type {?Cursor} + * @private + */ + this.cursor_ = null; + + /** + * The cursor's SVG element. + * @type {?SVGElement} + * @private + */ + this.cursorSvg_ = null; + + /** + * The map of markers for the workspace. + * @type {!Object} + * @private + */ + this.markers_ = Object.create(null); + + /** + * The workspace this marker manager is associated with. + * @type {!WorkspaceSvg} + * @private + */ + this.workspace_ = workspace; + + /** + * The marker's SVG element. + * @type {?SVGElement} + * @private + */ + this.markerSvg_ = null; + } /** - * The cursor's SVG element. - * @type {?SVGElement} - * @private + * Register the marker by adding it to the map of markers. + * @param {string} id A unique identifier for the marker. + * @param {!Marker} marker The marker to register. */ - this.cursorSvg_ = null; + registerMarker(id, marker) { + if (this.markers_[id]) { + this.unregisterMarker(id); + } + marker.setDrawer(this.workspace_.getRenderer().makeMarkerDrawer( + this.workspace_, marker)); + this.setMarkerSvg(marker.getDrawer().createDom()); + this.markers_[id] = marker; + } /** - * The map of markers for the workspace. - * @type {!Object} - * @private + * Unregister the marker by removing it from the map of markers. + * @param {string} id The ID of the marker to unregister. */ - this.markers_ = Object.create(null); + unregisterMarker(id) { + const marker = this.markers_[id]; + if (marker) { + marker.dispose(); + delete this.markers_[id]; + } else { + throw Error( + 'Marker with ID ' + id + ' does not exist. ' + + 'Can only unregister markers that exist.'); + } + } /** - * The workspace this marker manager is associated with. - * @type {!WorkspaceSvg} - * @private + * Get the cursor for the workspace. + * @return {?Cursor} The cursor for this workspace. */ - this.workspace_ = workspace; -}; + getCursor() { + return this.cursor_; + } + + /** + * Get a single marker that corresponds to the given ID. + * @param {string} id A unique identifier for the marker. + * @return {?Marker} The marker that corresponds to the given ID, + * or null if none exists. + */ + getMarker(id) { + return this.markers_[id] || null; + } + + /** + * Sets the cursor and initializes the drawer for use with keyboard + * navigation. + * @param {Cursor} cursor The cursor used to move around this workspace. + */ + setCursor(cursor) { + if (this.cursor_ && this.cursor_.getDrawer()) { + this.cursor_.getDrawer().dispose(); + } + this.cursor_ = cursor; + if (this.cursor_) { + const drawer = this.workspace_.getRenderer().makeMarkerDrawer( + this.workspace_, this.cursor_); + this.cursor_.setDrawer(drawer); + this.setCursorSvg(this.cursor_.getDrawer().createDom()); + } + } + + /** + * Add the cursor SVG to this workspace SVG group. + * @param {?SVGElement} cursorSvg The SVG root of the cursor to be added to + * the workspace SVG group. + * @package + */ + setCursorSvg(cursorSvg) { + if (!cursorSvg) { + this.cursorSvg_ = null; + return; + } + + this.workspace_.getBlockCanvas().appendChild(cursorSvg); + this.cursorSvg_ = cursorSvg; + } + + /** + * Add the marker SVG to this workspaces SVG group. + * @param {?SVGElement} markerSvg The SVG root of the marker to be added to + * the workspace SVG group. + * @package + */ + setMarkerSvg(markerSvg) { + if (!markerSvg) { + this.markerSvg_ = null; + return; + } + + if (this.workspace_.getBlockCanvas()) { + if (this.cursorSvg_) { + this.workspace_.getBlockCanvas().insertBefore( + markerSvg, this.cursorSvg_); + } else { + this.workspace_.getBlockCanvas().appendChild(markerSvg); + } + } + } + + /** + * Redraw the attached cursor SVG if needed. + * @package + */ + updateMarkers() { + if (this.workspace_.keyboardAccessibilityMode && this.cursorSvg_) { + this.workspace_.getCursor().draw(); + } + } + + /** + * Dispose of the marker manager. + * Go through and delete all markers associated with this marker manager. + * @suppress {checkTypes} + * @package + */ + dispose() { + const markerIds = Object.keys(this.markers_); + for (let i = 0, markerId; (markerId = markerIds[i]); i++) { + this.unregisterMarker(markerId); + } + this.markers_ = null; + if (this.cursor_) { + this.cursor_.dispose(); + this.cursor_ = null; + } + } +} /** * The name of the local marker. @@ -67,135 +210,4 @@ const MarkerManager = function(workspace) { */ MarkerManager.LOCAL_MARKER = 'local_marker_1'; -/** - * Register the marker by adding it to the map of markers. - * @param {string} id A unique identifier for the marker. - * @param {!Marker} marker The marker to register. - */ -MarkerManager.prototype.registerMarker = function(id, marker) { - if (this.markers_[id]) { - this.unregisterMarker(id); - } - marker.setDrawer( - this.workspace_.getRenderer().makeMarkerDrawer(this.workspace_, marker)); - this.setMarkerSvg(marker.getDrawer().createDom()); - this.markers_[id] = marker; -}; - -/** - * Unregister the marker by removing it from the map of markers. - * @param {string} id The ID of the marker to unregister. - */ -MarkerManager.prototype.unregisterMarker = function(id) { - const marker = this.markers_[id]; - if (marker) { - marker.dispose(); - delete this.markers_[id]; - } else { - throw Error( - 'Marker with ID ' + id + ' does not exist. ' + - 'Can only unregister markers that exist.'); - } -}; - -/** - * Get the cursor for the workspace. - * @return {?Cursor} The cursor for this workspace. - */ -MarkerManager.prototype.getCursor = function() { - return this.cursor_; -}; - -/** - * Get a single marker that corresponds to the given ID. - * @param {string} id A unique identifier for the marker. - * @return {?Marker} The marker that corresponds to the given ID, - * or null if none exists. - */ -MarkerManager.prototype.getMarker = function(id) { - return this.markers_[id] || null; -}; - -/** - * Sets the cursor and initializes the drawer for use with keyboard navigation. - * @param {Cursor} cursor The cursor used to move around this workspace. - */ -MarkerManager.prototype.setCursor = function(cursor) { - if (this.cursor_ && this.cursor_.getDrawer()) { - this.cursor_.getDrawer().dispose(); - } - this.cursor_ = cursor; - if (this.cursor_) { - const drawer = this.workspace_.getRenderer().makeMarkerDrawer( - this.workspace_, this.cursor_); - this.cursor_.setDrawer(drawer); - this.setCursorSvg(this.cursor_.getDrawer().createDom()); - } -}; - -/** - * Add the cursor SVG to this workspace SVG group. - * @param {?SVGElement} cursorSvg The SVG root of the cursor to be added to the - * workspace SVG group. - * @package - */ -MarkerManager.prototype.setCursorSvg = function(cursorSvg) { - if (!cursorSvg) { - this.cursorSvg_ = null; - return; - } - - this.workspace_.getBlockCanvas().appendChild(cursorSvg); - this.cursorSvg_ = cursorSvg; -}; - -/** - * Add the marker SVG to this workspaces SVG group. - * @param {?SVGElement} markerSvg The SVG root of the marker to be added to the - * workspace SVG group. - * @package - */ -MarkerManager.prototype.setMarkerSvg = function(markerSvg) { - if (!markerSvg) { - this.markerSvg_ = null; - return; - } - - if (this.workspace_.getBlockCanvas()) { - if (this.cursorSvg_) { - this.workspace_.getBlockCanvas().insertBefore(markerSvg, this.cursorSvg_); - } else { - this.workspace_.getBlockCanvas().appendChild(markerSvg); - } - } -}; - -/** - * Redraw the attached cursor SVG if needed. - * @package - */ -MarkerManager.prototype.updateMarkers = function() { - if (this.workspace_.keyboardAccessibilityMode && this.cursorSvg_) { - this.workspace_.getCursor().draw(); - } -}; - -/** - * Dispose of the marker manager. - * Go through and delete all markers associated with this marker manager. - * @suppress {checkTypes} - * @package - */ -MarkerManager.prototype.dispose = function() { - const markerIds = Object.keys(this.markers_); - for (let i = 0, markerId; (markerId = markerIds[i]); i++) { - this.unregisterMarker(markerId); - } - this.markers_ = null; - if (this.cursor_) { - this.cursor_.dispose(); - this.cursor_ = null; - } -}; - exports.MarkerManager = MarkerManager; diff --git a/core/mutator.js b/core/mutator.js index d1c2ba07d..97adf1b43 100644 --- a/core/mutator.js +++ b/core/mutator.js @@ -22,7 +22,6 @@ const Abstract = goog.requireType('Blockly.Events.Abstract'); const dom = goog.require('Blockly.utils.dom'); const eventUtils = goog.require('Blockly.Events.utils'); const internalConstants = goog.require('Blockly.internalConstants'); -const object = goog.require('Blockly.utils.object'); const toolbox = goog.require('Blockly.utils.toolbox'); const xml = goog.require('Blockly.utils.xml'); const {BlockChange} = goog.require('Blockly.Events.BlockChange'); @@ -49,526 +48,529 @@ goog.require('Blockly.Events.BubbleOpen'); /** * Class for a mutator dialog. - * @param {!Array} quarkNames List of names of sub-blocks for flyout. * @extends {Icon} - * @constructor - * @alias Blockly.Mutator */ -const Mutator = function(quarkNames) { - Mutator.superClass_.constructor.call(this, null); - this.quarkNames_ = quarkNames; - +class Mutator extends Icon { /** - * Workspace in the mutator's bubble. - * @type {?WorkspaceSvg} - * @private + * @param {!Array} quarkNames List of names of sub-blocks for flyout. + * @alias Blockly.Mutator */ - this.workspace_ = null; + constructor(quarkNames) { + super(null); + this.quarkNames_ = quarkNames; - /** - * Width of workspace. - * @type {number} - * @private - */ - this.workspaceWidth_ = 0; + /** + * Workspace in the mutator's bubble. + * @type {?WorkspaceSvg} + * @private + */ + this.workspace_ = null; - /** - * Height of workspace. - * @type {number} - * @private - */ - this.workspaceHeight_ = 0; + /** + * Width of workspace. + * @type {number} + * @private + */ + this.workspaceWidth_ = 0; - /** - * The SVG element that is the parent of the mutator workspace, or null if - * not created. - * @type {?SVGSVGElement} - * @private - */ - this.svgDialog_ = null; + /** + * Height of workspace. + * @type {number} + * @private + */ + this.workspaceHeight_ = 0; - /** - * The root block of the mutator workspace, created by decomposing the source - * block. - * @type {?BlockSvg} - * @private - */ - this.rootBlock_ = null; + /** + * The SVG element that is the parent of the mutator workspace, or null if + * not created. + * @type {?SVGSVGElement} + * @private + */ + this.svgDialog_ = null; - /** - * Function registered on the main workspace to update the mutator contents - * when the main workspace changes. - * @type {?Function} - * @private - */ - this.sourceListener_ = null; -}; -object.inherits(Mutator, Icon); + /** + * The root block of the mutator workspace, created by decomposing the + * source block. + * @type {?BlockSvg} + * @private + */ + this.rootBlock_ = null; -/** - * Set the block this mutator is associated with. - * @param {!BlockSvg} block The block associated with this mutator. - * @package - */ -Mutator.prototype.setBlock = function(block) { - this.block_ = block; -}; - -/** - * Returns the workspace inside this mutator icon's bubble. - * @return {?WorkspaceSvg} The workspace inside this mutator icon's - * bubble or null if the mutator isn't open. - * @package - */ -Mutator.prototype.getWorkspace = function() { - return this.workspace_; -}; - -/** - * Draw the mutator icon. - * @param {!Element} group The icon group. - * @protected - */ -Mutator.prototype.drawIcon_ = function(group) { - // Square with rounded corners. - dom.createSvgElement( - Svg.RECT, { - 'class': 'blocklyIconShape', - 'rx': '4', - 'ry': '4', - 'height': '16', - 'width': '16', - }, - group); - // Gear teeth. - dom.createSvgElement( - Svg.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', - }, - group); - // Axle hole. - dom.createSvgElement( - Svg.CIRCLE, - {'class': 'blocklyIconShape', 'r': '2.7', 'cx': '8', 'cy': '8'}, group); -}; - -/** - * Clicking on the icon toggles if the mutator bubble is visible. - * Disable if block is uneditable. - * @param {!Event} e Mouse click event. - * @protected - * @override - */ -Mutator.prototype.iconClick_ = function(e) { - if (this.block_.isEditable()) { - Icon.prototype.iconClick_.call(this, e); + /** + * Function registered on the main workspace to update the mutator contents + * when the main workspace changes. + * @type {?Function} + * @private + */ + this.sourceListener_ = null; } -}; -/** - * Create the editor for the mutator's bubble. - * @return {!SVGElement} The top-level node of the editor. - * @private - */ -Mutator.prototype.createEditor_ = function() { - /* Create the editor. Here's the markup that will be generated: - - [Workspace] - - */ - this.svgDialog_ = dom.createSvgElement( - Svg.SVG, {'x': Bubble.BORDER_WIDTH, 'y': Bubble.BORDER_WIDTH}, null); - // Convert the list of names into a list of XML objects for the flyout. - let quarkXml; - if (this.quarkNames_.length) { - quarkXml = xml.createElement('xml'); - for (let i = 0, quarkName; (quarkName = this.quarkNames_[i]); i++) { - const element = xml.createElement('block'); - element.setAttribute('type', quarkName); - quarkXml.appendChild(element); - } - } else { - quarkXml = null; + /** + * Set the block this mutator is associated with. + * @param {!BlockSvg} block The block associated with this mutator. + * @package + */ + setBlock(block) { + this.block_ = block; } - const workspaceOptions = new Options( - /** @type {!BlocklyOptions} */ - ({ - // If you want to enable disabling, also remove the - // event filter from workspaceChanged_ . - 'disable': false, - 'parentWorkspace': this.block_.workspace, - 'media': this.block_.workspace.options.pathToMedia, - 'rtl': this.block_.RTL, - 'horizontalLayout': false, - 'renderer': this.block_.workspace.options.renderer, - 'rendererOverrides': this.block_.workspace.options.rendererOverrides, - })); - workspaceOptions.toolboxPosition = - this.block_.RTL ? toolbox.Position.RIGHT : toolbox.Position.LEFT; - const hasFlyout = !!quarkXml; - if (hasFlyout) { - workspaceOptions.languageTree = toolbox.convertToolboxDefToJson(quarkXml); + + /** + * Returns the workspace inside this mutator icon's bubble. + * @return {?WorkspaceSvg} The workspace inside this mutator icon's + * bubble or null if the mutator isn't open. + * @package + */ + getWorkspace() { + return this.workspace_; } - this.workspace_ = new WorkspaceSvg(workspaceOptions); - this.workspace_.isMutator = true; - this.workspace_.addChangeListener(eventUtils.disableOrphans); - // Mutator flyouts go inside the mutator workspace's rather than in - // a top level SVG. Instead of handling scale themselves, mutators - // inherit scale from the parent workspace. - // To fix this, scale needs to be applied at a different level in the DOM. - const flyoutSvg = hasFlyout ? this.workspace_.addFlyout(Svg.G) : null; - const background = this.workspace_.createDom('blocklyMutatorBackground'); - - if (flyoutSvg) { - // Insert the flyout after the but before the block canvas so that - // the flyout is underneath in z-order. This makes blocks layering during - // dragging work properly. - background.insertBefore(flyoutSvg, this.workspace_.svgBlockCanvas_); + /** + * Draw the mutator icon. + * @param {!Element} group The icon group. + * @protected + */ + drawIcon_(group) { + // Square with rounded corners. + dom.createSvgElement( + Svg.RECT, { + 'class': 'blocklyIconShape', + 'rx': '4', + 'ry': '4', + 'height': '16', + 'width': '16', + }, + group); + // Gear teeth. + dom.createSvgElement( + Svg.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', + }, + group); + // Axle hole. + dom.createSvgElement( + Svg.CIRCLE, + {'class': 'blocklyIconShape', 'r': '2.7', 'cx': '8', 'cy': '8'}, group); } - this.svgDialog_.appendChild(background); - return this.svgDialog_; -}; - -/** - * Add or remove the UI indicating if this icon may be clicked or not. - */ -Mutator.prototype.updateEditable = function() { - Mutator.superClass_.updateEditable.call(this); - if (!this.block_.isInFlyout) { + /** + * Clicking on the icon toggles if the mutator bubble is visible. + * Disable if block is uneditable. + * @param {!Event} e Mouse click event. + * @protected + * @override + */ + iconClick_(e) { if (this.block_.isEditable()) { - if (this.iconGroup_) { - dom.removeClass( - /** @type {!Element} */ (this.iconGroup_), - 'blocklyIconGroupReadonly'); + Icon.prototype.iconClick_.call(this, e); + } + } + + /** + * Create the editor for the mutator's bubble. + * @return {!SVGElement} The top-level node of the editor. + * @private + */ + createEditor_() { + /* Create the editor. Here's the markup that will be generated: + + [Workspace] + + */ + this.svgDialog_ = dom.createSvgElement( + Svg.SVG, {'x': Bubble.BORDER_WIDTH, 'y': Bubble.BORDER_WIDTH}, null); + // Convert the list of names into a list of XML objects for the flyout. + let quarkXml; + if (this.quarkNames_.length) { + quarkXml = xml.createElement('xml'); + for (let i = 0, quarkName; (quarkName = this.quarkNames_[i]); i++) { + const element = xml.createElement('block'); + element.setAttribute('type', quarkName); + quarkXml.appendChild(element); } } else { - // Close any mutator bubble. Icon is not clickable. - this.setVisible(false); - if (this.iconGroup_) { - dom.addClass( - /** @type {!Element} */ (this.iconGroup_), - 'blocklyIconGroupReadonly'); + quarkXml = null; + } + const workspaceOptions = new Options( + /** @type {!BlocklyOptions} */ + ({ + // If you want to enable disabling, also remove the + // event filter from workspaceChanged_ . + 'disable': false, + 'parentWorkspace': this.block_.workspace, + 'media': this.block_.workspace.options.pathToMedia, + 'rtl': this.block_.RTL, + 'horizontalLayout': false, + 'renderer': this.block_.workspace.options.renderer, + 'rendererOverrides': this.block_.workspace.options.rendererOverrides, + })); + workspaceOptions.toolboxPosition = + this.block_.RTL ? toolbox.Position.RIGHT : toolbox.Position.LEFT; + const hasFlyout = !!quarkXml; + if (hasFlyout) { + workspaceOptions.languageTree = toolbox.convertToolboxDefToJson(quarkXml); + } + this.workspace_ = new WorkspaceSvg(workspaceOptions); + this.workspace_.isMutator = true; + this.workspace_.addChangeListener(eventUtils.disableOrphans); + + // Mutator flyouts go inside the mutator workspace's rather than in + // a top level SVG. Instead of handling scale themselves, mutators + // inherit scale from the parent workspace. + // To fix this, scale needs to be applied at a different level in the DOM. + const flyoutSvg = hasFlyout ? this.workspace_.addFlyout(Svg.G) : null; + const background = this.workspace_.createDom('blocklyMutatorBackground'); + + if (flyoutSvg) { + // Insert the flyout after the but before the block canvas so that + // the flyout is underneath in z-order. This makes blocks layering during + // dragging work properly. + background.insertBefore(flyoutSvg, this.workspace_.svgBlockCanvas_); + } + this.svgDialog_.appendChild(background); + + return this.svgDialog_; + } + + /** + * Add or remove the UI indicating if this icon may be clicked or not. + */ + updateEditable() { + super.updateEditable(); + if (!this.block_.isInFlyout) { + if (this.block_.isEditable()) { + if (this.iconGroup_) { + dom.removeClass( + /** @type {!Element} */ (this.iconGroup_), + 'blocklyIconGroupReadonly'); + } + } else { + // Close any mutator bubble. Icon is not clickable. + this.setVisible(false); + if (this.iconGroup_) { + dom.addClass( + /** @type {!Element} */ (this.iconGroup_), + 'blocklyIconGroupReadonly'); + } } } } -}; -/** - * Resize the bubble to match the size of the workspace. - * @private - */ -Mutator.prototype.resizeBubble_ = function() { - const doubleBorderWidth = 2 * Bubble.BORDER_WIDTH; - const workspaceSize = this.workspace_.getCanvas().getBBox(); - let width = workspaceSize.width + workspaceSize.x; - let height = workspaceSize.height + doubleBorderWidth * 3; - const flyout = this.workspace_.getFlyout(); - if (flyout) { - const flyoutScrollMetrics = - flyout.getWorkspace().getMetricsManager().getScrollMetrics(); - height = Math.max(height, flyoutScrollMetrics.height + 20); - width += flyout.getWidth(); - } - if (this.block_.RTL) { - width = -workspaceSize.x; - } - width += doubleBorderWidth * 3; - // Only resize if the size difference is significant. Eliminates shuddering. - if (Math.abs(this.workspaceWidth_ - width) > doubleBorderWidth || - Math.abs(this.workspaceHeight_ - height) > doubleBorderWidth) { - // Record some layout information for workspace metrics. - this.workspaceWidth_ = width; - this.workspaceHeight_ = height; - // Resize the bubble. - this.bubble_.setBubbleSize( - width + doubleBorderWidth, height + doubleBorderWidth); - this.svgDialog_.setAttribute('width', this.workspaceWidth_); - this.svgDialog_.setAttribute('height', this.workspaceHeight_); - this.workspace_.setCachedParentSvgSize( - this.workspaceWidth_, this.workspaceHeight_); - } - - if (this.block_.RTL) { - // Scroll the workspace to always left-align. - const translation = 'translate(' + this.workspaceWidth_ + ',0)'; - this.workspace_.getCanvas().setAttribute('transform', translation); - } - this.workspace_.resize(); -}; - -/** - * A method handler for when the bubble is moved. - * @private - */ -Mutator.prototype.onBubbleMove_ = function() { - if (this.workspace_) { - this.workspace_.recordDragTargets(); - } -}; - -/** - * Show or hide the mutator bubble. - * @param {boolean} visible True if the bubble should be visible. - */ -Mutator.prototype.setVisible = function(visible) { - if (visible === this.isVisible()) { - // No change. - return; - } - eventUtils.fire(new (eventUtils.get(eventUtils.BUBBLE_OPEN))( - this.block_, visible, 'mutator')); - if (visible) { - // Create the bubble. - this.bubble_ = new Bubble( - /** @type {!WorkspaceSvg} */ (this.block_.workspace), - this.createEditor_(), this.block_.pathObject.svgPath, - /** @type {!Coordinate} */ (this.iconXY_), null, null); - // Expose this mutator's block's ID on its top-level SVG group. - this.bubble_.setSvgId(this.block_.id); - this.bubble_.registerMoveEvent(this.onBubbleMove_.bind(this)); - const tree = this.workspace_.options.languageTree; + /** + * Resize the bubble to match the size of the workspace. + * @private + */ + resizeBubble_() { + const doubleBorderWidth = 2 * Bubble.BORDER_WIDTH; + const workspaceSize = this.workspace_.getCanvas().getBBox(); + let width = workspaceSize.width + workspaceSize.x; + let height = workspaceSize.height + doubleBorderWidth * 3; const flyout = this.workspace_.getFlyout(); - if (tree) { - flyout.init(this.workspace_); - flyout.show(tree); - } - - this.rootBlock_ = this.block_.decompose(this.workspace_); - const blocks = this.rootBlock_.getDescendants(false); - for (let i = 0, child; (child = blocks[i]); i++) { - child.render(); - } - // The root block should not be draggable or deletable. - this.rootBlock_.setMovable(false); - this.rootBlock_.setDeletable(false); - let margin; - let x; if (flyout) { - margin = flyout.CORNER_RADIUS * 2; - x = this.rootBlock_.RTL ? flyout.getWidth() + margin : margin; - } else { - margin = 16; - x = margin; + const flyoutScrollMetrics = + flyout.getWorkspace().getMetricsManager().getScrollMetrics(); + height = Math.max(height, flyoutScrollMetrics.height + 20); + width += flyout.getWidth(); } if (this.block_.RTL) { - x = -x; + width = -workspaceSize.x; } - this.rootBlock_.moveBy(x, margin); - // Save the initial connections, then listen for further changes. - if (this.block_.saveConnections) { - const thisRootBlock = this.rootBlock_; - const mutatorBlock = - /** @type {{saveConnections: function(!Block)}} */ (this.block_); - mutatorBlock.saveConnections(this.rootBlock_); - this.sourceListener_ = function() { - mutatorBlock.saveConnections(thisRootBlock); - }; - this.block_.workspace.addChangeListener(this.sourceListener_); + width += doubleBorderWidth * 3; + // Only resize if the size difference is significant. Eliminates + // shuddering. + if (Math.abs(this.workspaceWidth_ - width) > doubleBorderWidth || + Math.abs(this.workspaceHeight_ - height) > doubleBorderWidth) { + // Record some layout information for workspace metrics. + this.workspaceWidth_ = width; + this.workspaceHeight_ = height; + // Resize the bubble. + this.bubble_.setBubbleSize( + width + doubleBorderWidth, height + doubleBorderWidth); + this.svgDialog_.setAttribute('width', this.workspaceWidth_); + this.svgDialog_.setAttribute('height', this.workspaceHeight_); + this.workspace_.setCachedParentSvgSize( + this.workspaceWidth_, this.workspaceHeight_); } - this.resizeBubble_(); - // When the mutator's workspace changes, update the source block. - this.workspace_.addChangeListener(this.workspaceChanged_.bind(this)); - // Update the source block immediately after the bubble becomes visible. - this.updateWorkspace_(); - this.applyColour(); - } else { - // Dispose of the bubble. - this.svgDialog_ = null; - this.workspace_.dispose(); - this.workspace_ = null; - this.rootBlock_ = null; - this.bubble_.dispose(); - this.bubble_ = null; - this.workspaceWidth_ = 0; - this.workspaceHeight_ = 0; - if (this.sourceListener_) { - this.block_.workspace.removeChangeListener(this.sourceListener_); - this.sourceListener_ = null; + + if (this.block_.RTL) { + // Scroll the workspace to always left-align. + const translation = 'translate(' + this.workspaceWidth_ + ',0)'; + this.workspace_.getCanvas().setAttribute('transform', translation); + } + this.workspace_.resize(); + } + + /** + * A method handler for when the bubble is moved. + * @private + */ + onBubbleMove_() { + if (this.workspace_) { + this.workspace_.recordDragTargets(); } } -}; -/** - * Fired whenever a change is made to the mutator's workspace. - * @param {!Abstract} e Custom data for event. - * @private - */ -Mutator.prototype.workspaceChanged_ = function(e) { - if (!(e.isUiEvent || - (e.type === eventUtils.CHANGE && e.element === 'disabled') || - e.type === eventUtils.CREATE)) { - this.updateWorkspace_(); - } -}; - -/** - * Updates the source block when the mutator's blocks are changed. - * Bump down any block that's too high. - * @private - */ -Mutator.prototype.updateWorkspace_ = function() { - if (!this.workspace_.isDragging()) { - const blocks = this.workspace_.getTopBlocks(false); - const MARGIN = 20; - - for (let b = 0, block; (block = blocks[b]); b++) { - const blockXY = block.getRelativeToSurfaceXY(); - - // Bump any block that's above the top back inside. - if (blockXY.y < MARGIN) { - block.moveBy(0, MARGIN - blockXY.y); + /** + * Show or hide the mutator bubble. + * @param {boolean} visible True if the bubble should be visible. + */ + setVisible(visible) { + if (visible === this.isVisible()) { + // No change. + return; + } + eventUtils.fire(new (eventUtils.get(eventUtils.BUBBLE_OPEN))( + this.block_, visible, 'mutator')); + if (visible) { + // Create the bubble. + this.bubble_ = new Bubble( + /** @type {!WorkspaceSvg} */ (this.block_.workspace), + this.createEditor_(), this.block_.pathObject.svgPath, + /** @type {!Coordinate} */ (this.iconXY_), null, null); + // Expose this mutator's block's ID on its top-level SVG group. + this.bubble_.setSvgId(this.block_.id); + this.bubble_.registerMoveEvent(this.onBubbleMove_.bind(this)); + const tree = this.workspace_.options.languageTree; + const flyout = this.workspace_.getFlyout(); + if (tree) { + flyout.init(this.workspace_); + flyout.show(tree); } - // Bump any block overlapping the flyout back inside. - if (block.RTL) { - let right = -MARGIN; - const flyout = this.workspace_.getFlyout(); - if (flyout) { - right -= flyout.getWidth(); - } - if (blockXY.x > right) { - block.moveBy(right - blockXY.x, 0); - } - } else if (blockXY.x < MARGIN) { - block.moveBy(MARGIN - blockXY.x, 0); + + this.rootBlock_ = this.block_.decompose(this.workspace_); + const blocks = this.rootBlock_.getDescendants(false); + for (let i = 0, child; (child = blocks[i]); i++) { + child.render(); + } + // The root block should not be draggable or deletable. + this.rootBlock_.setMovable(false); + this.rootBlock_.setDeletable(false); + let margin; + let x; + if (flyout) { + margin = flyout.CORNER_RADIUS * 2; + x = this.rootBlock_.RTL ? flyout.getWidth() + margin : margin; + } else { + margin = 16; + x = margin; + } + if (this.block_.RTL) { + x = -x; + } + this.rootBlock_.moveBy(x, margin); + // Save the initial connections, then listen for further changes. + if (this.block_.saveConnections) { + const thisRootBlock = this.rootBlock_; + const mutatorBlock = + /** @type {{saveConnections: function(!Block)}} */ (this.block_); + mutatorBlock.saveConnections(this.rootBlock_); + this.sourceListener_ = function() { + mutatorBlock.saveConnections(thisRootBlock); + }; + this.block_.workspace.addChangeListener(this.sourceListener_); } - } - } - - // When the mutator's workspace changes, update the source block. - if (this.rootBlock_.workspace === this.workspace_) { - const existingGroup = eventUtils.getGroup(); - if (!existingGroup) { - eventUtils.setGroup(true); - } - const block = /** @type {!BlockSvg} */ (this.block_); - const oldExtraState = BlockChange.getExtraBlockState_(block); - - // Switch off rendering while the source block is rebuilt. - const savedRendered = block.rendered; - // TODO(#4288): We should not be setting the rendered property to false. - block.rendered = false; - - // Allow the source block to rebuild itself. - block.compose(this.rootBlock_); - // Restore rendering and show the changes. - block.rendered = savedRendered; - // Mutation may have added some elements that need initializing. - block.initSvg(); - - if (block.rendered) { - block.render(); - } - - const newExtraState = BlockChange.getExtraBlockState_(block); - if (oldExtraState !== newExtraState) { - eventUtils.fire(new (eventUtils.get(eventUtils.BLOCK_CHANGE))( - block, 'mutation', null, oldExtraState, newExtraState)); - // Ensure that any bump is part of this mutation's event group. - const mutationGroup = eventUtils.getGroup(); - setTimeout(function() { - const oldGroup = eventUtils.getGroup(); - eventUtils.setGroup(mutationGroup); - block.bumpNeighbours(); - eventUtils.setGroup(oldGroup); - }, internalConstants.BUMP_DELAY); - } - - // Don't update the bubble until the drag has ended, to avoid moving blocks - // under the cursor. - if (!this.workspace_.isDragging()) { this.resizeBubble_(); + // When the mutator's workspace changes, update the source block. + this.workspace_.addChangeListener(this.workspaceChanged_.bind(this)); + // Update the source block immediately after the bubble becomes visible. + this.updateWorkspace_(); + this.applyColour(); + } else { + // Dispose of the bubble. + this.svgDialog_ = null; + this.workspace_.dispose(); + this.workspace_ = null; + this.rootBlock_ = null; + this.bubble_.dispose(); + this.bubble_ = null; + this.workspaceWidth_ = 0; + this.workspaceHeight_ = 0; + if (this.sourceListener_) { + this.block_.workspace.removeChangeListener(this.sourceListener_); + this.sourceListener_ = null; + } } - eventUtils.setGroup(existingGroup); } -}; -/** - * Dispose of this mutator. - */ -Mutator.prototype.dispose = function() { - this.block_.mutator = null; - Icon.prototype.dispose.call(this); -}; + /** + * Fired whenever a change is made to the mutator's workspace. + * @param {!Abstract} e Custom data for event. + * @private + */ + workspaceChanged_(e) { + if (!(e.isUiEvent || + (e.type === eventUtils.CHANGE && e.element === 'disabled') || + e.type === eventUtils.CREATE)) { + this.updateWorkspace_(); + } + } -/** - * Update the styles on all blocks in the mutator. - * @public - */ -Mutator.prototype.updateBlockStyle = function() { - const ws = this.workspace_; + /** + * Updates the source block when the mutator's blocks are changed. + * Bump down any block that's too high. + * @private + */ + updateWorkspace_() { + if (!this.workspace_.isDragging()) { + const blocks = this.workspace_.getTopBlocks(false); + const MARGIN = 20; - if (ws && ws.getAllBlocks(false)) { - const workspaceBlocks = ws.getAllBlocks(false); - for (let i = 0, block; (block = workspaceBlocks[i]); i++) { - block.setStyle(block.getStyleName()); + for (let b = 0, block; (block = blocks[b]); b++) { + const blockXY = block.getRelativeToSurfaceXY(); + + // Bump any block that's above the top back inside. + if (blockXY.y < MARGIN) { + block.moveBy(0, MARGIN - blockXY.y); + } + // Bump any block overlapping the flyout back inside. + if (block.RTL) { + let right = -MARGIN; + const flyout = this.workspace_.getFlyout(); + if (flyout) { + right -= flyout.getWidth(); + } + if (blockXY.x > right) { + block.moveBy(right - blockXY.x, 0); + } + } else if (blockXY.x < MARGIN) { + block.moveBy(MARGIN - blockXY.x, 0); + } + } } - const flyout = ws.getFlyout(); - if (flyout) { - const flyoutBlocks = flyout.workspace_.getAllBlocks(false); - for (let i = 0, block; (block = flyoutBlocks[i]); i++) { + // When the mutator's workspace changes, update the source block. + if (this.rootBlock_.workspace === this.workspace_) { + const existingGroup = eventUtils.getGroup(); + if (!existingGroup) { + eventUtils.setGroup(true); + } + const block = /** @type {!BlockSvg} */ (this.block_); + const oldExtraState = BlockChange.getExtraBlockState_(block); + + // Switch off rendering while the source block is rebuilt. + const savedRendered = block.rendered; + // TODO(#4288): We should not be setting the rendered property to false. + block.rendered = false; + + // Allow the source block to rebuild itself. + block.compose(this.rootBlock_); + // Restore rendering and show the changes. + block.rendered = savedRendered; + // Mutation may have added some elements that need initializing. + block.initSvg(); + + if (block.rendered) { + block.render(); + } + + const newExtraState = BlockChange.getExtraBlockState_(block); + if (oldExtraState !== newExtraState) { + eventUtils.fire(new (eventUtils.get(eventUtils.BLOCK_CHANGE))( + block, 'mutation', null, oldExtraState, newExtraState)); + // Ensure that any bump is part of this mutation's event group. + const mutationGroup = eventUtils.getGroup(); + setTimeout(function() { + const oldGroup = eventUtils.getGroup(); + eventUtils.setGroup(mutationGroup); + block.bumpNeighbours(); + eventUtils.setGroup(oldGroup); + }, internalConstants.BUMP_DELAY); + } + + // Don't update the bubble until the drag has ended, to avoid moving + // blocks under the cursor. + if (!this.workspace_.isDragging()) { + this.resizeBubble_(); + } + eventUtils.setGroup(existingGroup); + } + } + + /** + * Dispose of this mutator. + */ + dispose() { + this.block_.mutator = null; + Icon.prototype.dispose.call(this); + } + + /** + * Update the styles on all blocks in the mutator. + * @public + */ + updateBlockStyle() { + const ws = this.workspace_; + + if (ws && ws.getAllBlocks(false)) { + const workspaceBlocks = ws.getAllBlocks(false); + for (let i = 0, block; (block = workspaceBlocks[i]); i++) { block.setStyle(block.getStyleName()); } - } - } -}; -/** - * Reconnect an block to a mutated input. - * @param {Connection} connectionChild Connection on child block. - * @param {!Block} block Parent block. - * @param {string} inputName Name of input on parent block. - * @return {boolean} True iff a reconnection was made, false otherwise. - */ -Mutator.reconnect = function(connectionChild, block, inputName) { - if (!connectionChild || !connectionChild.getSourceBlock().workspace) { - return false; // No connection or block has been deleted. - } - const connectionParent = block.getInput(inputName).connection; - const currentParent = connectionChild.targetBlock(); - if ((!currentParent || currentParent === block) && - connectionParent.targetConnection !== connectionChild) { - if (connectionParent.isConnected()) { - // There's already something connected here. Get rid of it. - connectionParent.disconnect(); - } - connectionParent.connect(connectionChild); - return true; - } - return false; -}; - -/** - * Get the parent workspace of a workspace that is inside a mutator, taking into - * account whether it is a flyout. - * @param {Workspace} workspace The workspace that is inside a mutator. - * @return {?Workspace} The mutator's parent workspace or null. - * @public - */ -Mutator.findParentWs = function(workspace) { - let outerWs = null; - if (workspace && workspace.options) { - const parent = workspace.options.parentWorkspace; - // If we were in a flyout in a mutator, need to go up two levels to find - // the actual parent. - if (workspace.isFlyout) { - if (parent && parent.options) { - outerWs = parent.options.parentWorkspace; + const flyout = ws.getFlyout(); + if (flyout) { + const flyoutBlocks = flyout.workspace_.getAllBlocks(false); + for (let i = 0, block; (block = flyoutBlocks[i]); i++) { + block.setStyle(block.getStyleName()); + } } - } else if (parent) { - outerWs = parent; } } - return outerWs; -}; + + /** + * Reconnect an block to a mutated input. + * @param {Connection} connectionChild Connection on child block. + * @param {!Block} block Parent block. + * @param {string} inputName Name of input on parent block. + * @return {boolean} True iff a reconnection was made, false otherwise. + */ + static reconnect(connectionChild, block, inputName) { + if (!connectionChild || !connectionChild.getSourceBlock().workspace) { + return false; // No connection or block has been deleted. + } + const connectionParent = block.getInput(inputName).connection; + const currentParent = connectionChild.targetBlock(); + if ((!currentParent || currentParent === block) && + connectionParent.targetConnection !== connectionChild) { + if (connectionParent.isConnected()) { + // There's already something connected here. Get rid of it. + connectionParent.disconnect(); + } + connectionParent.connect(connectionChild); + return true; + } + return false; + } + + /** + * Get the parent workspace of a workspace that is inside a mutator, taking + * into account whether it is a flyout. + * @param {Workspace} workspace The workspace that is inside a mutator. + * @return {?Workspace} The mutator's parent workspace or null. + * @public + */ + static findParentWs(workspace) { + let outerWs = null; + if (workspace && workspace.options) { + const parent = workspace.options.parentWorkspace; + // If we were in a flyout in a mutator, need to go up two levels to find + // the actual parent. + if (workspace.isFlyout) { + if (parent && parent.options) { + outerWs = parent.options.parentWorkspace; + } + } else if (parent) { + outerWs = parent; + } + } + return outerWs; + } +} exports.Mutator = Mutator; diff --git a/core/rendered_connection.js b/core/rendered_connection.js index 08d6529ec..a85ac3c95 100644 --- a/core/rendered_connection.js +++ b/core/rendered_connection.js @@ -19,7 +19,6 @@ const common = goog.require('Blockly.common'); const dom = goog.require('Blockly.utils.dom'); const eventUtils = goog.require('Blockly.Events.utils'); const internalConstants = goog.require('Blockly.internalConstants'); -const object = goog.require('Blockly.utils.object'); const svgPaths = goog.require('Blockly.utils.svgPaths'); const svgMath = goog.require('Blockly.utils.svgMath'); /* eslint-disable-next-line no-unused-vars */ @@ -35,53 +34,527 @@ const {Svg} = goog.require('Blockly.utils.Svg'); /** - * Class for a connection between blocks that may be rendered on screen. - * @param {!BlockSvg} source The block establishing this connection. - * @param {number} type The type of the connection. - * @extends {Connection} - * @constructor - * @alias Blockly.RenderedConnection + * Maximum randomness in workspace units for bumping a block. + * @const */ -const RenderedConnection = function(source, type) { - RenderedConnection.superClass_.constructor.call(this, source, type); +const BUMP_RANDOMNESS = 10; + +/** + * Class for a connection between blocks that may be rendered on screen. + * @extends {Connection} + */ +class RenderedConnection extends Connection { + /** + * @param {!BlockSvg} source The block establishing this connection. + * @param {number} type The type of the connection. + * @alias Blockly.RenderedConnection + */ + constructor(source, type) { + super(source, type); + + /** + * Connection database for connections of this type on the current + * workspace. + * @const {!ConnectionDB} + * @private + */ + this.db_ = source.workspace.connectionDBList[type]; + + /** + * Connection database for connections compatible with this type on the + * current workspace. + * @const {!ConnectionDB} + * @private + */ + this.dbOpposite_ = + source.workspace + .connectionDBList[internalConstants.OPPOSITE_TYPE[type]]; + + /** + * Workspace units, (0, 0) is top left of block. + * @type {!Coordinate} + * @private + */ + this.offsetInBlock_ = new Coordinate(0, 0); + + /** + * Describes the state of this connection's tracked-ness. + * @type {RenderedConnection.TrackedState} + * @private + */ + this.trackedState_ = RenderedConnection.TrackedState.WILL_TRACK; + + /** + * Connection this connection connects to. Null if not connected. + * @type {RenderedConnection} + */ + this.targetConnection = null; + } /** - * Connection database for connections of this type on the current workspace. - * @const {!ConnectionDB} - * @private + * Dispose of this connection. Remove it from the database (if it is + * tracked) and call the super-function to deal with connected blocks. + * @override + * @package */ - this.db_ = source.workspace.connectionDBList[type]; + dispose() { + super.dispose(); + if (this.trackedState_ === RenderedConnection.TrackedState.TRACKED) { + this.db_.removeConnection(this, this.y); + } + } /** - * Connection database for connections compatible with this type on the - * current workspace. - * @const {!ConnectionDB} - * @private + * Get the source block for this connection. + * @return {!BlockSvg} The source block. + * @override */ - this.dbOpposite_ = - source.workspace.connectionDBList[internalConstants.OPPOSITE_TYPE[type]]; + getSourceBlock() { + return /** @type {!BlockSvg} */ (super.getSourceBlock()); + } /** - * Workspace units, (0, 0) is top left of block. - * @type {!Coordinate} - * @private + * Returns the block that this connection connects to. + * @return {?BlockSvg} The connected block or null if none is connected. + * @override */ - this.offsetInBlock_ = new Coordinate(0, 0); + targetBlock() { + return /** @type {BlockSvg} */ (super.targetBlock()); + } /** - * Describes the state of this connection's tracked-ness. - * @type {RenderedConnection.TrackedState} - * @private + * Returns the distance between this connection and another connection in + * workspace units. + * @param {!Connection} otherConnection The other connection to measure + * the distance to. + * @return {number} The distance between connections, in workspace units. */ - this.trackedState_ = RenderedConnection.TrackedState.WILL_TRACK; + distanceFrom(otherConnection) { + const xDiff = this.x - otherConnection.x; + const yDiff = this.y - otherConnection.y; + return Math.sqrt(xDiff * xDiff + yDiff * yDiff); + } /** - * Connection this connection connects to. Null if not connected. - * @type {RenderedConnection} + * Move the block(s) belonging to the connection to a point where they don't + * visually interfere with the specified connection. + * @param {!Connection} staticConnection The connection to move away + * from. + * @package */ - this.targetConnection = null; -}; -object.inherits(RenderedConnection, Connection); + bumpAwayFrom(staticConnection) { + if (this.sourceBlock_.workspace.isDragging()) { + // Don't move blocks around while the user is doing the same. + return; + } + // Move the root block. + let rootBlock = this.sourceBlock_.getRootBlock(); + if (rootBlock.isInFlyout) { + // Don't move blocks around in a flyout. + return; + } + let reverse = false; + if (!rootBlock.isMovable()) { + // Can't bump an uneditable block away. + // Check to see if the other block is movable. + rootBlock = staticConnection.getSourceBlock().getRootBlock(); + if (!rootBlock.isMovable()) { + return; + } + // Swap the connections and move the 'static' connection instead. + staticConnection = this; + reverse = true; + } + // Raise it to the top for extra visibility. + const selected = common.getSelected() == rootBlock; + selected || rootBlock.addSelect(); + let dx = (staticConnection.x + internalConstants.SNAP_RADIUS + + Math.floor(Math.random() * BUMP_RANDOMNESS)) - + this.x; + let dy = (staticConnection.y + internalConstants.SNAP_RADIUS + + Math.floor(Math.random() * BUMP_RANDOMNESS)) - + this.y; + if (reverse) { + // When reversing a bump due to an uneditable block, bump up. + dy = -dy; + } + if (rootBlock.RTL) { + dx = (staticConnection.x - internalConstants.SNAP_RADIUS - + Math.floor(Math.random() * BUMP_RANDOMNESS)) - + this.x; + } + rootBlock.moveBy(dx, dy); + selected || rootBlock.removeSelect(); + } + + /** + * Change the connection's coordinates. + * @param {number} x New absolute x coordinate, in workspace coordinates. + * @param {number} y New absolute y coordinate, in workspace coordinates. + */ + moveTo(x, y) { + if (this.trackedState_ === RenderedConnection.TrackedState.WILL_TRACK) { + this.db_.addConnection(this, y); + this.trackedState_ = RenderedConnection.TrackedState.TRACKED; + } else if (this.trackedState_ === RenderedConnection.TrackedState.TRACKED) { + this.db_.removeConnection(this, this.y); + this.db_.addConnection(this, y); + } + this.x = x; + this.y = y; + } + + /** + * Change the connection's coordinates. + * @param {number} dx Change to x coordinate, in workspace units. + * @param {number} dy Change to y coordinate, in workspace units. + */ + moveBy(dx, dy) { + this.moveTo(this.x + dx, this.y + dy); + } + + /** + * Move this connection to the location given by its offset within the block + * and the location of the block's top left corner. + * @param {!Coordinate} blockTL The location of the top left + * corner of the block, in workspace coordinates. + */ + moveToOffset(blockTL) { + this.moveTo( + blockTL.x + this.offsetInBlock_.x, blockTL.y + this.offsetInBlock_.y); + } + + /** + * Set the offset of this connection relative to the top left of its block. + * @param {number} x The new relative x, in workspace units. + * @param {number} y The new relative y, in workspace units. + */ + setOffsetInBlock(x, y) { + this.offsetInBlock_.x = x; + this.offsetInBlock_.y = y; + } + + /** + * Get the offset of this connection relative to the top left of its block. + * @return {!Coordinate} The offset of the connection. + * @package + */ + getOffsetInBlock() { + return this.offsetInBlock_; + } + + /** + * Move the blocks on either side of this connection right next to each other. + * @package + */ + tighten() { + const dx = this.targetConnection.x - this.x; + const dy = this.targetConnection.y - this.y; + if (dx !== 0 || dy !== 0) { + const block = this.targetBlock(); + const svgRoot = block.getSvgRoot(); + if (!svgRoot) { + throw Error('block is not rendered.'); + } + // Workspace coordinates. + const xy = svgMath.getRelativeXY(svgRoot); + block.getSvgRoot().setAttribute( + 'transform', 'translate(' + (xy.x - dx) + ',' + (xy.y - dy) + ')'); + block.moveConnections(-dx, -dy); + } + } + + /** + * Find the closest compatible connection to this connection. + * All parameters are in workspace units. + * @param {number} maxLimit The maximum radius to another connection. + * @param {!Coordinate} dxy Offset between this connection's location + * in the database and the current location (as a result of dragging). + * @return {!{connection: ?Connection, radius: number}} Contains two + * properties: 'connection' which is either another connection or null, + * and 'radius' which is the distance. + */ + closest(maxLimit, dxy) { + return this.dbOpposite_.searchForClosest(this, maxLimit, dxy); + } + + /** + * Add highlighting around this connection. + */ + highlight() { + let steps; + const sourceBlockSvg = /** @type {!BlockSvg} */ (this.sourceBlock_); + const renderConstants = + sourceBlockSvg.workspace.getRenderer().getConstants(); + const shape = renderConstants.shapeFor(this); + if (this.type === ConnectionType.INPUT_VALUE || + this.type === ConnectionType.OUTPUT_VALUE) { + // Vertical line, puzzle tab, vertical line. + const yLen = renderConstants.TAB_OFFSET_FROM_TOP; + steps = svgPaths.moveBy(0, -yLen) + svgPaths.lineOnAxis('v', yLen) + + shape.pathDown + svgPaths.lineOnAxis('v', yLen); + } else { + const xLen = + renderConstants.NOTCH_OFFSET_LEFT - renderConstants.CORNER_RADIUS; + // Horizontal line, notch, horizontal line. + steps = svgPaths.moveBy(-xLen, 0) + svgPaths.lineOnAxis('h', xLen) + + shape.pathLeft + svgPaths.lineOnAxis('h', xLen); + } + const xy = this.sourceBlock_.getRelativeToSurfaceXY(); + const x = this.x - xy.x; + const y = this.y - xy.y; + Connection.highlightedPath_ = dom.createSvgElement( + Svg.PATH, { + 'class': 'blocklyHighlightedConnectionPath', + 'd': steps, + 'transform': 'translate(' + x + ',' + y + ')' + + (this.sourceBlock_.RTL ? ' scale(-1 1)' : ''), + }, + this.sourceBlock_.getSvgRoot()); + } + + /** + * Remove the highlighting around this connection. + */ + unhighlight() { + dom.removeNode(Connection.highlightedPath_); + delete Connection.highlightedPath_; + } + + /** + * Set whether this connections is tracked in the database or not. + * @param {boolean} doTracking If true, start tracking. If false, stop + * tracking. + * @package + */ + setTracking(doTracking) { + if ((doTracking && + this.trackedState_ === RenderedConnection.TrackedState.TRACKED) || + (!doTracking && + this.trackedState_ === RenderedConnection.TrackedState.UNTRACKED)) { + return; + } + if (this.sourceBlock_.isInFlyout) { + // Don't bother maintaining a database of connections in a flyout. + return; + } + if (doTracking) { + this.db_.addConnection(this, this.y); + this.trackedState_ = RenderedConnection.TrackedState.TRACKED; + return; + } + if (this.trackedState_ === RenderedConnection.TrackedState.TRACKED) { + this.db_.removeConnection(this, this.y); + } + this.trackedState_ = RenderedConnection.TrackedState.UNTRACKED; + } + + /** + * Stop tracking this connection, as well as all down-stream connections on + * any block attached to this connection. This happens when a block is + * collapsed. + * + * Also closes down-stream icons/bubbles. + * @package + */ + stopTrackingAll() { + this.setTracking(false); + if (this.targetConnection) { + const blocks = this.targetBlock().getDescendants(false); + for (let i = 0; i < blocks.length; i++) { + const block = blocks[i]; + // Stop tracking connections of all children. + const connections = block.getConnections_(true); + for (let j = 0; j < connections.length; j++) { + /** @type {!RenderedConnection} */ (connections[j]) + .setTracking(false); + } + // Close all bubbles of all children. + const icons = block.getIcons(); + for (let j = 0; j < icons.length; j++) { + icons[j].setVisible(false); + } + } + } + } + + /** + * Start tracking this connection, as well as all down-stream connections on + * any block attached to this connection. This happens when a block is + * expanded. + * @return {!Array} List of blocks to render. + */ + startTrackingAll() { + this.setTracking(true); + // All blocks that are not tracked must start tracking before any + // rendering takes place, since rendering requires knowing the dimensions + // of lower blocks. Also, since rendering a block renders all its parents, + // we only need to render the leaf nodes. + let renderList = []; + if (this.type !== ConnectionType.INPUT_VALUE && + this.type !== ConnectionType.NEXT_STATEMENT) { + // Only spider down. + return renderList; + } + const block = this.targetBlock(); + if (block) { + let connections; + if (block.isCollapsed()) { + // This block should only be partially revealed since it is collapsed. + connections = []; + block.outputConnection && connections.push(block.outputConnection); + block.nextConnection && connections.push(block.nextConnection); + block.previousConnection && connections.push(block.previousConnection); + } else { + // Show all connections of this block. + connections = block.getConnections_(true); + } + for (let i = 0; i < connections.length; i++) { + renderList.push.apply(renderList, connections[i].startTrackingAll()); + } + if (!renderList.length) { + // Leaf block. + renderList = [block]; + } + } + return renderList; + } + + /** + * Behavior after a connection attempt fails. + * Bumps this connection away from the other connection. Called when an + * attempted connection fails. + * @param {!Connection} otherConnection Connection that this connection + * failed to connect to. + * @package + */ + onFailedConnect(otherConnection) { + const block = this.getSourceBlock(); + if (eventUtils.getRecordUndo()) { + const group = eventUtils.getGroup(); + setTimeout(function() { + if (!block.isDisposed() && !block.getParent()) { + eventUtils.setGroup(group); + this.bumpAwayFrom(otherConnection); + eventUtils.setGroup(false); + } + }.bind(this), internalConstants.BUMP_DELAY); + } + } + + /** + * Disconnect two blocks that are connected by this connection. + * @param {!Block} parentBlock The superior block. + * @param {!Block} childBlock The inferior block. + * @protected + * @override + */ + disconnectInternal_(parentBlock, childBlock) { + super.disconnectInternal_(parentBlock, childBlock); + // Rerender the parent so that it may reflow. + if (parentBlock.rendered) { + parentBlock.render(); + } + if (childBlock.rendered) { + childBlock.updateDisabled(); + childBlock.render(); + // Reset visibility, since the child is now a top block. + childBlock.getSvgRoot().style.display = 'block'; + } + } + + /** + * Respawn the shadow block if there was one connected to the this connection. + * Render/rerender blocks as needed. + * @protected + * @override + */ + respawnShadow_() { + super.respawnShadow_(); + const blockShadow = this.targetBlock(); + if (!blockShadow) { + return; + } + blockShadow.initSvg(); + blockShadow.render(false); + + const parentBlock = this.getSourceBlock(); + if (parentBlock.rendered) { + parentBlock.render(); + } + } + + /** + * Find all nearby compatible connections to this connection. + * Type checking does not apply, since this function is used for bumping. + * @param {number} maxLimit The maximum radius to another connection, in + * workspace units. + * @return {!Array} List of connections. + * @package + */ + neighbours(maxLimit) { + return this.dbOpposite_.getNeighbours(this, maxLimit); + } + + /** + * Connect two connections together. This is the connection on the superior + * block. Rerender blocks as needed. + * @param {!Connection} childConnection Connection on inferior block. + * @protected + */ + connect_(childConnection) { + super.connect_(childConnection); + + const parentConnection = this; + const parentBlock = parentConnection.getSourceBlock(); + const childBlock = childConnection.getSourceBlock(); + const parentRendered = parentBlock.rendered; + const childRendered = childBlock.rendered; + + if (parentRendered) { + parentBlock.updateDisabled(); + } + if (childRendered) { + childBlock.updateDisabled(); + } + if (parentRendered && childRendered) { + if (parentConnection.type === ConnectionType.NEXT_STATEMENT || + parentConnection.type === ConnectionType.PREVIOUS_STATEMENT) { + // Child block may need to square off its corners if it is in a stack. + // Rendering a child will render its parent. + childBlock.render(); + } else { + // Child block does not change shape. Rendering the parent node will + // move its connected children into position. + parentBlock.render(); + } + } + + // The input the child block is connected to (if any). + const parentInput = parentBlock.getInputWithBlock(childBlock); + if (parentInput) { + const visible = parentInput.isVisible(); + childBlock.getSvgRoot().style.display = visible ? 'block' : 'none'; + } + } + + /** + * Function to be called when this connection's compatible types have changed. + * @protected + */ + onCheckChanged_() { + // The new value type may not be compatible with the existing connection. + if (this.isConnected() && + (!this.targetConnection || + !this.getConnectionChecker().canConnect( + this, this.targetConnection, false))) { + const child = this.isSuperior() ? this.targetBlock() : this.sourceBlock_; + child.unplug(); + // Bump away. + this.sourceBlock_.bumpNeighbours(); + } + } +} /** * Enum for different kinds of tracked states. @@ -101,475 +574,4 @@ RenderedConnection.TrackedState = { TRACKED: 1, }; -/** - * Maximum randomness in workspace units for bumping a block. - * @const - */ -const BUMP_RANDOMNESS = 10; - -/** - * Dispose of this connection. Remove it from the database (if it is - * tracked) and call the super-function to deal with connected blocks. - * @override - * @package - */ -RenderedConnection.prototype.dispose = function() { - RenderedConnection.superClass_.dispose.call(this); - if (this.trackedState_ === RenderedConnection.TrackedState.TRACKED) { - this.db_.removeConnection(this, this.y); - } -}; - -/** - * Get the source block for this connection. - * @return {!BlockSvg} The source block. - * @override - */ -RenderedConnection.prototype.getSourceBlock = function() { - return /** @type {!BlockSvg} */ ( - RenderedConnection.superClass_.getSourceBlock.call(this)); -}; - -/** - * Returns the block that this connection connects to. - * @return {?BlockSvg} The connected block or null if none is connected. - * @override - */ -RenderedConnection.prototype.targetBlock = function() { - return /** @type {BlockSvg} */ ( - RenderedConnection.superClass_.targetBlock.call(this)); -}; - -/** - * Returns the distance between this connection and another connection in - * workspace units. - * @param {!Connection} otherConnection The other connection to measure - * the distance to. - * @return {number} The distance between connections, in workspace units. - */ -RenderedConnection.prototype.distanceFrom = function(otherConnection) { - const xDiff = this.x - otherConnection.x; - const yDiff = this.y - otherConnection.y; - return Math.sqrt(xDiff * xDiff + yDiff * yDiff); -}; - -/** - * Move the block(s) belonging to the connection to a point where they don't - * visually interfere with the specified connection. - * @param {!Connection} staticConnection The connection to move away - * from. - * @package - */ -RenderedConnection.prototype.bumpAwayFrom = function(staticConnection) { - if (this.sourceBlock_.workspace.isDragging()) { - // Don't move blocks around while the user is doing the same. - return; - } - // Move the root block. - let rootBlock = this.sourceBlock_.getRootBlock(); - if (rootBlock.isInFlyout) { - // Don't move blocks around in a flyout. - return; - } - let reverse = false; - if (!rootBlock.isMovable()) { - // Can't bump an uneditable block away. - // Check to see if the other block is movable. - rootBlock = staticConnection.getSourceBlock().getRootBlock(); - if (!rootBlock.isMovable()) { - return; - } - // Swap the connections and move the 'static' connection instead. - staticConnection = this; - reverse = true; - } - // Raise it to the top for extra visibility. - const selected = common.getSelected() == rootBlock; - selected || rootBlock.addSelect(); - let dx = (staticConnection.x + internalConstants.SNAP_RADIUS + - Math.floor(Math.random() * BUMP_RANDOMNESS)) - - this.x; - let dy = (staticConnection.y + internalConstants.SNAP_RADIUS + - Math.floor(Math.random() * BUMP_RANDOMNESS)) - - this.y; - if (reverse) { - // When reversing a bump due to an uneditable block, bump up. - dy = -dy; - } - if (rootBlock.RTL) { - dx = (staticConnection.x - internalConstants.SNAP_RADIUS - - Math.floor(Math.random() * BUMP_RANDOMNESS)) - - this.x; - } - rootBlock.moveBy(dx, dy); - selected || rootBlock.removeSelect(); -}; - -/** - * Change the connection's coordinates. - * @param {number} x New absolute x coordinate, in workspace coordinates. - * @param {number} y New absolute y coordinate, in workspace coordinates. - */ -RenderedConnection.prototype.moveTo = function(x, y) { - if (this.trackedState_ === RenderedConnection.TrackedState.WILL_TRACK) { - this.db_.addConnection(this, y); - this.trackedState_ = RenderedConnection.TrackedState.TRACKED; - } else if (this.trackedState_ === RenderedConnection.TrackedState.TRACKED) { - this.db_.removeConnection(this, this.y); - this.db_.addConnection(this, y); - } - this.x = x; - this.y = y; -}; - -/** - * Change the connection's coordinates. - * @param {number} dx Change to x coordinate, in workspace units. - * @param {number} dy Change to y coordinate, in workspace units. - */ -RenderedConnection.prototype.moveBy = function(dx, dy) { - this.moveTo(this.x + dx, this.y + dy); -}; - -/** - * Move this connection to the location given by its offset within the block and - * the location of the block's top left corner. - * @param {!Coordinate} blockTL The location of the top left - * corner of the block, in workspace coordinates. - */ -RenderedConnection.prototype.moveToOffset = function(blockTL) { - this.moveTo( - blockTL.x + this.offsetInBlock_.x, blockTL.y + this.offsetInBlock_.y); -}; - -/** - * Set the offset of this connection relative to the top left of its block. - * @param {number} x The new relative x, in workspace units. - * @param {number} y The new relative y, in workspace units. - */ -RenderedConnection.prototype.setOffsetInBlock = function(x, y) { - this.offsetInBlock_.x = x; - this.offsetInBlock_.y = y; -}; - -/** - * Get the offset of this connection relative to the top left of its block. - * @return {!Coordinate} The offset of the connection. - * @package - */ -RenderedConnection.prototype.getOffsetInBlock = function() { - return this.offsetInBlock_; -}; - -/** - * Move the blocks on either side of this connection right next to each other. - * @package - */ -RenderedConnection.prototype.tighten = function() { - const dx = this.targetConnection.x - this.x; - const dy = this.targetConnection.y - this.y; - if (dx !== 0 || dy !== 0) { - const block = this.targetBlock(); - const svgRoot = block.getSvgRoot(); - if (!svgRoot) { - throw Error('block is not rendered.'); - } - // Workspace coordinates. - const xy = svgMath.getRelativeXY(svgRoot); - block.getSvgRoot().setAttribute( - 'transform', 'translate(' + (xy.x - dx) + ',' + (xy.y - dy) + ')'); - block.moveConnections(-dx, -dy); - } -}; - -/** - * Find the closest compatible connection to this connection. - * All parameters are in workspace units. - * @param {number} maxLimit The maximum radius to another connection. - * @param {!Coordinate} dxy Offset between this connection's location - * in the database and the current location (as a result of dragging). - * @return {!{connection: ?Connection, radius: number}} Contains two - * properties: 'connection' which is either another connection or null, - * and 'radius' which is the distance. - */ -RenderedConnection.prototype.closest = function(maxLimit, dxy) { - return this.dbOpposite_.searchForClosest(this, maxLimit, dxy); -}; - -/** - * Add highlighting around this connection. - */ -RenderedConnection.prototype.highlight = function() { - let steps; - const sourceBlockSvg = /** @type {!BlockSvg} */ (this.sourceBlock_); - const renderConstants = sourceBlockSvg.workspace.getRenderer().getConstants(); - const shape = renderConstants.shapeFor(this); - if (this.type === ConnectionType.INPUT_VALUE || - this.type === ConnectionType.OUTPUT_VALUE) { - // Vertical line, puzzle tab, vertical line. - const yLen = renderConstants.TAB_OFFSET_FROM_TOP; - steps = svgPaths.moveBy(0, -yLen) + svgPaths.lineOnAxis('v', yLen) + - shape.pathDown + svgPaths.lineOnAxis('v', yLen); - } else { - const xLen = - renderConstants.NOTCH_OFFSET_LEFT - renderConstants.CORNER_RADIUS; - // Horizontal line, notch, horizontal line. - steps = svgPaths.moveBy(-xLen, 0) + svgPaths.lineOnAxis('h', xLen) + - shape.pathLeft + svgPaths.lineOnAxis('h', xLen); - } - const xy = this.sourceBlock_.getRelativeToSurfaceXY(); - const x = this.x - xy.x; - const y = this.y - xy.y; - Connection.highlightedPath_ = dom.createSvgElement( - Svg.PATH, { - 'class': 'blocklyHighlightedConnectionPath', - 'd': steps, - 'transform': 'translate(' + x + ',' + y + ')' + - (this.sourceBlock_.RTL ? ' scale(-1 1)' : ''), - }, - this.sourceBlock_.getSvgRoot()); -}; - -/** - * Remove the highlighting around this connection. - */ -RenderedConnection.prototype.unhighlight = function() { - dom.removeNode(Connection.highlightedPath_); - delete Connection.highlightedPath_; -}; - -/** - * Set whether this connections is tracked in the database or not. - * @param {boolean} doTracking If true, start tracking. If false, stop tracking. - * @package - */ -RenderedConnection.prototype.setTracking = function(doTracking) { - if ((doTracking && - this.trackedState_ === RenderedConnection.TrackedState.TRACKED) || - (!doTracking && - this.trackedState_ === RenderedConnection.TrackedState.UNTRACKED)) { - return; - } - if (this.sourceBlock_.isInFlyout) { - // Don't bother maintaining a database of connections in a flyout. - return; - } - if (doTracking) { - this.db_.addConnection(this, this.y); - this.trackedState_ = RenderedConnection.TrackedState.TRACKED; - return; - } - if (this.trackedState_ === RenderedConnection.TrackedState.TRACKED) { - this.db_.removeConnection(this, this.y); - } - this.trackedState_ = RenderedConnection.TrackedState.UNTRACKED; -}; - -/** - * Stop tracking this connection, as well as all down-stream connections on - * any block attached to this connection. This happens when a block is - * collapsed. - * - * Also closes down-stream icons/bubbles. - * @package - */ -RenderedConnection.prototype.stopTrackingAll = function() { - this.setTracking(false); - if (this.targetConnection) { - const blocks = this.targetBlock().getDescendants(false); - for (let i = 0; i < blocks.length; i++) { - const block = blocks[i]; - // Stop tracking connections of all children. - const connections = block.getConnections_(true); - for (let j = 0; j < connections.length; j++) { - connections[j].setTracking(false); - } - // Close all bubbles of all children. - const icons = block.getIcons(); - for (let j = 0; j < icons.length; j++) { - icons[j].setVisible(false); - } - } - } -}; - -/** - * Start tracking this connection, as well as all down-stream connections on - * any block attached to this connection. This happens when a block is expanded. - * @return {!Array} List of blocks to render. - */ -RenderedConnection.prototype.startTrackingAll = function() { - this.setTracking(true); - // All blocks that are not tracked must start tracking before any - // rendering takes place, since rendering requires knowing the dimensions - // of lower blocks. Also, since rendering a block renders all its parents, - // we only need to render the leaf nodes. - let renderList = []; - if (this.type !== ConnectionType.INPUT_VALUE && - this.type !== ConnectionType.NEXT_STATEMENT) { - // Only spider down. - return renderList; - } - const block = this.targetBlock(); - if (block) { - let connections; - if (block.isCollapsed()) { - // This block should only be partially revealed since it is collapsed. - connections = []; - block.outputConnection && connections.push(block.outputConnection); - block.nextConnection && connections.push(block.nextConnection); - block.previousConnection && connections.push(block.previousConnection); - } else { - // Show all connections of this block. - connections = block.getConnections_(true); - } - for (let i = 0; i < connections.length; i++) { - renderList.push.apply(renderList, connections[i].startTrackingAll()); - } - if (!renderList.length) { - // Leaf block. - renderList = [block]; - } - } - return renderList; -}; - -/** - * Behavior after a connection attempt fails. - * Bumps this connection away from the other connection. Called when an - * attempted connection fails. - * @param {!Connection} otherConnection Connection that this connection - * failed to connect to. - * @package - */ -RenderedConnection.prototype.onFailedConnect = function(otherConnection) { - const block = this.getSourceBlock(); - if (eventUtils.getRecordUndo()) { - const group = eventUtils.getGroup(); - setTimeout(function() { - if (!block.isDisposed() && !block.getParent()) { - eventUtils.setGroup(group); - this.bumpAwayFrom(otherConnection); - eventUtils.setGroup(false); - } - }.bind(this), internalConstants.BUMP_DELAY); - } -}; - - -/** - * Disconnect two blocks that are connected by this connection. - * @param {!Block} parentBlock The superior block. - * @param {!Block} childBlock The inferior block. - * @protected - * @override - */ -RenderedConnection.prototype.disconnectInternal_ = function( - parentBlock, childBlock) { - RenderedConnection.superClass_.disconnectInternal_.call( - this, parentBlock, childBlock); - // Rerender the parent so that it may reflow. - if (parentBlock.rendered) { - parentBlock.render(); - } - if (childBlock.rendered) { - childBlock.updateDisabled(); - childBlock.render(); - // Reset visibility, since the child is now a top block. - childBlock.getSvgRoot().style.display = 'block'; - } -}; - -/** - * Respawn the shadow block if there was one connected to the this connection. - * Render/rerender blocks as needed. - * @protected - * @override - */ -RenderedConnection.prototype.respawnShadow_ = function() { - RenderedConnection.superClass_.respawnShadow_.call(this); - const blockShadow = this.targetBlock(); - if (!blockShadow) { - return; - } - blockShadow.initSvg(); - blockShadow.render(false); - - const parentBlock = this.getSourceBlock(); - if (parentBlock.rendered) { - parentBlock.render(); - } -}; - -/** - * Find all nearby compatible connections to this connection. - * Type checking does not apply, since this function is used for bumping. - * @param {number} maxLimit The maximum radius to another connection, in - * workspace units. - * @return {!Array} List of connections. - * @package - */ -RenderedConnection.prototype.neighbours = function(maxLimit) { - return this.dbOpposite_.getNeighbours(this, maxLimit); -}; - -/** - * Connect two connections together. This is the connection on the superior - * block. Rerender blocks as needed. - * @param {!Connection} childConnection Connection on inferior block. - * @protected - */ -RenderedConnection.prototype.connect_ = function(childConnection) { - RenderedConnection.superClass_.connect_.call(this, childConnection); - - const parentConnection = this; - const parentBlock = parentConnection.getSourceBlock(); - const childBlock = childConnection.getSourceBlock(); - const parentRendered = parentBlock.rendered; - const childRendered = childBlock.rendered; - - if (parentRendered) { - parentBlock.updateDisabled(); - } - if (childRendered) { - childBlock.updateDisabled(); - } - if (parentRendered && childRendered) { - if (parentConnection.type === ConnectionType.NEXT_STATEMENT || - parentConnection.type === ConnectionType.PREVIOUS_STATEMENT) { - // Child block may need to square off its corners if it is in a stack. - // Rendering a child will render its parent. - childBlock.render(); - } else { - // Child block does not change shape. Rendering the parent node will - // move its connected children into position. - parentBlock.render(); - } - } - - // The input the child block is connected to (if any). - const parentInput = parentBlock.getInputWithBlock(childBlock); - if (parentInput) { - const visible = parentInput.isVisible(); - childBlock.getSvgRoot().style.display = visible ? 'block' : 'none'; - } -}; - -/** - * Function to be called when this connection's compatible types have changed. - * @protected - */ -RenderedConnection.prototype.onCheckChanged_ = function() { - // The new value type may not be compatible with the existing connection. - if (this.isConnected() && - (!this.targetConnection || - !this.getConnectionChecker().canConnect( - this, this.targetConnection, false))) { - const child = this.isSuperior() ? this.targetBlock() : this.sourceBlock_; - child.unplug(); - // Bump away. - this.sourceBlock_.bumpNeighbours(); - } -}; - exports.RenderedConnection = RenderedConnection; diff --git a/core/renderers/common/constants.js b/core/renderers/common/constants.js index 295ccf368..1c21b7195 100644 --- a/core/renderers/common/constants.js +++ b/core/renderers/common/constants.js @@ -31,1212 +31,1220 @@ const {Theme} = goog.requireType('Blockly.Theme'); /** * An object that provides constants for rendering blocks. - * @constructor - * @package - * @alias Blockly.blockRendering.ConstantProvider */ -const ConstantProvider = function() { +class ConstantProvider { /** - * The size of an empty spacer. - * @type {number} - */ - this.NO_PADDING = 0; - - /** - * The size of small padding. - * @type {number} - */ - this.SMALL_PADDING = 3; - - /** - * The size of medium padding. - * @type {number} - */ - this.MEDIUM_PADDING = 5; - - /** - * The size of medium-large padding. - * @type {number} - */ - this.MEDIUM_LARGE_PADDING = 8; - - /** - * The size of large padding. - * @type {number} - */ - this.LARGE_PADDING = 10; - - /** - * Offset from the top of the row for placing fields on inline input rows - * and statement input rows. - * Matches existing rendering (in 2019). - * @type {number} - */ - this.TALL_INPUT_FIELD_OFFSET_Y = this.MEDIUM_PADDING; - - /** - * The height of the puzzle tab used for input and output connections. - * @type {number} - */ - this.TAB_HEIGHT = 15; - - /** - * The offset from the top of the block at which a puzzle tab is positioned. - * @type {number} - */ - this.TAB_OFFSET_FROM_TOP = 5; - - /** - * Vertical overlap of the puzzle tab, used to make it look more like a puzzle - * piece. - * @type {number} - */ - this.TAB_VERTICAL_OVERLAP = 2.5; - - /** - * The width of the puzzle tab used for input and output connections. - * @type {number} - */ - this.TAB_WIDTH = 8; - - /** - * The width of the notch used for previous and next connections. - * @type {number} - */ - this.NOTCH_WIDTH = 15; - - /** - * The height of the notch used for previous and next connections. - * @type {number} - */ - this.NOTCH_HEIGHT = 4; - - /** - * The minimum width of the block. - * @type {number} - */ - this.MIN_BLOCK_WIDTH = 12; - - this.EMPTY_BLOCK_SPACER_HEIGHT = 16; - - /** - * The minimum height of a dummy input row. - * @type {number} - */ - this.DUMMY_INPUT_MIN_HEIGHT = this.TAB_HEIGHT; - - /** - * The minimum height of a dummy input row in a shadow block. - * @type {number} - */ - this.DUMMY_INPUT_SHADOW_MIN_HEIGHT = this.TAB_HEIGHT; - - /** - * Rounded corner radius. - * @type {number} - */ - this.CORNER_RADIUS = 8; - - /** - * Offset from the left side of a block or the inside of a statement input to - * the left side of the notch. - * @type {number} - */ - this.NOTCH_OFFSET_LEFT = 15; - - /** - * Additional offset added to the statement input's width to account for the - * notch. - * @type {number} - */ - this.STATEMENT_INPUT_NOTCH_OFFSET = this.NOTCH_OFFSET_LEFT; - - this.STATEMENT_BOTTOM_SPACER = 0; - this.STATEMENT_INPUT_PADDING_LEFT = 20; - - /** - * Vertical padding between consecutive statement inputs. - * @type {number} - */ - this.BETWEEN_STATEMENT_PADDING_Y = 4; - - /** - * The top row's minimum height. - * @type {number} - */ - this.TOP_ROW_MIN_HEIGHT = this.MEDIUM_PADDING; - - /** - * The top row's minimum height if it precedes a statement. - * @type {number} - */ - this.TOP_ROW_PRECEDES_STATEMENT_MIN_HEIGHT = this.LARGE_PADDING; - - /** - * The bottom row's minimum height. - * @type {number} - */ - this.BOTTOM_ROW_MIN_HEIGHT = this.MEDIUM_PADDING; - - /** - * The bottom row's minimum height if it follows a statement input. - * @type {number} - */ - this.BOTTOM_ROW_AFTER_STATEMENT_MIN_HEIGHT = this.LARGE_PADDING; - - /** - * Whether to add a 'hat' on top of all blocks with no previous or output - * connections. Can be overridden by 'hat' property on Theme.BlockStyle. - * @type {boolean} - */ - this.ADD_START_HATS = false; - - /** - * Height of the top hat. - * @type {number} - */ - this.START_HAT_HEIGHT = 15; - - /** - * Width of the top hat. - * @type {number} - */ - this.START_HAT_WIDTH = 100; - - this.SPACER_DEFAULT_HEIGHT = 15; - - this.MIN_BLOCK_HEIGHT = 24; - - this.EMPTY_INLINE_INPUT_PADDING = 14.5; - - /** - * The height of an empty inline input. - * @type {number} - */ - this.EMPTY_INLINE_INPUT_HEIGHT = this.TAB_HEIGHT + 11; - - this.EXTERNAL_VALUE_INPUT_PADDING = 2; - - /** - * The height of an empty statement input. Note that in the old rendering - * this varies slightly depending on whether the block has external or inline - * inputs. In the new rendering this is consistent. It seems unlikely that - * the old behaviour was intentional. - * @type {number} - */ - this.EMPTY_STATEMENT_INPUT_HEIGHT = this.MIN_BLOCK_HEIGHT; - - this.START_POINT = svgPaths.moveBy(0, 0); - - /** - * Height of SVG path for jagged teeth at the end of collapsed blocks. - * @type {number} - */ - this.JAGGED_TEETH_HEIGHT = 12; - - /** - * Width of SVG path for jagged teeth at the end of collapsed blocks. - * @type {number} - */ - this.JAGGED_TEETH_WIDTH = 6; - - /** - * Point size of text. - * @type {number} - */ - this.FIELD_TEXT_FONTSIZE = 11; - - /** - * Text font weight. - * @type {string} - */ - this.FIELD_TEXT_FONTWEIGHT = 'normal'; - - /** - * Text font family. - * @type {string} - */ - this.FIELD_TEXT_FONTFAMILY = 'sans-serif'; - - /** - * Height of text. This constant is dynamically set in ``setFontConstants_`` - * to be the height of the text based on the font used. - * @type {number} - */ - this.FIELD_TEXT_HEIGHT = -1; // Dynamically set. - - /** - * Text baseline. This constant is dynamically set in ``setFontConstants_`` - * to be the baseline of the text based on the font used. - * @type {number} - */ - this.FIELD_TEXT_BASELINE = -1; // Dynamically set. - - /** - * A field's border rect corner radius. - * @type {number} - */ - this.FIELD_BORDER_RECT_RADIUS = 4; - - /** - * A field's border rect default height. - * @type {number} - */ - this.FIELD_BORDER_RECT_HEIGHT = 16; - - /** - * A field's border rect X padding. - * @type {number} - */ - this.FIELD_BORDER_RECT_X_PADDING = 5; - - /** - * A field's border rect Y padding. - * @type {number} - */ - this.FIELD_BORDER_RECT_Y_PADDING = 3; - - /** - * The backing colour of a field's border rect. - * @type {string} * @package + * @alias Blockly.blockRendering.ConstantProvider */ - this.FIELD_BORDER_RECT_COLOUR = '#fff'; + constructor() { + /** + * The size of an empty spacer. + * @type {number} + */ + this.NO_PADDING = 0; - /** - * A field's text element's dominant baseline. - * @type {boolean} - */ - this.FIELD_TEXT_BASELINE_CENTER = !userAgent.IE && !userAgent.EDGE; + /** + * The size of small padding. + * @type {number} + */ + this.SMALL_PADDING = 3; - /** - * A dropdown field's border rect height. - * @type {number} - */ - this.FIELD_DROPDOWN_BORDER_RECT_HEIGHT = this.FIELD_BORDER_RECT_HEIGHT; + /** + * The size of medium padding. + * @type {number} + */ + this.MEDIUM_PADDING = 5; - /** - * Whether or not a dropdown field should add a border rect when in a shadow - * block. - * @type {boolean} - */ - this.FIELD_DROPDOWN_NO_BORDER_RECT_SHADOW = false; + /** + * The size of medium-large padding. + * @type {number} + */ + this.MEDIUM_LARGE_PADDING = 8; - /** - * Whether or not a dropdown field's div should be coloured to match the - * block colours. - * @type {boolean} - */ - this.FIELD_DROPDOWN_COLOURED_DIV = false; + /** + * The size of large padding. + * @type {number} + */ + this.LARGE_PADDING = 10; - /** - * Whether or not a dropdown field uses a text or SVG arrow. - * @type {boolean} - */ - this.FIELD_DROPDOWN_SVG_ARROW = false; + /** + * Offset from the top of the row for placing fields on inline input rows + * and statement input rows. + * Matches existing rendering (in 2019). + * @type {number} + */ + this.TALL_INPUT_FIELD_OFFSET_Y = this.MEDIUM_PADDING; - /** - * A dropdown field's SVG arrow padding. - * @type {number} - */ - this.FIELD_DROPDOWN_SVG_ARROW_PADDING = this.FIELD_BORDER_RECT_X_PADDING; + /** + * The height of the puzzle tab used for input and output connections. + * @type {number} + */ + this.TAB_HEIGHT = 15; - /** - * A dropdown field's SVG arrow size. - * @type {number} - */ - this.FIELD_DROPDOWN_SVG_ARROW_SIZE = 12; + /** + * The offset from the top of the block at which a puzzle tab is positioned. + * @type {number} + */ + this.TAB_OFFSET_FROM_TOP = 5; - /** - * A dropdown field's SVG arrow datauri. - * @type {string} - */ - this.FIELD_DROPDOWN_SVG_ARROW_DATAURI = - 'data:image/svg+xml;base64,PHN2ZyBpZD0iTGF5ZXJfMSIgZGF0YS1uYW1lPSJMYXllci' + - 'AxIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxMi43MSIgaG' + - 'VpZ2h0PSI4Ljc5IiB2aWV3Qm94PSIwIDAgMTIuNzEgOC43OSI+PHRpdGxlPmRyb3Bkb3duLW' + - 'Fycm93PC90aXRsZT48ZyBvcGFjaXR5PSIwLjEiPjxwYXRoIGQ9Ik0xMi43MSwyLjQ0QTIuND' + - 'EsMi40MSwwLDAsMSwxMiw0LjE2TDguMDgsOC4wOGEyLjQ1LDIuNDUsMCwwLDEtMy40NSwwTD' + - 'AuNzIsNC4xNkEyLjQyLDIuNDIsMCwwLDEsMCwyLjQ0LDIuNDgsMi40OCwwLDAsMSwuNzEuNz' + - 'FDMSwwLjQ3LDEuNDMsMCw2LjM2LDBTMTEuNzUsMC40NiwxMiwuNzFBMi40NCwyLjQ0LDAsMC' + - 'wxLDEyLjcxLDIuNDRaIiBmaWxsPSIjMjMxZjIwIi8+PC9nPjxwYXRoIGQ9Ik02LjM2LDcuNz' + - 'lhMS40MywxLjQzLDAsMCwxLTEtLjQyTDEuNDIsMy40NWExLjQ0LDEuNDQsMCwwLDEsMC0yYz' + - 'AuNTYtLjU2LDkuMzEtMC41Niw5Ljg3LDBhMS40NCwxLjQ0LDAsMCwxLDAsMkw3LjM3LDcuMz' + - 'dBMS40MywxLjQzLDAsMCwxLDYuMzYsNy43OVoiIGZpbGw9IiNmZmYiLz48L3N2Zz4='; + /** + * Vertical overlap of the puzzle tab, used to make it look more like a + * puzzle piece. + * @type {number} + */ + this.TAB_VERTICAL_OVERLAP = 2.5; - /** - * Whether or not to show a box shadow around the widget div. This is only a - * feature of full block fields. - * @type {boolean} - */ - this.FIELD_TEXTINPUT_BOX_SHADOW = false; + /** + * The width of the puzzle tab used for input and output connections. + * @type {number} + */ + this.TAB_WIDTH = 8; - /** - * Whether or not the colour field should display its colour value on the - * entire block. - * @type {boolean} - */ - this.FIELD_COLOUR_FULL_BLOCK = false; + /** + * The width of the notch used for previous and next connections. + * @type {number} + */ + this.NOTCH_WIDTH = 15; - /** - * A colour field's default width. - * @type {number} - */ - this.FIELD_COLOUR_DEFAULT_WIDTH = 26; + /** + * The height of the notch used for previous and next connections. + * @type {number} + */ + this.NOTCH_HEIGHT = 4; - /** - * A colour field's default height. - * @type {number} - */ - this.FIELD_COLOUR_DEFAULT_HEIGHT = this.FIELD_BORDER_RECT_HEIGHT; + /** + * The minimum width of the block. + * @type {number} + */ + this.MIN_BLOCK_WIDTH = 12; - /** - * A checkbox field's X offset. - * @type {number} - */ - this.FIELD_CHECKBOX_X_OFFSET = this.FIELD_BORDER_RECT_X_PADDING - 3; + this.EMPTY_BLOCK_SPACER_HEIGHT = 16; - /** - * A random identifier used to ensure a unique ID is used for each - * filter/pattern for the case of multiple Blockly instances on a page. - * @type {string} - * @package - */ - this.randomIdentifier = String(Math.random()).substring(2); + /** + * The minimum height of a dummy input row. + * @type {number} + */ + this.DUMMY_INPUT_MIN_HEIGHT = this.TAB_HEIGHT; - /** - * The defs tag that contains all filters and patterns for this Blockly - * instance. - * @type {?SVGElement} - * @private - */ - this.defs_ = null; + /** + * The minimum height of a dummy input row in a shadow block. + * @type {number} + */ + this.DUMMY_INPUT_SHADOW_MIN_HEIGHT = this.TAB_HEIGHT; - /** - * The ID of the emboss filter, or the empty string if no filter is set. - * @type {string} - * @package - */ - this.embossFilterId = ''; + /** + * Rounded corner radius. + * @type {number} + */ + this.CORNER_RADIUS = 8; - /** - * The element to use for highlighting, or null if not set. - * @type {SVGElement} - * @private - */ - this.embossFilter_ = null; + /** + * Offset from the left side of a block or the inside of a statement input + * to the left side of the notch. + * @type {number} + */ + this.NOTCH_OFFSET_LEFT = 15; - /** - * The ID of the disabled pattern, or the empty string if no pattern is set. - * @type {string} - * @package - */ - this.disabledPatternId = ''; + /** + * Additional offset added to the statement input's width to account for the + * notch. + * @type {number} + */ + this.STATEMENT_INPUT_NOTCH_OFFSET = this.NOTCH_OFFSET_LEFT; - /** - * The element to use for disabled blocks, or null if not set. - * @type {SVGElement} - * @private - */ - this.disabledPattern_ = null; + this.STATEMENT_BOTTOM_SPACER = 0; + this.STATEMENT_INPUT_PADDING_LEFT = 20; - /** - * The ID of the debug filter, or the empty string if no pattern is set. - * @type {string} - * @package - */ - this.debugFilterId = ''; + /** + * Vertical padding between consecutive statement inputs. + * @type {number} + */ + this.BETWEEN_STATEMENT_PADDING_Y = 4; - /** - * The element to use for a debug highlight, or null if not set. - * @type {SVGElement} - * @private - */ - this.debugFilter_ = null; + /** + * The top row's minimum height. + * @type {number} + */ + this.TOP_ROW_MIN_HEIGHT = this.MEDIUM_PADDING; - /** - * The +
diff --git a/tests/playgrounds/blockly.mjs b/tests/playgrounds/blockly.mjs new file mode 100644 index 000000000..dcbc95a6d --- /dev/null +++ b/tests/playgrounds/blockly.mjs @@ -0,0 +1,38 @@ +/** + * @license + * Copyright 2022 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ + +/** + * @fileoverview Finishes loading Blockly and exports it as this + * module's default export. + * + * It is exported as the default export to avoid having to + * re-export each property on Blockly individually, because you + * can't do: + * + * export * from ; // SYNTAX ERROR + * + * You must use a '); + // Load dependency graph info from test/deps.js. To update + // deps.js, run `npm run build:deps`. + document.write(''); + + // Msg loading kludge. This should go away once #5409 and/or + // #1895 are fixed. + + // Load messages into a temporary Blockly.Msg object, deleting it + // afterwards (after saving the messages!) + window.Blockly = {Msg: Object.create(null)}; + document.write(''); + document.write(` + `); + + document.write(` + `); + } else { + // We need to load Blockly in compiled mode. + + // Load blockly_compressed.js et al. using '); + document.write(''); + document.write(''); + document.write(''); + document.write(''); + document.write(''); + document.write(''); + document.write(''); + } +})(); From 0c1362ff1cfe79c0064840ad1fbef44967a62f5b Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 23 Feb 2022 11:50:14 -0800 Subject: [PATCH 080/128] chore(deps): bump webdriverio from 7.16.14 to 7.16.15 (#5935) Bumps [webdriverio](https://github.com/webdriverio/webdriverio) from 7.16.14 to 7.16.15. - [Release notes](https://github.com/webdriverio/webdriverio/releases) - [Changelog](https://github.com/webdriverio/webdriverio/blob/main/CHANGELOG.md) - [Commits](https://github.com/webdriverio/webdriverio/compare/v7.16.14...v7.16.15) --- updated-dependencies: - dependency-name: webdriverio dependency-type: direct:development update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- package-lock.json | 160 ++++++++++++++++++++++------------------------ 1 file changed, 76 insertions(+), 84 deletions(-) diff --git a/package-lock.json b/package-lock.json index 5e75095e9..901d47b98 100644 --- a/package-lock.json +++ b/package-lock.json @@ -2885,6 +2885,15 @@ "node": ">= 6" } }, + "node_modules/cross-fetch": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/cross-fetch/-/cross-fetch-3.1.5.tgz", + "integrity": "sha512-lvb1SBsI0Z7GDwmuid+mU3kWVBwTVUbe7S0H52yaaAdQOXq2YktTCZdlAcNKFzE6QtRz0snpw9bNiPeOIkkQvw==", + "dev": true, + "dependencies": { + "node-fetch": "2.6.7" + } + }, "node_modules/cross-spawn": { "version": "7.0.3", "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.3.tgz", @@ -3252,9 +3261,9 @@ } }, "node_modules/devtools": { - "version": "7.16.14", - "resolved": "https://registry.npmjs.org/devtools/-/devtools-7.16.14.tgz", - "integrity": "sha512-cmTl4D/4BgKFf4ceaUB4CTd8uqFZrBT/9IU81bx/dasX+YmkJIjQpECYo+uHspyQLW6AdjZPPv39eG4YFpaLIw==", + "version": "7.16.15", + "resolved": "https://registry.npmjs.org/devtools/-/devtools-7.16.15.tgz", + "integrity": "sha512-34WOK2tzeFiIvu1nln0Gwjxwo0slt75ATloI9cNnEtW21NM5PrWwcMUjn6Gl2kLl0eqtLVH+uHhBgInbT4qvFg==", "dev": true, "dependencies": { "@types/node": "^17.0.4", @@ -3266,7 +3275,7 @@ "@wdio/utils": "7.16.14", "chrome-launcher": "^0.15.0", "edge-paths": "^2.1.0", - "puppeteer-core": "^13.0.0", + "puppeteer-core": "^13.1.3", "query-selector-shadow-dom": "^1.0.0", "ua-parser-js": "^1.0.1", "uuid": "^8.0.0" @@ -3276,15 +3285,15 @@ } }, "node_modules/devtools-protocol": { - "version": "0.0.964462", - "resolved": "https://registry.npmjs.org/devtools-protocol/-/devtools-protocol-0.0.964462.tgz", - "integrity": "sha512-8rv6vWn+v0eYLTJKMlb3L2I3XT8jpbx3H3OmpD6e1W4QwbnOd0VrPXr/kr+U5vGLqTTRVGW7wePOJnikHN4bGw==", + "version": "0.0.966116", + "resolved": "https://registry.npmjs.org/devtools-protocol/-/devtools-protocol-0.0.966116.tgz", + "integrity": "sha512-uCqUDw5Y4ajQoFqGdYbvjrVdsXqlDb54JcmEPO4kpXjSU+Szyisi2BQDfnSVLeHRDELmzOcm9reZ959slDwD7g==", "dev": true }, "node_modules/devtools/node_modules/@types/node": { - "version": "17.0.14", - "resolved": "https://registry.npmjs.org/@types/node/-/node-17.0.14.tgz", - "integrity": "sha512-SbjLmERksKOGzWzPNuW7fJM7fk3YXVTFiZWB/Hs99gwhk+/dnrQRPBQjPW9aO+fi1tAffi9PrwFvsmOKmDTyng==", + "version": "17.0.17", + "resolved": "https://registry.npmjs.org/@types/node/-/node-17.0.17.tgz", + "integrity": "sha512-e8PUNQy1HgJGV3iU/Bp2+D/DXh3PYeyli8LgIwsQcs1Ar1LoaWHSIT6Rw+H2rNJmiq6SNWiDytfx8+gYj7wDHw==", "dev": true }, "node_modules/devtools/node_modules/@wdio/config": { @@ -9332,55 +9341,38 @@ } }, "node_modules/puppeteer-core": { - "version": "13.1.3", - "resolved": "https://registry.npmjs.org/puppeteer-core/-/puppeteer-core-13.1.3.tgz", - "integrity": "sha512-96pzvVBzq5lUGt3L/QrIH3mxn3NfZylHeusNhq06xBAHPI0Upc0SC/9u7tXjL0oRnmcExeVRJivr1lj7Ah/yDQ==", + "version": "13.3.1", + "resolved": "https://registry.npmjs.org/puppeteer-core/-/puppeteer-core-13.3.1.tgz", + "integrity": "sha512-II9uo5MFh+otoJSoYp/kfY3jf1iWt0ySKyK8vFVfdbn3rl+k3SLh9nQRdINyoO1Kt6Tk4dPp6GZipD9jgU9wmw==", "dev": true, "dependencies": { - "debug": "4.3.2", - "devtools-protocol": "0.0.948846", + "cross-fetch": "3.1.5", + "debug": "4.3.3", + "devtools-protocol": "0.0.960912", "extract-zip": "2.0.1", "https-proxy-agent": "5.0.0", - "node-fetch": "2.6.7", "pkg-dir": "4.2.0", "progress": "2.0.3", "proxy-from-env": "1.1.0", "rimraf": "3.0.2", "tar-fs": "2.1.1", "unbzip2-stream": "1.4.3", - "ws": "8.2.3" + "ws": "8.5.0" }, "engines": { "node": ">=10.18.1" } }, - "node_modules/puppeteer-core/node_modules/debug": { - "version": "4.3.2", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.2.tgz", - "integrity": "sha512-mOp8wKcvj7XxC78zLgw/ZA+6TSgkoE2C/ienthhRD298T7UNwAg9diBpLRxC0mOezLl4B0xV7M0cCO6P/O0Xhw==", - "dev": true, - "dependencies": { - "ms": "2.1.2" - }, - "engines": { - "node": ">=6.0" - }, - "peerDependenciesMeta": { - "supports-color": { - "optional": true - } - } - }, "node_modules/puppeteer-core/node_modules/devtools-protocol": { - "version": "0.0.948846", - "resolved": "https://registry.npmjs.org/devtools-protocol/-/devtools-protocol-0.0.948846.tgz", - "integrity": "sha512-5fGyt9xmMqUl2VI7+rnUkKCiAQIpLns8sfQtTENy5L70ktbNw0Z3TFJ1JoFNYdx/jffz4YXU45VF75wKZD7sZQ==", + "version": "0.0.960912", + "resolved": "https://registry.npmjs.org/devtools-protocol/-/devtools-protocol-0.0.960912.tgz", + "integrity": "sha512-I3hWmV9rWHbdnUdmMKHF2NuYutIM2kXz2mdXW8ha7TbRlGTVs+PF+PsB5QWvpCek4Fy9B+msiispCfwlhG5Sqg==", "dev": true }, "node_modules/puppeteer-core/node_modules/ws": { - "version": "8.2.3", - "resolved": "https://registry.npmjs.org/ws/-/ws-8.2.3.tgz", - "integrity": "sha512-wBuoj1BDpC6ZQ1B7DWQBYVLphPWkm8i9Y0/3YdHjHKHiohOJ1ws+3OccDWtH+PoC9DZD5WOTrJvNbWvjS6JWaA==", + "version": "8.5.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.5.0.tgz", + "integrity": "sha512-BWX0SWVgLPzYwF8lTzEy1egjhS4S4OEAHfsO8o65WOVsrnSRGaSiUaa9e0ggGlkMTtBlmOpEXiie9RUcBO86qg==", "dev": true, "engines": { "node": ">=10.0.0" @@ -11884,9 +11876,9 @@ } }, "node_modules/webdriverio": { - "version": "7.16.14", - "resolved": "https://registry.npmjs.org/webdriverio/-/webdriverio-7.16.14.tgz", - "integrity": "sha512-uzGGT0vXkkm5WKFwdr3MuzrKaqKERlikoaoO57bSFiwM3uBIQQqQPdwbwOMtwDaDH9Vjy+qEMtLvtTZEmp3oEg==", + "version": "7.16.15", + "resolved": "https://registry.npmjs.org/webdriverio/-/webdriverio-7.16.15.tgz", + "integrity": "sha512-f9Hdn0CTX2y1E3kbN/6QLUXo0JZlnnhPkuJbBlSJMV3+/xFj5MBcBszJBT5Frwzcs48YNikimPbR79VLxfX3AA==", "dev": true, "dependencies": { "@types/aria-query": "^5.0.0", @@ -11901,8 +11893,8 @@ "aria-query": "^5.0.0", "css-shorthand-properties": "^1.1.1", "css-value": "^0.0.1", - "devtools": "7.16.14", - "devtools-protocol": "^0.0.964462", + "devtools": "7.16.15", + "devtools-protocol": "^0.0.966116", "fs-extra": "^10.0.0", "get-port": "^5.1.1", "grapheme-splitter": "^1.0.2", @@ -11911,7 +11903,7 @@ "lodash.isplainobject": "^4.0.6", "lodash.zip": "^4.2.0", "minimatch": "^3.0.4", - "puppeteer-core": "^13.0.0", + "puppeteer-core": "^13.1.3", "query-selector-shadow-dom": "^1.0.0", "resq": "^1.9.1", "rgb2hex": "0.2.5", @@ -14638,6 +14630,15 @@ } } }, + "cross-fetch": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/cross-fetch/-/cross-fetch-3.1.5.tgz", + "integrity": "sha512-lvb1SBsI0Z7GDwmuid+mU3kWVBwTVUbe7S0H52yaaAdQOXq2YktTCZdlAcNKFzE6QtRz0snpw9bNiPeOIkkQvw==", + "dev": true, + "requires": { + "node-fetch": "2.6.7" + } + }, "cross-spawn": { "version": "7.0.3", "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.3.tgz", @@ -14927,9 +14928,9 @@ "dev": true }, "devtools": { - "version": "7.16.14", - "resolved": "https://registry.npmjs.org/devtools/-/devtools-7.16.14.tgz", - "integrity": "sha512-cmTl4D/4BgKFf4ceaUB4CTd8uqFZrBT/9IU81bx/dasX+YmkJIjQpECYo+uHspyQLW6AdjZPPv39eG4YFpaLIw==", + "version": "7.16.15", + "resolved": "https://registry.npmjs.org/devtools/-/devtools-7.16.15.tgz", + "integrity": "sha512-34WOK2tzeFiIvu1nln0Gwjxwo0slt75ATloI9cNnEtW21NM5PrWwcMUjn6Gl2kLl0eqtLVH+uHhBgInbT4qvFg==", "dev": true, "requires": { "@types/node": "^17.0.4", @@ -14941,16 +14942,16 @@ "@wdio/utils": "7.16.14", "chrome-launcher": "^0.15.0", "edge-paths": "^2.1.0", - "puppeteer-core": "^13.0.0", + "puppeteer-core": "^13.1.3", "query-selector-shadow-dom": "^1.0.0", "ua-parser-js": "^1.0.1", "uuid": "^8.0.0" }, "dependencies": { "@types/node": { - "version": "17.0.14", - "resolved": "https://registry.npmjs.org/@types/node/-/node-17.0.14.tgz", - "integrity": "sha512-SbjLmERksKOGzWzPNuW7fJM7fk3YXVTFiZWB/Hs99gwhk+/dnrQRPBQjPW9aO+fi1tAffi9PrwFvsmOKmDTyng==", + "version": "17.0.17", + "resolved": "https://registry.npmjs.org/@types/node/-/node-17.0.17.tgz", + "integrity": "sha512-e8PUNQy1HgJGV3iU/Bp2+D/DXh3PYeyli8LgIwsQcs1Ar1LoaWHSIT6Rw+H2rNJmiq6SNWiDytfx8+gYj7wDHw==", "dev": true }, "@wdio/config": { @@ -14995,9 +14996,9 @@ } }, "devtools-protocol": { - "version": "0.0.964462", - "resolved": "https://registry.npmjs.org/devtools-protocol/-/devtools-protocol-0.0.964462.tgz", - "integrity": "sha512-8rv6vWn+v0eYLTJKMlb3L2I3XT8jpbx3H3OmpD6e1W4QwbnOd0VrPXr/kr+U5vGLqTTRVGW7wePOJnikHN4bGw==", + "version": "0.0.966116", + "resolved": "https://registry.npmjs.org/devtools-protocol/-/devtools-protocol-0.0.966116.tgz", + "integrity": "sha512-uCqUDw5Y4ajQoFqGdYbvjrVdsXqlDb54JcmEPO4kpXjSU+Szyisi2BQDfnSVLeHRDELmzOcm9reZ959slDwD7g==", "dev": true }, "diff": { @@ -19816,44 +19817,35 @@ "integrity": "sha512-XRsRjdf+j5ml+y/6GKHPZbrF/8p2Yga0JPtdqTIY2Xe5ohJPD9saDJJLPvp9+NSBprVvevdXZybnj2cv8OEd0A==" }, "puppeteer-core": { - "version": "13.1.3", - "resolved": "https://registry.npmjs.org/puppeteer-core/-/puppeteer-core-13.1.3.tgz", - "integrity": "sha512-96pzvVBzq5lUGt3L/QrIH3mxn3NfZylHeusNhq06xBAHPI0Upc0SC/9u7tXjL0oRnmcExeVRJivr1lj7Ah/yDQ==", + "version": "13.3.1", + "resolved": "https://registry.npmjs.org/puppeteer-core/-/puppeteer-core-13.3.1.tgz", + "integrity": "sha512-II9uo5MFh+otoJSoYp/kfY3jf1iWt0ySKyK8vFVfdbn3rl+k3SLh9nQRdINyoO1Kt6Tk4dPp6GZipD9jgU9wmw==", "dev": true, "requires": { - "debug": "4.3.2", - "devtools-protocol": "0.0.948846", + "cross-fetch": "3.1.5", + "debug": "4.3.3", + "devtools-protocol": "0.0.960912", "extract-zip": "2.0.1", "https-proxy-agent": "5.0.0", - "node-fetch": "2.6.7", "pkg-dir": "4.2.0", "progress": "2.0.3", "proxy-from-env": "1.1.0", "rimraf": "3.0.2", "tar-fs": "2.1.1", "unbzip2-stream": "1.4.3", - "ws": "8.2.3" + "ws": "8.5.0" }, "dependencies": { - "debug": { - "version": "4.3.2", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.2.tgz", - "integrity": "sha512-mOp8wKcvj7XxC78zLgw/ZA+6TSgkoE2C/ienthhRD298T7UNwAg9diBpLRxC0mOezLl4B0xV7M0cCO6P/O0Xhw==", - "dev": true, - "requires": { - "ms": "2.1.2" - } - }, "devtools-protocol": { - "version": "0.0.948846", - "resolved": "https://registry.npmjs.org/devtools-protocol/-/devtools-protocol-0.0.948846.tgz", - "integrity": "sha512-5fGyt9xmMqUl2VI7+rnUkKCiAQIpLns8sfQtTENy5L70ktbNw0Z3TFJ1JoFNYdx/jffz4YXU45VF75wKZD7sZQ==", + "version": "0.0.960912", + "resolved": "https://registry.npmjs.org/devtools-protocol/-/devtools-protocol-0.0.960912.tgz", + "integrity": "sha512-I3hWmV9rWHbdnUdmMKHF2NuYutIM2kXz2mdXW8ha7TbRlGTVs+PF+PsB5QWvpCek4Fy9B+msiispCfwlhG5Sqg==", "dev": true }, "ws": { - "version": "8.2.3", - "resolved": "https://registry.npmjs.org/ws/-/ws-8.2.3.tgz", - "integrity": "sha512-wBuoj1BDpC6ZQ1B7DWQBYVLphPWkm8i9Y0/3YdHjHKHiohOJ1ws+3OccDWtH+PoC9DZD5WOTrJvNbWvjS6JWaA==", + "version": "8.5.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.5.0.tgz", + "integrity": "sha512-BWX0SWVgLPzYwF8lTzEy1egjhS4S4OEAHfsO8o65WOVsrnSRGaSiUaa9e0ggGlkMTtBlmOpEXiie9RUcBO86qg==", "dev": true, "requires": {} } @@ -21913,9 +21905,9 @@ } }, "webdriverio": { - "version": "7.16.14", - "resolved": "https://registry.npmjs.org/webdriverio/-/webdriverio-7.16.14.tgz", - "integrity": "sha512-uzGGT0vXkkm5WKFwdr3MuzrKaqKERlikoaoO57bSFiwM3uBIQQqQPdwbwOMtwDaDH9Vjy+qEMtLvtTZEmp3oEg==", + "version": "7.16.15", + "resolved": "https://registry.npmjs.org/webdriverio/-/webdriverio-7.16.15.tgz", + "integrity": "sha512-f9Hdn0CTX2y1E3kbN/6QLUXo0JZlnnhPkuJbBlSJMV3+/xFj5MBcBszJBT5Frwzcs48YNikimPbR79VLxfX3AA==", "dev": true, "requires": { "@types/aria-query": "^5.0.0", @@ -21930,8 +21922,8 @@ "aria-query": "^5.0.0", "css-shorthand-properties": "^1.1.1", "css-value": "^0.0.1", - "devtools": "7.16.14", - "devtools-protocol": "^0.0.964462", + "devtools": "7.16.15", + "devtools-protocol": "^0.0.966116", "fs-extra": "^10.0.0", "get-port": "^5.1.1", "grapheme-splitter": "^1.0.2", @@ -21940,7 +21932,7 @@ "lodash.isplainobject": "^4.0.6", "lodash.zip": "^4.2.0", "minimatch": "^3.0.4", - "puppeteer-core": "^13.0.0", + "puppeteer-core": "^13.1.3", "query-selector-shadow-dom": "^1.0.0", "resq": "^1.9.1", "rgb2hex": "0.2.5", From 5078dcbc6d4d48422313732e87191b29569b5eed Mon Sep 17 00:00:00 2001 From: Christopher Allen Date: Wed, 23 Feb 2022 21:25:52 +0000 Subject: [PATCH 081/128] refactor(blocks)!: Rename Blockly.blocks.* modules to Blockly.libraryBlocks.* (#5953) ...and rename Blockly.blocks.all (blocks/all.js) to Blockly.libraryBlocks (blocks/blocks.js BREAKING CHANGE: (only) because the exports object from the `blocks_compressed.js` chunk will be accessed as `Blockly.libraryBlocks` instead of `Blockly.blocks.all` when the chunk is loaded in a browser via a ` diff --git a/tests/mocha/index.html b/tests/mocha/index.html index b054c4af8..7d734de53 100644 --- a/tests/mocha/index.html +++ b/tests/mocha/index.html @@ -43,15 +43,15 @@ goog.require('Blockly.PHP.texts'); goog.require('Blockly.Python'); goog.require('Blockly.Python.texts'); - goog.require('Blockly.blocks.colour'); - goog.require('Blockly.blocks.logic'); - goog.require('Blockly.blocks.lists'); - goog.require('Blockly.blocks.loops'); - goog.require('Blockly.blocks.math'); - goog.require('Blockly.blocks.procedures'); - goog.require('Blockly.blocks.texts'); - goog.require('Blockly.blocks.variables'); - goog.require('Blockly.blocks.variablesDynamic'); + goog.require('Blockly.libraryBlocks.colour'); + goog.require('Blockly.libraryBlocks.logic'); + goog.require('Blockly.libraryBlocks.lists'); + goog.require('Blockly.libraryBlocks.loops'); + goog.require('Blockly.libraryBlocks.math'); + goog.require('Blockly.libraryBlocks.procedures'); + goog.require('Blockly.libraryBlocks.texts'); + goog.require('Blockly.libraryBlocks.variables'); + goog.require('Blockly.libraryBlocks.variablesDynamic'); // Run tests. goog.require('Blockly.test.astNode'); diff --git a/tests/playgrounds/advanced_playground.html b/tests/playgrounds/advanced_playground.html index e5279d74c..d322bc0e0 100644 --- a/tests/playgrounds/advanced_playground.html +++ b/tests/playgrounds/advanced_playground.html @@ -18,12 +18,12 @@ goog.require('Blockly.Themes.Zelos'); // Other. goog.require('Blockly.WorkspaceCommentSvg'); +goog.require('Blockly.libraryBlocks'); goog.require('Blockly.Dart.all'); goog.require('Blockly.JavaScript.all'); goog.require('Blockly.Lua.all'); goog.require('Blockly.PHP.all'); goog.require('Blockly.Python.all'); -goog.require('Blockly.blocks.all'); `); document.write(``); } else { document.write( ``); + document.write(``); document.write(``); document.write(``); document.write(``); document.write(``); document.write(``); - document.write(``); document.write(``); } })(); diff --git a/tests/playgrounds/prepare.js b/tests/playgrounds/prepare.js index a077cc533..8b9d534cb 100644 --- a/tests/playgrounds/prepare.js +++ b/tests/playgrounds/prepare.js @@ -55,7 +55,7 @@ goog.bootstrap( [ 'Blockly', - 'Blockly.blocks.all', + 'Blockly.libraryBlocks', 'Blockly.Dart.all', 'Blockly.JavaScript.all', 'Blockly.Lua.all', @@ -74,12 +74,12 @@ // Load blockly_compressed.js et al. using '); + document.write(''); + document.write(''); document.write(''); document.write(''); document.write(''); document.write(''); document.write(''); - document.write(''); - document.write(''); } })(); From 00a75ca0487f06ff48ffa91d1d25a0ca102f805b Mon Sep 17 00:00:00 2001 From: Christopher Allen Date: Wed, 23 Feb 2022 22:12:15 +0000 Subject: [PATCH 082/128] refactor: Be more selective in eslint ignorance (#5955) Rather than ignoring blockly_uncompressed.js, gulpfile.js and core/utils/global.js entirely, add suitable eslint-disable directives to those files so that they lint cleanly (and migrate gulpfile to use const instead of var). --- .eslintignore | 3 --- blockly_uncompressed.js | 5 ++++- core/utils/global.js | 2 ++ gulpfile.js | 17 +++++++++-------- 4 files changed, 15 insertions(+), 12 deletions(-) diff --git a/.eslintignore b/.eslintignore index 38c86f3d1..45e036d9c 100644 --- a/.eslintignore +++ b/.eslintignore @@ -1,10 +1,7 @@ *_compressed*.js -blockly_uncompressed.js -gulpfile.js /msg/* /build/* /dist/* -/core/utils/global.js /tests/blocks/* /tests/themes/* /tests/compile/* diff --git a/blockly_uncompressed.js b/blockly_uncompressed.js index 435954011..35d025f37 100644 --- a/blockly_uncompressed.js +++ b/blockly_uncompressed.js @@ -10,13 +10,15 @@ 'use strict'; +/* eslint-disable no-var */ + /** * Blockly uncompiled-mode startup code. If running in a browser * loads closure/goog/base.js and tests/deps.js, then (in any case) * requires Blockly.requires. */ (function(globalThis) { - /* eslint-disable no-undef */ + /* eslint-disable-next-line no-undef */ var IS_NODE_JS = !!(typeof module !== 'undefined' && module.exports); if (IS_NODE_JS) { @@ -52,4 +54,5 @@ // Load the rest of Blockly. document.write(''); } + /* eslint-disable-next-line no-invalid-this */ })(this); diff --git a/core/utils/global.js b/core/utils/global.js index 47bcb17a0..241e3aaec 100644 --- a/core/utils/global.js +++ b/core/utils/global.js @@ -16,6 +16,8 @@ goog.module('Blockly.utils.global'); +/* eslint-disable no-undef, no-invalid-this */ + /** * Reference to the global object. * diff --git a/gulpfile.js b/gulpfile.js index fe2a0b90f..c78ac405a 100644 --- a/gulpfile.js +++ b/gulpfile.js @@ -8,16 +8,17 @@ * @fileoverview Gulp script to build Blockly for Node & NPM. * Run this script by calling "npm install" in this directory. */ +/* eslint-env node */ -var gulp = require('gulp'); +const gulp = require('gulp'); -var buildTasks = require('./scripts/gulpfiles/build_tasks'); -var packageTasks = require('./scripts/gulpfiles/package_tasks'); -var gitTasks = require('./scripts/gulpfiles/git_tasks'); -var licenseTasks = require('./scripts/gulpfiles/license_tasks'); -var appengineTasks = require('./scripts/gulpfiles/appengine_tasks'); -var releaseTasks = require('./scripts/gulpfiles/release_tasks'); -var cleanupTasks = require('./scripts/gulpfiles/cleanup_tasks'); +const buildTasks = require('./scripts/gulpfiles/build_tasks'); +const packageTasks = require('./scripts/gulpfiles/package_tasks'); +const gitTasks = require('./scripts/gulpfiles/git_tasks'); +const licenseTasks = require('./scripts/gulpfiles/license_tasks'); +const appengineTasks = require('./scripts/gulpfiles/appengine_tasks'); +const releaseTasks = require('./scripts/gulpfiles/release_tasks'); +const cleanupTasks = require('./scripts/gulpfiles/cleanup_tasks'); module.exports = { deployDemos: appengineTasks.deployDemos, From 7e221c20deae780a4791dd6da5a70cf9dff76980 Mon Sep 17 00:00:00 2001 From: Beka Westberg Date: Wed, 23 Feb 2022 22:12:32 +0000 Subject: [PATCH 083/128] refactor: convert PathObject to an ES6 class (#5954) * refactor: add super call to geras path_object * refactor: run conversion script * clean: cleanup from conversion script * fix: make debug build happy * clean: add clarifying comment * clean: format --- core/renderers/common/path_object.js | 431 ++++++++++++++------------- core/renderers/geras/path_object.js | 253 ++++++++-------- core/renderers/zelos/path_object.js | 1 - tests/deps.js | 2 +- 4 files changed, 337 insertions(+), 350 deletions(-) diff --git a/core/renderers/common/path_object.js b/core/renderers/common/path_object.js index 7898078c8..712e16bde 100644 --- a/core/renderers/common/path_object.js +++ b/core/renderers/common/path_object.js @@ -33,248 +33,251 @@ const {Theme} = goog.requireType('Blockly.Theme'); /** * An object that handles creating and setting each of the SVG elements * used by the renderer. - * @param {!SVGElement} root The root SVG element. - * @param {!Theme.BlockStyle} style The style object to use for - * colouring. - * @param {!ConstantProvider} constants The renderer's - * constants. - * @constructor * @implements {IPathObject} - * @package - * @alias Blockly.blockRendering.PathObject */ -const PathObject = function(root, style, constants) { +class PathObject { /** - * The renderer's constant provider. - * @type {!ConstantProvider} + * @param {!SVGElement} root The root SVG element. + * @param {!Theme.BlockStyle} style The style object to use for + * colouring. + * @param {!ConstantProvider} constants The renderer's + * constants. * @package + * @alias Blockly.blockRendering.PathObject */ - this.constants = constants; + constructor(root, style, constants) { + /** + * The renderer's constant provider. + * @type {!ConstantProvider} + * @package + */ + this.constants = constants; - this.svgRoot = root; + this.svgRoot = root; - /** - * The primary path of the block. - * @type {!SVGElement} - * @package - */ - this.svgPath = - dom.createSvgElement(Svg.PATH, {'class': 'blocklyPath'}, this.svgRoot); + /** + * The primary path of the block. + * @type {!SVGElement} + * @package + */ + this.svgPath = + dom.createSvgElement(Svg.PATH, {'class': 'blocklyPath'}, this.svgRoot); - /** - * The style object to use when colouring block paths. - * @type {!Theme.BlockStyle} - * @package - */ - this.style = style; + /** + * The style object to use when colouring block paths. + * @type {!Theme.BlockStyle} + * @package + */ + this.style = style; - /** - * Holds the cursors svg element when the cursor is attached to the block. - * This is null if there is no cursor on the block. - * @type {SVGElement} - * @package - */ - this.cursorSvg = null; - - /** - * Holds the markers svg element when the marker is attached to the block. - * This is null if there is no marker on the block. - * @type {SVGElement} - * @package - */ - this.markerSvg = null; -}; - -/** - * Set the path generated by the renderer onto the respective SVG element. - * @param {string} pathString The path. - * @package - */ -PathObject.prototype.setPath = function(pathString) { - this.svgPath.setAttribute('d', pathString); -}; - -/** - * Flip the SVG paths in RTL. - * @package - */ -PathObject.prototype.flipRTL = function() { - // Mirror the block's path. - this.svgPath.setAttribute('transform', 'scale(-1 1)'); -}; - -/** - * Add the cursor SVG to this block's SVG group. - * @param {SVGElement} cursorSvg The SVG root of the cursor to be added to the - * block SVG group. - * @package - */ -PathObject.prototype.setCursorSvg = function(cursorSvg) { - if (!cursorSvg) { + /** + * Holds the cursors svg element when the cursor is attached to the block. + * This is null if there is no cursor on the block. + * @type {SVGElement} + * @package + */ this.cursorSvg = null; - return; - } - this.svgRoot.appendChild(cursorSvg); - this.cursorSvg = cursorSvg; -}; - -/** - * Add the marker SVG to this block's SVG group. - * @param {SVGElement} markerSvg The SVG root of the marker to be added to the - * block SVG group. - * @package - */ -PathObject.prototype.setMarkerSvg = function(markerSvg) { - if (!markerSvg) { + /** + * Holds the markers svg element when the marker is attached to the block. + * This is null if there is no marker on the block. + * @type {SVGElement} + * @package + */ this.markerSvg = null; - return; } - if (this.cursorSvg) { - this.svgRoot.insertBefore(markerSvg, this.cursorSvg); - } else { - this.svgRoot.appendChild(markerSvg); + /** + * Set the path generated by the renderer onto the respective SVG element. + * @param {string} pathString The path. + * @package + */ + setPath(pathString) { + this.svgPath.setAttribute('d', pathString); } - this.markerSvg = markerSvg; -}; -/** - * Apply the stored colours to the block's path, taking into account whether - * the paths belong to a shadow block. - * @param {!Block} block The source block. - * @package - */ -PathObject.prototype.applyColour = function(block) { - this.svgPath.setAttribute('stroke', this.style.colourTertiary); - this.svgPath.setAttribute('fill', this.style.colourPrimary); - - this.updateShadow_(block.isShadow()); - this.updateDisabled_(!block.isEnabled() || block.getInheritedDisabled()); -}; - -/** - * Set the style. - * @param {!Theme.BlockStyle} blockStyle The block style to use. - * @package - */ -PathObject.prototype.setStyle = function(blockStyle) { - this.style = blockStyle; -}; - -/** - * Add or remove the given CSS class on the path object's root SVG element. - * @param {string} className The name of the class to add or remove - * @param {boolean} add True if the class should be added. False if it should - * be removed. - * @protected - */ -PathObject.prototype.setClass_ = function(className, add) { - if (add) { - dom.addClass(/** @type {!Element} */ (this.svgRoot), className); - } else { - dom.removeClass(/** @type {!Element} */ (this.svgRoot), className); + /** + * Flip the SVG paths in RTL. + * @package + */ + flipRTL() { + // Mirror the block's path. + this.svgPath.setAttribute('transform', 'scale(-1 1)'); } -}; -/** - * Set whether the block shows a highlight or not. Block highlighting is - * often used to visually mark blocks currently being executed. - * @param {boolean} enable True if highlighted. - * @package - */ -PathObject.prototype.updateHighlighted = function(enable) { - if (enable) { - this.svgPath.setAttribute( - 'filter', 'url(#' + this.constants.embossFilterId + ')'); - } else { - this.svgPath.setAttribute('filter', 'none'); + /** + * Add the cursor SVG to this block's SVG group. + * @param {SVGElement} cursorSvg The SVG root of the cursor to be added to the + * block SVG group. + * @package + */ + setCursorSvg(cursorSvg) { + if (!cursorSvg) { + this.cursorSvg = null; + return; + } + + this.svgRoot.appendChild(cursorSvg); + this.cursorSvg = cursorSvg; } -}; -/** - * Updates the look of the block to reflect a shadow state. - * @param {boolean} shadow True if the block is a shadow block. - * @protected - */ -PathObject.prototype.updateShadow_ = function(shadow) { - if (shadow) { - this.svgPath.setAttribute('stroke', 'none'); - this.svgPath.setAttribute('fill', this.style.colourSecondary); + /** + * Add the marker SVG to this block's SVG group. + * @param {SVGElement} markerSvg The SVG root of the marker to be added to the + * block SVG group. + * @package + */ + setMarkerSvg(markerSvg) { + if (!markerSvg) { + this.markerSvg = null; + return; + } + + if (this.cursorSvg) { + this.svgRoot.insertBefore(markerSvg, this.cursorSvg); + } else { + this.svgRoot.appendChild(markerSvg); + } + this.markerSvg = markerSvg; } -}; -/** - * Updates the look of the block to reflect a disabled state. - * @param {boolean} disabled True if disabled. - * @protected - */ -PathObject.prototype.updateDisabled_ = function(disabled) { - this.setClass_('blocklyDisabled', disabled); - if (disabled) { - this.svgPath.setAttribute( - 'fill', 'url(#' + this.constants.disabledPatternId + ')'); + /** + * Apply the stored colours to the block's path, taking into account whether + * the paths belong to a shadow block. + * @param {!Block} block The source block. + * @package + */ + applyColour(block) { + this.svgPath.setAttribute('stroke', this.style.colourTertiary); + this.svgPath.setAttribute('fill', this.style.colourPrimary); + + this.updateShadow_(block.isShadow()); + this.updateDisabled_(!block.isEnabled() || block.getInheritedDisabled()); } -}; -/** - * Add or remove styling showing that a block is selected. - * @param {boolean} enable True if selection is enabled, false otherwise. - * @package - */ -PathObject.prototype.updateSelected = function(enable) { - this.setClass_('blocklySelected', enable); -}; + /** + * Set the style. + * @param {!Theme.BlockStyle} blockStyle The block style to use. + * @package + */ + setStyle(blockStyle) { + this.style = blockStyle; + } -/** - * Add or remove styling showing that a block is dragged over a delete area. - * @param {boolean} enable True if the block is being dragged over a delete - * area, false otherwise. - * @package - */ -PathObject.prototype.updateDraggingDelete = function(enable) { - this.setClass_('blocklyDraggingDelete', enable); -}; + /** + * Add or remove the given CSS class on the path object's root SVG element. + * @param {string} className The name of the class to add or remove + * @param {boolean} add True if the class should be added. False if it should + * be removed. + * @protected + */ + setClass_(className, add) { + if (add) { + dom.addClass(/** @type {!Element} */ (this.svgRoot), className); + } else { + dom.removeClass(/** @type {!Element} */ (this.svgRoot), className); + } + } -/** - * Add or remove styling showing that a block is an insertion marker. - * @param {boolean} enable True if the block is an insertion marker, false - * otherwise. - * @package - */ -PathObject.prototype.updateInsertionMarker = function(enable) { - this.setClass_('blocklyInsertionMarker', enable); -}; + /** + * Set whether the block shows a highlight or not. Block highlighting is + * often used to visually mark blocks currently being executed. + * @param {boolean} enable True if highlighted. + * @package + */ + updateHighlighted(enable) { + if (enable) { + this.svgPath.setAttribute( + 'filter', 'url(#' + this.constants.embossFilterId + ')'); + } else { + this.svgPath.setAttribute('filter', 'none'); + } + } -/** - * Add or remove styling showing that a block is movable. - * @param {boolean} enable True if the block is movable, false otherwise. - * @package - */ -PathObject.prototype.updateMovable = function(enable) { - this.setClass_('blocklyDraggable', enable); -}; + /** + * Updates the look of the block to reflect a shadow state. + * @param {boolean} shadow True if the block is a shadow block. + * @protected + */ + updateShadow_(shadow) { + if (shadow) { + this.svgPath.setAttribute('stroke', 'none'); + this.svgPath.setAttribute('fill', this.style.colourSecondary); + } + } -/** - * Add or remove styling that shows that if the dragging block is dropped, this - * block will be replaced. If a shadow block, it will disappear. Otherwise it - * will bump. - * @param {boolean} enable True if styling should be added. - * @package - */ -PathObject.prototype.updateReplacementFade = function(enable) { - this.setClass_('blocklyReplaceable', enable); -}; + /** + * Updates the look of the block to reflect a disabled state. + * @param {boolean} disabled True if disabled. + * @protected + */ + updateDisabled_(disabled) { + this.setClass_('blocklyDisabled', disabled); + if (disabled) { + this.svgPath.setAttribute( + 'fill', 'url(#' + this.constants.disabledPatternId + ')'); + } + } -/** - * Add or remove styling that shows that if the dragging block is dropped, this - * block will be connected to the input. - * @param {Connection} _conn The connection on the input to highlight. - * @param {boolean} _enable True if styling should be added. - * @package - */ -PathObject.prototype.updateShapeForInputHighlight = function(_conn, _enable) { - // NOP -}; + /** + * Add or remove styling showing that a block is selected. + * @param {boolean} enable True if selection is enabled, false otherwise. + * @package + */ + updateSelected(enable) { + this.setClass_('blocklySelected', enable); + } + + /** + * Add or remove styling showing that a block is dragged over a delete area. + * @param {boolean} enable True if the block is being dragged over a delete + * area, false otherwise. + * @package + */ + updateDraggingDelete(enable) { + this.setClass_('blocklyDraggingDelete', enable); + } + + /** + * Add or remove styling showing that a block is an insertion marker. + * @param {boolean} enable True if the block is an insertion marker, false + * otherwise. + * @package + */ + updateInsertionMarker(enable) { + this.setClass_('blocklyInsertionMarker', enable); + } + + /** + * Add or remove styling showing that a block is movable. + * @param {boolean} enable True if the block is movable, false otherwise. + * @package + */ + updateMovable(enable) { + this.setClass_('blocklyDraggable', enable); + } + + /** + * Add or remove styling that shows that if the dragging block is dropped, + * this block will be replaced. If a shadow block, it will disappear. + * Otherwise it will bump. + * @param {boolean} enable True if styling should be added. + * @package + */ + updateReplacementFade(enable) { + this.setClass_('blocklyReplaceable', enable); + } + + /** + * Add or remove styling that shows that if the dragging block is dropped, + * this block will be connected to the input. + * @param {Connection} _conn The connection on the input to highlight. + * @param {boolean} _enable True if styling should be added. + * @package + */ + updateShapeForInputHighlight(_conn, _enable) { + // NOP + } +} exports.PathObject = PathObject; diff --git a/core/renderers/geras/path_object.js b/core/renderers/geras/path_object.js index d8497279f..139a27579 100644 --- a/core/renderers/geras/path_object.js +++ b/core/renderers/geras/path_object.js @@ -18,7 +18,6 @@ goog.module('Blockly.geras.PathObject'); const colour = goog.require('Blockly.utils.colour'); const dom = goog.require('Blockly.utils.dom'); -const object = goog.require('Blockly.utils.object'); /* eslint-disable-next-line no-unused-vars */ const {ConstantProvider} = goog.requireType('Blockly.geras.ConstantProvider'); const {PathObject: BasePathObject} = goog.require('Blockly.blockRendering.PathObject'); @@ -30,152 +29,138 @@ const {Theme} = goog.requireType('Blockly.Theme'); /** * An object that handles creating and setting each of the SVG elements * used by the renderer. - * @param {!SVGElement} root The root SVG element. - * @param {!Theme.BlockStyle} style The style object to use for - * colouring. - * @param {!ConstantProvider} constants The renderer's constants. - * @constructor - * @extends {BasePathObject} - * @package - * @alias Blockly.geras.PathObject */ -const PathObject = function(root, style, constants) { +class PathObject extends BasePathObject { /** - * The renderer's constant provider. - * @type {!ConstantProvider} - */ - this.constants = constants; - - this.svgRoot = root; - - // The order of creation for these next three matters, because that - // effectively sets their z-indices. - - /** - * The dark path of the block. - * @type {SVGElement} + * @param {!SVGElement} root The root SVG element. + * @param {!Theme.BlockStyle} style The style object to use for + * colouring. + * @param {!ConstantProvider} constants The renderer's constants. + * @alias Blockly.geras.PathObject * @package */ - this.svgPathDark = dom.createSvgElement( - Svg.PATH, {'class': 'blocklyPathDark', 'transform': 'translate(1,1)'}, - this.svgRoot); + constructor(root, style, constants) { + super(root, style, constants); + /** + * The renderer's constant provider. + * @type {!ConstantProvider} + */ + this.constants = constants; - /** - * The primary path of the block. - * @type {!SVGElement} - * @package - */ - this.svgPath = - dom.createSvgElement(Svg.PATH, {'class': 'blocklyPath'}, this.svgRoot); + /** + * The dark path of the block. + * @type {SVGElement} + * @package + */ + this.svgPathDark = dom.createSvgElement( + Svg.PATH, {'class': 'blocklyPathDark', 'transform': 'translate(1,1)'}); - /** - * The light path of the block. - * @type {SVGElement} - * @package - */ - this.svgPathLight = dom.createSvgElement( - Svg.PATH, {'class': 'blocklyPathLight'}, this.svgRoot); + // SVG draw order is based on the order of elements (top most = back most) + // So we need to insert the dark path before the base path to make sure it + // gets drawn first. + this.svgRoot.insertBefore(this.svgPathDark, this.svgPath); - /** - * The colour of the dark path on the block in '#RRGGBB' format. - * @type {string} - * @package - */ - this.colourDark = '#000000'; + /** + * The light path of the block. + * @type {SVGElement} + * @package + */ + this.svgPathLight = dom.createSvgElement( + Svg.PATH, {'class': 'blocklyPathLight'}, this.svgRoot); - /** - * The style object to use when colouring block paths. - * @type {!Theme.BlockStyle} - * @package - */ - this.style = style; -}; -object.inherits(PathObject, BasePathObject); - -/** - * @override - */ -PathObject.prototype.setPath = function(mainPath) { - this.svgPath.setAttribute('d', mainPath); - this.svgPathDark.setAttribute('d', mainPath); -}; - -/** - * Set the highlight path generated by the renderer onto the SVG element. - * @param {string} highlightPath The highlight path. - * @package - */ -PathObject.prototype.setHighlightPath = function(highlightPath) { - this.svgPathLight.setAttribute('d', highlightPath); -}; - -/** - * @override - */ -PathObject.prototype.flipRTL = function() { - // Mirror the block's path. - this.svgPath.setAttribute('transform', 'scale(-1 1)'); - this.svgPathLight.setAttribute('transform', 'scale(-1 1)'); - this.svgPathDark.setAttribute('transform', 'translate(1,1) scale(-1 1)'); -}; - -/** - * @override - */ -PathObject.prototype.applyColour = function(block) { - this.svgPathLight.style.display = ''; - this.svgPathDark.style.display = ''; - this.svgPathLight.setAttribute('stroke', this.style.colourTertiary); - this.svgPathDark.setAttribute('fill', this.colourDark); - - PathObject.superClass_.applyColour.call(this, block); - - this.svgPath.setAttribute('stroke', 'none'); -}; - -/** - * @override - */ -PathObject.prototype.setStyle = function(blockStyle) { - this.style = blockStyle; - this.colourDark = - colour.blend('#000', this.style.colourPrimary, 0.2) || this.colourDark; -}; - -/** - * @override - */ -PathObject.prototype.updateHighlighted = function(highlighted) { - if (highlighted) { - this.svgPath.setAttribute( - 'filter', 'url(#' + this.constants.embossFilterId + ')'); - this.svgPathLight.style.display = 'none'; - } else { - this.svgPath.setAttribute('filter', 'none'); - this.svgPathLight.style.display = 'inline'; + /** + * The colour of the dark path on the block in '#RRGGBB' format. + * @type {string} + * @package + */ + this.colourDark = '#000000'; } -}; -/** - * @override - */ -PathObject.prototype.updateShadow_ = function(shadow) { - if (shadow) { - this.svgPathLight.style.display = 'none'; - this.svgPathDark.setAttribute('fill', this.style.colourSecondary); - this.svgPath.setAttribute('stroke', 'none'); - this.svgPath.setAttribute('fill', this.style.colourSecondary); + /** + * @override + */ + setPath(mainPath) { + this.svgPath.setAttribute('d', mainPath); + this.svgPathDark.setAttribute('d', mainPath); } -}; -/** - * @override - */ -PathObject.prototype.updateDisabled_ = function(disabled) { - PathObject.superClass_.updateDisabled_.call(this, disabled); - if (disabled) { + /** + * Set the highlight path generated by the renderer onto the SVG element. + * @param {string} highlightPath The highlight path. + * @package + */ + setHighlightPath(highlightPath) { + this.svgPathLight.setAttribute('d', highlightPath); + } + + /** + * @override + */ + flipRTL() { + // Mirror the block's path. + this.svgPath.setAttribute('transform', 'scale(-1 1)'); + this.svgPathLight.setAttribute('transform', 'scale(-1 1)'); + this.svgPathDark.setAttribute('transform', 'translate(1,1) scale(-1 1)'); + } + + /** + * @override + */ + applyColour(block) { + this.svgPathLight.style.display = ''; + this.svgPathDark.style.display = ''; + this.svgPathLight.setAttribute('stroke', this.style.colourTertiary); + this.svgPathDark.setAttribute('fill', this.colourDark); + + super.applyColour(block); + this.svgPath.setAttribute('stroke', 'none'); } -}; + + /** + * @override + */ + setStyle(blockStyle) { + this.style = blockStyle; + this.colourDark = + colour.blend('#000', this.style.colourPrimary, 0.2) || this.colourDark; + } + + /** + * @override + */ + updateHighlighted(highlighted) { + if (highlighted) { + this.svgPath.setAttribute( + 'filter', 'url(#' + this.constants.embossFilterId + ')'); + this.svgPathLight.style.display = 'none'; + } else { + this.svgPath.setAttribute('filter', 'none'); + this.svgPathLight.style.display = 'inline'; + } + } + + /** + * @override + */ + updateShadow_(shadow) { + if (shadow) { + this.svgPathLight.style.display = 'none'; + this.svgPathDark.setAttribute('fill', this.style.colourSecondary); + this.svgPath.setAttribute('stroke', 'none'); + this.svgPath.setAttribute('fill', this.style.colourSecondary); + } + } + + /** + * @override + */ + updateDisabled_(disabled) { + super.updateDisabled_(disabled); + if (disabled) { + this.svgPath.setAttribute('stroke', 'none'); + } + } +} exports.PathObject = PathObject; diff --git a/core/renderers/zelos/path_object.js b/core/renderers/zelos/path_object.js index 84131e166..387770eba 100644 --- a/core/renderers/zelos/path_object.js +++ b/core/renderers/zelos/path_object.js @@ -28,7 +28,6 @@ const {Theme} = goog.requireType('Blockly.Theme'); /** * An object that handles creating and setting each of the SVG elements * used by the renderer. - * @extends {BasePathObject} */ class PathObject extends BasePathObject { /** diff --git a/tests/deps.js b/tests/deps.js index 19b5c7257..f6bb165b6 100644 --- a/tests/deps.js +++ b/tests/deps.js @@ -159,7 +159,7 @@ goog.addDependency('../../core/renderers/geras/highlighter.js', ['Blockly.geras. goog.addDependency('../../core/renderers/geras/info.js', ['Blockly.geras.RenderInfo'], ['Blockly.blockRendering.ExternalValueInput', 'Blockly.blockRendering.InRowSpacer', 'Blockly.blockRendering.RenderInfo', 'Blockly.blockRendering.Types', 'Blockly.geras.InlineInput', 'Blockly.geras.StatementInput', 'Blockly.inputTypes'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/renderers/geras/measurables/inline_input.js', ['Blockly.geras.InlineInput'], ['Blockly.blockRendering.InlineInput'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/renderers/geras/measurables/statement_input.js', ['Blockly.geras.StatementInput'], ['Blockly.blockRendering.StatementInput'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/renderers/geras/path_object.js', ['Blockly.geras.PathObject'], ['Blockly.blockRendering.PathObject', 'Blockly.utils.Svg', 'Blockly.utils.colour', 'Blockly.utils.dom', 'Blockly.utils.object'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/renderers/geras/path_object.js', ['Blockly.geras.PathObject'], ['Blockly.blockRendering.PathObject', 'Blockly.utils.Svg', 'Blockly.utils.colour', 'Blockly.utils.dom'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/renderers/geras/renderer.js', ['Blockly.geras.Renderer'], ['Blockly.blockRendering', 'Blockly.blockRendering.Renderer', 'Blockly.geras.ConstantProvider', 'Blockly.geras.Drawer', 'Blockly.geras.HighlightConstantProvider', 'Blockly.geras.PathObject', 'Blockly.geras.RenderInfo'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/renderers/measurables/base.js', ['Blockly.blockRendering.Measurable'], ['Blockly.blockRendering.Types'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/renderers/measurables/bottom_row.js', ['Blockly.blockRendering.BottomRow'], ['Blockly.blockRendering.Row', 'Blockly.blockRendering.Types'], {'lang': 'es6', 'module': 'goog'}); From 00e1dade3ab5344f50156a60f95db7299884ae9b Mon Sep 17 00:00:00 2001 From: Christopher Allen Date: Thu, 24 Feb 2022 00:04:32 +0000 Subject: [PATCH 084/128] chore(build): Disable visibility warnings (#5958) Because of our mis-use of @package, and the removal of the hack that made it work reasonably (in PR #5918), compilation was generating a large number of JSC_BAD_PACKAGE_PROPERTY_ACCESS warnings, making it hard to see any other warnings/errors that might be generated. To make compiler diagnostics more useful, disable the visibility diagnostic group entirely for the time being. Also improve the documentation for JSCOMP_ERROR and the newly- -introduced JSCOMP_WARNING and JSCOMP_OFF. --- scripts/gulpfiles/build_tasks.js | 79 ++++++++++++++++++++++---------- 1 file changed, 55 insertions(+), 24 deletions(-) diff --git a/scripts/gulpfiles/build_tasks.js b/scripts/gulpfiles/build_tasks.js index 5119ba0af..b95cb7c52 100644 --- a/scripts/gulpfiles/build_tasks.js +++ b/scripts/gulpfiles/build_tasks.js @@ -168,11 +168,20 @@ function stripApacheLicense() { } /** - * Closure compiler warning groups used to treat warnings as errors. - * For a full list of closure compiler groups, consult: - * https://github.com/google/closure-compiler/blob/master/src/com/google/javascript/jscomp/DiagnosticGroups.java#L113 + * Closure compiler diagnostic groups we want to be treated as errors. + * These are effected when the --debug or --strict flags are passed. + * For a full list of closure compiler groups, consult the output of + * google-closure-compiler --help or look in the source here: + * https://github.com/google/closure-compiler/blob/master/src/com/google/javascript/jscomp/DiagnosticGroups.java#L117 + * + * The list in JSCOMP_ERROR contains all the diagnostic groups we know + * about, but some are commented out if we don't want them, and may + * appear in JSCOMP_WARNING or JSCOMP_OFF instead. Items not + * appearing on any list will default to setting provided by the + * compiler, which may vary depending on compilation level. */ var JSCOMP_ERROR = [ + // 'accessControls', // Deprecated; means same as visibility. 'checkPrototypalTypes', 'checkRegExp', 'checkTypes', @@ -185,27 +194,29 @@ var JSCOMP_ERROR = [ 'duplicateMessage', 'es5Strict', 'externsValidation', - 'extraRequire', + 'extraRequire', // Undocumented but valid. 'functionParams', 'globalThis', 'invalidCasts', 'misplacedTypeAnnotation', - // 'missingOverride', + // 'missingOverride', // There are many of these, which should be fixed. 'missingPolyfill', 'missingProperties', 'missingProvide', 'missingRequire', 'missingReturn', - // 'missingSourcesWarnings', + // 'missingSourcesWarnings', // Group of several other options. 'moduleLoad', 'msgDescriptions', 'nonStandardJsDocs', - // 'polymer', - // 'reportUnknownTypes', - // 'strictCheckTypes', - // 'strictMissingProperties', + 'partialAlias', + // 'polymer', // Not applicable. + // 'reportUnknownTypes', // VERY verbose. + // 'strictCheckTypes', // Use --strict to enable. + // 'strictMissingProperties', // Part of strictCheckTypes. + 'strictModuleChecks', // Undocumented but valid. 'strictModuleDepCheck', - // 'strictPrimitiveOperators', + // 'strictPrimitiveOperators', // Part of strictCheckTypes. 'suspiciousCode', 'typeInvalidation', 'undefinedVars', @@ -215,19 +226,38 @@ var JSCOMP_ERROR = [ 'unusedPrivateMembers', 'uselessCode', 'untranspilableFeatures', - /* In order to transition to ES modules, modules will need to import one - * another by relative paths. This means that the existing practice of moving - * all source files into the same directory for compilation (see docs for - * flattenCorePaths) would break imports. Not flattening files in this way - * breaks our usage of @package however; files were flattened so that all - * Blockly source files are in the same directory and can use @package to mark - * methods that are only allowed for use by Blockly, while still allowing - * access between e.g. core/events/* and core/utils/*. For now, we're - * downgrading access control violations (including @private) to warnings. - * Once ES module migration is complete, they will be re-enabled and an - * alternative to @package will be established. + // 'visibility', // Disabled; see note in JSCOMP_OFF. +]; + +/** + * Closure compiler diagnostic groups we want to be treated as warnings. + * These are effected when the --debug or --strict flags are passed. + */ +var JSCOMP_WARNING = [ +]; + +/** + * Closure compiler diagnostic groups we want to be ignored. + * These suppressions are always effected by default. + */ +var JSCOMP_OFF = [ + /* In order to transition to ES modules, modules will need to import + * one another by relative paths. This means that the existing + * practice of moving all source files into the same directory for + * compilation (see docs for flattenCorePaths) would break + * imports. Not flattening files in this way breaks our usage + * of @package however; files were flattened so that all Blockly + * source files are in the same directory and can use @package to + * mark methods that are only allowed for use by Blockly, while + * still allowing access between e.g. core/events/* and + * core/utils/*. We were downgrading access control violations + * (including @private) to warnings, but this ends up being so + * spammy that it makes the compiler output nearly useless. + * + * Once ES module migration is complete, they will be re-enabled and + * an alternative to @package will be established. */ - // 'visibility' + 'visibility', ]; /** @@ -514,6 +544,7 @@ function compile(options) { warning_level: argv.verbose ? 'VERBOSE' : 'DEFAULT', language_in: 'ECMASCRIPT_2020', language_out: 'ECMASCRIPT5_STRICT', + jscomp_off: [...JSCOMP_OFF], rewrite_polyfills: true, hide_warnings_for: 'node_modules', define: ['COMPILED=true'], @@ -521,6 +552,7 @@ function compile(options) { }; if (argv.debug || argv.strict) { defaultOptions.jscomp_error = [...JSCOMP_ERROR]; + defaultOptions.jscomp_warning = [...JSCOMP_WARNING]; if (argv.strict) { defaultOptions.jscomp_error.push('strictCheckTypes'); } @@ -586,7 +618,6 @@ function buildAdvancedCompilationTest() { compilation_level: 'ADVANCED_OPTIMIZATIONS', entry_point: './tests/compile/main.js', js_output_file: 'main_compressed.js', - jscomp_warning: ['visibility'], }; return gulp.src(srcs, {base: './'}) .pipe(stripApacheLicense()) From 237e66cf29c4e9704cef70e71bc9868cfc213e91 Mon Sep 17 00:00:00 2001 From: Beka Westberg Date: Fri, 25 Feb 2022 11:06:12 -0800 Subject: [PATCH 085/128] refactor: convert row.js and base.js to ES6 classes (#5957) * fix: remove unnecessary properties from rows * refactor: run conversion script on measurables * clean: cleanup from conversion * fix: make debug build happy * clean: format * fix: remove widthWithConnectedBlocks assignment on element * fix: add inline docs for statementEdge --- core/renderers/common/debugger.js | 9 +- core/renderers/common/drawer.js | 6 +- core/renderers/common/info.js | 2 +- core/renderers/geras/highlighter.js | 3 +- core/renderers/geras/info.js | 10 +- core/renderers/measurables/base.js | 59 ++-- core/renderers/measurables/input_row.js | 10 +- core/renderers/measurables/row.js | 363 ++++++++++++------------ core/renderers/measurables/top_row.js | 3 +- core/renderers/zelos/info.js | 41 ++- scripts/gulpfiles/chunks.json | 4 +- tests/deps.js | 12 +- 12 files changed, 284 insertions(+), 238 deletions(-) diff --git a/core/renderers/common/debugger.js b/core/renderers/common/debugger.js index 38c4a1b8d..032867b3a 100644 --- a/core/renderers/common/debugger.js +++ b/core/renderers/common/debugger.js @@ -9,6 +9,7 @@ */ 'use strict'; + /** * Methods for rendering debug graphics. * @class @@ -21,7 +22,9 @@ const {BlockSvg} = goog.requireType('Blockly.BlockSvg'); const {ConnectionType} = goog.require('Blockly.ConnectionType'); /* eslint-disable-next-line no-unused-vars */ const {ConstantProvider} = goog.requireType('Blockly.blockRendering.ConstantProvider'); +const {Field} = goog.require('Blockly.blockRendering.Field'); const {FieldLabel} = goog.require('Blockly.FieldLabel'); +const {InputConnection} = goog.require('Blockly.blockRendering.InputConnection'); /* eslint-disable-next-line no-unused-vars */ const {InRowSpacer} = goog.requireType('Blockly.blockRendering.InRowSpacer'); /* eslint-disable-next-line no-unused-vars */ @@ -184,7 +187,8 @@ class Debug { }, this.svgRoot_)); - if (Types.isField(elem) && elem.field instanceof FieldLabel) { + if (Types.isField(elem) && elem instanceof Field && + elem.field instanceof FieldLabel) { const baseline = this.constants_.FIELD_TEXT_BASELINE; this.debugElements_.push(dom.createSvgElement( Svg.RECT, { @@ -202,7 +206,8 @@ class Debug { } - if (Types.isInput(elem) && Debug.config.connections) { + if (Types.isInput(elem) && elem instanceof InputConnection && + Debug.config.connections) { this.drawConnection(elem.connectionModel); } } diff --git a/core/renderers/common/drawer.js b/core/renderers/common/drawer.js index 82cf7162d..3897cea26 100644 --- a/core/renderers/common/drawer.js +++ b/core/renderers/common/drawer.js @@ -19,6 +19,7 @@ const debug = goog.require('Blockly.blockRendering.debug'); const svgPaths = goog.require('Blockly.utils.svgPaths'); /* eslint-disable-next-line no-unused-vars */ const {BlockSvg} = goog.requireType('Blockly.BlockSvg'); +const {Connection} = goog.require('Blockly.blockRendering.Connection'); /* eslint-disable-next-line no-unused-vars */ const {ConstantProvider} = goog.requireType('Blockly.blockRendering.ConstantProvider'); /* eslint-disable-next-line no-unused-vars */ @@ -149,7 +150,8 @@ class Drawer { this.outlinePath_ += this.constants_.OUTSIDE_CORNERS.topLeft; } else if (Types.isRightRoundedCorner(elem)) { this.outlinePath_ += this.constants_.OUTSIDE_CORNERS.topRight; - } else if (Types.isPreviousConnection(elem)) { + } else if ( + Types.isPreviousConnection(elem) && elem instanceof Connection) { this.outlinePath_ += elem.shape.pathLeft; } else if (Types.isHat(elem)) { this.outlinePath_ += this.constants_.START_HAT.path; @@ -241,7 +243,7 @@ class Drawer { let rightCornerYOffset = 0; let outlinePath = ''; for (let i = elems.length - 1, elem; (elem = elems[i]); i--) { - if (Types.isNextConnection(elem)) { + if (Types.isNextConnection(elem) && elem instanceof Connection) { outlinePath += elem.shape.pathRight; } else if (Types.isLeftSquareCorner(elem)) { outlinePath += svgPaths.lineOnAxis('H', bottomRow.xPos); diff --git a/core/renderers/common/info.js b/core/renderers/common/info.js index bb157ecca..c9483b8aa 100644 --- a/core/renderers/common/info.js +++ b/core/renderers/common/info.js @@ -568,7 +568,7 @@ class RenderInfo { * Modify the given row to add the given amount of padding around its fields. * The exact location of the padding is based on the alignment property of the * last input in the field. - * @param {Row} row The row to add padding to. + * @param {!Row} row The row to add padding to. * @param {number} missingSpace How much padding to add. * @protected */ diff --git a/core/renderers/geras/highlighter.js b/core/renderers/geras/highlighter.js index c10206c36..dbbe15b56 100644 --- a/core/renderers/geras/highlighter.js +++ b/core/renderers/geras/highlighter.js @@ -32,6 +32,7 @@ const {RenderInfo} = goog.requireType('Blockly.geras.RenderInfo'); const {Renderer} = goog.requireType('Blockly.geras.Renderer'); /* eslint-disable-next-line no-unused-vars */ const {Row} = goog.requireType('Blockly.blockRendering.Row'); +const {SpacerRow} = goog.require('Blockly.blockRendering.SpacerRow'); /* eslint-disable-next-line no-unused-vars */ const {TopRow} = goog.require('Blockly.blockRendering.TopRow'); const {Types} = goog.require('Blockly.blockRendering.Types'); @@ -193,7 +194,7 @@ class Highlighter { */ drawRightSideRow(row) { const rightEdge = row.xPos + row.width - this.highlightOffset_; - if (row.followsStatement) { + if (row instanceof SpacerRow && row.followsStatement) { this.steps_ += svgPaths.lineOnAxis('H', rightEdge); } if (this.RTL_) { diff --git a/core/renderers/geras/info.js b/core/renderers/geras/info.js index c3964fb35..40cfd9423 100644 --- a/core/renderers/geras/info.js +++ b/core/renderers/geras/info.js @@ -386,9 +386,10 @@ class RenderInfo extends BaseRenderInfo { // Walk backgrounds through rows on the block, keeping track of the right // input edge. let nextRightEdge = 0; + const rowNextRightEdges = new WeakMap(); let prevInput = null; for (let i = this.rows.length - 1, row; (row = this.rows[i]); i--) { - row.nextRightEdge = nextRightEdge; + rowNextRightEdges.set(row, nextRightEdge); if (Types.isInputRow(row)) { if (row.hasStatement) { this.alignStatementRow_( @@ -396,7 +397,7 @@ class RenderInfo extends BaseRenderInfo { } if (prevInput && prevInput.hasStatement && row.width < prevInput.width) { - row.nextRightEdge = prevInput.width; + rowNextRightEdges.set(row, prevInput.width); } else { nextRightEdge = row.width; } @@ -411,10 +412,11 @@ class RenderInfo extends BaseRenderInfo { prevRightEdge = this.getDesiredRowWidth_(row); } else if (Types.isSpacer(row)) { // Set the spacer row to the max of the prev or next input width. - row.width = Math.max(prevRightEdge, row.nextRightEdge); + row.width = Math.max(prevRightEdge, rowNextRightEdges.get(row)); } else { const currentWidth = row.width; - const desiredWidth = Math.max(prevRightEdge, row.nextRightEdge); + const desiredWidth = + Math.max(prevRightEdge, rowNextRightEdges.get(row)); const missingSpace = desiredWidth - currentWidth; if (missingSpace > 0) { this.addAlignmentPadding_(row, missingSpace); diff --git a/core/renderers/measurables/base.js b/core/renderers/measurables/base.js index f09039a4a..1daa406b0 100644 --- a/core/renderers/measurables/base.js +++ b/core/renderers/measurables/base.js @@ -25,37 +25,40 @@ const {Types} = goog.require('Blockly.blockRendering.Types'); * The base class to represent a part of a block that takes up space during * rendering. The constructor for each non-spacer Measurable records the size * of the block element (e.g. field, statement input). - * @param {!ConstantProvider} constants The rendering - * constants provider. - * @package - * @constructor - * @alias Blockly.blockRendering.Measurable */ -const Measurable = function(constants) { - /** @type {number} */ - this.width = 0; - - /** @type {number} */ - this.height = 0; - - /** @type {number} */ - this.type = Types.NONE; - - /** @type {number} */ - this.xPos = 0; - - /** @type {number} */ - this.centerline = 0; - +class Measurable { /** - * The renderer's constant provider. - * @type {!ConstantProvider} - * @protected + * @param {!ConstantProvider} constants The rendering + * constants provider. + * @package + * @alias Blockly.blockRendering.Measurable */ - this.constants_ = constants; + constructor(constants) { + /** @type {number} */ + this.width = 0; - /** @type {number} */ - this.notchOffset = this.constants_.NOTCH_OFFSET_LEFT; -}; + /** @type {number} */ + this.height = 0; + + /** @type {number} */ + this.type = Types.NONE; + + /** @type {number} */ + this.xPos = 0; + + /** @type {number} */ + this.centerline = 0; + + /** + * The renderer's constant provider. + * @type {!ConstantProvider} + * @protected + */ + this.constants_ = constants; + + /** @type {number} */ + this.notchOffset = this.constants_.NOTCH_OFFSET_LEFT; + } +} exports.Measurable = Measurable; diff --git a/core/renderers/measurables/input_row.js b/core/renderers/measurables/input_row.js index 46eec63fe..cfff371f3 100644 --- a/core/renderers/measurables/input_row.js +++ b/core/renderers/measurables/input_row.js @@ -18,7 +18,10 @@ goog.module('Blockly.blockRendering.InputRow'); /* eslint-disable-next-line no-unused-vars */ const {ConstantProvider} = goog.requireType('Blockly.blockRendering.ConstantProvider'); +const {InputConnection} = goog.require('Blockly.blockRendering.InputConnection'); +const {ExternalValueInput} = goog.require('Blockly.blockRendering.ExternalValueInput'); const {Row} = goog.require('Blockly.blockRendering.Row'); +const {StatementInput} = goog.require('Blockly.blockRendering.StatementInput'); const {Types} = goog.require('Blockly.blockRendering.Types'); @@ -57,11 +60,12 @@ class InputRow extends Row { for (let i = 0; i < this.elements.length; i++) { const elem = this.elements[i]; this.width += elem.width; - if (Types.isInput(elem)) { - if (Types.isStatementInput(elem)) { + if (Types.isInput(elem) && elem instanceof InputConnection) { + if (Types.isStatementInput(elem) && elem instanceof StatementInput) { connectedBlockWidths += elem.connectedBlockWidth; } else if ( - Types.isExternalInput(elem) && elem.connectedBlockWidth !== 0) { + Types.isExternalInput(elem) && elem instanceof ExternalValueInput && + elem.connectedBlockWidth !== 0) { connectedBlockWidths += (elem.connectedBlockWidth - elem.connectionWidth); } diff --git a/core/renderers/measurables/row.js b/core/renderers/measurables/row.js index 40a592c7a..574b9006a 100644 --- a/core/renderers/measurables/row.js +++ b/core/renderers/measurables/row.js @@ -28,207 +28,220 @@ const {Types} = goog.require('Blockly.blockRendering.Types'); /** * An object representing a single row on a rendered block and all of its * subcomponents. - * @param {!ConstantProvider} constants The rendering - * constants provider. - * @package - * @constructor - * @alias Blockly.blockRendering.Row */ -const Row = function(constants) { +class Row { /** - * The type of this rendering object. + * @param {!ConstantProvider} constants The rendering + * constants provider. * @package - * @type {number} + * @alias Blockly.blockRendering.Row */ - this.type = Types.ROW; + constructor(constants) { + /** + * The type of this rendering object. + * @package + * @type {number} + */ + this.type = Types.ROW; - /** - * An array of elements contained in this row. - * @package - * @type {!Array} - */ - this.elements = []; + /** + * An array of elements contained in this row. + * @package + * @type {!Array} + */ + this.elements = []; - /** - * The height of the row. - * @package - * @type {number} - */ - this.height = 0; + /** + * The height of the row. + * @package + * @type {number} + */ + this.height = 0; - /** - * The width of the row, from the left edge of the block to the right. - * Does not include child blocks unless they are inline. - * @package - * @type {number} - */ - this.width = 0; + /** + * The width of the row, from the left edge of the block to the right. + * Does not include child blocks unless they are inline. + * @package + * @type {number} + */ + this.width = 0; - /** - * The minimum height of the row. - * @package - * @type {number} - */ - this.minHeight = 0; + /** + * The minimum height of the row. + * @package + * @type {number} + */ + this.minHeight = 0; - /** - * The minimum width of the row, from the left edge of the block to the right. - * Does not include child blocks unless they are inline. - * @package - * @type {number} - */ - this.minWidth = 0; + /** + * The minimum width of the row, from the left edge of the block to the + * right. Does not include child blocks unless they are inline. + * @package + * @type {number} + */ + this.minWidth = 0; - /** - * The width of the row, from the left edge of the block to the edge of the - * block or any connected child blocks. - * @package - * @type {number} - */ - this.widthWithConnectedBlocks = 0; + /** + * The width of the row, from the left edge of the block to the edge of the + * block or any connected child blocks. + * @package + * @type {number} + */ + this.widthWithConnectedBlocks = 0; - /** - * The Y position of the row relative to the origin of the block's svg group. - * @package - * @type {number} - */ - this.yPos = 0; + /** + * The Y position of the row relative to the origin of the block's svg + * group. + * @package + * @type {number} + */ + this.yPos = 0; - /** - * The X position of the row relative to the origin of the block's svg group. - * @package - * @type {number} - */ - this.xPos = 0; + /** + * The X position of the row relative to the origin of the block's svg + * group. + * @package + * @type {number} + */ + this.xPos = 0; - /** - * Whether the row has any external inputs. - * @package - * @type {boolean} - */ - this.hasExternalInput = false; + /** + * Whether the row has any external inputs. + * @package + * @type {boolean} + */ + this.hasExternalInput = false; - /** - * Whether the row has any statement inputs. - * @package - * @type {boolean} - */ - this.hasStatement = false; + /** + * Whether the row has any statement inputs. + * @package + * @type {boolean} + */ + this.hasStatement = false; - /** - * Whether the row has any inline inputs. - * @package - * @type {boolean} - */ - this.hasInlineInput = false; + /** + * Where the left edge of all of the statement inputs on the block should + * be. This makes sure that statement inputs which are proceded by fields + * of varius widths are all aligned. + * @type {number} + */ + this.statementEdge = 0; - /** - * Whether the row has any dummy inputs. - * @package - * @type {boolean} - */ - this.hasDummyInput = false; + /** + * Whether the row has any inline inputs. + * @package + * @type {boolean} + */ + this.hasInlineInput = false; - /** - * Whether the row has a jagged edge. - * @package - * @type {boolean} - */ - this.hasJaggedEdge = false; + /** + * Whether the row has any dummy inputs. + * @package + * @type {boolean} + */ + this.hasDummyInput = false; - /** - * The renderer's constant provider. - * @type {!ConstantProvider} - * @protected - */ - this.constants_ = constants; + /** + * Whether the row has a jagged edge. + * @package + * @type {boolean} + */ + this.hasJaggedEdge = false; - /** - * @type {number} - */ - this.notchOffset = this.constants_.NOTCH_OFFSET_LEFT; + /** + * The renderer's constant provider. + * @type {!ConstantProvider} + * @protected + */ + this.constants_ = constants; - /** - * Alignment of the row. - * @package - * @type {?number} - */ - this.align = null; -}; + /** + * @type {number} + */ + this.notchOffset = this.constants_.NOTCH_OFFSET_LEFT; -/** - * Get the last input on this row, if it has one. - * @return {InputConnection} The last input on the row, - * or null. - * @package - */ -// TODO: Consider moving this to InputRow, if possible. -Row.prototype.getLastInput = function() { - for (let i = this.elements.length - 1; i >= 0; i--) { - const elem = this.elements[i]; - if (Types.isInput(elem)) { - return /** @type {InputConnection} */ (elem); - } + /** + * Alignment of the row. + * @package + * @type {?number} + */ + this.align = null; } - return null; -}; -/** - * Inspect all subcomponents and populate all size properties on the row. - * @package - */ -Row.prototype.measure = function() { - throw Error('Unexpected attempt to measure a base Row.'); -}; - -/** - * Determines whether this row should start with an element spacer. - * @return {boolean} Whether the row should start with a spacer. - * @package - */ -Row.prototype.startsWithElemSpacer = function() { - return true; -}; - -/** - * Determines whether this row should end with an element spacer. - * @return {boolean} Whether the row should end with a spacer. - * @package - */ -Row.prototype.endsWithElemSpacer = function() { - return true; -}; - -/** - * Convenience method to get the first spacer element on this row. - * @return {InRowSpacer} The first spacer element on - * this row. - * @package - */ -Row.prototype.getFirstSpacer = function() { - for (let i = 0; i < this.elements.length; i++) { - const elem = this.elements[i]; - if (Types.isSpacer(elem)) { - return /** @type {InRowSpacer} */ (elem); + /** + * Get the last input on this row, if it has one. + * @return {InputConnection} The last input on the row, + * or null. + * @package + */ + getLastInput() { + // TODO: Consider moving this to InputRow, if possible. + for (let i = this.elements.length - 1; i >= 0; i--) { + const elem = this.elements[i]; + if (Types.isInput(elem)) { + return /** @type {InputConnection} */ (elem); + } } + return null; } - return null; -}; -/** - * Convenience method to get the last spacer element on this row. - * @return {InRowSpacer} The last spacer element on - * this row. - * @package - */ -Row.prototype.getLastSpacer = function() { - for (let i = this.elements.length - 1; i >= 0; i--) { - const elem = this.elements[i]; - if (Types.isSpacer(elem)) { - return /** @type {InRowSpacer} */ (elem); - } + /** + * Inspect all subcomponents and populate all size properties on the row. + * @package + */ + measure() { + throw Error('Unexpected attempt to measure a base Row.'); } - return null; -}; + + /** + * Determines whether this row should start with an element spacer. + * @return {boolean} Whether the row should start with a spacer. + * @package + */ + startsWithElemSpacer() { + return true; + } + + /** + * Determines whether this row should end with an element spacer. + * @return {boolean} Whether the row should end with a spacer. + * @package + */ + endsWithElemSpacer() { + return true; + } + + /** + * Convenience method to get the first spacer element on this row. + * @return {InRowSpacer} The first spacer element on + * this row. + * @package + */ + getFirstSpacer() { + for (let i = 0; i < this.elements.length; i++) { + const elem = this.elements[i]; + if (Types.isSpacer(elem)) { + return /** @type {InRowSpacer} */ (elem); + } + } + return null; + } + + /** + * Convenience method to get the last spacer element on this row. + * @return {InRowSpacer} The last spacer element on + * this row. + * @package + */ + getLastSpacer() { + for (let i = this.elements.length - 1; i >= 0; i--) { + const elem = this.elements[i]; + if (Types.isSpacer(elem)) { + return /** @type {InRowSpacer} */ (elem); + } + } + return null; + } +} exports.Row = Row; diff --git a/core/renderers/measurables/top_row.js b/core/renderers/measurables/top_row.js index b8f277826..7d071ec74 100644 --- a/core/renderers/measurables/top_row.js +++ b/core/renderers/measurables/top_row.js @@ -18,6 +18,7 @@ goog.module('Blockly.blockRendering.TopRow'); const {BlockSvg} = goog.requireType('Blockly.BlockSvg'); /* eslint-disable-next-line no-unused-vars */ const {ConstantProvider} = goog.requireType('Blockly.blockRendering.ConstantProvider'); +const {Hat} = goog.require('Blockly.blockRendering.Hat'); /* eslint-disable-next-line no-unused-vars */ const {PreviousConnection} = goog.requireType('Blockly.blockRendering.PreviousConnection'); const {Row} = goog.require('Blockly.blockRendering.Row'); @@ -110,7 +111,7 @@ class TopRow extends Row { const elem = this.elements[i]; width += elem.width; if (!(Types.isSpacer(elem))) { - if (Types.isHat(elem)) { + if (Types.isHat(elem) && elem instanceof Hat) { ascenderHeight = Math.max(ascenderHeight, elem.ascenderHeight); } else { height = Math.max(height, elem.height); diff --git a/core/renderers/zelos/info.js b/core/renderers/zelos/info.js index eb47eecd8..e9ae03df5 100644 --- a/core/renderers/zelos/info.js +++ b/core/renderers/zelos/info.js @@ -22,9 +22,13 @@ const {BlockSvg} = goog.requireType('Blockly.BlockSvg'); const {BottomRow} = goog.require('Blockly.zelos.BottomRow'); /* eslint-disable-next-line no-unused-vars */ const {ConstantProvider} = goog.requireType('Blockly.zelos.ConstantProvider'); +const {Field} = goog.require('Blockly.blockRendering.Field'); const {FieldImage} = goog.require('Blockly.FieldImage'); const {FieldLabel} = goog.require('Blockly.FieldLabel'); const {FieldTextInput} = goog.require('Blockly.FieldTextInput'); +/* eslint-disable-next-line no-unused-vars */ +const {Input} = goog.requireType('Blockly.Input'); +const {InputConnection} = goog.require('Blockly.blockRendering.InputConnection'); const {InRowSpacer} = goog.require('Blockly.blockRendering.InRowSpacer'); /* eslint-disable-next-line no-unused-vars */ const {Measurable} = goog.requireType('Blockly.blockRendering.Measurable'); @@ -33,6 +37,8 @@ const {RenderInfo: BaseRenderInfo} = goog.require('Blockly.blockRendering.Render const {Renderer} = goog.requireType('Blockly.zelos.Renderer'); const {RightConnectionShape} = goog.require('Blockly.zelos.RightConnectionShape'); /* eslint-disable-next-line no-unused-vars */ +const {Row} = goog.require('Blockly.blockRendering.Row'); +/* eslint-disable-next-line no-unused-vars */ const {SpacerRow} = goog.requireType('Blockly.blockRendering.SpacerRow'); const {StatementInput} = goog.require('Blockly.zelos.StatementInput'); const {TopRow} = goog.require('Blockly.zelos.TopRow'); @@ -100,6 +106,14 @@ class RenderInfo extends BaseRenderInfo { this.rightSide = this.outputConnection ? new RightConnectionShape(this.constants_) : null; + + /** + * A map of rows to right aligned dummy inputs within those rows. Used to + * add padding between left and right aligned inputs. + * @type {!WeakMap} + * @private + */ + this.rightAlignedDummyInputs_ = new WeakMap(); } /** @@ -254,7 +268,7 @@ class RenderInfo extends BaseRenderInfo { !Types.isStatementInput(elem)) { return row.yPos + this.constants_.EMPTY_STATEMENT_INPUT_HEIGHT / 2; } - if (Types.isInlineInput(elem)) { + if (Types.isInlineInput(elem) && elem instanceof InputConnection) { const connectedBlock = elem.connectedBlock; if (connectedBlock && connectedBlock.outputConnection && connectedBlock.nextConnection) { @@ -273,7 +287,7 @@ class RenderInfo extends BaseRenderInfo { // padding later. if (input.type === inputTypes.DUMMY && activeRow.hasDummyInput && activeRow.align === Align.LEFT && input.align === Align.RIGHT) { - activeRow.rightAlignedDummyInput = input; + this.rightAlignedDummyInputs_.set(activeRow, input); } else if (input.type === inputTypes.STATEMENT) { // Handle statements without next connections correctly. activeRow.elements.push(new StatementInput(this.constants_, input)); @@ -291,15 +305,15 @@ class RenderInfo extends BaseRenderInfo { * @override */ addAlignmentPadding_(row, missingSpace) { - if (row.rightAlignedDummyInput) { + if (this.rightAlignedDummyInputs_.get(row)) { let alignmentDivider; for (let i = 0; i < row.elements.length; i++) { const elem = row.elements[i]; if (Types.isSpacer(elem)) { alignmentDivider = elem; } - if (Types.isField(elem) && - elem.parentInput === row.rightAlignedDummyInput) { + if (Types.isField(elem) && elem instanceof Field && + elem.parentInput === this.rightAlignedDummyInputs_.get(row)) { break; } } @@ -351,7 +365,7 @@ class RenderInfo extends BaseRenderInfo { } if (prevInRowSpacer && (Types.isField(elem) || Types.isInput(elem))) { if (xCursor < minXPos && - !(Types.isField(elem) && + !(Types.isField(elem) && elem instanceof Field && (elem.field instanceof FieldLabel || elem.field instanceof FieldImage))) { const difference = minXPos - xCursor; @@ -459,7 +473,6 @@ class RenderInfo extends BaseRenderInfo { const row = this.rows[i]; if (Types.isTopOrBottomRow(row)) { row.elements[1].width -= totalNegativeSpacing; - row.elements[1].widthWithConnectedBlocks -= totalNegativeSpacing; } row.width -= totalNegativeSpacing; row.widthWithConnectedBlocks -= totalNegativeSpacing; @@ -498,7 +511,7 @@ class RenderInfo extends BaseRenderInfo { return 0; } } - if (Types.isInlineInput(elem)) { + if (Types.isInlineInput(elem) && elem instanceof InputConnection) { const connectedBlock = elem.connectedBlock; const innerShape = connectedBlock ? connectedBlock.pathObject.outputShapeType : @@ -516,7 +529,7 @@ class RenderInfo extends BaseRenderInfo { } return connectionWidth - this.constants_.SHAPE_IN_SHAPE_PADDING[outerShape][innerShape]; - } else if (Types.isField(elem)) { + } else if (Types.isField(elem) && elem instanceof Field) { // Special case for text inputs. if (outerShape === constants.SHAPES.ROUND && elem.field instanceof FieldTextInput) { @@ -555,9 +568,11 @@ class RenderInfo extends BaseRenderInfo { !!nextSpacer.precedesStatement; if (hasPrevNotch) { + const elem = row.elements[1]; const hasSingleTextOrImageField = row.elements.length === 3 && - (row.elements[1].field instanceof FieldLabel || - row.elements[1].field instanceof FieldImage); + elem instanceof Field && + (elem.field instanceof FieldLabel || + elem.field instanceof FieldImage); if (!firstRow && hasSingleTextOrImageField) { // Remove some padding if we have a single image or text field. prevSpacer.height -= this.constants_.SMALL_PADDING; @@ -572,8 +587,8 @@ class RenderInfo extends BaseRenderInfo { const minVerticalTightNestingHeight = 40; for (let j = 0; j < row.elements.length; j++) { const elem = row.elements[j]; - if (Types.isInlineInput(elem) && elem.connectedBlock && - !elem.connectedBlock.isShadow() && + if (elem instanceof InputConnection && Types.isInlineInput(elem) && + elem.connectedBlock && !elem.connectedBlock.isShadow() && elem.connectedBlock.getHeightWidth().height >= minVerticalTightNestingHeight) { hasNonShadowConnectedBlocks = true; diff --git a/scripts/gulpfiles/chunks.json b/scripts/gulpfiles/chunks.json index 4f80d1dce..79331823a 100644 --- a/scripts/gulpfiles/chunks.json +++ b/scripts/gulpfiles/chunks.json @@ -141,7 +141,6 @@ "./core/renderers/zelos/measurables/bottom_row.js", "./core/renderers/zelos/info.js", "./core/renderers/measurables/top_row.js", - "./core/renderers/measurables/statement_input.js", "./core/renderers/measurables/square_corner.js", "./core/renderers/measurables/spacer_row.js", "./core/renderers/measurables/round_corner.js", @@ -159,6 +158,7 @@ "./core/renderers/measurables/previous_connection.js", "./core/renderers/measurables/output_connection.js", "./core/renderers/measurables/jagged_edge.js", + "./core/renderers/measurables/statement_input.js", "./core/renderers/measurables/input_row.js", "./core/renderers/measurables/inline_input.js", "./core/scrollbar.js", @@ -177,9 +177,9 @@ "./core/icon.js", "./core/renderers/measurables/icon.js", "./core/renderers/measurables/hat.js", - "./core/renderers/measurables/field.js", "./core/renderers/measurables/external_value_input.js", "./core/renderers/common/info.js", + "./core/renderers/measurables/field.js", "./core/renderers/common/debugger.js", "./core/renderers/measurables/input_connection.js", "./core/renderers/measurables/in_row_spacer.js", diff --git a/tests/deps.js b/tests/deps.js index f6bb165b6..96699e744 100644 --- a/tests/deps.js +++ b/tests/deps.js @@ -144,8 +144,8 @@ goog.addDependency('../../core/rendered_connection.js', ['Blockly.RenderedConnec goog.addDependency('../../core/renderers/common/block_rendering.js', ['Blockly.blockRendering'], ['Blockly.blockRendering.BottomRow', 'Blockly.blockRendering.Connection', 'Blockly.blockRendering.ConstantProvider', 'Blockly.blockRendering.Debug', 'Blockly.blockRendering.Drawer', 'Blockly.blockRendering.ExternalValueInput', 'Blockly.blockRendering.Field', 'Blockly.blockRendering.Hat', 'Blockly.blockRendering.IPathObject', 'Blockly.blockRendering.Icon', 'Blockly.blockRendering.InRowSpacer', 'Blockly.blockRendering.InlineInput', 'Blockly.blockRendering.InputConnection', 'Blockly.blockRendering.InputRow', 'Blockly.blockRendering.JaggedEdge', 'Blockly.blockRendering.MarkerSvg', 'Blockly.blockRendering.Measurable', 'Blockly.blockRendering.NextConnection', 'Blockly.blockRendering.OutputConnection', 'Blockly.blockRendering.PathObject', 'Blockly.blockRendering.PreviousConnection', 'Blockly.blockRendering.RenderInfo', 'Blockly.blockRendering.Renderer', 'Blockly.blockRendering.RoundCorner', 'Blockly.blockRendering.Row', 'Blockly.blockRendering.SpacerRow', 'Blockly.blockRendering.SquareCorner', 'Blockly.blockRendering.StatementInput', 'Blockly.blockRendering.TopRow', 'Blockly.blockRendering.Types', 'Blockly.blockRendering.debug', 'Blockly.registry', 'Blockly.utils.deprecation'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/renderers/common/constants.js', ['Blockly.blockRendering.ConstantProvider'], ['Blockly.ConnectionType', 'Blockly.utils.Svg', 'Blockly.utils.colour', 'Blockly.utils.dom', 'Blockly.utils.object', 'Blockly.utils.parsing', 'Blockly.utils.svgPaths', 'Blockly.utils.userAgent'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/renderers/common/debug.js', ['Blockly.blockRendering.debug'], [], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/renderers/common/debugger.js', ['Blockly.blockRendering.Debug'], ['Blockly.ConnectionType', 'Blockly.FieldLabel', 'Blockly.blockRendering.Types', 'Blockly.utils.Svg', 'Blockly.utils.dom'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/renderers/common/drawer.js', ['Blockly.blockRendering.Drawer'], ['Blockly.blockRendering.Types', 'Blockly.blockRendering.debug', 'Blockly.utils.svgPaths'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/renderers/common/debugger.js', ['Blockly.blockRendering.Debug'], ['Blockly.ConnectionType', 'Blockly.FieldLabel', 'Blockly.blockRendering.Field', 'Blockly.blockRendering.InputConnection', 'Blockly.blockRendering.Types', 'Blockly.utils.Svg', 'Blockly.utils.dom'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/renderers/common/drawer.js', ['Blockly.blockRendering.Drawer'], ['Blockly.blockRendering.Connection', 'Blockly.blockRendering.Types', 'Blockly.blockRendering.debug', 'Blockly.utils.svgPaths'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/renderers/common/i_path_object.js', ['Blockly.blockRendering.IPathObject'], [], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/renderers/common/info.js', ['Blockly.blockRendering.RenderInfo'], ['Blockly.Input', 'Blockly.blockRendering.BottomRow', 'Blockly.blockRendering.ExternalValueInput', 'Blockly.blockRendering.Field', 'Blockly.blockRendering.Hat', 'Blockly.blockRendering.Icon', 'Blockly.blockRendering.InRowSpacer', 'Blockly.blockRendering.InlineInput', 'Blockly.blockRendering.InputRow', 'Blockly.blockRendering.JaggedEdge', 'Blockly.blockRendering.NextConnection', 'Blockly.blockRendering.OutputConnection', 'Blockly.blockRendering.PreviousConnection', 'Blockly.blockRendering.RoundCorner', 'Blockly.blockRendering.SpacerRow', 'Blockly.blockRendering.SquareCorner', 'Blockly.blockRendering.StatementInput', 'Blockly.blockRendering.TopRow', 'Blockly.blockRendering.Types', 'Blockly.inputTypes'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/renderers/common/marker_svg.js', ['Blockly.blockRendering.MarkerSvg'], ['Blockly.ASTNode', 'Blockly.ConnectionType', 'Blockly.Events.MarkerMove', 'Blockly.Events.utils', 'Blockly.utils.Svg', 'Blockly.utils.dom', 'Blockly.utils.svgPaths'], {'lang': 'es6', 'module': 'goog'}); @@ -155,7 +155,7 @@ goog.addDependency('../../core/renderers/geras/constants.js', ['Blockly.geras.Co goog.addDependency('../../core/renderers/geras/drawer.js', ['Blockly.geras.Drawer'], ['Blockly.blockRendering.Drawer', 'Blockly.blockRendering.debug', 'Blockly.geras.Highlighter', 'Blockly.geras.InlineInput', 'Blockly.utils.svgPaths'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/renderers/geras/geras.js', ['Blockly.geras'], ['Blockly.geras.ConstantProvider', 'Blockly.geras.Drawer', 'Blockly.geras.HighlightConstantProvider', 'Blockly.geras.Highlighter', 'Blockly.geras.InlineInput', 'Blockly.geras.PathObject', 'Blockly.geras.RenderInfo', 'Blockly.geras.Renderer', 'Blockly.geras.StatementInput'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/renderers/geras/highlight_constants.js', ['Blockly.geras.HighlightConstantProvider'], ['Blockly.utils.svgPaths'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/renderers/geras/highlighter.js', ['Blockly.geras.Highlighter'], ['Blockly.blockRendering.BottomRow', 'Blockly.blockRendering.TopRow', 'Blockly.blockRendering.Types', 'Blockly.geras.InlineInput', 'Blockly.utils.svgPaths'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/renderers/geras/highlighter.js', ['Blockly.geras.Highlighter'], ['Blockly.blockRendering.BottomRow', 'Blockly.blockRendering.SpacerRow', 'Blockly.blockRendering.TopRow', 'Blockly.blockRendering.Types', 'Blockly.geras.InlineInput', 'Blockly.utils.svgPaths'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/renderers/geras/info.js', ['Blockly.geras.RenderInfo'], ['Blockly.blockRendering.ExternalValueInput', 'Blockly.blockRendering.InRowSpacer', 'Blockly.blockRendering.RenderInfo', 'Blockly.blockRendering.Types', 'Blockly.geras.InlineInput', 'Blockly.geras.StatementInput', 'Blockly.inputTypes'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/renderers/geras/measurables/inline_input.js', ['Blockly.geras.InlineInput'], ['Blockly.blockRendering.InlineInput'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/renderers/geras/measurables/statement_input.js', ['Blockly.geras.StatementInput'], ['Blockly.blockRendering.StatementInput'], {'lang': 'es6', 'module': 'goog'}); @@ -171,7 +171,7 @@ goog.addDependency('../../core/renderers/measurables/icon.js', ['Blockly.blockRe goog.addDependency('../../core/renderers/measurables/in_row_spacer.js', ['Blockly.blockRendering.InRowSpacer'], ['Blockly.blockRendering.Measurable', 'Blockly.blockRendering.Types'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/renderers/measurables/inline_input.js', ['Blockly.blockRendering.InlineInput'], ['Blockly.blockRendering.InputConnection', 'Blockly.blockRendering.Types'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/renderers/measurables/input_connection.js', ['Blockly.blockRendering.InputConnection'], ['Blockly.blockRendering.Connection', 'Blockly.blockRendering.Types'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/renderers/measurables/input_row.js', ['Blockly.blockRendering.InputRow'], ['Blockly.blockRendering.Row', 'Blockly.blockRendering.Types'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/renderers/measurables/input_row.js', ['Blockly.blockRendering.InputRow'], ['Blockly.blockRendering.ExternalValueInput', 'Blockly.blockRendering.InputConnection', 'Blockly.blockRendering.Row', 'Blockly.blockRendering.StatementInput', 'Blockly.blockRendering.Types'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/renderers/measurables/jagged_edge.js', ['Blockly.blockRendering.JaggedEdge'], ['Blockly.blockRendering.Measurable', 'Blockly.blockRendering.Types'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/renderers/measurables/next_connection.js', ['Blockly.blockRendering.NextConnection'], ['Blockly.blockRendering.Connection', 'Blockly.blockRendering.Types'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/renderers/measurables/output_connection.js', ['Blockly.blockRendering.OutputConnection'], ['Blockly.blockRendering.Connection', 'Blockly.blockRendering.Types'], {'lang': 'es6', 'module': 'goog'}); @@ -181,7 +181,7 @@ goog.addDependency('../../core/renderers/measurables/row.js', ['Blockly.blockRen goog.addDependency('../../core/renderers/measurables/spacer_row.js', ['Blockly.blockRendering.SpacerRow'], ['Blockly.blockRendering.InRowSpacer', 'Blockly.blockRendering.Row', 'Blockly.blockRendering.Types'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/renderers/measurables/square_corner.js', ['Blockly.blockRendering.SquareCorner'], ['Blockly.blockRendering.Measurable', 'Blockly.blockRendering.Types'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/renderers/measurables/statement_input.js', ['Blockly.blockRendering.StatementInput'], ['Blockly.blockRendering.InputConnection', 'Blockly.blockRendering.Types'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/renderers/measurables/top_row.js', ['Blockly.blockRendering.TopRow'], ['Blockly.blockRendering.Row', 'Blockly.blockRendering.Types'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/renderers/measurables/top_row.js', ['Blockly.blockRendering.TopRow'], ['Blockly.blockRendering.Hat', 'Blockly.blockRendering.Row', 'Blockly.blockRendering.Types'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/renderers/measurables/types.js', ['Blockly.blockRendering.Types'], [], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/renderers/minimalist/constants.js', ['Blockly.minimalist.ConstantProvider'], ['Blockly.blockRendering.ConstantProvider'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/renderers/minimalist/drawer.js', ['Blockly.minimalist.Drawer'], ['Blockly.blockRendering.Drawer'], {'lang': 'es6', 'module': 'goog'}); @@ -193,7 +193,7 @@ goog.addDependency('../../core/renderers/thrasos/renderer.js', ['Blockly.thrasos goog.addDependency('../../core/renderers/thrasos/thrasos.js', ['Blockly.thrasos'], ['Blockly.thrasos.RenderInfo', 'Blockly.thrasos.Renderer'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/renderers/zelos/constants.js', ['Blockly.zelos.ConstantProvider'], ['Blockly.ConnectionType', 'Blockly.blockRendering.ConstantProvider', 'Blockly.utils.Svg', 'Blockly.utils.colour', 'Blockly.utils.dom', 'Blockly.utils.svgPaths'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/renderers/zelos/drawer.js', ['Blockly.zelos.Drawer'], ['Blockly.blockRendering.Drawer', 'Blockly.blockRendering.Types', 'Blockly.blockRendering.debug', 'Blockly.utils.svgPaths'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/renderers/zelos/info.js', ['Blockly.zelos.RenderInfo'], ['Blockly.FieldImage', 'Blockly.FieldLabel', 'Blockly.FieldTextInput', 'Blockly.Input', 'Blockly.blockRendering.InRowSpacer', 'Blockly.blockRendering.RenderInfo', 'Blockly.blockRendering.Types', 'Blockly.inputTypes', 'Blockly.zelos.BottomRow', 'Blockly.zelos.RightConnectionShape', 'Blockly.zelos.StatementInput', 'Blockly.zelos.TopRow'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/renderers/zelos/info.js', ['Blockly.zelos.RenderInfo'], ['Blockly.FieldImage', 'Blockly.FieldLabel', 'Blockly.FieldTextInput', 'Blockly.Input', 'Blockly.blockRendering.Field', 'Blockly.blockRendering.InRowSpacer', 'Blockly.blockRendering.InputConnection', 'Blockly.blockRendering.RenderInfo', 'Blockly.blockRendering.Row', 'Blockly.blockRendering.Types', 'Blockly.inputTypes', 'Blockly.zelos.BottomRow', 'Blockly.zelos.RightConnectionShape', 'Blockly.zelos.StatementInput', 'Blockly.zelos.TopRow'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/renderers/zelos/marker_svg.js', ['Blockly.zelos.MarkerSvg'], ['Blockly.blockRendering.MarkerSvg', 'Blockly.utils.Svg', 'Blockly.utils.dom'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/renderers/zelos/measurables/bottom_row.js', ['Blockly.zelos.BottomRow'], ['Blockly.blockRendering.BottomRow'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/renderers/zelos/measurables/inputs.js', ['Blockly.zelos.StatementInput'], ['Blockly.blockRendering.StatementInput'], {'lang': 'es6', 'module': 'goog'}); From 4cbb4c45631652be4c088fb48ae8c0f01e99f3b1 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 28 Feb 2022 08:05:51 -0800 Subject: [PATCH 086/128] chore(deps): bump @wdio/selenium-standalone-service (#5962) Bumps [@wdio/selenium-standalone-service](https://github.com/webdriverio/webdriverio) from 7.16.14 to 7.16.16. - [Release notes](https://github.com/webdriverio/webdriverio/releases) - [Changelog](https://github.com/webdriverio/webdriverio/blob/main/CHANGELOG.md) - [Commits](https://github.com/webdriverio/webdriverio/compare/v7.16.14...v7.16.16) --- updated-dependencies: - dependency-name: "@wdio/selenium-standalone-service" dependency-type: direct:development update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- package-lock.json | 40 ++++++++++++++++++++-------------------- 1 file changed, 20 insertions(+), 20 deletions(-) diff --git a/package-lock.json b/package-lock.json index 901d47b98..870742759 100644 --- a/package-lock.json +++ b/package-lock.json @@ -980,15 +980,15 @@ } }, "node_modules/@wdio/selenium-standalone-service": { - "version": "7.16.14", - "resolved": "https://registry.npmjs.org/@wdio/selenium-standalone-service/-/selenium-standalone-service-7.16.14.tgz", - "integrity": "sha512-lkygYvdN8XUejuMTnyWtXVp583J3sBT0Fge/ww/06xU2tYek0TpodKoNNmuU779uIXAM3Lz3L4L4n67Gis4NmA==", + "version": "7.16.16", + "resolved": "https://registry.npmjs.org/@wdio/selenium-standalone-service/-/selenium-standalone-service-7.16.16.tgz", + "integrity": "sha512-RPjwTNfIHE53RmtQY0ZV6Bwh+rDfMz79fmwX0WHRVOoPIcjRV68UctGjU3pQInOwrDyyP7ztLnFFEYLhOYZRfQ==", "dev": true, "dependencies": { "@types/fs-extra": "^9.0.1", "@types/node": "^17.0.4", "@types/selenium-standalone": "^7.0.0", - "@wdio/config": "7.16.14", + "@wdio/config": "7.16.16", "@wdio/logger": "7.16.0", "@wdio/types": "7.16.14", "fs-extra": "^10.0.0", @@ -1002,15 +1002,15 @@ } }, "node_modules/@wdio/selenium-standalone-service/node_modules/@types/node": { - "version": "17.0.14", - "resolved": "https://registry.npmjs.org/@types/node/-/node-17.0.14.tgz", - "integrity": "sha512-SbjLmERksKOGzWzPNuW7fJM7fk3YXVTFiZWB/Hs99gwhk+/dnrQRPBQjPW9aO+fi1tAffi9PrwFvsmOKmDTyng==", + "version": "17.0.21", + "resolved": "https://registry.npmjs.org/@types/node/-/node-17.0.21.tgz", + "integrity": "sha512-DBZCJbhII3r90XbQxI8Y9IjjiiOGlZ0Hr32omXIZvwwZ7p4DMMXGrKXVyPfuoBOri9XNtL0UK69jYIBIsRX3QQ==", "dev": true }, "node_modules/@wdio/selenium-standalone-service/node_modules/@wdio/config": { - "version": "7.16.14", - "resolved": "https://registry.npmjs.org/@wdio/config/-/config-7.16.14.tgz", - "integrity": "sha512-CdB8F4XFbuH9W3JaLYQoJMPRzM+GQirg9Ay1dW4xNcmJk7m3TJbk3/L78oz8ey1TpCLjQTG8aNqI4SZlFO4JRg==", + "version": "7.16.16", + "resolved": "https://registry.npmjs.org/@wdio/config/-/config-7.16.16.tgz", + "integrity": "sha512-K/ObPuo6Da2liz++OKOIfbdpFwI7UWiFcBylfJkCYbweuXCoW1aUqlKI6rmKPwCH9Uqr/RHWu6p8eo0zWe6xVA==", "dev": true, "dependencies": { "@wdio/logger": "7.16.0", @@ -13152,15 +13152,15 @@ } }, "@wdio/selenium-standalone-service": { - "version": "7.16.14", - "resolved": "https://registry.npmjs.org/@wdio/selenium-standalone-service/-/selenium-standalone-service-7.16.14.tgz", - "integrity": "sha512-lkygYvdN8XUejuMTnyWtXVp583J3sBT0Fge/ww/06xU2tYek0TpodKoNNmuU779uIXAM3Lz3L4L4n67Gis4NmA==", + "version": "7.16.16", + "resolved": "https://registry.npmjs.org/@wdio/selenium-standalone-service/-/selenium-standalone-service-7.16.16.tgz", + "integrity": "sha512-RPjwTNfIHE53RmtQY0ZV6Bwh+rDfMz79fmwX0WHRVOoPIcjRV68UctGjU3pQInOwrDyyP7ztLnFFEYLhOYZRfQ==", "dev": true, "requires": { "@types/fs-extra": "^9.0.1", "@types/node": "^17.0.4", "@types/selenium-standalone": "^7.0.0", - "@wdio/config": "7.16.14", + "@wdio/config": "7.16.16", "@wdio/logger": "7.16.0", "@wdio/types": "7.16.14", "fs-extra": "^10.0.0", @@ -13168,15 +13168,15 @@ }, "dependencies": { "@types/node": { - "version": "17.0.14", - "resolved": "https://registry.npmjs.org/@types/node/-/node-17.0.14.tgz", - "integrity": "sha512-SbjLmERksKOGzWzPNuW7fJM7fk3YXVTFiZWB/Hs99gwhk+/dnrQRPBQjPW9aO+fi1tAffi9PrwFvsmOKmDTyng==", + "version": "17.0.21", + "resolved": "https://registry.npmjs.org/@types/node/-/node-17.0.21.tgz", + "integrity": "sha512-DBZCJbhII3r90XbQxI8Y9IjjiiOGlZ0Hr32omXIZvwwZ7p4DMMXGrKXVyPfuoBOri9XNtL0UK69jYIBIsRX3QQ==", "dev": true }, "@wdio/config": { - "version": "7.16.14", - "resolved": "https://registry.npmjs.org/@wdio/config/-/config-7.16.14.tgz", - "integrity": "sha512-CdB8F4XFbuH9W3JaLYQoJMPRzM+GQirg9Ay1dW4xNcmJk7m3TJbk3/L78oz8ey1TpCLjQTG8aNqI4SZlFO4JRg==", + "version": "7.16.16", + "resolved": "https://registry.npmjs.org/@wdio/config/-/config-7.16.16.tgz", + "integrity": "sha512-K/ObPuo6Da2liz++OKOIfbdpFwI7UWiFcBylfJkCYbweuXCoW1aUqlKI6rmKPwCH9Uqr/RHWu6p8eo0zWe6xVA==", "dev": true, "requires": { "@wdio/logger": "7.16.0", From 4201d43d558c9fcd3d72682e742241ef1358542d Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 28 Feb 2022 16:39:11 +0000 Subject: [PATCH 087/128] chore(deps): bump webdriverio from 7.16.15 to 7.16.16 (#5964) Bumps [webdriverio](https://github.com/webdriverio/webdriverio) from 7.16.15 to 7.16.16. - [Release notes](https://github.com/webdriverio/webdriverio/releases) - [Changelog](https://github.com/webdriverio/webdriverio/blob/main/CHANGELOG.md) - [Commits](https://github.com/webdriverio/webdriverio/compare/v7.16.15...v7.16.16) --- updated-dependencies: - dependency-name: webdriverio dependency-type: direct:development update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- package-lock.json | 213 +++++++++++++++++++++++++++++----------------- 1 file changed, 136 insertions(+), 77 deletions(-) diff --git a/package-lock.json b/package-lock.json index 870742759..8010a1c8f 100644 --- a/package-lock.json +++ b/package-lock.json @@ -3261,14 +3261,14 @@ } }, "node_modules/devtools": { - "version": "7.16.15", - "resolved": "https://registry.npmjs.org/devtools/-/devtools-7.16.15.tgz", - "integrity": "sha512-34WOK2tzeFiIvu1nln0Gwjxwo0slt75ATloI9cNnEtW21NM5PrWwcMUjn6Gl2kLl0eqtLVH+uHhBgInbT4qvFg==", + "version": "7.16.16", + "resolved": "https://registry.npmjs.org/devtools/-/devtools-7.16.16.tgz", + "integrity": "sha512-M0kzkuSgfEhpqIis3gdtWsNjn/HQ+vRAmEzDnbYx/7FfjFxhSv1d+rOOT20pvd60soItMYpsOova1igACEGkGQ==", "dev": true, "dependencies": { "@types/node": "^17.0.4", "@types/ua-parser-js": "^0.7.33", - "@wdio/config": "7.16.14", + "@wdio/config": "7.16.16", "@wdio/logger": "7.16.0", "@wdio/protocols": "7.16.7", "@wdio/types": "7.16.14", @@ -3285,21 +3285,21 @@ } }, "node_modules/devtools-protocol": { - "version": "0.0.966116", - "resolved": "https://registry.npmjs.org/devtools-protocol/-/devtools-protocol-0.0.966116.tgz", - "integrity": "sha512-uCqUDw5Y4ajQoFqGdYbvjrVdsXqlDb54JcmEPO4kpXjSU+Szyisi2BQDfnSVLeHRDELmzOcm9reZ959slDwD7g==", + "version": "0.0.973690", + "resolved": "https://registry.npmjs.org/devtools-protocol/-/devtools-protocol-0.0.973690.tgz", + "integrity": "sha512-myh3hSFp0YWa2GED11PmbLhV4dv9RdO7YUz27XJrbQLnP5bMbZL6dfOOILTHO57yH0kX5GfuOZBsg/4NamfPvQ==", "dev": true }, "node_modules/devtools/node_modules/@types/node": { - "version": "17.0.17", - "resolved": "https://registry.npmjs.org/@types/node/-/node-17.0.17.tgz", - "integrity": "sha512-e8PUNQy1HgJGV3iU/Bp2+D/DXh3PYeyli8LgIwsQcs1Ar1LoaWHSIT6Rw+H2rNJmiq6SNWiDytfx8+gYj7wDHw==", + "version": "17.0.21", + "resolved": "https://registry.npmjs.org/@types/node/-/node-17.0.21.tgz", + "integrity": "sha512-DBZCJbhII3r90XbQxI8Y9IjjiiOGlZ0Hr32omXIZvwwZ7p4DMMXGrKXVyPfuoBOri9XNtL0UK69jYIBIsRX3QQ==", "dev": true }, "node_modules/devtools/node_modules/@wdio/config": { - "version": "7.16.14", - "resolved": "https://registry.npmjs.org/@wdio/config/-/config-7.16.14.tgz", - "integrity": "sha512-CdB8F4XFbuH9W3JaLYQoJMPRzM+GQirg9Ay1dW4xNcmJk7m3TJbk3/L78oz8ey1TpCLjQTG8aNqI4SZlFO4JRg==", + "version": "7.16.16", + "resolved": "https://registry.npmjs.org/@wdio/config/-/config-7.16.16.tgz", + "integrity": "sha512-K/ObPuo6Da2liz++OKOIfbdpFwI7UWiFcBylfJkCYbweuXCoW1aUqlKI6rmKPwCH9Uqr/RHWu6p8eo0zWe6xVA==", "dev": true, "dependencies": { "@wdio/logger": "7.16.0", @@ -7056,6 +7056,7 @@ "resolved": "https://registry.npmjs.org/ky/-/ky-0.28.7.tgz", "integrity": "sha512-a23i6qSr/ep15vdtw/zyEQIDLoUaKDg9Jf04CYl/0ns/wXNYna26zJpI+MeIFaPeDvkrjLPrKtKOiiI3IE53RQ==", "dev": true, + "peer": true, "engines": { "node": ">=12" }, @@ -9341,9 +9342,9 @@ } }, "node_modules/puppeteer-core": { - "version": "13.3.1", - "resolved": "https://registry.npmjs.org/puppeteer-core/-/puppeteer-core-13.3.1.tgz", - "integrity": "sha512-II9uo5MFh+otoJSoYp/kfY3jf1iWt0ySKyK8vFVfdbn3rl+k3SLh9nQRdINyoO1Kt6Tk4dPp6GZipD9jgU9wmw==", + "version": "13.4.0", + "resolved": "https://registry.npmjs.org/puppeteer-core/-/puppeteer-core-13.4.0.tgz", + "integrity": "sha512-TcGT5Qgq9tgI0msFrIhq70N1+WrnGowjn0hc4vtzEIizJETXOZVrQZVWy051lO/nxEVGyqRXHwtpWjv4/fRbUw==", "dev": true, "dependencies": { "cross-fetch": "3.1.5", @@ -11808,19 +11809,19 @@ } }, "node_modules/webdriver": { - "version": "7.16.14", - "resolved": "https://registry.npmjs.org/webdriver/-/webdriver-7.16.14.tgz", - "integrity": "sha512-wfD3Okv+XJVMzrFVSTkhU381pJn2HlbKyURC7uY4E2QLaalhJLrrqekofBOUsr7WMf9nqoQwiVHQygnyt0afFw==", + "version": "7.16.16", + "resolved": "https://registry.npmjs.org/webdriver/-/webdriver-7.16.16.tgz", + "integrity": "sha512-x8UoG9k/P8KDrfSh1pOyNevt9tns3zexoMxp9cKnyA/7HYSErhZYTLGlgxscAXLtQG41cMH/Ba/oBmOx7Hgd8w==", "dev": true, "dependencies": { "@types/node": "^17.0.4", - "@wdio/config": "7.16.14", + "@wdio/config": "7.16.16", "@wdio/logger": "7.16.0", "@wdio/protocols": "7.16.7", "@wdio/types": "7.16.14", "@wdio/utils": "7.16.14", "got": "^11.0.2", - "ky": "^0.28.5", + "ky": "^0.29.0", "lodash.merge": "^4.6.1" }, "engines": { @@ -11828,15 +11829,15 @@ } }, "node_modules/webdriver/node_modules/@types/node": { - "version": "17.0.14", - "resolved": "https://registry.npmjs.org/@types/node/-/node-17.0.14.tgz", - "integrity": "sha512-SbjLmERksKOGzWzPNuW7fJM7fk3YXVTFiZWB/Hs99gwhk+/dnrQRPBQjPW9aO+fi1tAffi9PrwFvsmOKmDTyng==", + "version": "17.0.21", + "resolved": "https://registry.npmjs.org/@types/node/-/node-17.0.21.tgz", + "integrity": "sha512-DBZCJbhII3r90XbQxI8Y9IjjiiOGlZ0Hr32omXIZvwwZ7p4DMMXGrKXVyPfuoBOri9XNtL0UK69jYIBIsRX3QQ==", "dev": true }, "node_modules/webdriver/node_modules/@wdio/config": { - "version": "7.16.14", - "resolved": "https://registry.npmjs.org/@wdio/config/-/config-7.16.14.tgz", - "integrity": "sha512-CdB8F4XFbuH9W3JaLYQoJMPRzM+GQirg9Ay1dW4xNcmJk7m3TJbk3/L78oz8ey1TpCLjQTG8aNqI4SZlFO4JRg==", + "version": "7.16.16", + "resolved": "https://registry.npmjs.org/@wdio/config/-/config-7.16.16.tgz", + "integrity": "sha512-K/ObPuo6Da2liz++OKOIfbdpFwI7UWiFcBylfJkCYbweuXCoW1aUqlKI6rmKPwCH9Uqr/RHWu6p8eo0zWe6xVA==", "dev": true, "dependencies": { "@wdio/logger": "7.16.0", @@ -11875,15 +11876,27 @@ "node": ">=12.0.0" } }, + "node_modules/webdriver/node_modules/ky": { + "version": "0.29.0", + "resolved": "https://registry.npmjs.org/ky/-/ky-0.29.0.tgz", + "integrity": "sha512-01TBSOqlHmLfcQhHseugGHLxPtU03OyZWaLDWt5MfzCkijG6xWFvAQPhKVn0cR2MMjYvBP9keQ8A3+rQEhLO5g==", + "dev": true, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sindresorhus/ky?sponsor=1" + } + }, "node_modules/webdriverio": { - "version": "7.16.15", - "resolved": "https://registry.npmjs.org/webdriverio/-/webdriverio-7.16.15.tgz", - "integrity": "sha512-f9Hdn0CTX2y1E3kbN/6QLUXo0JZlnnhPkuJbBlSJMV3+/xFj5MBcBszJBT5Frwzcs48YNikimPbR79VLxfX3AA==", + "version": "7.16.16", + "resolved": "https://registry.npmjs.org/webdriverio/-/webdriverio-7.16.16.tgz", + "integrity": "sha512-caPaEWyuD3Qoa7YkW4xCCQA4v9Pa9wmhFGPvNZh3ERtjMCNi8L/XXOdkekWNZmFh3tY0kFguBj7+fAwSY7HAGw==", "dev": true, "dependencies": { "@types/aria-query": "^5.0.0", "@types/node": "^17.0.4", - "@wdio/config": "7.16.14", + "@wdio/config": "7.16.16", "@wdio/logger": "7.16.0", "@wdio/protocols": "7.16.7", "@wdio/repl": "7.16.14", @@ -11893,8 +11906,8 @@ "aria-query": "^5.0.0", "css-shorthand-properties": "^1.1.1", "css-value": "^0.0.1", - "devtools": "7.16.15", - "devtools-protocol": "^0.0.966116", + "devtools": "7.16.16", + "devtools-protocol": "^0.0.973690", "fs-extra": "^10.0.0", "get-port": "^5.1.1", "grapheme-splitter": "^1.0.2", @@ -11902,13 +11915,13 @@ "lodash.isobject": "^3.0.2", "lodash.isplainobject": "^4.0.6", "lodash.zip": "^4.2.0", - "minimatch": "^3.0.4", + "minimatch": "^5.0.0", "puppeteer-core": "^13.1.3", "query-selector-shadow-dom": "^1.0.0", "resq": "^1.9.1", "rgb2hex": "0.2.5", "serialize-error": "^8.0.0", - "webdriver": "7.16.14" + "webdriver": "7.16.16" }, "engines": { "node": ">=12.0.0" @@ -11921,9 +11934,9 @@ "dev": true }, "node_modules/webdriverio/node_modules/@wdio/config": { - "version": "7.16.14", - "resolved": "https://registry.npmjs.org/@wdio/config/-/config-7.16.14.tgz", - "integrity": "sha512-CdB8F4XFbuH9W3JaLYQoJMPRzM+GQirg9Ay1dW4xNcmJk7m3TJbk3/L78oz8ey1TpCLjQTG8aNqI4SZlFO4JRg==", + "version": "7.16.16", + "resolved": "https://registry.npmjs.org/@wdio/config/-/config-7.16.16.tgz", + "integrity": "sha512-K/ObPuo6Da2liz++OKOIfbdpFwI7UWiFcBylfJkCYbweuXCoW1aUqlKI6rmKPwCH9Uqr/RHWu6p8eo0zWe6xVA==", "dev": true, "dependencies": { "@wdio/logger": "7.16.0", @@ -11962,6 +11975,27 @@ "node": ">=12.0.0" } }, + "node_modules/webdriverio/node_modules/brace-expansion": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.1.tgz", + "integrity": "sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA==", + "dev": true, + "dependencies": { + "balanced-match": "^1.0.0" + } + }, + "node_modules/webdriverio/node_modules/minimatch": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-5.0.1.tgz", + "integrity": "sha512-nLDxIFRyhDblz3qMuq+SoRZED4+miJ/G+tdDrjkkkRnjAsBexeGpgjLEQ0blJy7rHhR2b93rhQY4SvyWu9v03g==", + "dev": true, + "dependencies": { + "brace-expansion": "^2.0.1" + }, + "engines": { + "node": ">=10" + } + }, "node_modules/webidl-conversions": { "version": "4.0.2", "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-4.0.2.tgz", @@ -14928,14 +14962,14 @@ "dev": true }, "devtools": { - "version": "7.16.15", - "resolved": "https://registry.npmjs.org/devtools/-/devtools-7.16.15.tgz", - "integrity": "sha512-34WOK2tzeFiIvu1nln0Gwjxwo0slt75ATloI9cNnEtW21NM5PrWwcMUjn6Gl2kLl0eqtLVH+uHhBgInbT4qvFg==", + "version": "7.16.16", + "resolved": "https://registry.npmjs.org/devtools/-/devtools-7.16.16.tgz", + "integrity": "sha512-M0kzkuSgfEhpqIis3gdtWsNjn/HQ+vRAmEzDnbYx/7FfjFxhSv1d+rOOT20pvd60soItMYpsOova1igACEGkGQ==", "dev": true, "requires": { "@types/node": "^17.0.4", "@types/ua-parser-js": "^0.7.33", - "@wdio/config": "7.16.14", + "@wdio/config": "7.16.16", "@wdio/logger": "7.16.0", "@wdio/protocols": "7.16.7", "@wdio/types": "7.16.14", @@ -14949,15 +14983,15 @@ }, "dependencies": { "@types/node": { - "version": "17.0.17", - "resolved": "https://registry.npmjs.org/@types/node/-/node-17.0.17.tgz", - "integrity": "sha512-e8PUNQy1HgJGV3iU/Bp2+D/DXh3PYeyli8LgIwsQcs1Ar1LoaWHSIT6Rw+H2rNJmiq6SNWiDytfx8+gYj7wDHw==", + "version": "17.0.21", + "resolved": "https://registry.npmjs.org/@types/node/-/node-17.0.21.tgz", + "integrity": "sha512-DBZCJbhII3r90XbQxI8Y9IjjiiOGlZ0Hr32omXIZvwwZ7p4DMMXGrKXVyPfuoBOri9XNtL0UK69jYIBIsRX3QQ==", "dev": true }, "@wdio/config": { - "version": "7.16.14", - "resolved": "https://registry.npmjs.org/@wdio/config/-/config-7.16.14.tgz", - "integrity": "sha512-CdB8F4XFbuH9W3JaLYQoJMPRzM+GQirg9Ay1dW4xNcmJk7m3TJbk3/L78oz8ey1TpCLjQTG8aNqI4SZlFO4JRg==", + "version": "7.16.16", + "resolved": "https://registry.npmjs.org/@wdio/config/-/config-7.16.16.tgz", + "integrity": "sha512-K/ObPuo6Da2liz++OKOIfbdpFwI7UWiFcBylfJkCYbweuXCoW1aUqlKI6rmKPwCH9Uqr/RHWu6p8eo0zWe6xVA==", "dev": true, "requires": { "@wdio/logger": "7.16.0", @@ -14996,9 +15030,9 @@ } }, "devtools-protocol": { - "version": "0.0.966116", - "resolved": "https://registry.npmjs.org/devtools-protocol/-/devtools-protocol-0.0.966116.tgz", - "integrity": "sha512-uCqUDw5Y4ajQoFqGdYbvjrVdsXqlDb54JcmEPO4kpXjSU+Szyisi2BQDfnSVLeHRDELmzOcm9reZ959slDwD7g==", + "version": "0.0.973690", + "resolved": "https://registry.npmjs.org/devtools-protocol/-/devtools-protocol-0.0.973690.tgz", + "integrity": "sha512-myh3hSFp0YWa2GED11PmbLhV4dv9RdO7YUz27XJrbQLnP5bMbZL6dfOOILTHO57yH0kX5GfuOZBsg/4NamfPvQ==", "dev": true }, "diff": { @@ -17976,7 +18010,8 @@ "version": "0.28.7", "resolved": "https://registry.npmjs.org/ky/-/ky-0.28.7.tgz", "integrity": "sha512-a23i6qSr/ep15vdtw/zyEQIDLoUaKDg9Jf04CYl/0ns/wXNYna26zJpI+MeIFaPeDvkrjLPrKtKOiiI3IE53RQ==", - "dev": true + "dev": true, + "peer": true }, "last-run": { "version": "1.1.1", @@ -19817,9 +19852,9 @@ "integrity": "sha512-XRsRjdf+j5ml+y/6GKHPZbrF/8p2Yga0JPtdqTIY2Xe5ohJPD9saDJJLPvp9+NSBprVvevdXZybnj2cv8OEd0A==" }, "puppeteer-core": { - "version": "13.3.1", - "resolved": "https://registry.npmjs.org/puppeteer-core/-/puppeteer-core-13.3.1.tgz", - "integrity": "sha512-II9uo5MFh+otoJSoYp/kfY3jf1iWt0ySKyK8vFVfdbn3rl+k3SLh9nQRdINyoO1Kt6Tk4dPp6GZipD9jgU9wmw==", + "version": "13.4.0", + "resolved": "https://registry.npmjs.org/puppeteer-core/-/puppeteer-core-13.4.0.tgz", + "integrity": "sha512-TcGT5Qgq9tgI0msFrIhq70N1+WrnGowjn0hc4vtzEIizJETXOZVrQZVWy051lO/nxEVGyqRXHwtpWjv4/fRbUw==", "dev": true, "requires": { "cross-fetch": "3.1.5", @@ -21847,32 +21882,32 @@ } }, "webdriver": { - "version": "7.16.14", - "resolved": "https://registry.npmjs.org/webdriver/-/webdriver-7.16.14.tgz", - "integrity": "sha512-wfD3Okv+XJVMzrFVSTkhU381pJn2HlbKyURC7uY4E2QLaalhJLrrqekofBOUsr7WMf9nqoQwiVHQygnyt0afFw==", + "version": "7.16.16", + "resolved": "https://registry.npmjs.org/webdriver/-/webdriver-7.16.16.tgz", + "integrity": "sha512-x8UoG9k/P8KDrfSh1pOyNevt9tns3zexoMxp9cKnyA/7HYSErhZYTLGlgxscAXLtQG41cMH/Ba/oBmOx7Hgd8w==", "dev": true, "requires": { "@types/node": "^17.0.4", - "@wdio/config": "7.16.14", + "@wdio/config": "7.16.16", "@wdio/logger": "7.16.0", "@wdio/protocols": "7.16.7", "@wdio/types": "7.16.14", "@wdio/utils": "7.16.14", "got": "^11.0.2", - "ky": "^0.28.5", + "ky": "^0.29.0", "lodash.merge": "^4.6.1" }, "dependencies": { "@types/node": { - "version": "17.0.14", - "resolved": "https://registry.npmjs.org/@types/node/-/node-17.0.14.tgz", - "integrity": "sha512-SbjLmERksKOGzWzPNuW7fJM7fk3YXVTFiZWB/Hs99gwhk+/dnrQRPBQjPW9aO+fi1tAffi9PrwFvsmOKmDTyng==", + "version": "17.0.21", + "resolved": "https://registry.npmjs.org/@types/node/-/node-17.0.21.tgz", + "integrity": "sha512-DBZCJbhII3r90XbQxI8Y9IjjiiOGlZ0Hr32omXIZvwwZ7p4DMMXGrKXVyPfuoBOri9XNtL0UK69jYIBIsRX3QQ==", "dev": true }, "@wdio/config": { - "version": "7.16.14", - "resolved": "https://registry.npmjs.org/@wdio/config/-/config-7.16.14.tgz", - "integrity": "sha512-CdB8F4XFbuH9W3JaLYQoJMPRzM+GQirg9Ay1dW4xNcmJk7m3TJbk3/L78oz8ey1TpCLjQTG8aNqI4SZlFO4JRg==", + "version": "7.16.16", + "resolved": "https://registry.npmjs.org/@wdio/config/-/config-7.16.16.tgz", + "integrity": "sha512-K/ObPuo6Da2liz++OKOIfbdpFwI7UWiFcBylfJkCYbweuXCoW1aUqlKI6rmKPwCH9Uqr/RHWu6p8eo0zWe6xVA==", "dev": true, "requires": { "@wdio/logger": "7.16.0", @@ -21901,18 +21936,24 @@ "@wdio/types": "7.16.14", "p-iteration": "^1.1.8" } + }, + "ky": { + "version": "0.29.0", + "resolved": "https://registry.npmjs.org/ky/-/ky-0.29.0.tgz", + "integrity": "sha512-01TBSOqlHmLfcQhHseugGHLxPtU03OyZWaLDWt5MfzCkijG6xWFvAQPhKVn0cR2MMjYvBP9keQ8A3+rQEhLO5g==", + "dev": true } } }, "webdriverio": { - "version": "7.16.15", - "resolved": "https://registry.npmjs.org/webdriverio/-/webdriverio-7.16.15.tgz", - "integrity": "sha512-f9Hdn0CTX2y1E3kbN/6QLUXo0JZlnnhPkuJbBlSJMV3+/xFj5MBcBszJBT5Frwzcs48YNikimPbR79VLxfX3AA==", + "version": "7.16.16", + "resolved": "https://registry.npmjs.org/webdriverio/-/webdriverio-7.16.16.tgz", + "integrity": "sha512-caPaEWyuD3Qoa7YkW4xCCQA4v9Pa9wmhFGPvNZh3ERtjMCNi8L/XXOdkekWNZmFh3tY0kFguBj7+fAwSY7HAGw==", "dev": true, "requires": { "@types/aria-query": "^5.0.0", "@types/node": "^17.0.4", - "@wdio/config": "7.16.14", + "@wdio/config": "7.16.16", "@wdio/logger": "7.16.0", "@wdio/protocols": "7.16.7", "@wdio/repl": "7.16.14", @@ -21922,8 +21963,8 @@ "aria-query": "^5.0.0", "css-shorthand-properties": "^1.1.1", "css-value": "^0.0.1", - "devtools": "7.16.15", - "devtools-protocol": "^0.0.966116", + "devtools": "7.16.16", + "devtools-protocol": "^0.0.973690", "fs-extra": "^10.0.0", "get-port": "^5.1.1", "grapheme-splitter": "^1.0.2", @@ -21931,13 +21972,13 @@ "lodash.isobject": "^3.0.2", "lodash.isplainobject": "^4.0.6", "lodash.zip": "^4.2.0", - "minimatch": "^3.0.4", + "minimatch": "^5.0.0", "puppeteer-core": "^13.1.3", "query-selector-shadow-dom": "^1.0.0", "resq": "^1.9.1", "rgb2hex": "0.2.5", "serialize-error": "^8.0.0", - "webdriver": "7.16.14" + "webdriver": "7.16.16" }, "dependencies": { "@types/node": { @@ -21947,9 +21988,9 @@ "dev": true }, "@wdio/config": { - "version": "7.16.14", - "resolved": "https://registry.npmjs.org/@wdio/config/-/config-7.16.14.tgz", - "integrity": "sha512-CdB8F4XFbuH9W3JaLYQoJMPRzM+GQirg9Ay1dW4xNcmJk7m3TJbk3/L78oz8ey1TpCLjQTG8aNqI4SZlFO4JRg==", + "version": "7.16.16", + "resolved": "https://registry.npmjs.org/@wdio/config/-/config-7.16.16.tgz", + "integrity": "sha512-K/ObPuo6Da2liz++OKOIfbdpFwI7UWiFcBylfJkCYbweuXCoW1aUqlKI6rmKPwCH9Uqr/RHWu6p8eo0zWe6xVA==", "dev": true, "requires": { "@wdio/logger": "7.16.0", @@ -21978,6 +22019,24 @@ "@wdio/types": "7.16.14", "p-iteration": "^1.1.8" } + }, + "brace-expansion": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.1.tgz", + "integrity": "sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA==", + "dev": true, + "requires": { + "balanced-match": "^1.0.0" + } + }, + "minimatch": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-5.0.1.tgz", + "integrity": "sha512-nLDxIFRyhDblz3qMuq+SoRZED4+miJ/G+tdDrjkkkRnjAsBexeGpgjLEQ0blJy7rHhR2b93rhQY4SvyWu9v03g==", + "dev": true, + "requires": { + "brace-expansion": "^2.0.1" + } } } }, From cb4521b645735c6cb55f8f80fcbef83930377d8a Mon Sep 17 00:00:00 2001 From: Beka Westberg Date: Mon, 28 Feb 2022 08:59:33 -0800 Subject: [PATCH 088/128] refactor: Convert fields to ES6 classes (#5943) * refactor: Initial test at refactoring fields to ES6 * refact: reorganize text input and descendants to call super first * refact: run conversion script on text input field and subclasses * clean: cleanup fields post-conversion script * refact: reorganize dropdown and variable fields to call super first * refact: run class conversion script on dropdown and variable * clean: clean fields post conversion script * refact: reorganize misc fields to call super first * refact: run conversion script on misc fields * clean: cleanup misc fields after conversion * fix: add setting the value and whatnot back to the base field. Pass sentinel conistently * format * refact: work on making debug compiler happy * clean: finish making debug build happy * fix: work on making tests happy * fix: finish making tests happy * Fix: fixup angle and multiline fields * clean: format * fix: move default value back to DEFAULT_VALUE * fix: change SENTINEL to SKIP_SETUP * fix: inline docs * fix: some misc PR comments * fix: format * fix: make compiler hapy with new.target * fix: types in FieldDropdown * fix: add @final annotations to Field * feat: move Sentinel to a utils file * fix: remove ImageProperties from external API * clean: cleanup chunks and deps --- core/extensions.js | 3 +- core/field.js | 2247 ++++++++++++++-------------- core/field_angle.js | 864 +++++------ core/field_checkbox.js | 398 ++--- core/field_colour.js | 1000 +++++++------ core/field_dropdown.js | 1267 ++++++++-------- core/field_image.js | 473 +++--- core/field_label.js | 197 +-- core/field_label_serializable.js | 6 +- core/field_multilineinput.js | 35 +- core/field_number.js | 559 +++---- core/field_textinput.js | 1074 ++++++------- core/field_variable.js | 924 ++++++------ core/utils/sentinel.js | 24 + scripts/gulpfiles/chunks.json | 93 +- tests/deps.js | 25 +- tests/mocha/field_registry_test.js | 14 +- tests/mocha/field_test.js | 58 +- 18 files changed, 4765 insertions(+), 4496 deletions(-) create mode 100644 core/utils/sentinel.js diff --git a/core/extensions.js b/core/extensions.js index d0c219d4f..4043ba95c 100644 --- a/core/extensions.js +++ b/core/extensions.js @@ -24,6 +24,7 @@ goog.module('Blockly.Extensions'); const parsing = goog.require('Blockly.utils.parsing'); /* eslint-disable-next-line no-unused-vars */ const {Block} = goog.requireType('Blockly.Block'); +const {FieldDropdown} = goog.require('Blockly.FieldDropdown'); goog.requireType('Blockly.Mutator'); @@ -454,7 +455,7 @@ exports.buildTooltipForDropdown = buildTooltipForDropdown; const checkDropdownOptionsInTable = function(block, dropdownName, lookupTable) { // Validate all dropdown options have values. const dropdown = block.getField(dropdownName); - if (!dropdown.isOptionListDynamic()) { + if (dropdown instanceof FieldDropdown && !dropdown.isOptionListDynamic()) { const options = dropdown.getOptions(); for (let i = 0; i < options.length; i++) { const optionKey = options[i][1]; // label, then value diff --git a/core/field.js b/core/field.js index f1fd06b2f..7b8daf0de 100644 --- a/core/field.js +++ b/core/field.js @@ -50,6 +50,7 @@ const {IRegistrable} = goog.require('Blockly.IRegistrable'); const {Input} = goog.requireType('Blockly.Input'); const {MarkerManager} = goog.require('Blockly.MarkerManager'); const {Rect} = goog.require('Blockly.utils.Rect'); +const {Sentinel} = goog.require('Blockly.utils.Sentinel'); /* eslint-disable-next-line no-unused-vars */ const {ShortcutRegistry} = goog.requireType('Blockly.ShortcutRegistry'); const {Size} = goog.require('Blockly.utils.Size'); @@ -64,114 +65,1193 @@ goog.require('Blockly.Gesture'); /** * Abstract class for an editable field. - * @param {*} value The initial value of the field. - * @param {?Function=} opt_validator A function that is called to validate - * changes to the field's value. Takes in a value & returns a validated - * value, or null to abort the change. - * @param {Object=} opt_config A map of options used to configure the field. See - * the individual field's documentation for a list of properties this - * parameter supports. - * @constructor - * @abstract * @implements {IASTNodeLocationSvg} * @implements {IASTNodeLocationWithBlock} * @implements {IKeyboardAccessible} * @implements {IRegistrable} - * @alias Blockly.Field + * @abstract */ -const Field = function(value, opt_validator, opt_config) { +class Field { /** - * A generic value possessed by the field. - * Should generally be non-null, only null when the field is created. - * @type {*} - * @protected + * @param {*} value The initial value of the field. + * Also accepts Field.SKIP_SETUP if you wish to skip setup (only used by + * subclasses that want to handle configuration and setting the field + * value after their own constructors have run). + * @param {?Function=} opt_validator A function that is called to validate + * changes to the field's value. Takes in a value & returns a validated + * value, or null to abort the change. + * @param {Object=} opt_config A map of options used to configure the field. + * Refer to the individual field's documentation for a list of properties + * this parameter supports. + * @alias Blockly.Field */ - this.value_ = this.DEFAULT_VALUE; + constructor(value, opt_validator, opt_config) { + /** + * Name of field. Unique within each block. + * Static labels are usually unnamed. + * @type {string|undefined} + */ + this.name = undefined; + + /** + * A generic value possessed by the field. + * Should generally be non-null, only null when the field is created. + * @type {*} + * @protected + */ + this.value_ = + /** @type {typeof Field} */ (new.target).prototype.DEFAULT_VALUE; + + /** + * Validation function called when user edits an editable field. + * @type {Function} + * @protected + */ + this.validator_ = null; + + /** + * Used to cache the field's tooltip value if setTooltip is called when the + * field is not yet initialized. Is *not* guaranteed to be accurate. + * @type {?Tooltip.TipInfo} + * @private + */ + this.tooltip_ = null; + + /** + * The size of the area rendered by the field. + * @type {!Size} + * @protected + */ + this.size_ = new Size(0, 0); + + /** + * Holds the cursors svg element when the cursor is attached to the field. + * This is null if there is no cursor on the field. + * @type {SVGElement} + * @private + */ + this.cursorSvg_ = null; + + /** + * Holds the markers svg element when the marker is attached to the field. + * This is null if there is no marker on the field. + * @type {SVGElement} + * @private + */ + this.markerSvg_ = null; + + /** + * The rendered field's SVG group element. + * @type {SVGGElement} + * @protected + */ + this.fieldGroup_ = null; + + /** + * The rendered field's SVG border element. + * @type {SVGRectElement} + * @protected + */ + this.borderRect_ = null; + + /** + * The rendered field's SVG text element. + * @type {SVGTextElement} + * @protected + */ + this.textElement_ = null; + + /** + * The rendered field's text content element. + * @type {Text} + * @protected + */ + this.textContent_ = null; + + /** + * Mouse down event listener data. + * @type {?browserEvents.Data} + * @private + */ + this.mouseDownWrapper_ = null; + + /** + * Constants associated with the source block's renderer. + * @type {ConstantProvider} + * @protected + */ + this.constants_ = null; + + /** + * Has this field been disposed of? + * @type {boolean} + * @package + */ + this.disposed = false; + + /** + * Maximum characters of text to display before adding an ellipsis. + * @type {number} + */ + this.maxDisplayLength = 50; + + /** + * Block this field is attached to. Starts as null, then set in init. + * @type {Block} + * @protected + */ + this.sourceBlock_ = null; + + /** + * Does this block need to be re-rendered? + * @type {boolean} + * @protected + */ + this.isDirty_ = true; + + /** + * Is the field visible, or hidden due to the block being collapsed? + * @type {boolean} + * @protected + */ + this.visible_ = true; + + /** + * Can the field value be changed using the editor on an editable block? + * @type {boolean} + * @protected + */ + this.enabled_ = true; + + /** + * The element the click handler is bound to. + * @type {Element} + * @protected + */ + this.clickTarget_ = null; + + /** + * The prefix field. + * @type {?string} + * @package + */ + this.prefixField = null; + + /** + * The suffix field. + * @type {?string} + * @package + */ + this.suffixField = null; + + /** + * Editable fields usually show some sort of UI indicating they are + * editable. They will also be saved by the serializer. + * @type {boolean} + */ + this.EDITABLE = true; + + /** + * Serializable fields are saved by the serializer, non-serializable fields + * are not. Editable fields should also be serializable. This is not the + * case by default so that SERIALIZABLE is backwards compatible. + * @type {boolean} + */ + this.SERIALIZABLE = false; + + /** + * Mouse cursor style when over the hotspot that initiates the editor. + * @type {string} + */ + this.CURSOR = ''; + + if (value === Field.SKIP_SETUP) return; + if (opt_config) this.configure_(opt_config); + this.setValue(value); + if (opt_validator) this.setValidator(opt_validator); + } /** - * Validation function called when user edits an editable field. - * @type {Function} + * Process the configuration map passed to the field. + * @param {!Object} config A map of options used to configure the field. See + * the individual field's documentation for a list of properties this + * parameter supports. * @protected */ - this.validator_ = null; + configure_(config) { + let tooltip = config['tooltip']; + if (typeof tooltip === 'string') { + tooltip = parsing.replaceMessageReferences(config['tooltip']); + } + tooltip && this.setTooltip(tooltip); + + // TODO (#2884): Possibly add CSS class config option. + // TODO (#2885): Possibly add cursor config option. + } /** - * Used to cache the field's tooltip value if setTooltip is called when the - * field is not yet initialized. Is *not* guaranteed to be accurate. - * @type {?Tooltip.TipInfo} + * Attach this field to a block. + * @param {!Block} block The block containing this field. + */ + setSourceBlock(block) { + if (this.sourceBlock_) { + throw Error('Field already bound to a block'); + } + this.sourceBlock_ = block; + } + + /** + * Get the renderer constant provider. + * @return {?ConstantProvider} The renderer constant + * provider. + */ + getConstants() { + if (!this.constants_ && this.sourceBlock_ && this.sourceBlock_.workspace && + this.sourceBlock_.workspace.rendered) { + this.constants_ = + this.sourceBlock_.workspace.getRenderer().getConstants(); + } + return this.constants_; + } + + /** + * Get the block this field is attached to. + * @return {Block} The block containing this field. + */ + getSourceBlock() { + return this.sourceBlock_; + } + + /** + * Initialize everything to render this field. Override + * methods initModel and initView rather than this method. + * @package + * @final + */ + init() { + if (this.fieldGroup_) { + // Field has already been initialized once. + return; + } + this.fieldGroup_ = dom.createSvgElement(Svg.G, {}, null); + if (!this.isVisible()) { + this.fieldGroup_.style.display = 'none'; + } + const sourceBlockSvg = /** @type {!BlockSvg} **/ (this.sourceBlock_); + sourceBlockSvg.getSvgRoot().appendChild(this.fieldGroup_); + this.initView(); + this.updateEditable(); + this.setTooltip(this.tooltip_); + this.bindEvents_(); + this.initModel(); + } + + /** + * Create the block UI for this field. + * @package + */ + initView() { + this.createBorderRect_(); + this.createTextElement_(); + } + + /** + * Initializes the model of the field after it has been installed on a block. + * No-op by default. + * @package + */ + initModel() {} + + /** + * Create a field border rect element. Not to be overridden by subclasses. + * Instead modify the result of the function inside initView, or create a + * separate function to call. + * @protected + */ + createBorderRect_() { + this.borderRect_ = dom.createSvgElement( + Svg.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_); + } + + /** + * Create a field text element. Not to be overridden by subclasses. Instead + * modify the result of the function inside initView, or create a separate + * function to call. + * @protected + */ + createTextElement_() { + this.textElement_ = dom.createSvgElement( + Svg.TEXT, { + 'class': 'blocklyText', + }, + this.fieldGroup_); + if (this.getConstants().FIELD_TEXT_BASELINE_CENTER) { + this.textElement_.setAttribute('dominant-baseline', 'central'); + } + this.textContent_ = document.createTextNode(''); + this.textElement_.appendChild(this.textContent_); + } + + /** + * Bind events to the field. Can be overridden by subclasses if they need to + * do custom input handling. + * @protected + */ + bindEvents_() { + Tooltip.bindMouseEvents(this.getClickTarget_()); + this.mouseDownWrapper_ = browserEvents.conditionalBind( + this.getClickTarget_(), 'mousedown', this, this.onMouseDown_); + } + + /** + * Sets the field's value based on the given XML element. Should only be + * called by Blockly.Xml. + * @param {!Element} fieldElement The element containing info about the + * field's state. + * @package + */ + fromXml(fieldElement) { + this.setValue(fieldElement.textContent); + } + + /** + * Serializes this field's value to XML. Should only be called by Blockly.Xml. + * @param {!Element} fieldElement The element to populate with info about the + * field's state. + * @return {!Element} The element containing info about the field's state. + * @package + */ + toXml(fieldElement) { + fieldElement.textContent = this.getValue(); + return fieldElement; + } + + /** + * Saves this fields value as something which can be serialized to JSON. + * Should only be called by the serialization system. + * @param {boolean=} _doFullSerialization If true, this signals to the field + * that if it normally just saves a reference to some state (eg variable + * fields) it should instead serialize the full state of the thing being + * referenced. + * @return {*} JSON serializable state. + * @package + */ + saveState(_doFullSerialization) { + const legacyState = this.saveLegacyState(Field); + if (legacyState !== null) { + return legacyState; + } + return this.getValue(); + } + + /** + * Sets the field's state based on the given state value. Should only be + * called by the serialization system. + * @param {*} state The state we want to apply to the field. + * @package + */ + loadState(state) { + if (this.loadLegacyState(Field, state)) { + return; + } + this.setValue(state); + } + + /** + * Returns a stringified version of the XML state, if it should be used. + * Otherwise this returns null, to signal the field should use its own + * serialization. + * @param {*} callingClass The class calling this method. + * Used to see if `this` has overridden any relevant hooks. + * @return {?string} The stringified version of the XML state, or null. + * @protected + */ + saveLegacyState(callingClass) { + if (callingClass.prototype.saveState === this.saveState && + callingClass.prototype.toXml !== this.toXml) { + const elem = utilsXml.createElement('field'); + elem.setAttribute('name', this.name || ''); + const text = Xml.domToText(this.toXml(elem)); + return text.replace( + ' xmlns="https://developers.google.com/blockly/xml"', ''); + } + // Either they called this on purpose from their saveState, or they have + // no implementations of either hook. Just do our thing. + return null; + } + + /** + * Loads the given state using either the old XML hoooks, if they should be + * used. Returns true to indicate loading has been handled, false otherwise. + * @param {*} callingClass The class calling this method. + * Used to see if `this` has overridden any relevant hooks. + * @param {*} state The state to apply to the field. + * @return {boolean} Whether the state was applied or not. + */ + loadLegacyState(callingClass, state) { + if (callingClass.prototype.loadState === this.loadState && + callingClass.prototype.fromXml !== this.fromXml) { + this.fromXml(Xml.textToDom(/** @type {string} */ (state))); + return true; + } + // Either they called this on purpose from their loadState, or they have + // no implementations of either hook. Just do our thing. + return false; + } + + /** + * Dispose of all DOM objects and events belonging to this editable field. + * @package + */ + dispose() { + DropDownDiv.hideIfOwner(this); + WidgetDiv.hideIfOwner(this); + Tooltip.unbindMouseEvents(this.getClickTarget_()); + + if (this.mouseDownWrapper_) { + browserEvents.unbind(this.mouseDownWrapper_); + } + + dom.removeNode(this.fieldGroup_); + + this.disposed = true; + } + + /** + * Add or remove the UI indicating if this field is editable or not. + */ + updateEditable() { + const group = this.fieldGroup_; + if (!this.EDITABLE || !group) { + return; + } + if (this.enabled_ && this.sourceBlock_.isEditable()) { + dom.addClass(group, 'blocklyEditableText'); + dom.removeClass(group, 'blocklyNonEditableText'); + group.style.cursor = this.CURSOR; + } else { + dom.addClass(group, 'blocklyNonEditableText'); + dom.removeClass(group, 'blocklyEditableText'); + group.style.cursor = ''; + } + } + + /** + * Set whether this field's value can be changed using the editor when the + * source block is editable. + * @param {boolean} enabled True if enabled. + */ + setEnabled(enabled) { + this.enabled_ = enabled; + this.updateEditable(); + } + + /** + * Check whether this field's value can be changed using the editor when the + * source block is editable. + * @return {boolean} Whether this field is enabled. + */ + isEnabled() { + return this.enabled_; + } + + /** + * Check whether this field defines the showEditor_ function. + * @return {boolean} Whether this field is clickable. + */ + isClickable() { + return this.enabled_ && !!this.sourceBlock_ && + this.sourceBlock_.isEditable() && + this.showEditor_ !== Field.prototype.showEditor_; + } + + /** + * Check whether this field is currently editable. Some fields are never + * EDITABLE (e.g. text labels). Other fields may be EDITABLE but may exist on + * non-editable blocks or be currently disabled. + * @return {boolean} Whether this field is currently enabled, editable and on + * an editable block. + */ + isCurrentlyEditable() { + return this.enabled_ && this.EDITABLE && !!this.sourceBlock_ && + this.sourceBlock_.isEditable(); + } + + /** + * Check whether this field should be serialized by the XML renderer. + * Handles the logic for backwards compatibility and incongruous states. + * @return {boolean} Whether this field should be serialized or not. + */ + isSerializable() { + let isSerializable = false; + if (this.name) { + if (this.SERIALIZABLE) { + isSerializable = true; + } else if (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.'); + isSerializable = true; + } + } + return isSerializable; + } + + /** + * Gets whether this editable field is visible or not. + * @return {boolean} True if visible. + */ + isVisible() { + return this.visible_; + } + + /** + * Sets whether this editable field is visible or not. Should only be called + * by input.setVisible. + * @param {boolean} visible True if visible. + * @package + */ + setVisible(visible) { + if (this.visible_ === visible) { + return; + } + this.visible_ = visible; + const root = this.getSvgRoot(); + if (root) { + root.style.display = visible ? 'block' : 'none'; + } + } + + /** + * Sets a new validation function for editable fields, or clears a previously + * set validator. + * + * The validator function takes in the new field value, and returns + * validated value. The validated value could be the input value, a modified + * version of the input value, or null to abort the change. + * + * If the function does not return anything (or returns undefined) the new + * value is accepted as valid. This is to allow for fields using the + * validated function as a field-level change event notification. + * + * @param {Function} handler The validator function + * or null to clear a previous validator. + */ + setValidator(handler) { + this.validator_ = handler; + } + + /** + * Gets the validation function for editable fields, or null if not set. + * @return {?Function} Validation function, or null. + */ + getValidator() { + return this.validator_; + } + + /** + * Gets the group element for this editable field. + * Used for measuring the size and for positioning. + * @return {!SVGGElement} The group element. + */ + getSvgRoot() { + return /** @type {!SVGGElement} */ (this.fieldGroup_); + } + + /** + * Updates the field to match the colour/style of the block. Should only be + * called by BlockSvg.applyColour(). + * @package + */ + applyColour() { + // Non-abstract sub-classes may wish to implement this. See FieldDropdown. + } + + /** + * Used by getSize() to move/resize any DOM elements, and get the new size. + * + * All rendering that has an effect on the size/shape of the block should be + * done here, and should be triggered by getSize(). + * @protected + */ + render_() { + if (this.textContent_) { + this.textContent_.nodeValue = this.getDisplayText_(); + } + this.updateSize_(); + } + + /** + * Calls showEditor_ when the field is clicked if the field is clickable. + * Do not override. + * @param {Event=} opt_e Optional mouse event that triggered the field to + * open, or undefined if triggered programmatically. + * @package + * @final + */ + showEditor(opt_e) { + if (this.isClickable()) { + this.showEditor_(opt_e); + } + } + + /** + * A developer hook to create an editor for the field. This is no-op by + * default, and must be overriden to create an editor. + * @param {Event=} _e Optional mouse event that triggered the field to + * open, or undefined if triggered programmatically. + * @return {void} + * @protected + */ + showEditor_(_e) { + // NOP + } + + /** + * Updates the size of the field based on the text. + * @param {number=} opt_margin margin to use when positioning the text + * element. + * @protected + */ + updateSize_(opt_margin) { + const constants = this.getConstants(); + const xOffset = opt_margin !== undefined ? + opt_margin : + (this.borderRect_ ? this.getConstants().FIELD_BORDER_RECT_X_PADDING : + 0); + let totalWidth = xOffset * 2; + let totalHeight = constants.FIELD_TEXT_HEIGHT; + + let contentWidth = 0; + if (this.textElement_) { + contentWidth = dom.getFastTextWidth( + this.textElement_, constants.FIELD_TEXT_FONTSIZE, + constants.FIELD_TEXT_FONTWEIGHT, constants.FIELD_TEXT_FONTFAMILY); + totalWidth += contentWidth; + } + if (this.borderRect_) { + totalHeight = Math.max(totalHeight, constants.FIELD_BORDER_RECT_HEIGHT); + } + + this.size_.height = totalHeight; + this.size_.width = totalWidth; + + this.positionTextElement_(xOffset, contentWidth); + this.positionBorderRect_(); + } + + /** + * Position a field's text element after a size change. This handles both LTR + * and RTL positioning. + * @param {number} xOffset x offset to use when positioning the text element. + * @param {number} contentWidth The content width. + * @protected + */ + positionTextElement_(xOffset, contentWidth) { + if (!this.textElement_) { + return; + } + const constants = this.getConstants(); + const halfHeight = this.size_.height / 2; + + this.textElement_.setAttribute( + 'x', + this.sourceBlock_.RTL ? this.size_.width - contentWidth - xOffset : + xOffset); + this.textElement_.setAttribute( + 'y', + constants.FIELD_TEXT_BASELINE_CENTER ? + halfHeight : + halfHeight - constants.FIELD_TEXT_HEIGHT / 2 + + constants.FIELD_TEXT_BASELINE); + } + + /** + * Position a field's border rect after a size change. + * @protected + */ + positionBorderRect_() { + if (!this.borderRect_) { + return; + } + 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); + } + + /** + * Returns the height and width of the field. + * + * This should *in general* be the only place render_ gets called from. + * @return {!Size} Height and width. + */ + getSize() { + if (!this.isVisible()) { + return new Size(0, 0); + } + + if (this.isDirty_) { + this.render_(); + this.isDirty_ = false; + } else if (this.visible_ && this.size_.width === 0) { + // If the field is not visible the width will be 0 as well, one of the + // problems with the old system. + console.warn( + 'Deprecated use of setting size_.width to 0 to rerender a' + + ' field. Set field.isDirty_ to true instead.'); + this.render_(); + } + return this.size_; + } + + /** + * Returns the bounding box of the rendered field, accounting for workspace + * scaling. + * @return {!Rect} An object with top, bottom, left, and right in + * pixels relative to the top left corner of the page (window + * coordinates). + * @package + */ + getScaledBBox() { + let scaledWidth; + let scaledHeight; + let xy; + if (!this.borderRect_) { + // Browsers are inconsistent in what they return for a bounding box. + // - Webkit / Blink: fill-box / object bounding box + // - Gecko / Triden / EdgeHTML: stroke-box + const bBox = this.sourceBlock_.getHeightWidth(); + const scale = this.sourceBlock_.workspace.scale; + xy = this.getAbsoluteXY_(); + scaledWidth = bBox.width * scale; + scaledHeight = bBox.height * scale; + + if (userAgent.GECKO) { + xy.x += 1.5 * scale; + xy.y += 1.5 * scale; + scaledWidth += 1 * scale; + scaledHeight += 1 * scale; + } else { + if (!userAgent.EDGE && !userAgent.IE) { + xy.x -= 0.5 * scale; + xy.y -= 0.5 * scale; + } + scaledWidth += 1 * scale; + scaledHeight += 1 * scale; + } + } else { + const bBox = this.borderRect_.getBoundingClientRect(); + xy = style.getPageOffset(this.borderRect_); + scaledWidth = bBox.width; + scaledHeight = bBox.height; + } + return new Rect(xy.y, xy.y + scaledHeight, xy.x, xy.x + scaledWidth); + } + + /** + * Get the text from this field to display on the block. May differ from + * ``getText`` due to ellipsis, and other formatting. + * @return {string} Text to display. + * @protected + */ + getDisplayText_() { + let text = this.getText(); + if (!text) { + // Prevent the field from disappearing if empty. + return Field.NBSP; + } + if (text.length > this.maxDisplayLength) { + // Truncate displayed string and add an ellipsis ('...'). + text = text.substring(0, this.maxDisplayLength - 2) + '\u2026'; + } + // Replace whitespace with non-breaking spaces so the text doesn't collapse. + text = text.replace(/\s/g, Field.NBSP); + if (this.sourceBlock_ && this.sourceBlock_.RTL) { + // The SVG is LTR, force text to be RTL. + text += '\u200F'; + } + return text; + } + + /** + * Get the text from this field. + * Override getText_ to provide a different behavior than simply casting the + * value to a string. + * @return {string} Current text. + * @final + */ + getText() { + // this.getText_ was intended so that devs don't have to remember to call + // super when overriding how the text of the field is generated. (#2910) + const text = this.getText_(); + if (text !== null) return String(text); + return String(this.getValue()); + } + + /** + * A developer hook to override the returned text of this field. + * Override if the text representation of the value of this field + * is not just a string cast of its value. + * Return null to resort to a string cast. + * @return {?string} Current text or null. + * @protected + */ + getText_() { + return null; + } + + /** + * Force a rerender of the block that this field is installed on, which will + * rerender this field and adjust for any sizing changes. + * Other fields on the same block will not rerender, because their sizes have + * already been recorded. + * @package + */ + markDirty() { + this.isDirty_ = true; + this.constants_ = null; + } + + /** + * Force a rerender of the block that this field is installed on, which will + * rerender this field and adjust for any sizing changes. + * Other fields on the same block will not rerender, because their sizes have + * already been recorded. + * @package + */ + forceRerender() { + this.isDirty_ = true; + if (this.sourceBlock_ && this.sourceBlock_.rendered) { + this.sourceBlock_.render(); + this.sourceBlock_.bumpNeighbours(); + this.updateMarkers_(); + } + } + + /** + * Used to change the value of the field. Handles validation and events. + * Subclasses should override doClassValidation_ and doValueUpdate_ rather + * than this method. + * @param {*} newValue New value. + * @final + */ + setValue(newValue) { + const doLogging = false; + if (newValue === null) { + doLogging && console.log('null, return'); + // Not a valid value to check. + return; + } + + let validatedValue = this.doClassValidation_(newValue); + // Class validators might accidentally forget to return, we'll ignore that. + newValue = this.processValidation_(newValue, validatedValue); + if (newValue instanceof Error) { + doLogging && console.log('invalid class validation, return'); + return; + } + + const localValidator = this.getValidator(); + if (localValidator) { + validatedValue = localValidator.call(this, newValue); + // Local validators might accidentally forget to return, we'll ignore + // that. + newValue = this.processValidation_(newValue, validatedValue); + if (newValue instanceof Error) { + doLogging && console.log('invalid local validation, return'); + return; + } + } + const source = this.sourceBlock_; + if (source && source.disposed) { + doLogging && console.log('source disposed, return'); + return; + } + const oldValue = this.getValue(); + if (oldValue === newValue) { + doLogging && console.log('same, doValueUpdate_, return'); + this.doValueUpdate_(newValue); + return; + } + + this.doValueUpdate_(newValue); + if (source && eventUtils.isEnabled()) { + eventUtils.fire(new (eventUtils.get(eventUtils.BLOCK_CHANGE))( + source, 'field', this.name || null, oldValue, newValue)); + } + if (this.isDirty_) { + this.forceRerender(); + } + doLogging && console.log(this.value_); + } + + /** + * Process the result of validation. + * @param {*} newValue New value. + * @param {*} validatedValue Validated value. + * @return {*} New value, or an Error object. * @private */ - this.tooltip_ = null; + processValidation_(newValue, validatedValue) { + if (validatedValue === null) { + this.doValueInvalid_(newValue); + if (this.isDirty_) { + this.forceRerender(); + } + return Error(); + } + if (validatedValue !== undefined) { + newValue = validatedValue; + } + return newValue; + } /** - * The size of the area rendered by the field. - * @type {!Size} + * Get the current value of the field. + * @return {*} Current value. + */ + getValue() { + return this.value_; + } + + /** + * Used to validate a value. Returns input by default. Can be overridden by + * subclasses, see FieldDropdown. + * @param {*=} opt_newValue The value to be validated. + * @return {*} The validated value, same as input by default. * @protected */ - this.size_ = new Size(0, 0); + doClassValidation_(opt_newValue) { + if (opt_newValue === null || opt_newValue === undefined) { + return null; + } + return opt_newValue; + } /** - * Holds the cursors svg element when the cursor is attached to the field. - * This is null if there is no cursor on the field. - * @type {SVGElement} - * @private - */ - this.cursorSvg_ = null; - - /** - * Holds the markers svg element when the marker is attached to the field. - * This is null if there is no marker on the field. - * @type {SVGElement} - * @private - */ - this.markerSvg_ = null; - - /** - * The rendered field's SVG group element. - * @type {SVGGElement} + * Used to update the value of a field. Can be overridden by subclasses to do + * custom storage of values/updating of external things. + * @param {*} newValue The value to be saved. * @protected */ - this.fieldGroup_ = null; + doValueUpdate_(newValue) { + this.value_ = newValue; + this.isDirty_ = true; + } /** - * The rendered field's SVG border element. - * @type {SVGRectElement} + * Used to notify the field an invalid value was input. Can be overridden by + * subclasses, see FieldTextInput. + * No-op by default. + * @param {*} _invalidValue The input value that was determined to be invalid. * @protected */ - this.borderRect_ = null; + doValueInvalid_(_invalidValue) { + // NOP + } /** - * The rendered field's SVG text element. - * @type {SVGTextElement} + * Handle a mouse down event on a field. + * @param {!Event} e Mouse down event. * @protected */ - this.textElement_ = null; + onMouseDown_(e) { + if (!this.sourceBlock_ || !this.sourceBlock_.workspace) { + return; + } + const gesture = this.sourceBlock_.workspace.getGesture(e); + if (gesture) { + gesture.setStartField(this); + } + } /** - * The rendered field's text content element. - * @type {Text} + * Sets the tooltip for this field. + * @param {?Tooltip.TipInfo} newTip The + * text for the tooltip, a function that returns the text for the tooltip, + * a parent object whose tooltip will be used, or null to display the tooltip + * of the parent block. To not display a tooltip pass the empty string. + */ + setTooltip(newTip) { + if (!newTip && newTip !== '') { // If null or undefined. + newTip = this.sourceBlock_; + } + const clickTarget = this.getClickTarget_(); + if (clickTarget) { + clickTarget.tooltip = newTip; + } else { + // Field has not been initialized yet. + this.tooltip_ = newTip; + } + } + + /** + * Returns the tooltip text for this field. + * @return {string} The tooltip text for this field. + */ + getTooltip() { + const clickTarget = this.getClickTarget_(); + if (clickTarget) { + return Tooltip.getTooltipOfObject(clickTarget); + } + // Field has not been initialized yet. Return stashed this.tooltip_ value. + return Tooltip.getTooltipOfObject({tooltip: this.tooltip_}); + } + + /** + * The element to bind the click handler to. If not set explicitly, defaults + * to the SVG root of the field. When this element is + * clicked on an editable field, the editor will open. + * @return {!Element} Element to bind click handler to. * @protected */ - this.textContent_ = null; + getClickTarget_() { + return this.clickTarget_ || this.getSvgRoot(); + } /** - * Mouse down event listener data. - * @type {?browserEvents.Data} - * @private - */ - this.mouseDownWrapper_ = null; - - /** - * Constants associated with the source block's renderer. - * @type {ConstantProvider} + * Return the absolute coordinates of the top-left corner of this field. + * The origin (0,0) is the top-left corner of the page body. + * @return {!Coordinate} Object with .x and .y properties. * @protected */ - this.constants_ = null; + getAbsoluteXY_() { + return style.getPageOffset( + /** @type {!SVGRectElement} */ (this.getClickTarget_())); + } - opt_config && this.configure_(opt_config); - this.setValue(value); - opt_validator && this.setValidator(opt_validator); -}; + /** + * Whether this field references any Blockly variables. If true it may need + * to be handled differently during serialization and deserialization. + * Subclasses may override this. + * @return {boolean} True if this field has any variable references. + * @package + */ + referencesVariables() { + return false; + } + + /** + * Refresh the variable name referenced by this field if this field references + * variables. + * @package + */ + refreshVariableName() { + // NOP + } + + /** + * Search through the list of inputs and their fields in order to find the + * parent input of a field. + * @return {Input} The input that the field belongs to. + * @package + */ + getParentInput() { + let parentInput = null; + const block = this.sourceBlock_; + const inputs = block.inputList; + + for (let idx = 0; idx < block.inputList.length; idx++) { + const input = inputs[idx]; + const fieldRows = input.fieldRow; + for (let j = 0; j < fieldRows.length; j++) { + if (fieldRows[j] === this) { + parentInput = input; + break; + } + } + } + return parentInput; + } + + /** + * Returns whether or not we should flip the field in RTL. + * @return {boolean} True if we should flip in RTL. + */ + getFlipRtl() { + return false; + } + + /** + * Returns whether or not the field is tab navigable. + * @return {boolean} True if the field is tab navigable. + */ + isTabNavigable() { + return false; + } + + /** + * Handles the given keyboard shortcut. + * @param {!ShortcutRegistry.KeyboardShortcut} _shortcut The shortcut to be + * handled. + * @return {boolean} True if the shortcut has been handled, false otherwise. + * @public + */ + onShortcut(_shortcut) { + return false; + } + + /** + * Add the cursor SVG to this fields SVG group. + * @param {SVGElement} cursorSvg The SVG root of the cursor to be added to the + * field group. + * @package + */ + setCursorSvg(cursorSvg) { + if (!cursorSvg) { + this.cursorSvg_ = null; + return; + } + + this.fieldGroup_.appendChild(cursorSvg); + this.cursorSvg_ = cursorSvg; + } + + /** + * Add the marker SVG to this fields SVG group. + * @param {SVGElement} markerSvg The SVG root of the marker to be added to the + * field group. + * @package + */ + setMarkerSvg(markerSvg) { + if (!markerSvg) { + this.markerSvg_ = null; + return; + } + + this.fieldGroup_.appendChild(markerSvg); + this.markerSvg_ = markerSvg; + } + + /** + * Redraw any attached marker or cursor svgs if needed. + * @protected + */ + updateMarkers_() { + const workspace = + /** @type {!WorkspaceSvg} */ (this.sourceBlock_.workspace); + if (workspace.keyboardAccessibilityMode && this.cursorSvg_) { + workspace.getCursor().draw(); + } + if (workspace.keyboardAccessibilityMode && this.markerSvg_) { + // TODO(#4592): Update all markers on the field. + workspace.getMarker(MarkerManager.LOCAL_MARKER).draw(); + } + } +} /** * The default value for this field. @@ -180,82 +1260,6 @@ const Field = function(value, opt_validator, opt_config) { */ Field.prototype.DEFAULT_VALUE = null; -/** - * Name of field. Unique within each block. - * Static labels are usually unnamed. - * @type {string|undefined} - */ -Field.prototype.name = undefined; - -/** - * Has this field been disposed of? - * @type {boolean} - * @package - */ -Field.prototype.disposed = false; - -/** - * Maximum characters of text to display before adding an ellipsis. - * @type {number} - */ -Field.prototype.maxDisplayLength = 50; - -/** - * Block this field is attached to. Starts as null, then set in init. - * @type {Block} - * @protected - */ -Field.prototype.sourceBlock_ = null; - -/** - * Does this block need to be re-rendered? - * @type {boolean} - * @protected - */ -Field.prototype.isDirty_ = true; - -/** - * Is the field visible, or hidden due to the block being collapsed? - * @type {boolean} - * @protected - */ -Field.prototype.visible_ = true; - -/** - * Can the field value be changed using the editor on an editable block? - * @type {boolean} - * @protected - */ -Field.prototype.enabled_ = true; - -/** - * The element the click handler is bound to. - * @type {Element} - * @protected - */ -Field.prototype.clickTarget_ = null; - -/** - * A developer hook to override the returned text of this field. - * Override if the text representation of the value of this field - * is not just a string cast of its value. - * Return null to resort to a string cast. - * @return {?string} Current text. Return null to resort to a string cast. - * @protected - */ -Field.prototype.getText_; - -/** - * An optional method that can be defined to show an editor when the field is - * clicked. Blockly will automatically set the field as clickable if this - * method is defined. - * @param {Event=} opt_e Optional mouse event that triggered the field to open, - * or undefined if triggered programmatically. - * @return {void} - * @protected - */ -Field.prototype.showEditor_; - /** * Non-breaking space. * @const @@ -263,956 +1267,11 @@ Field.prototype.showEditor_; Field.NBSP = '\u00A0'; /** - * Editable fields usually show some sort of UI indicating they are editable. - * They will also be saved by the XML renderer. - * @type {boolean} + * A value used to signal when a field's constructor should *not* set the + * field's value or run configure_, and should allow a subclass to do that + * instead. + * @const */ -Field.prototype.EDITABLE = true; - -/** - * Serializable fields are saved by the XML renderer, non-serializable fields - * are not. Editable fields should also be serializable. This is not the - * case by default so that SERIALIZABLE is backwards compatible. - * @type {boolean} - */ -Field.prototype.SERIALIZABLE = false; - -/** - * Process the configuration map passed to the field. - * @param {!Object} config A map of options used to configure the field. See - * the individual field's documentation for a list of properties this - * parameter supports. - * @protected - */ -Field.prototype.configure_ = function(config) { - let tooltip = config['tooltip']; - if (typeof tooltip === 'string') { - tooltip = parsing.replaceMessageReferences(config['tooltip']); - } - tooltip && this.setTooltip(tooltip); - - // TODO (#2884): Possibly add CSS class config option. - // TODO (#2885): Possibly add cursor config option. -}; - -/** - * Attach this field to a block. - * @param {!Block} block The block containing this field. - */ -Field.prototype.setSourceBlock = function(block) { - if (this.sourceBlock_) { - throw Error('Field already bound to a block'); - } - this.sourceBlock_ = block; -}; - -/** - * Get the renderer constant provider. - * @return {?ConstantProvider} The renderer constant - * provider. - */ -Field.prototype.getConstants = function() { - if (!this.constants_ && this.sourceBlock_ && this.sourceBlock_.workspace && - this.sourceBlock_.workspace.rendered) { - this.constants_ = this.sourceBlock_.workspace.getRenderer().getConstants(); - } - return this.constants_; -}; - -/** - * Get the block this field is attached to. - * @return {Block} The block containing this field. - */ -Field.prototype.getSourceBlock = function() { - return this.sourceBlock_; -}; - -/** - * Initialize everything to render this field. Override - * methods initModel and initView rather than this method. - * @package - */ -Field.prototype.init = function() { - if (this.fieldGroup_) { - // Field has already been initialized once. - return; - } - this.fieldGroup_ = dom.createSvgElement(Svg.G, {}, null); - if (!this.isVisible()) { - this.fieldGroup_.style.display = 'none'; - } - const sourceBlockSvg = /** @type {!BlockSvg} **/ (this.sourceBlock_); - sourceBlockSvg.getSvgRoot().appendChild(this.fieldGroup_); - this.initView(); - this.updateEditable(); - this.setTooltip(this.tooltip_); - this.bindEvents_(); - this.initModel(); -}; - -/** - * Create the block UI for this field. - * @package - */ -Field.prototype.initView = function() { - this.createBorderRect_(); - this.createTextElement_(); -}; - -/** - * Initializes the model of the field after it has been installed on a block. - * No-op by default. - * @package - */ -Field.prototype.initModel = function() {}; - -/** - * Create a field border rect element. Not to be overridden by subclasses. - * Instead modify the result of the function inside initView, or create a - * separate function to call. - * @protected - */ -Field.prototype.createBorderRect_ = function() { - this.borderRect_ = dom.createSvgElement( - Svg.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_); -}; - -/** - * Create a field text element. Not to be overridden by subclasses. Instead - * modify the result of the function inside initView, or create a separate - * function to call. - * @protected - */ -Field.prototype.createTextElement_ = function() { - this.textElement_ = dom.createSvgElement( - Svg.TEXT, { - 'class': 'blocklyText', - }, - this.fieldGroup_); - if (this.getConstants().FIELD_TEXT_BASELINE_CENTER) { - this.textElement_.setAttribute('dominant-baseline', 'central'); - } - this.textContent_ = document.createTextNode(''); - this.textElement_.appendChild(this.textContent_); -}; - -/** - * Bind events to the field. Can be overridden by subclasses if they need to do - * custom input handling. - * @protected - */ -Field.prototype.bindEvents_ = function() { - Tooltip.bindMouseEvents(this.getClickTarget_()); - this.mouseDownWrapper_ = browserEvents.conditionalBind( - this.getClickTarget_(), 'mousedown', this, this.onMouseDown_); -}; - -/** - * Sets the field's value based on the given XML element. Should only be called - * by Blockly.Xml. - * @param {!Element} fieldElement The element containing info about the - * field's state. - * @package - */ -Field.prototype.fromXml = function(fieldElement) { - this.setValue(fieldElement.textContent); -}; - -/** - * Serializes this field's value to XML. Should only be called by Blockly.Xml. - * @param {!Element} fieldElement The element to populate with info about the - * field's state. - * @return {!Element} The element containing info about the field's state. - * @package - */ -Field.prototype.toXml = function(fieldElement) { - fieldElement.textContent = this.getValue(); - return fieldElement; -}; - -/** - * Saves this fields value as something which can be serialized to JSON. Should - * only be called by the serialization system. - * @param {boolean=} _doFullSerialization If true, this signals to the field - * that if it normally just saves a reference to some state (eg variable - * fields) it should instead serialize the full state of the thing being - * referenced. - * @return {*} JSON serializable state. - * @package - */ -Field.prototype.saveState = function(_doFullSerialization) { - const legacyState = this.saveLegacyState(Field); - if (legacyState !== null) { - return legacyState; - } - return this.getValue(); -}; - -/** - * Sets the field's state based on the given state value. Should only be called - * by the serialization system. - * @param {*} state The state we want to apply to the field. - * @package - */ -Field.prototype.loadState = function(state) { - if (this.loadLegacyState(Field, state)) { - return; - } - this.setValue(state); -}; - -/** - * Returns a stringified version of the XML state, if it should be used. - * Otherwise this returns null, to signal the field should use its own - * serialization. - * @param {*} callingClass The class calling this method. - * Used to see if `this` has overridden any relevant hooks. - * @return {?string} The stringified version of the XML state, or null. - * @protected - */ -Field.prototype.saveLegacyState = function(callingClass) { - if (callingClass.prototype.saveState === this.saveState && - callingClass.prototype.toXml !== this.toXml) { - const elem = utilsXml.createElement('field'); - elem.setAttribute('name', this.name || ''); - const text = Xml.domToText(this.toXml(elem)); - return text.replace( - ' xmlns="https://developers.google.com/blockly/xml"', ''); - } - // Either they called this on purpose from their saveState, or they have - // no implementations of either hook. Just do our thing. - return null; -}; - -/** - * Loads the given state using either the old XML hoooks, if they should be - * used. Returns true to indicate loading has been handled, false otherwise. - * @param {*} callingClass The class calling this method. - * Used to see if `this` has overridden any relevant hooks. - * @param {*} state The state to apply to the field. - * @return {boolean} Whether the state was applied or not. - */ -Field.prototype.loadLegacyState = function(callingClass, state) { - if (callingClass.prototype.loadState === this.loadState && - callingClass.prototype.fromXml !== this.fromXml) { - this.fromXml(Xml.textToDom(/** @type {string} */ (state))); - return true; - } - // Either they called this on purpose from their loadState, or they have - // no implementations of either hook. Just do our thing. - return false; -}; - -/** - * Dispose of all DOM objects and events belonging to this editable field. - * @package - */ -Field.prototype.dispose = function() { - DropDownDiv.hideIfOwner(this); - WidgetDiv.hideIfOwner(this); - Tooltip.unbindMouseEvents(this.getClickTarget_()); - - if (this.mouseDownWrapper_) { - browserEvents.unbind(this.mouseDownWrapper_); - } - - dom.removeNode(this.fieldGroup_); - - this.disposed = true; -}; - -/** - * Add or remove the UI indicating if this field is editable or not. - */ -Field.prototype.updateEditable = function() { - const group = this.fieldGroup_; - if (!this.EDITABLE || !group) { - return; - } - if (this.enabled_ && this.sourceBlock_.isEditable()) { - dom.addClass(group, 'blocklyEditableText'); - dom.removeClass(group, 'blocklyNonEditableText'); - group.style.cursor = this.CURSOR; - } else { - dom.addClass(group, 'blocklyNonEditableText'); - dom.removeClass(group, 'blocklyEditableText'); - group.style.cursor = ''; - } -}; - -/** - * Set whether this field's value can be changed using the editor when the - * source block is editable. - * @param {boolean} enabled True if enabled. - */ -Field.prototype.setEnabled = function(enabled) { - this.enabled_ = enabled; - this.updateEditable(); -}; - -/** - * Check whether this field's value can be changed using the editor when the - * source block is editable. - * @return {boolean} Whether this field is enabled. - */ -Field.prototype.isEnabled = function() { - return this.enabled_; -}; - -/** - * Check whether this field defines the showEditor_ function. - * @return {boolean} Whether this field is clickable. - */ -Field.prototype.isClickable = function() { - return this.enabled_ && !!this.sourceBlock_ && - this.sourceBlock_.isEditable() && !!this.showEditor_ && - (typeof this.showEditor_ === 'function'); -}; - -/** - * Check whether this field is currently editable. Some fields are never - * EDITABLE (e.g. text labels). Other fields may be EDITABLE but may exist on - * non-editable blocks or be currently disabled. - * @return {boolean} Whether this field is currently enabled, editable and on - * an editable block. - */ -Field.prototype.isCurrentlyEditable = function() { - return this.enabled_ && this.EDITABLE && !!this.sourceBlock_ && - this.sourceBlock_.isEditable(); -}; - -/** - * Check whether this field should be serialized by the XML renderer. - * Handles the logic for backwards compatibility and incongruous states. - * @return {boolean} Whether this field should be serialized or not. - */ -Field.prototype.isSerializable = function() { - let isSerializable = false; - if (this.name) { - if (this.SERIALIZABLE) { - isSerializable = true; - } else if (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.'); - isSerializable = true; - } - } - return isSerializable; -}; - -/** - * Gets whether this editable field is visible or not. - * @return {boolean} True if visible. - */ -Field.prototype.isVisible = function() { - return this.visible_; -}; - -/** - * Sets whether this editable field is visible or not. Should only be called - * by input.setVisible. - * @param {boolean} visible True if visible. - * @package - */ -Field.prototype.setVisible = function(visible) { - if (this.visible_ === visible) { - return; - } - this.visible_ = visible; - const root = this.getSvgRoot(); - if (root) { - root.style.display = visible ? 'block' : 'none'; - } -}; - -/** - * Sets a new validation function for editable fields, or clears a previously - * set validator. - * - * The validator function takes in the new field value, and returns - * validated value. The validated value could be the input value, a modified - * version of the input value, or null to abort the change. - * - * If the function does not return anything (or returns undefined) the new - * value is accepted as valid. This is to allow for fields using the - * validated function as a field-level change event notification. - * - * @param {Function} handler The validator function - * or null to clear a previous validator. - */ -Field.prototype.setValidator = function(handler) { - this.validator_ = handler; -}; - -/** - * Gets the validation function for editable fields, or null if not set. - * @return {?Function} Validation function, or null. - */ -Field.prototype.getValidator = function() { - return this.validator_; -}; - -/** - * Gets the group element for this editable field. - * Used for measuring the size and for positioning. - * @return {!SVGGElement} The group element. - */ -Field.prototype.getSvgRoot = function() { - return /** @type {!SVGGElement} */ (this.fieldGroup_); -}; - -/** - * Updates the field to match the colour/style of the block. Should only be - * called by BlockSvg.applyColour(). - * @package - */ -Field.prototype.applyColour = function() { - // Non-abstract sub-classes may wish to implement this. See FieldDropdown. -}; - -/** - * Used by getSize() to move/resize any DOM elements, and get the new size. - * - * All rendering that has an effect on the size/shape of the block should be - * done here, and should be triggered by getSize(). - * @protected - */ -Field.prototype.render_ = function() { - if (this.textContent_) { - this.textContent_.nodeValue = this.getDisplayText_(); - } - this.updateSize_(); -}; - -/** - * Show an editor when the field is clicked only if the field is clickable. - * @param {Event=} opt_e Optional mouse event that triggered the field to open, - * or undefined if triggered programmatically. - * @package - */ -Field.prototype.showEditor = function(opt_e) { - if (this.isClickable()) { - this.showEditor_(opt_e); - } -}; - -/** - * Updates the size of the field based on the text. - * @param {number=} opt_margin margin to use when positioning the text element. - * @protected - */ -Field.prototype.updateSize_ = function(opt_margin) { - const constants = this.getConstants(); - const xOffset = opt_margin !== undefined ? - opt_margin : - (this.borderRect_ ? this.getConstants().FIELD_BORDER_RECT_X_PADDING : 0); - let totalWidth = xOffset * 2; - let totalHeight = constants.FIELD_TEXT_HEIGHT; - - let contentWidth = 0; - if (this.textElement_) { - contentWidth = dom.getFastTextWidth( - this.textElement_, constants.FIELD_TEXT_FONTSIZE, - constants.FIELD_TEXT_FONTWEIGHT, constants.FIELD_TEXT_FONTFAMILY); - totalWidth += contentWidth; - } - if (this.borderRect_) { - totalHeight = Math.max(totalHeight, constants.FIELD_BORDER_RECT_HEIGHT); - } - - this.size_.height = totalHeight; - this.size_.width = totalWidth; - - this.positionTextElement_(xOffset, contentWidth); - this.positionBorderRect_(); -}; - -/** - * Position a field's text element after a size change. This handles both LTR - * and RTL positioning. - * @param {number} xOffset x offset to use when positioning the text element. - * @param {number} contentWidth The content width. - * @protected - */ -Field.prototype.positionTextElement_ = function(xOffset, contentWidth) { - if (!this.textElement_) { - return; - } - const constants = this.getConstants(); - const halfHeight = this.size_.height / 2; - - this.textElement_.setAttribute( - 'x', - this.sourceBlock_.RTL ? this.size_.width - contentWidth - xOffset : - xOffset); - this.textElement_.setAttribute( - 'y', - constants.FIELD_TEXT_BASELINE_CENTER ? halfHeight : - halfHeight - - constants.FIELD_TEXT_HEIGHT / 2 + constants.FIELD_TEXT_BASELINE); -}; - -/** - * Position a field's border rect after a size change. - * @protected - */ -Field.prototype.positionBorderRect_ = function() { - if (!this.borderRect_) { - return; - } - 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); -}; - - -/** - * Returns the height and width of the field. - * - * This should *in general* be the only place render_ gets called from. - * @return {!Size} Height and width. - */ -Field.prototype.getSize = function() { - if (!this.isVisible()) { - return new Size(0, 0); - } - - if (this.isDirty_) { - this.render_(); - this.isDirty_ = false; - } else if (this.visible_ && this.size_.width === 0) { - // If the field is not visible the width will be 0 as well, one of the - // problems with the old system. - console.warn( - 'Deprecated use of setting size_.width to 0 to rerender a' + - ' field. Set field.isDirty_ to true instead.'); - this.render_(); - } - return this.size_; -}; - -/** - * Returns the bounding box of the rendered field, accounting for workspace - * scaling. - * @return {!Rect} An object with top, bottom, left, and right in - * pixels relative to the top left corner of the page (window coordinates). - * @package - */ -Field.prototype.getScaledBBox = function() { - let scaledWidth; - let scaledHeight; - let xy; - if (!this.borderRect_) { - // Browsers are inconsistent in what they return for a bounding box. - // - Webkit / Blink: fill-box / object bounding box - // - Gecko / Triden / EdgeHTML: stroke-box - const bBox = this.sourceBlock_.getHeightWidth(); - const scale = this.sourceBlock_.workspace.scale; - xy = this.getAbsoluteXY_(); - scaledWidth = bBox.width * scale; - scaledHeight = bBox.height * scale; - - if (userAgent.GECKO) { - xy.x += 1.5 * scale; - xy.y += 1.5 * scale; - scaledWidth += 1 * scale; - scaledHeight += 1 * scale; - } else { - if (!userAgent.EDGE && !userAgent.IE) { - xy.x -= 0.5 * scale; - xy.y -= 0.5 * scale; - } - scaledWidth += 1 * scale; - scaledHeight += 1 * scale; - } - } else { - const bBox = this.borderRect_.getBoundingClientRect(); - xy = style.getPageOffset(this.borderRect_); - scaledWidth = bBox.width; - scaledHeight = bBox.height; - } - return new Rect(xy.y, xy.y + scaledHeight, xy.x, xy.x + scaledWidth); -}; - -/** - * Get the text from this field to display on the block. May differ from - * ``getText`` due to ellipsis, and other formatting. - * @return {string} Text to display. - * @protected - */ -Field.prototype.getDisplayText_ = function() { - let text = this.getText(); - if (!text) { - // Prevent the field from disappearing if empty. - return Field.NBSP; - } - if (text.length > this.maxDisplayLength) { - // Truncate displayed string and add an ellipsis ('...'). - text = text.substring(0, this.maxDisplayLength - 2) + '\u2026'; - } - // Replace whitespace with non-breaking spaces so the text doesn't collapse. - text = text.replace(/\s/g, Field.NBSP); - if (this.sourceBlock_ && this.sourceBlock_.RTL) { - // The SVG is LTR, force text to be RTL. - text += '\u200F'; - } - return text; -}; - -/** - * Get the text from this field. - * @return {string} Current text. - */ -Field.prototype.getText = function() { - if (this.getText_) { - const text = this.getText_.call(this); - if (text !== null) { - return String(text); - } - } - return String(this.getValue()); -}; - -/** - * Force a rerender of the block that this field is installed on, which will - * rerender this field and adjust for any sizing changes. - * Other fields on the same block will not rerender, because their sizes have - * already been recorded. - * @package - */ -Field.prototype.markDirty = function() { - this.isDirty_ = true; - this.constants_ = null; -}; - -/** - * Force a rerender of the block that this field is installed on, which will - * rerender this field and adjust for any sizing changes. - * Other fields on the same block will not rerender, because their sizes have - * already been recorded. - * @package - */ -Field.prototype.forceRerender = function() { - this.isDirty_ = true; - if (this.sourceBlock_ && this.sourceBlock_.rendered) { - this.sourceBlock_.render(); - this.sourceBlock_.bumpNeighbours(); - this.updateMarkers_(); - } -}; - -/** - * Used to change the value of the field. Handles validation and events. - * Subclasses should override doClassValidation_ and doValueUpdate_ rather - * than this method. - * @param {*} newValue New value. - */ -Field.prototype.setValue = function(newValue) { - const doLogging = false; - if (newValue === null) { - doLogging && console.log('null, return'); - // Not a valid value to check. - return; - } - - let validatedValue = this.doClassValidation_(newValue); - // Class validators might accidentally forget to return, we'll ignore that. - newValue = this.processValidation_(newValue, validatedValue); - if (newValue instanceof Error) { - doLogging && console.log('invalid class validation, return'); - return; - } - - const localValidator = this.getValidator(); - if (localValidator) { - validatedValue = localValidator.call(this, newValue); - // Local validators might accidentally forget to return, we'll ignore that. - newValue = this.processValidation_(newValue, validatedValue); - if (newValue instanceof Error) { - doLogging && console.log('invalid local validation, return'); - return; - } - } - const source = this.sourceBlock_; - if (source && source.disposed) { - doLogging && console.log('source disposed, return'); - return; - } - const oldValue = this.getValue(); - if (oldValue === newValue) { - doLogging && console.log('same, doValueUpdate_, return'); - this.doValueUpdate_(newValue); - return; - } - - this.doValueUpdate_(newValue); - if (source && eventUtils.isEnabled()) { - eventUtils.fire(new (eventUtils.get(eventUtils.BLOCK_CHANGE))( - source, 'field', this.name || null, oldValue, newValue)); - } - if (this.isDirty_) { - this.forceRerender(); - } - doLogging && console.log(this.value_); -}; - -/** - * Process the result of validation. - * @param {*} newValue New value. - * @param {*} validatedValue Validated value. - * @return {*} New value, or an Error object. - * @private - */ -Field.prototype.processValidation_ = function(newValue, validatedValue) { - if (validatedValue === null) { - this.doValueInvalid_(newValue); - if (this.isDirty_) { - this.forceRerender(); - } - return Error(); - } - if (validatedValue !== undefined) { - newValue = validatedValue; - } - return newValue; -}; - -/** - * Get the current value of the field. - * @return {*} Current value. - */ -Field.prototype.getValue = function() { - return this.value_; -}; - -/** - * Used to validate a value. Returns input by default. Can be overridden by - * subclasses, see FieldDropdown. - * @param {*=} opt_newValue The value to be validated. - * @return {*} The validated value, same as input by default. - * @protected - */ -Field.prototype.doClassValidation_ = function(opt_newValue) { - if (opt_newValue === null || opt_newValue === undefined) { - return null; - } - return opt_newValue; -}; - -/** - * Used to update the value of a field. Can be overridden by subclasses to do - * custom storage of values/updating of external things. - * @param {*} newValue The value to be saved. - * @protected - */ -Field.prototype.doValueUpdate_ = function(newValue) { - this.value_ = newValue; - this.isDirty_ = true; -}; - -/** - * Used to notify the field an invalid value was input. Can be overridden by - * subclasses, see FieldTextInput. - * No-op by default. - * @param {*} _invalidValue The input value that was determined to be invalid. - * @protected - */ -Field.prototype.doValueInvalid_ = function(_invalidValue) { - // NOP -}; - -/** - * Handle a mouse down event on a field. - * @param {!Event} e Mouse down event. - * @protected - */ -Field.prototype.onMouseDown_ = function(e) { - if (!this.sourceBlock_ || !this.sourceBlock_.workspace) { - return; - } - const gesture = this.sourceBlock_.workspace.getGesture(e); - if (gesture) { - gesture.setStartField(this); - } -}; - -/** - * Sets the tooltip for this field. - * @param {?Tooltip.TipInfo} newTip The - * text for the tooltip, a function that returns the text for the tooltip, a - * parent object whose tooltip will be used, or null to display the tooltip - * of the parent block. To not display a tooltip pass the empty string. - */ -Field.prototype.setTooltip = function(newTip) { - if (!newTip && newTip !== '') { // If null or undefined. - newTip = this.sourceBlock_; - } - const clickTarget = this.getClickTarget_(); - if (clickTarget) { - clickTarget.tooltip = newTip; - } else { - // Field has not been initialized yet. - this.tooltip_ = newTip; - } -}; - -/** - * Returns the tooltip text for this field. - * @return {string} The tooltip text for this field. - */ -Field.prototype.getTooltip = function() { - const clickTarget = this.getClickTarget_(); - if (clickTarget) { - return Tooltip.getTooltipOfObject(clickTarget); - } - // Field has not been initialized yet. Return stashed this.tooltip_ value. - return Tooltip.getTooltipOfObject({tooltip: this.tooltip_}); -}; - -/** - * The element to bind the click handler to. If not set explicitly, defaults - * to the SVG root of the field. When this element is - * clicked on an editable field, the editor will open. - * @return {!Element} Element to bind click handler to. - * @protected - */ -Field.prototype.getClickTarget_ = function() { - return this.clickTarget_ || this.getSvgRoot(); -}; - -/** - * Return the absolute coordinates of the top-left corner of this field. - * The origin (0,0) is the top-left corner of the page body. - * @return {!Coordinate} Object with .x and .y properties. - * @protected - */ -Field.prototype.getAbsoluteXY_ = function() { - return style.getPageOffset( - /** @type {!SVGRectElement} */ (this.getClickTarget_())); -}; - -/** - * Whether this field references any Blockly variables. If true it may need to - * be handled differently during serialization and deserialization. Subclasses - * may override this. - * @return {boolean} True if this field has any variable references. - * @package - */ -Field.prototype.referencesVariables = function() { - return false; -}; - -/** - * Search through the list of inputs and their fields in order to find the - * parent input of a field. - * @return {Input} The input that the field belongs to. - * @package - */ -Field.prototype.getParentInput = function() { - let parentInput = null; - const block = this.sourceBlock_; - const inputs = block.inputList; - - for (let idx = 0; idx < block.inputList.length; idx++) { - const input = inputs[idx]; - const fieldRows = input.fieldRow; - for (let j = 0; j < fieldRows.length; j++) { - if (fieldRows[j] === this) { - parentInput = input; - break; - } - } - } - return parentInput; -}; - -/** - * Returns whether or not we should flip the field in RTL. - * @return {boolean} True if we should flip in RTL. - */ -Field.prototype.getFlipRtl = function() { - return false; -}; - -/** - * Returns whether or not the field is tab navigable. - * @return {boolean} True if the field is tab navigable. - */ -Field.prototype.isTabNavigable = function() { - return false; -}; - -/** - * Handles the given keyboard shortcut. - * @param {!ShortcutRegistry.KeyboardShortcut} _shortcut The shortcut to be - * handled. - * @return {boolean} True if the shortcut has been handled, false otherwise. - * @public - */ -Field.prototype.onShortcut = function(_shortcut) { - return false; -}; - -/** - * Add the cursor SVG to this fields SVG group. - * @param {SVGElement} cursorSvg The SVG root of the cursor to be added to the - * field group. - * @package - */ -Field.prototype.setCursorSvg = function(cursorSvg) { - if (!cursorSvg) { - this.cursorSvg_ = null; - return; - } - - this.fieldGroup_.appendChild(cursorSvg); - this.cursorSvg_ = cursorSvg; -}; - -/** - * Add the marker SVG to this fields SVG group. - * @param {SVGElement} markerSvg The SVG root of the marker to be added to the - * field group. - * @package - */ -Field.prototype.setMarkerSvg = function(markerSvg) { - if (!markerSvg) { - this.markerSvg_ = null; - return; - } - - this.fieldGroup_.appendChild(markerSvg); - this.markerSvg_ = markerSvg; -}; - -/** - * Redraw any attached marker or cursor svgs if needed. - * @protected - */ -Field.prototype.updateMarkers_ = function() { - const workspace = - /** @type {!WorkspaceSvg} */ (this.sourceBlock_.workspace); - if (workspace.keyboardAccessibilityMode && this.cursorSvg_) { - workspace.getCursor().draw(); - } - if (workspace.keyboardAccessibilityMode && this.markerSvg_) { - // TODO(#4592): Update all markers on the field. - workspace.getMarker(MarkerManager.LOCAL_MARKER).draw(); - } -}; +Field.SKIP_SETUP = new Sentinel(); exports.Field = Field; diff --git a/core/field_angle.js b/core/field_angle.js index bfc5843ea..ea498fcad 100644 --- a/core/field_angle.js +++ b/core/field_angle.js @@ -21,108 +21,491 @@ const browserEvents = goog.require('Blockly.browserEvents'); const dom = goog.require('Blockly.utils.dom'); const fieldRegistry = goog.require('Blockly.fieldRegistry'); const math = goog.require('Blockly.utils.math'); -const object = goog.require('Blockly.utils.object'); const userAgent = goog.require('Blockly.utils.userAgent'); const {DropDownDiv} = goog.require('Blockly.DropDownDiv'); +const {Field} = goog.require('Blockly.Field'); const {FieldTextInput} = goog.require('Blockly.FieldTextInput'); const {KeyCodes} = goog.require('Blockly.utils.KeyCodes'); +/* eslint-disable-next-line no-unused-vars */ +const {Sentinel} = goog.requireType('Blockly.utils.Sentinel'); const {Svg} = goog.require('Blockly.utils.Svg'); /** * Class for an editable angle field. - * @param {string|number=} opt_value The initial value of the field. Should cast - * to a number. Defaults to 0. - * @param {Function=} opt_validator A function that is called to validate - * changes to the field's value. Takes in a number & returns a - * validated number, or null to abort the change. - * @param {Object=} opt_config A map of options used to configure the field. - * See the [field creation documentation]{@link - * https://developers.google.com/blockly/guides/create-custom-blocks/fields/built-in-fields/angle#creation} - * for a list of properties this parameter supports. * @extends {FieldTextInput} - * @constructor - * @alias Blockly.FieldAngle */ -const FieldAngle = function(opt_value, opt_validator, opt_config) { +class FieldAngle extends FieldTextInput { /** - * Should the angle increase as the angle picker is moved clockwise (true) - * or counterclockwise (false) - * @see FieldAngle.CLOCKWISE - * @type {boolean} + * @param {(string|number|!Sentinel)=} opt_value The initial value of + * the field. Should cast to a number. Defaults to 0. + * Also accepts Field.SKIP_SETUP if you wish to skip setup (only used by + * subclasses that want to handle configuration and setting the field + * value after their own constructors have run). + * @param {Function=} opt_validator A function that is called to validate + * changes to the field's value. Takes in a number & returns a + * validated number, or null to abort the change. + * @param {Object=} opt_config A map of options used to configure the field. + * See the [field creation documentation]{@link + * https://developers.google.com/blockly/guides/create-custom-blocks/fields/built-in-fields/angle#creation} + * for a list of properties this parameter supports. + * @alias Blockly.FieldAngle + */ + constructor(opt_value, opt_validator, opt_config) { + super(Field.SKIP_SETUP); + + /** + * Should the angle increase as the angle picker is moved clockwise (true) + * or counterclockwise (false) + * @see FieldAngle.CLOCKWISE + * @type {boolean} + * @private + */ + this.clockwise_ = FieldAngle.CLOCKWISE; + + /** + * The offset of zero degrees (and all other angles). + * @see FieldAngle.OFFSET + * @type {number} + * @private + */ + this.offset_ = FieldAngle.OFFSET; + + /** + * The maximum angle to allow before wrapping. + * @see FieldAngle.WRAP + * @type {number} + * @private + */ + this.wrap_ = FieldAngle.WRAP; + + /** + * The amount to round angles to when using a mouse or keyboard nav input. + * @see FieldAngle.ROUND + * @type {number} + * @private + */ + this.round_ = FieldAngle.ROUND; + + /** + * The angle picker's SVG element. + * @type {?SVGElement} + * @private + */ + this.editor_ = null; + + /** + * The angle picker's gauge path depending on the value. + * @type {?SVGElement} + */ + this.gauge_ = null; + + /** + * The angle picker's line drawn representing the value's angle. + * @type {?SVGElement} + */ + this.line_ = null; + + /** + * The degree symbol for this field. + * @type {SVGTSpanElement} + * @protected + */ + this.symbol_ = null; + + /** + * Wrapper click event data. + * @type {?browserEvents.Data} + * @private + */ + this.clickWrapper_ = null; + + /** + * Surface click event data. + * @type {?browserEvents.Data} + * @private + */ + this.clickSurfaceWrapper_ = null; + + /** + * Surface mouse move event data. + * @type {?browserEvents.Data} + * @private + */ + this.moveSurfaceWrapper_ = null; + + /** + * Serializable fields are saved by the serializer, non-serializable fields + * are not. Editable fields should also be serializable. + * @type {boolean} + */ + this.SERIALIZABLE = true; + + if (opt_value === Field.SKIP_SETUP) return; + if (opt_config) this.configure_(opt_config); + this.setValue(opt_value); + if (opt_validator) this.setValidator(opt_validator); + } + + /** + * Configure the field based on the given map of options. + * @param {!Object} config A map of options to configure the field based on. + * @protected + * @override + */ + configure_(config) { + super.configure_(config); + + switch (config['mode']) { + case 'compass': + this.clockwise_ = true; + this.offset_ = 90; + break; + case 'protractor': + // This is the default mode, so we could do nothing. But just to + // future-proof, we'll set it anyway. + this.clockwise_ = false; + this.offset_ = 0; + break; + } + + // Allow individual settings to override the mode setting. + const clockwise = config['clockwise']; + if (typeof clockwise === 'boolean') { + this.clockwise_ = clockwise; + } + + // If these are passed as null then we should leave them on the default. + let offset = config['offset']; + if (offset !== null) { + offset = Number(offset); + if (!isNaN(offset)) { + this.offset_ = offset; + } + } + let wrap = config['wrap']; + if (wrap !== null) { + wrap = Number(wrap); + if (!isNaN(wrap)) { + this.wrap_ = wrap; + } + } + let round = config['round']; + if (round !== null) { + round = Number(round); + if (!isNaN(round)) { + this.round_ = round; + } + } + } + + /** + * Create the block UI for this field. + * @package + */ + initView() { + super.initView(); + // Add the degree symbol to the left of the number, even in RTL (issue + // #2380) + this.symbol_ = dom.createSvgElement(Svg.TSPAN, {}, null); + this.symbol_.appendChild(document.createTextNode('\u00B0')); + this.textElement_.appendChild(this.symbol_); + } + + /** + * Updates the graph when the field rerenders. + * @protected + * @override + */ + render_() { + super.render_(); + this.updateGraph_(); + } + + /** + * Create and show the angle field's editor. + * @param {Event=} opt_e Optional mouse event that triggered the field to + * open, or undefined if triggered programmatically. + * @protected + */ + showEditor_(opt_e) { + // Mobile browsers have issues with in-line textareas (focus & keyboards). + const noFocus = userAgent.MOBILE || userAgent.ANDROID || userAgent.IPAD; + super.showEditor_(opt_e, noFocus); + + this.dropdownCreate_(); + DropDownDiv.getContentDiv().appendChild(this.editor_); + + DropDownDiv.setColour( + this.sourceBlock_.style.colourPrimary, + this.sourceBlock_.style.colourTertiary); + + DropDownDiv.showPositionedByField(this, this.dropdownDispose_.bind(this)); + + this.updateGraph_(); + } + + /** + * Create the angle dropdown editor. * @private */ - this.clockwise_ = FieldAngle.CLOCKWISE; + dropdownCreate_() { + const svg = dom.createSvgElement( + Svg.SVG, { + 'xmlns': dom.SVG_NS, + 'xmlns:html': dom.HTML_NS, + 'xmlns:xlink': dom.XLINK_NS, + 'version': '1.1', + 'height': (FieldAngle.HALF * 2) + 'px', + 'width': (FieldAngle.HALF * 2) + 'px', + 'style': 'touch-action: none', + }, + null); + const circle = dom.createSvgElement( + Svg.CIRCLE, { + 'cx': FieldAngle.HALF, + 'cy': FieldAngle.HALF, + 'r': FieldAngle.RADIUS, + 'class': 'blocklyAngleCircle', + }, + svg); + this.gauge_ = + dom.createSvgElement(Svg.PATH, {'class': 'blocklyAngleGauge'}, svg); + this.line_ = dom.createSvgElement( + Svg.LINE, { + 'x1': FieldAngle.HALF, + 'y1': FieldAngle.HALF, + 'class': 'blocklyAngleLine', + }, + svg); + // Draw markers around the edge. + for (let angle = 0; angle < 360; angle += 15) { + dom.createSvgElement( + Svg.LINE, { + 'x1': FieldAngle.HALF + FieldAngle.RADIUS, + 'y1': FieldAngle.HALF, + 'x2': FieldAngle.HALF + FieldAngle.RADIUS - + (angle % 45 === 0 ? 10 : 5), + 'y2': FieldAngle.HALF, + 'class': 'blocklyAngleMarks', + 'transform': 'rotate(' + angle + ',' + FieldAngle.HALF + ',' + + FieldAngle.HALF + ')', + }, + svg); + } + + // The angle picker is different from other fields in that it updates on + // mousemove even if it's not in the middle of a drag. In future we may + // change this behaviour. + this.clickWrapper_ = + browserEvents.conditionalBind(svg, 'click', this, this.hide_); + // On touch devices, the picker's value is only updated with a drag. Add + // a click handler on the drag surface to update the value if the surface + // is clicked. + this.clickSurfaceWrapper_ = browserEvents.conditionalBind( + circle, 'click', this, this.onMouseMove_, true, true); + this.moveSurfaceWrapper_ = browserEvents.conditionalBind( + circle, 'mousemove', this, this.onMouseMove_, true, true); + this.editor_ = svg; + } /** - * The offset of zero degrees (and all other angles). - * @see FieldAngle.OFFSET - * @type {number} + * Disposes of events and DOM-references belonging to the angle editor. * @private */ - this.offset_ = FieldAngle.OFFSET; + dropdownDispose_() { + if (this.clickWrapper_) { + browserEvents.unbind(this.clickWrapper_); + this.clickWrapper_ = null; + } + if (this.clickSurfaceWrapper_) { + browserEvents.unbind(this.clickSurfaceWrapper_); + this.clickSurfaceWrapper_ = null; + } + if (this.moveSurfaceWrapper_) { + browserEvents.unbind(this.moveSurfaceWrapper_); + this.moveSurfaceWrapper_ = null; + } + this.gauge_ = null; + this.line_ = null; + } /** - * The maximum angle to allow before wrapping. - * @see FieldAngle.WRAP - * @type {number} + * Hide the editor. * @private */ - this.wrap_ = FieldAngle.WRAP; + hide_() { + DropDownDiv.hideIfOwner(this); + WidgetDiv.hide(); + } /** - * The amount to round angles to when using a mouse or keyboard nav input. - * @see FieldAngle.ROUND - * @type {number} + * Set the angle to match the mouse's position. + * @param {!Event} e Mouse move event. + * @protected + */ + onMouseMove_(e) { + // Calculate angle. + const bBox = this.gauge_.ownerSVGElement.getBoundingClientRect(); + const dx = e.clientX - bBox.left - FieldAngle.HALF; + const dy = e.clientY - bBox.top - FieldAngle.HALF; + let angle = Math.atan(-dy / dx); + if (isNaN(angle)) { + // This shouldn't happen, but let's not let this error propagate further. + return; + } + angle = math.toDegrees(angle); + // 0: East, 90: North, 180: West, 270: South. + if (dx < 0) { + angle += 180; + } else if (dy > 0) { + angle += 360; + } + + // Do offsetting. + if (this.clockwise_) { + angle = this.offset_ + 360 - angle; + } else { + angle = 360 - (this.offset_ - angle); + } + + this.displayMouseOrKeyboardValue_(angle); + } + + /** + * Handles and displays values that are input via mouse or arrow key input. + * These values need to be rounded and wrapped before being displayed so + * that the text input's value is appropriate. + * @param {number} angle New angle. * @private */ - this.round_ = FieldAngle.ROUND; - - FieldAngle.superClass_.constructor.call( - this, opt_value, opt_validator, opt_config); + displayMouseOrKeyboardValue_(angle) { + if (this.round_) { + angle = Math.round(angle / this.round_) * this.round_; + } + angle = this.wrapValue_(angle); + if (angle !== this.value_) { + this.setEditorValue_(angle); + } + } /** - * The angle picker's SVG element. - * @type {?SVGElement} + * Redraw the graph with the current angle. * @private */ - this.editor_ = null; + updateGraph_() { + if (!this.gauge_) { + return; + } + // Always display the input (i.e. getText) even if it is invalid. + let angleDegrees = Number(this.getText()) + this.offset_; + angleDegrees %= 360; + let angleRadians = math.toRadians(angleDegrees); + const path = ['M ', FieldAngle.HALF, ',', FieldAngle.HALF]; + let x2 = FieldAngle.HALF; + let y2 = FieldAngle.HALF; + if (!isNaN(angleRadians)) { + const clockwiseFlag = Number(this.clockwise_); + const angle1 = math.toRadians(this.offset_); + const x1 = Math.cos(angle1) * FieldAngle.RADIUS; + const y1 = Math.sin(angle1) * -FieldAngle.RADIUS; + if (clockwiseFlag) { + angleRadians = 2 * angle1 - angleRadians; + } + x2 += Math.cos(angleRadians) * FieldAngle.RADIUS; + y2 -= Math.sin(angleRadians) * FieldAngle.RADIUS; + // Don't ask how the flag calculations work. They just do. + let largeFlag = + Math.abs(Math.floor((angleRadians - angle1) / Math.PI) % 2); + if (clockwiseFlag) { + largeFlag = 1 - largeFlag; + } + path.push( + ' l ', x1, ',', y1, ' A ', FieldAngle.RADIUS, ',', FieldAngle.RADIUS, + ' 0 ', largeFlag, ' ', clockwiseFlag, ' ', x2, ',', y2, ' z'); + } + this.gauge_.setAttribute('d', path.join('')); + this.line_.setAttribute('x2', x2); + this.line_.setAttribute('y2', y2); + } /** - * The angle picker's gauge path depending on the value. - * @type {?SVGElement} + * Handle key down to the editor. + * @param {!Event} e Keyboard event. + * @protected + * @override */ - this.gauge_ = null; + onHtmlInputKeyDown_(e) { + super.onHtmlInputKeyDown_(e); + + let multiplier; + if (e.keyCode === KeyCodes.LEFT) { + // decrement (increment in RTL) + multiplier = this.sourceBlock_.RTL ? 1 : -1; + } else if (e.keyCode === KeyCodes.RIGHT) { + // increment (decrement in RTL) + multiplier = this.sourceBlock_.RTL ? -1 : 1; + } else if (e.keyCode === KeyCodes.DOWN) { + // decrement + multiplier = -1; + } else if (e.keyCode === KeyCodes.UP) { + // increment + multiplier = 1; + } + if (multiplier) { + const value = /** @type {number} */ (this.getValue()); + this.displayMouseOrKeyboardValue_(value + (multiplier * this.round_)); + e.preventDefault(); + e.stopPropagation(); + } + } /** - * The angle picker's line drawn representing the value's angle. - * @type {?SVGElement} + * Ensure that the input value is a valid angle. + * @param {*=} opt_newValue The input value. + * @return {?number} A valid angle, or null if invalid. + * @protected + * @override */ - this.line_ = null; + doClassValidation_(opt_newValue) { + const value = Number(opt_newValue); + if (isNaN(value) || !isFinite(value)) { + return null; + } + return this.wrapValue_(value); + } /** - * Wrapper click event data. - * @type {?browserEvents.Data} + * Wraps the value so that it is in the range (-360 + wrap, wrap). + * @param {number} value The value to wrap. + * @return {number} The wrapped value. * @private */ - this.clickWrapper_ = null; + wrapValue_(value) { + value %= 360; + if (value < 0) { + value += 360; + } + if (value > this.wrap_) { + value -= 360; + } + return value; + } /** - * Surface click event data. - * @type {?browserEvents.Data} - * @private + * Construct a FieldAngle from a JSON arg object. + * @param {!Object} options A JSON object with options (angle). + * @return {!FieldAngle} The new field instance. + * @package + * @nocollapse + * @override */ - this.clickSurfaceWrapper_ = null; - - /** - * Surface mouse move event data. - * @type {?browserEvents.Data} - * @private - */ - this.moveSurfaceWrapper_ = null; -}; -object.inherits(FieldAngle, FieldTextInput); - + static fromJson(options) { + // `this` might be a subclass of FieldAngle if that class doesn't override + // the static fromJson method. + return new this(options['angle'], undefined, options); + } +} /** * The default value for this field. @@ -131,26 +514,6 @@ object.inherits(FieldAngle, FieldTextInput); */ FieldAngle.prototype.DEFAULT_VALUE = 0; -/** - * Construct a FieldAngle from a JSON arg object. - * @param {!Object} options A JSON object with options (angle). - * @return {!FieldAngle} The new field instance. - * @package - * @nocollapse - */ -FieldAngle.fromJson = function(options) { - // `this` might be a subclass of FieldAngle if that class doesn't override - // the static fromJson method. - return new this(options['angle'], undefined, options); -}; - -/** - * Serializable fields are saved by the XML renderer, non-serializable fields - * are not. Editable fields should also be serializable. - * @type {boolean} - */ -FieldAngle.prototype.SERIALIZABLE = true; - /** * The default amount to round angles to when using a mouse or keyboard nav * input. Must be a positive integer to support keyboard navigation. @@ -193,349 +556,6 @@ FieldAngle.WRAP = 360; */ FieldAngle.RADIUS = FieldAngle.HALF - 1; -/** - * Configure the field based on the given map of options. - * @param {!Object} config A map of options to configure the field based on. - * @protected - * @override - */ -FieldAngle.prototype.configure_ = function(config) { - FieldAngle.superClass_.configure_.call(this, config); - - switch (config['mode']) { - case 'compass': - this.clockwise_ = true; - this.offset_ = 90; - break; - case 'protractor': - // This is the default mode, so we could do nothing. But just to - // future-proof, we'll set it anyway. - this.clockwise_ = false; - this.offset_ = 0; - break; - } - - // Allow individual settings to override the mode setting. - const clockwise = config['clockwise']; - if (typeof clockwise === 'boolean') { - this.clockwise_ = clockwise; - } - - // If these are passed as null then we should leave them on the default. - let offset = config['offset']; - if (offset !== null) { - offset = Number(offset); - if (!isNaN(offset)) { - this.offset_ = offset; - } - } - let wrap = config['wrap']; - if (wrap !== null) { - wrap = Number(wrap); - if (!isNaN(wrap)) { - this.wrap_ = wrap; - } - } - let round = config['round']; - if (round !== null) { - round = Number(round); - if (!isNaN(round)) { - this.round_ = round; - } - } -}; - -/** - * Create the block UI for this field. - * @package - */ -FieldAngle.prototype.initView = function() { - FieldAngle.superClass_.initView.call(this); - // Add the degree symbol to the left of the number, even in RTL (issue #2380) - this.symbol_ = dom.createSvgElement(Svg.TSPAN, {}, null); - this.symbol_.appendChild(document.createTextNode('\u00B0')); - this.textElement_.appendChild(this.symbol_); -}; - -/** - * Updates the graph when the field rerenders. - * @protected - * @override - */ -FieldAngle.prototype.render_ = function() { - FieldAngle.superClass_.render_.call(this); - this.updateGraph_(); -}; - -/** - * Create and show the angle field's editor. - * @param {Event=} opt_e Optional mouse event that triggered the field to open, - * or undefined if triggered programmatically. - * @protected - */ -FieldAngle.prototype.showEditor_ = function(opt_e) { - // Mobile browsers have issues with in-line textareas (focus & keyboards). - const noFocus = userAgent.MOBILE || userAgent.ANDROID || userAgent.IPAD; - FieldAngle.superClass_.showEditor_.call(this, opt_e, noFocus); - - this.dropdownCreate_(); - DropDownDiv.getContentDiv().appendChild(this.editor_); - - DropDownDiv.setColour( - this.sourceBlock_.style.colourPrimary, - this.sourceBlock_.style.colourTertiary); - - DropDownDiv.showPositionedByField(this, this.dropdownDispose_.bind(this)); - - this.updateGraph_(); -}; - -/** - * Create the angle dropdown editor. - * @private - */ -FieldAngle.prototype.dropdownCreate_ = function() { - const svg = dom.createSvgElement( - Svg.SVG, { - 'xmlns': dom.SVG_NS, - 'xmlns:html': dom.HTML_NS, - 'xmlns:xlink': dom.XLINK_NS, - 'version': '1.1', - 'height': (FieldAngle.HALF * 2) + 'px', - 'width': (FieldAngle.HALF * 2) + 'px', - 'style': 'touch-action: none', - }, - null); - const circle = dom.createSvgElement( - Svg.CIRCLE, { - 'cx': FieldAngle.HALF, - 'cy': FieldAngle.HALF, - 'r': FieldAngle.RADIUS, - 'class': 'blocklyAngleCircle', - }, - svg); - this.gauge_ = - dom.createSvgElement(Svg.PATH, {'class': 'blocklyAngleGauge'}, svg); - this.line_ = dom.createSvgElement( - Svg.LINE, { - 'x1': FieldAngle.HALF, - 'y1': FieldAngle.HALF, - 'class': 'blocklyAngleLine', - }, - svg); - // Draw markers around the edge. - for (let angle = 0; angle < 360; angle += 15) { - dom.createSvgElement( - Svg.LINE, { - 'x1': FieldAngle.HALF + FieldAngle.RADIUS, - 'y1': FieldAngle.HALF, - 'x2': - FieldAngle.HALF + FieldAngle.RADIUS - (angle % 45 === 0 ? 10 : 5), - 'y2': FieldAngle.HALF, - 'class': 'blocklyAngleMarks', - 'transform': 'rotate(' + angle + ',' + FieldAngle.HALF + ',' + - FieldAngle.HALF + ')', - }, - svg); - } - - // The angle picker is different from other fields in that it updates on - // mousemove even if it's not in the middle of a drag. In future we may - // change this behaviour. - this.clickWrapper_ = - browserEvents.conditionalBind(svg, 'click', this, this.hide_); - // On touch devices, the picker's value is only updated with a drag. Add - // a click handler on the drag surface to update the value if the surface - // is clicked. - this.clickSurfaceWrapper_ = browserEvents.conditionalBind( - circle, 'click', this, this.onMouseMove_, true, true); - this.moveSurfaceWrapper_ = browserEvents.conditionalBind( - circle, 'mousemove', this, this.onMouseMove_, true, true); - this.editor_ = svg; -}; - -/** - * Disposes of events and DOM-references belonging to the angle editor. - * @private - */ -FieldAngle.prototype.dropdownDispose_ = function() { - if (this.clickWrapper_) { - browserEvents.unbind(this.clickWrapper_); - this.clickWrapper_ = null; - } - if (this.clickSurfaceWrapper_) { - browserEvents.unbind(this.clickSurfaceWrapper_); - this.clickSurfaceWrapper_ = null; - } - if (this.moveSurfaceWrapper_) { - browserEvents.unbind(this.moveSurfaceWrapper_); - this.moveSurfaceWrapper_ = null; - } - this.gauge_ = null; - this.line_ = null; -}; - -/** - * Hide the editor. - * @private - */ -FieldAngle.prototype.hide_ = function() { - DropDownDiv.hideIfOwner(this); - WidgetDiv.hide(); -}; - -/** - * Set the angle to match the mouse's position. - * @param {!Event} e Mouse move event. - * @protected - */ -FieldAngle.prototype.onMouseMove_ = function(e) { - // Calculate angle. - const bBox = this.gauge_.ownerSVGElement.getBoundingClientRect(); - const dx = e.clientX - bBox.left - FieldAngle.HALF; - const dy = e.clientY - bBox.top - FieldAngle.HALF; - let angle = Math.atan(-dy / dx); - if (isNaN(angle)) { - // This shouldn't happen, but let's not let this error propagate further. - return; - } - angle = math.toDegrees(angle); - // 0: East, 90: North, 180: West, 270: South. - if (dx < 0) { - angle += 180; - } else if (dy > 0) { - angle += 360; - } - - // Do offsetting. - if (this.clockwise_) { - angle = this.offset_ + 360 - angle; - } else { - angle = 360 - (this.offset_ - angle); - } - - this.displayMouseOrKeyboardValue_(angle); -}; - -/** - * Handles and displays values that are input via mouse or arrow key input. - * These values need to be rounded and wrapped before being displayed so - * that the text input's value is appropriate. - * @param {number} angle New angle. - * @private - */ -FieldAngle.prototype.displayMouseOrKeyboardValue_ = function(angle) { - if (this.round_) { - angle = Math.round(angle / this.round_) * this.round_; - } - angle = this.wrapValue_(angle); - if (angle !== this.value_) { - this.setEditorValue_(angle); - } -}; - -/** - * Redraw the graph with the current angle. - * @private - */ -FieldAngle.prototype.updateGraph_ = function() { - if (!this.gauge_) { - return; - } - // Always display the input (i.e. getText) even if it is invalid. - let angleDegrees = Number(this.getText()) + this.offset_; - angleDegrees %= 360; - let angleRadians = math.toRadians(angleDegrees); - const path = ['M ', FieldAngle.HALF, ',', FieldAngle.HALF]; - let x2 = FieldAngle.HALF; - let y2 = FieldAngle.HALF; - if (!isNaN(angleRadians)) { - const clockwiseFlag = Number(this.clockwise_); - const angle1 = math.toRadians(this.offset_); - const x1 = Math.cos(angle1) * FieldAngle.RADIUS; - const y1 = Math.sin(angle1) * -FieldAngle.RADIUS; - if (clockwiseFlag) { - angleRadians = 2 * angle1 - angleRadians; - } - x2 += Math.cos(angleRadians) * FieldAngle.RADIUS; - y2 -= Math.sin(angleRadians) * FieldAngle.RADIUS; - // Don't ask how the flag calculations work. They just do. - let largeFlag = Math.abs(Math.floor((angleRadians - angle1) / Math.PI) % 2); - if (clockwiseFlag) { - largeFlag = 1 - largeFlag; - } - path.push( - ' l ', x1, ',', y1, ' A ', FieldAngle.RADIUS, ',', FieldAngle.RADIUS, - ' 0 ', largeFlag, ' ', clockwiseFlag, ' ', x2, ',', y2, ' z'); - } - this.gauge_.setAttribute('d', path.join('')); - this.line_.setAttribute('x2', x2); - this.line_.setAttribute('y2', y2); -}; - -/** - * Handle key down to the editor. - * @param {!Event} e Keyboard event. - * @protected - * @override - */ -FieldAngle.prototype.onHtmlInputKeyDown_ = function(e) { - FieldAngle.superClass_.onHtmlInputKeyDown_.call(this, e); - - let multiplier; - if (e.keyCode === KeyCodes.LEFT) { - // decrement (increment in RTL) - multiplier = this.sourceBlock_.RTL ? 1 : -1; - } else if (e.keyCode === KeyCodes.RIGHT) { - // increment (decrement in RTL) - multiplier = this.sourceBlock_.RTL ? -1 : 1; - } else if (e.keyCode === KeyCodes.DOWN) { - // decrement - multiplier = -1; - } else if (e.keyCode === KeyCodes.UP) { - // increment - multiplier = 1; - } - if (multiplier) { - const value = /** @type {number} */ (this.getValue()); - this.displayMouseOrKeyboardValue_(value + (multiplier * this.round_)); - e.preventDefault(); - e.stopPropagation(); - } -}; - -/** - * Ensure that the input value is a valid angle. - * @param {*=} opt_newValue The input value. - * @return {?number} A valid angle, or null if invalid. - * @protected - * @override - */ -FieldAngle.prototype.doClassValidation_ = function(opt_newValue) { - const value = Number(opt_newValue); - if (isNaN(value) || !isFinite(value)) { - return null; - } - return this.wrapValue_(value); -}; - -/** - * Wraps the value so that it is in the range (-360 + wrap, wrap). - * @param {number} value The value to wrap. - * @return {number} The wrapped value. - * @private - */ -FieldAngle.prototype.wrapValue_ = function(value) { - value %= 360; - if (value < 0) { - value += 360; - } - if (value > this.wrap_) { - value -= 360; - } - return value; -}; - /** * CSS for angle field. See css.js for use. */ diff --git a/core/field_checkbox.js b/core/field_checkbox.js index ddbe38711..2e2cdc481 100644 --- a/core/field_checkbox.js +++ b/core/field_checkbox.js @@ -17,41 +17,224 @@ goog.module('Blockly.FieldCheckbox'); const dom = goog.require('Blockly.utils.dom'); const fieldRegistry = goog.require('Blockly.fieldRegistry'); -const object = goog.require('Blockly.utils.object'); const {Field} = goog.require('Blockly.Field'); +/* eslint-disable-next-line no-unused-vars */ +const {Sentinel} = goog.requireType('Blockly.utils.Sentinel'); /** @suppress {extraRequire} */ goog.require('Blockly.Events.BlockChange'); /** * Class for a checkbox field. - * @param {string|boolean=} opt_value The initial value of the field. Should - * either be 'TRUE', 'FALSE' or a boolean. Defaults to 'FALSE'. - * @param {Function=} opt_validator A function that is called to validate - * changes to the field's value. Takes in a value ('TRUE' or 'FALSE') & - * returns a validated value ('TRUE' or 'FALSE'), or null to abort the - * change. - * @param {Object=} opt_config A map of options used to configure the field. - * See the [field creation documentation]{@link - * https://developers.google.com/blockly/guides/create-custom-blocks/fields/built-in-fields/checkbox#creation} - * for a list of properties this parameter supports. * @extends {Field} - * @constructor - * @alias Blockly.FieldCheckbox */ -const FieldCheckbox = function(opt_value, opt_validator, opt_config) { +class FieldCheckbox extends Field { /** - * Character for the check mark. Used to apply a different check mark - * character to individual fields. - * @type {?string} + * @param {(string|boolean|!Sentinel)=} opt_value The initial value of + * the field. Should either be 'TRUE', 'FALSE' or a boolean. Defaults to + * 'FALSE'. + * Also accepts Field.SKIP_SETUP if you wish to skip setup (only used by + * subclasses that want to handle configuration and setting the field + * value after their own constructors have run). + * @param {Function=} opt_validator A function that is called to validate + * changes to the field's value. Takes in a value ('TRUE' or 'FALSE') & + * returns a validated value ('TRUE' or 'FALSE'), or null to abort the + * change. + * @param {Object=} opt_config A map of options used to configure the field. + * See the [field creation documentation]{@link + * https://developers.google.com/blockly/guides/create-custom-blocks/fields/built-in-fields/checkbox#creation} + * for a list of properties this parameter supports. + * @alias Blockly.FieldCheckbox + */ + constructor(opt_value, opt_validator, opt_config) { + super(Field.SKIP_SETUP); + + /** + * Character for the check mark. Used to apply a different check mark + * character to individual fields. + * @type {string} + * @private + */ + this.checkChar_ = FieldCheckbox.CHECK_CHAR; + + /** + * Serializable fields are saved by the serializer, non-serializable fields + * are not. Editable fields should also be serializable. + * @type {boolean} + */ + this.SERIALIZABLE = true; + + /** + * Mouse cursor style when over the hotspot that initiates editability. + * @type {string} + */ + this.CURSOR = 'default'; + + if (opt_value === Field.SKIP_SETUP) return; + if (opt_config) this.configure_(opt_config); + this.setValue(opt_value); + if (opt_validator) this.setValidator(opt_validator); + } + + /** + * Configure the field based on the given map of options. + * @param {!Object} config A map of options to configure the field based on. + * @protected + * @override + */ + configure_(config) { + super.configure_(config); + if (config['checkCharacter']) { + this.checkChar_ = config['checkCharacter']; + } + } + + /** + * Saves this field's value. + * @return {*} The boolean value held by this field. + * @override + * @package + */ + saveState() { + const legacyState = this.saveLegacyState(FieldCheckbox); + if (legacyState !== null) { + return legacyState; + } + return this.getValueBoolean(); + } + + /** + * Create the block UI for this checkbox. + * @package + */ + initView() { + super.initView(); + + dom.addClass( + /** @type {!SVGTextElement} **/ (this.textElement_), 'blocklyCheckbox'); + this.textElement_.style.display = this.value_ ? 'block' : 'none'; + } + + /** + * @override + */ + render_() { + if (this.textContent_) { + this.textContent_.nodeValue = this.getDisplayText_(); + } + this.updateSize_(this.getConstants().FIELD_CHECKBOX_X_OFFSET); + } + + /** + * @override + */ + getDisplayText_() { + return this.checkChar_; + } + + /** + * Set the character used for the check mark. + * @param {?string} character The character to use for the check mark, or + * null to use the default. + */ + setCheckCharacter(character) { + this.checkChar_ = character || FieldCheckbox.CHECK_CHAR; + this.forceRerender(); + } + + /** + * Toggle the state of the checkbox on click. + * @protected + */ + showEditor_() { + this.setValue(!this.value_); + } + + /** + * Ensure that the input value is valid ('TRUE' or 'FALSE'). + * @param {*=} opt_newValue The input value. + * @return {?string} A valid value ('TRUE' or 'FALSE), or null if invalid. + * @protected + */ + doClassValidation_(opt_newValue) { + if (opt_newValue === true || opt_newValue === 'TRUE') { + return 'TRUE'; + } + if (opt_newValue === false || opt_newValue === 'FALSE') { + return 'FALSE'; + } + return null; + } + + /** + * Update the value of the field, and update the checkElement. + * @param {*} newValue The value to be saved. The default validator guarantees + * that this is a either 'TRUE' or 'FALSE'. + * @protected + */ + doValueUpdate_(newValue) { + this.value_ = this.convertValueToBool_(newValue); + // Update visual. + if (this.textElement_) { + this.textElement_.style.display = this.value_ ? 'block' : 'none'; + } + } + + /** + * Get the value of this field, either 'TRUE' or 'FALSE'. + * @return {string} The value of this field. + */ + getValue() { + return this.value_ ? 'TRUE' : 'FALSE'; + } + + /** + * Get the boolean value of this field. + * @return {boolean} The boolean value of this field. + */ + getValueBoolean() { + return /** @type {boolean} */ (this.value_); + } + + /** + * Get the text of this field. Used when the block is collapsed. + * @return {string} Text representing the value of this field + * ('true' or 'false'). + */ + getText() { + return String(this.convertValueToBool_(this.value_)); + } + + /** + * Convert a value into a pure boolean. + * + * Converts 'TRUE' to true and 'FALSE' to false correctly, everything else + * is cast to a boolean. + * @param {*} value The value to convert. + * @return {boolean} The converted value. * @private */ - this.checkChar_ = null; + convertValueToBool_(value) { + if (typeof value === 'string') { + return value === 'TRUE'; + } else { + return !!value; + } + } - FieldCheckbox.superClass_.constructor.call( - this, opt_value, opt_validator, opt_config); -}; -object.inherits(FieldCheckbox, Field); + /** + * Construct a FieldCheckbox from a JSON arg object. + * @param {!Object} options A JSON object with options (checked). + * @return {!FieldCheckbox} The new field instance. + * @package + * @nocollapse + */ + static fromJson(options) { + // `this` might be a subclass of FieldCheckbox if that class doesn't + // 'override' the static fromJson method. + return new this(options['checked'], undefined, options); + } +} /** * The default value for this field. @@ -60,19 +243,6 @@ object.inherits(FieldCheckbox, Field); */ FieldCheckbox.prototype.DEFAULT_VALUE = false; -/** - * Construct a FieldCheckbox from a JSON arg object. - * @param {!Object} options A JSON object with options (checked). - * @return {!FieldCheckbox} The new field instance. - * @package - * @nocollapse - */ -FieldCheckbox.fromJson = function(options) { - // `this` might be a subclass of FieldCheckbox if that class doesn't override - // the static fromJson method. - return new this(options['checked'], undefined, options); -}; - /** * Default character for the checkmark. * @type {string} @@ -80,164 +250,6 @@ FieldCheckbox.fromJson = function(options) { */ FieldCheckbox.CHECK_CHAR = '\u2713'; -/** - * Serializable fields are saved by the XML renderer, non-serializable fields - * are not. Editable fields should also be serializable. - * @type {boolean} - */ -FieldCheckbox.prototype.SERIALIZABLE = true; - -/** - * Mouse cursor style when over the hotspot that initiates editability. - */ -FieldCheckbox.prototype.CURSOR = 'default'; - -/** - * Configure the field based on the given map of options. - * @param {!Object} config A map of options to configure the field based on. - * @protected - * @override - */ -FieldCheckbox.prototype.configure_ = function(config) { - FieldCheckbox.superClass_.configure_.call(this, config); - if (config['checkCharacter']) { - this.checkChar_ = config['checkCharacter']; - } -}; - -/** - * Saves this field's value. - * @return {*} The boolean value held by this field. - * @override - * @package - */ -FieldCheckbox.prototype.saveState = function() { - const legacyState = this.saveLegacyState(FieldCheckbox); - if (legacyState !== null) { - return legacyState; - } - return this.getValueBoolean(); -}; - -/** - * Create the block UI for this checkbox. - * @package - */ -FieldCheckbox.prototype.initView = function() { - FieldCheckbox.superClass_.initView.call(this); - - dom.addClass( - /** @type {!SVGTextElement} **/ (this.textElement_), 'blocklyCheckbox'); - this.textElement_.style.display = this.value_ ? 'block' : 'none'; -}; - -/** - * @override - */ -FieldCheckbox.prototype.render_ = function() { - if (this.textContent_) { - this.textContent_.nodeValue = this.getDisplayText_(); - } - this.updateSize_(this.getConstants().FIELD_CHECKBOX_X_OFFSET); -}; - -/** - * @override - */ -FieldCheckbox.prototype.getDisplayText_ = function() { - return this.checkChar_ || FieldCheckbox.CHECK_CHAR; -}; - -/** - * Set the character used for the check mark. - * @param {?string} character The character to use for the check mark, or - * null to use the default. - */ -FieldCheckbox.prototype.setCheckCharacter = function(character) { - this.checkChar_ = character; - this.forceRerender(); -}; - -/** - * Toggle the state of the checkbox on click. - * @protected - */ -FieldCheckbox.prototype.showEditor_ = function() { - this.setValue(!this.value_); -}; - -/** - * Ensure that the input value is valid ('TRUE' or 'FALSE'). - * @param {*=} opt_newValue The input value. - * @return {?string} A valid value ('TRUE' or 'FALSE), or null if invalid. - * @protected - */ -FieldCheckbox.prototype.doClassValidation_ = function(opt_newValue) { - if (opt_newValue === true || opt_newValue === 'TRUE') { - return 'TRUE'; - } - if (opt_newValue === false || opt_newValue === 'FALSE') { - return 'FALSE'; - } - return null; -}; - -/** - * Update the value of the field, and update the checkElement. - * @param {*} newValue The value to be saved. The default validator guarantees - * that this is a either 'TRUE' or 'FALSE'. - * @protected - */ -FieldCheckbox.prototype.doValueUpdate_ = function(newValue) { - this.value_ = this.convertValueToBool_(newValue); - // Update visual. - if (this.textElement_) { - this.textElement_.style.display = this.value_ ? 'block' : 'none'; - } -}; - -/** - * Get the value of this field, either 'TRUE' or 'FALSE'. - * @return {string} The value of this field. - */ -FieldCheckbox.prototype.getValue = function() { - return this.value_ ? 'TRUE' : 'FALSE'; -}; - -/** - * Get the boolean value of this field. - * @return {boolean} The boolean value of this field. - */ -FieldCheckbox.prototype.getValueBoolean = function() { - return /** @type {boolean} */ (this.value_); -}; - -/** - * Get the text of this field. Used when the block is collapsed. - * @return {string} Text representing the value of this field - * ('true' or 'false'). - */ -FieldCheckbox.prototype.getText = function() { - return String(this.convertValueToBool_(this.value_)); -}; - -/** - * Convert a value into a pure boolean. - * - * Converts 'TRUE' to true and 'FALSE' to false correctly, everything else - * is cast to a boolean. - * @param {*} value The value to convert. - * @return {boolean} The converted value. - * @private - */ -FieldCheckbox.prototype.convertValueToBool_ = function(value) { - if (typeof value === 'string') { - return value === 'TRUE'; - } else { - return !!value; - } -}; - fieldRegistry.register('field_checkbox', FieldCheckbox); exports.FieldCheckbox = FieldCheckbox; diff --git a/core/field_colour.js b/core/field_colour.js index a769844ef..a2d11c3f2 100644 --- a/core/field_colour.js +++ b/core/field_colour.js @@ -22,10 +22,11 @@ const colour = goog.require('Blockly.utils.colour'); const dom = goog.require('Blockly.utils.dom'); const fieldRegistry = goog.require('Blockly.fieldRegistry'); const idGenerator = goog.require('Blockly.utils.idGenerator'); -const object = goog.require('Blockly.utils.object'); const {DropDownDiv} = goog.require('Blockly.DropDownDiv'); const {Field} = goog.require('Blockly.Field'); const {KeyCodes} = goog.require('Blockly.utils.KeyCodes'); +/* eslint-disable-next-line no-unused-vars */ +const {Sentinel} = goog.requireType('Blockly.utils.Sentinel'); const {Size} = goog.require('Blockly.utils.Size'); /** @suppress {extraRequire} */ goog.require('Blockly.Events.BlockChange'); @@ -33,219 +34,539 @@ goog.require('Blockly.Events.BlockChange'); /** * Class for a colour input field. - * @param {string=} opt_value The initial value of the field. Should be in - * '#rrggbb' format. Defaults to the first value in the default colour array. - * @param {Function=} opt_validator A function that is called to validate - * changes to the field's value. Takes in a colour string & returns a - * validated colour string ('#rrggbb' format), or null to abort the - * change.Blockly. - * @param {Object=} opt_config A map of options used to configure the field. - * See the [field creation documentation]{@link - * https://developers.google.com/blockly/guides/create-custom-blocks/fields/built-in-fields/colour} - * for a list of properties this parameter supports. * @extends {Field} - * @constructor - * @alias Blockly.FieldColour */ -const FieldColour = function(opt_value, opt_validator, opt_config) { - FieldColour.superClass_.constructor.call( - this, opt_value, opt_validator, opt_config); - +class FieldColour extends Field { /** - * The field's colour picker element. - * @type {?Element} - * @private + * @param {(string|!Sentinel)=} opt_value The initial value of the + * field. Should be in '#rrggbb' format. Defaults to the first value in + * the default colour array. + * Also accepts Field.SKIP_SETUP if you wish to skip setup (only used by + * subclasses that want to handle configuration and setting the field + * value after their own constructors have run). + * @param {Function=} opt_validator A function that is called to validate + * changes to the field's value. Takes in a colour string & returns a + * validated colour string ('#rrggbb' format), or null to abort the + * change.Blockly. + * @param {Object=} opt_config A map of options used to configure the field. + * See the [field creation documentation]{@link + * https://developers.google.com/blockly/guides/create-custom-blocks/fields/built-in-fields/colour} + * for a list of properties this parameter supports. + * @alias Blockly.FieldColour */ - this.picker_ = null; + constructor(opt_value, opt_validator, opt_config) { + super(Field.SKIP_SETUP); - /** - * Index of the currently highlighted element. - * @type {?number} - * @private - */ - this.highlightedIndex_ = null; + /** + * The field's colour picker element. + * @type {?Element} + * @private + */ + this.picker_ = null; - /** - * Mouse click event data. - * @type {?browserEvents.Data} - * @private - */ - this.onClickWrapper_ = null; + /** + * Index of the currently highlighted element. + * @type {?number} + * @private + */ + this.highlightedIndex_ = null; - /** - * Mouse move event data. - * @type {?browserEvents.Data} - * @private - */ - this.onMouseMoveWrapper_ = null; + /** + * Mouse click event data. + * @type {?browserEvents.Data} + * @private + */ + this.onClickWrapper_ = null; - /** - * Mouse enter event data. - * @type {?browserEvents.Data} - * @private - */ - this.onMouseEnterWrapper_ = null; + /** + * Mouse move event data. + * @type {?browserEvents.Data} + * @private + */ + this.onMouseMoveWrapper_ = null; - /** - * Mouse leave event data. - * @type {?browserEvents.Data} - * @private - */ - this.onMouseLeaveWrapper_ = null; + /** + * Mouse enter event data. + * @type {?browserEvents.Data} + * @private + */ + this.onMouseEnterWrapper_ = null; - /** - * Key down event data. - * @type {?browserEvents.Data} - * @private - */ - this.onKeyDownWrapper_ = null; -}; -object.inherits(FieldColour, Field); + /** + * Mouse leave event data. + * @type {?browserEvents.Data} + * @private + */ + this.onMouseLeaveWrapper_ = null; -/** - * Construct a FieldColour from a JSON arg object. - * @param {!Object} options A JSON object with options (colour). - * @return {!FieldColour} The new field instance. - * @package - * @nocollapse - */ -FieldColour.fromJson = function(options) { - // `this` might be a subclass of FieldColour if that class doesn't override - // the static fromJson method. - return new this(options['colour'], undefined, options); -}; + /** + * Key down event data. + * @type {?browserEvents.Data} + * @private + */ + this.onKeyDownWrapper_ = null; -/** - * Serializable fields are saved by the XML renderer, non-serializable fields - * are not. Editable fields should also be serializable. - * @type {boolean} - */ -FieldColour.prototype.SERIALIZABLE = true; + /** + * Serializable fields are saved by the serializer, non-serializable fields + * are not. Editable fields should also be serializable. + * @type {boolean} + */ + this.SERIALIZABLE = true; -/** - * Mouse cursor style when over the hotspot that initiates the editor. - */ -FieldColour.prototype.CURSOR = 'default'; + /** + * Mouse cursor style when over the hotspot that initiates the editor. + * @type {string} + */ + this.CURSOR = 'default'; -/** - * Used to tell if the field needs to be rendered the next time the block is - * rendered. Colour fields are statically sized, and only need to be - * rendered at initialization. - * @type {boolean} - * @protected - */ -FieldColour.prototype.isDirty_ = false; + /** + * Used to tell if the field needs to be rendered the next time the block is + * rendered. Colour fields are statically sized, and only need to be + * rendered at initialization. + * @type {boolean} + * @protected + */ + this.isDirty_ = false; -/** - * Array of colours used by this field. If null, use the global list. - * @type {Array} - * @private - */ -FieldColour.prototype.colours_ = null; + /** + * Array of colours used by this field. If null, use the global list. + * @type {Array} + * @private + */ + this.colours_ = null; -/** - * Array of colour tooltips used by this field. If null, use the global list. - * @type {Array} - * @private - */ -FieldColour.prototype.titles_ = null; + /** + * Array of colour tooltips used by this field. If null, use the global + * list. + * @type {Array} + * @private + */ + this.titles_ = null; -/** - * Number of colour columns used by this field. If 0, use the global setting. - * By default use the global constants for columns. - * @type {number} - * @private - */ -FieldColour.prototype.columns_ = 0; + /** + * Number of colour columns used by this field. If 0, use the global + * setting. By default use the global constants for columns. + * @type {number} + * @private + */ + this.columns_ = 0; -/** - * Configure the field based on the given map of options. - * @param {!Object} config A map of options to configure the field based on. - * @protected - * @override - */ -FieldColour.prototype.configure_ = function(config) { - FieldColour.superClass_.configure_.call(this, config); - if (config['colourOptions']) { - this.colours_ = config['colourOptions']; - this.titles_ = config['colourTitles']; + if (opt_value === Field.SKIP_SETUP) return; + if (opt_config) this.configure_(opt_config); + this.setValue(opt_value); + if (opt_validator) this.setValidator(opt_validator); } - if (config['columns']) { - this.columns_ = config['columns']; - } -}; -/** - * Create the block UI for this colour field. - * @package - */ -FieldColour.prototype.initView = function() { - this.size_ = new Size( - this.getConstants().FIELD_COLOUR_DEFAULT_WIDTH, - this.getConstants().FIELD_COLOUR_DEFAULT_HEIGHT); - if (!this.getConstants().FIELD_COLOUR_FULL_BLOCK) { - this.createBorderRect_(); - this.borderRect_.style['fillOpacity'] = '1'; - } else { - this.clickTarget_ = this.sourceBlock_.getSvgRoot(); - } -}; - -/** - * @override - */ -FieldColour.prototype.applyColour = function() { - if (!this.getConstants().FIELD_COLOUR_FULL_BLOCK) { - if (this.borderRect_) { - this.borderRect_.style.fill = /** @type {string} */ (this.getValue()); + /** + * Configure the field based on the given map of options. + * @param {!Object} config A map of options to configure the field based on. + * @protected + * @override + */ + configure_(config) { + super.configure_(config); + if (config['colourOptions']) { + this.colours_ = config['colourOptions']; + this.titles_ = config['colourTitles']; + } + if (config['columns']) { + this.columns_ = config['columns']; } - } else { - this.sourceBlock_.pathObject.svgPath.setAttribute('fill', this.getValue()); - this.sourceBlock_.pathObject.svgPath.setAttribute('stroke', '#fff'); } -}; -/** - * Ensure that the input value is a valid colour. - * @param {*=} opt_newValue The input value. - * @return {?string} A valid colour, or null if invalid. - * @protected - */ -FieldColour.prototype.doClassValidation_ = function(opt_newValue) { - if (typeof opt_newValue !== 'string') { - return null; + /** + * Create the block UI for this colour field. + * @package + */ + initView() { + this.size_ = new Size( + this.getConstants().FIELD_COLOUR_DEFAULT_WIDTH, + this.getConstants().FIELD_COLOUR_DEFAULT_HEIGHT); + if (!this.getConstants().FIELD_COLOUR_FULL_BLOCK) { + this.createBorderRect_(); + this.borderRect_.style['fillOpacity'] = '1'; + } else { + this.clickTarget_ = this.sourceBlock_.getSvgRoot(); + } } - return colour.parse(opt_newValue); -}; -/** - * Update the value of this colour field, and update the displayed colour. - * @param {*} newValue The value to be saved. The default validator guarantees - * that this is a colour in '#rrggbb' format. - * @protected - */ -FieldColour.prototype.doValueUpdate_ = function(newValue) { - this.value_ = newValue; - if (this.borderRect_) { - this.borderRect_.style.fill = /** @type {string} */ (newValue); - } else if (this.sourceBlock_ && this.sourceBlock_.rendered) { - this.sourceBlock_.pathObject.svgPath.setAttribute('fill', newValue); - this.sourceBlock_.pathObject.svgPath.setAttribute('stroke', '#fff'); + /** + * @override + */ + applyColour() { + if (!this.getConstants().FIELD_COLOUR_FULL_BLOCK) { + if (this.borderRect_) { + this.borderRect_.style.fill = /** @type {string} */ (this.getValue()); + } + } else { + this.sourceBlock_.pathObject.svgPath.setAttribute( + 'fill', this.getValue()); + this.sourceBlock_.pathObject.svgPath.setAttribute('stroke', '#fff'); + } } -}; -/** - * Get the text for this field. Used when the block is collapsed. - * @return {string} Text representing the value of this field. - */ -FieldColour.prototype.getText = function() { - let colour = /** @type {string} */ (this.value_); - // Try to use #rgb format if possible, rather than #rrggbb. - if (/^#(.)\1(.)\2(.)\3$/.test(colour)) { - colour = '#' + colour[1] + colour[3] + colour[5]; + /** + * Ensure that the input value is a valid colour. + * @param {*=} opt_newValue The input value. + * @return {?string} A valid colour, or null if invalid. + * @protected + */ + doClassValidation_(opt_newValue) { + if (typeof opt_newValue !== 'string') { + return null; + } + return colour.parse(opt_newValue); } - return colour; -}; + + /** + * Update the value of this colour field, and update the displayed colour. + * @param {*} newValue The value to be saved. The default validator guarantees + * that this is a colour in '#rrggbb' format. + * @protected + */ + doValueUpdate_(newValue) { + this.value_ = newValue; + if (this.borderRect_) { + this.borderRect_.style.fill = /** @type {string} */ (newValue); + } else if (this.sourceBlock_ && this.sourceBlock_.rendered) { + this.sourceBlock_.pathObject.svgPath.setAttribute('fill', newValue); + this.sourceBlock_.pathObject.svgPath.setAttribute('stroke', '#fff'); + } + } + + /** + * Get the text for this field. Used when the block is collapsed. + * @return {string} Text representing the value of this field. + */ + getText() { + let colour = /** @type {string} */ (this.value_); + // Try to use #rgb format if possible, rather than #rrggbb. + if (/^#(.)\1(.)\2(.)\3$/.test(colour)) { + colour = '#' + colour[1] + colour[3] + colour[5]; + } + return colour; + } + + /** + * Set a custom colour grid for this field. + * @param {Array} colours Array of colours for this block, + * or null to use default (FieldColour.COLOURS). + * @param {Array=} opt_titles Optional array of colour tooltips, + * or null to use default (FieldColour.TITLES). + * @return {!FieldColour} Returns itself (for method chaining). + */ + setColours(colours, opt_titles) { + this.colours_ = colours; + if (opt_titles) { + this.titles_ = opt_titles; + } + return this; + } + + /** + * Set a custom grid size for this field. + * @param {number} columns Number of columns for this block, + * or 0 to use default (FieldColour.COLUMNS). + * @return {!FieldColour} Returns itself (for method chaining). + */ + setColumns(columns) { + this.columns_ = columns; + return this; + } + + /** + * Create and show the colour field's editor. + * @protected + */ + showEditor_() { + this.dropdownCreate_(); + DropDownDiv.getContentDiv().appendChild(this.picker_); + + DropDownDiv.showPositionedByField(this, this.dropdownDispose_.bind(this)); + + // Focus so we can start receiving keyboard events. + this.picker_.focus({preventScroll: true}); + } + + /** + * Handle a click on a colour cell. + * @param {!MouseEvent} e Mouse event. + * @private + */ + onClick_(e) { + const cell = /** @type {!Element} */ (e.target); + const colour = cell && cell.label; + if (colour !== null) { + this.setValue(colour); + DropDownDiv.hideIfOwner(this); + } + } + + /** + * Handle a key down event. Navigate around the grid with the + * arrow keys. Enter selects the highlighted colour. + * @param {!KeyboardEvent} e Keyboard event. + * @private + */ + onKeyDown_(e) { + let handled = false; + if (e.keyCode === KeyCodes.UP) { + this.moveHighlightBy_(0, -1); + handled = true; + } else if (e.keyCode === KeyCodes.DOWN) { + this.moveHighlightBy_(0, 1); + handled = true; + } else if (e.keyCode === KeyCodes.LEFT) { + this.moveHighlightBy_(-1, 0); + handled = true; + } else if (e.keyCode === KeyCodes.RIGHT) { + this.moveHighlightBy_(1, 0); + handled = true; + } else if (e.keyCode === KeyCodes.ENTER) { + // Select the highlighted colour. + const highlighted = this.getHighlighted_(); + if (highlighted) { + const colour = highlighted && highlighted.label; + if (colour !== null) { + this.setValue(colour); + } + } + DropDownDiv.hideWithoutAnimation(); + handled = true; + } + if (handled) { + e.stopPropagation(); + } + } + + /** + * Move the currently highlighted position by dx and dy. + * @param {number} dx Change of x + * @param {number} dy Change of y + * @private + */ + moveHighlightBy_(dx, dy) { + const colours = this.colours_ || FieldColour.COLOURS; + const columns = this.columns_ || FieldColour.COLUMNS; + + // Get the current x and y coordinates + let x = this.highlightedIndex_ % columns; + let y = Math.floor(this.highlightedIndex_ / columns); + + // Add the offset + x += dx; + y += dy; + + if (dx < 0) { + // Move left one grid cell, even in RTL. + // Loop back to the end of the previous row if we have room. + if (x < 0 && y > 0) { + x = columns - 1; + y--; + } else if (x < 0) { + x = 0; + } + } else if (dx > 0) { + // Move right one grid cell, even in RTL. + // Loop to the start of the next row, if there's room. + if (x > columns - 1 && y < Math.floor(colours.length / columns) - 1) { + x = 0; + y++; + } else if (x > columns - 1) { + x--; + } + } else if (dy < 0) { + // Move up one grid cell, stop at the top. + if (y < 0) { + y = 0; + } + } else if (dy > 0) { + // Move down one grid cell, stop at the bottom. + if (y > Math.floor(colours.length / columns) - 1) { + y = Math.floor(colours.length / columns) - 1; + } + } + + // Move the highlight to the new coordinates. + const cell = + /** @type {!Element} */ (this.picker_.childNodes[y].childNodes[x]); + const index = (y * columns) + x; + this.setHighlightedCell_(cell, index); + } + + /** + * Handle a mouse move event. Highlight the hovered colour. + * @param {!MouseEvent} e Mouse event. + * @private + */ + onMouseMove_(e) { + const cell = /** @type {!Element} */ (e.target); + const index = cell && Number(cell.getAttribute('data-index')); + if (index !== null && index !== this.highlightedIndex_) { + this.setHighlightedCell_(cell, index); + } + } + + /** + * Handle a mouse enter event. Focus the picker. + * @private + */ + onMouseEnter_() { + this.picker_.focus({preventScroll: true}); + } + + /** + * Handle a mouse leave event. Blur the picker and unhighlight + * the currently highlighted colour. + * @private + */ + onMouseLeave_() { + this.picker_.blur(); + const highlighted = this.getHighlighted_(); + if (highlighted) { + dom.removeClass(highlighted, 'blocklyColourHighlighted'); + } + } + + /** + * Returns the currently highlighted item (if any). + * @return {?HTMLElement} Highlighted item (null if none). + * @private + */ + getHighlighted_() { + const columns = this.columns_ || FieldColour.COLUMNS; + const x = this.highlightedIndex_ % columns; + const y = Math.floor(this.highlightedIndex_ / columns); + const row = this.picker_.childNodes[y]; + if (!row) { + return null; + } + const col = /** @type {HTMLElement} */ (row.childNodes[x]); + return col; + } + + /** + * Update the currently highlighted cell. + * @param {!Element} cell the new cell to highlight + * @param {number} index the index of the new cell + * @private + */ + setHighlightedCell_(cell, index) { + // Unhighlight the current item. + const highlighted = this.getHighlighted_(); + if (highlighted) { + dom.removeClass(highlighted, 'blocklyColourHighlighted'); + } + // Highlight new item. + dom.addClass(cell, 'blocklyColourHighlighted'); + // Set new highlighted index. + this.highlightedIndex_ = index; + + // Update accessibility roles. + aria.setState( + /** @type {!Element} */ (this.picker_), aria.State.ACTIVEDESCENDANT, + cell.getAttribute('id')); + } + + /** + * Create a colour picker dropdown editor. + * @private + */ + dropdownCreate_() { + const columns = this.columns_ || FieldColour.COLUMNS; + const colours = this.colours_ || FieldColour.COLOURS; + const titles = this.titles_ || FieldColour.TITLES; + const selectedColour = this.getValue(); + // Create the palette. + const table = document.createElement('table'); + table.className = 'blocklyColourTable'; + table.tabIndex = 0; + table.dir = 'ltr'; + aria.setRole(table, aria.Role.GRID); + aria.setState(table, aria.State.EXPANDED, true); + aria.setState( + table, aria.State.ROWCOUNT, Math.floor(colours.length / columns)); + aria.setState(table, aria.State.COLCOUNT, columns); + let row; + for (let i = 0; i < colours.length; i++) { + if (i % columns === 0) { + row = document.createElement('tr'); + aria.setRole(row, aria.Role.ROW); + table.appendChild(row); + } + const cell = document.createElement('td'); + row.appendChild(cell); + cell.label = colours[i]; // This becomes the value, if clicked. + cell.title = titles[i] || colours[i]; + cell.id = idGenerator.getNextUniqueId(); + cell.setAttribute('data-index', i); + aria.setRole(cell, aria.Role.GRIDCELL); + aria.setState(cell, aria.State.LABEL, colours[i]); + aria.setState(cell, aria.State.SELECTED, colours[i] === selectedColour); + cell.style.backgroundColor = colours[i]; + if (colours[i] === selectedColour) { + cell.className = 'blocklyColourSelected'; + this.highlightedIndex_ = i; + } + } + + // Configure event handler on the table to listen for any event in a cell. + this.onClickWrapper_ = browserEvents.conditionalBind( + table, 'click', this, this.onClick_, true); + this.onMouseMoveWrapper_ = browserEvents.conditionalBind( + table, 'mousemove', this, this.onMouseMove_, true); + this.onMouseEnterWrapper_ = browserEvents.conditionalBind( + table, 'mouseenter', this, this.onMouseEnter_, true); + this.onMouseLeaveWrapper_ = browserEvents.conditionalBind( + table, 'mouseleave', this, this.onMouseLeave_, true); + this.onKeyDownWrapper_ = + browserEvents.conditionalBind(table, 'keydown', this, this.onKeyDown_); + + this.picker_ = table; + } + + /** + * Disposes of events and DOM-references belonging to the colour editor. + * @private + */ + dropdownDispose_() { + if (this.onClickWrapper_) { + browserEvents.unbind(this.onClickWrapper_); + this.onClickWrapper_ = null; + } + if (this.onMouseMoveWrapper_) { + browserEvents.unbind(this.onMouseMoveWrapper_); + this.onMouseMoveWrapper_ = null; + } + if (this.onMouseEnterWrapper_) { + browserEvents.unbind(this.onMouseEnterWrapper_); + this.onMouseEnterWrapper_ = null; + } + if (this.onMouseLeaveWrapper_) { + browserEvents.unbind(this.onMouseLeaveWrapper_); + this.onMouseLeaveWrapper_ = null; + } + if (this.onKeyDownWrapper_) { + browserEvents.unbind(this.onKeyDownWrapper_); + this.onKeyDownWrapper_ = null; + } + this.picker_ = null; + this.highlightedIndex_ = null; + } + + /** + * Construct a FieldColour from a JSON arg object. + * @param {!Object} options A JSON object with options (colour). + * @return {!FieldColour} The new field instance. + * @package + * @nocollapse + */ + static fromJson(options) { + // `this` might be a subclass of FieldColour if that class doesn't override + // the static fromJson method. + return new this(options['colour'], undefined, options); + } +} /** * An array of colour strings for the palette. @@ -357,313 +678,6 @@ FieldColour.TITLES = []; */ FieldColour.COLUMNS = 7; -/** - * Set a custom colour grid for this field. - * @param {Array} colours Array of colours for this block, - * or null to use default (FieldColour.COLOURS). - * @param {Array=} opt_titles Optional array of colour tooltips, - * or null to use default (FieldColour.TITLES). - * @return {!FieldColour} Returns itself (for method chaining). - */ -FieldColour.prototype.setColours = function(colours, opt_titles) { - this.colours_ = colours; - if (opt_titles) { - this.titles_ = opt_titles; - } - return this; -}; - -/** - * Set a custom grid size for this field. - * @param {number} columns Number of columns for this block, - * or 0 to use default (FieldColour.COLUMNS). - * @return {!FieldColour} Returns itself (for method chaining). - */ -FieldColour.prototype.setColumns = function(columns) { - this.columns_ = columns; - return this; -}; - -/** - * Create and show the colour field's editor. - * @protected - */ -FieldColour.prototype.showEditor_ = function() { - this.dropdownCreate_(); - DropDownDiv.getContentDiv().appendChild(this.picker_); - - DropDownDiv.showPositionedByField(this, this.dropdownDispose_.bind(this)); - - // Focus so we can start receiving keyboard events. - this.picker_.focus({preventScroll: true}); -}; - -/** - * Handle a click on a colour cell. - * @param {!MouseEvent} e Mouse event. - * @private - */ -FieldColour.prototype.onClick_ = function(e) { - const cell = /** @type {!Element} */ (e.target); - const colour = cell && cell.label; - if (colour !== null) { - this.setValue(colour); - DropDownDiv.hideIfOwner(this); - } -}; - -/** - * Handle a key down event. Navigate around the grid with the - * arrow keys. Enter selects the highlighted colour. - * @param {!KeyboardEvent} e Keyboard event. - * @private - */ -FieldColour.prototype.onKeyDown_ = function(e) { - let handled = false; - if (e.keyCode === KeyCodes.UP) { - this.moveHighlightBy_(0, -1); - handled = true; - } else if (e.keyCode === KeyCodes.DOWN) { - this.moveHighlightBy_(0, 1); - handled = true; - } else if (e.keyCode === KeyCodes.LEFT) { - this.moveHighlightBy_(-1, 0); - handled = true; - } else if (e.keyCode === KeyCodes.RIGHT) { - this.moveHighlightBy_(1, 0); - handled = true; - } else if (e.keyCode === KeyCodes.ENTER) { - // Select the highlighted colour. - const highlighted = this.getHighlighted_(); - if (highlighted) { - const colour = highlighted && highlighted.label; - if (colour !== null) { - this.setValue(colour); - } - } - DropDownDiv.hideWithoutAnimation(); - handled = true; - } - if (handled) { - e.stopPropagation(); - } -}; - -/** - * Move the currently highlighted position by dx and dy. - * @param {number} dx Change of x - * @param {number} dy Change of y - * @private - */ -FieldColour.prototype.moveHighlightBy_ = function(dx, dy) { - const colours = this.colours_ || FieldColour.COLOURS; - const columns = this.columns_ || FieldColour.COLUMNS; - - // Get the current x and y coordinates - let x = this.highlightedIndex_ % columns; - let y = Math.floor(this.highlightedIndex_ / columns); - - // Add the offset - x += dx; - y += dy; - - if (dx < 0) { - // Move left one grid cell, even in RTL. - // Loop back to the end of the previous row if we have room. - if (x < 0 && y > 0) { - x = columns - 1; - y--; - } else if (x < 0) { - x = 0; - } - } else if (dx > 0) { - // Move right one grid cell, even in RTL. - // Loop to the start of the next row, if there's room. - if (x > columns - 1 && y < Math.floor(colours.length / columns) - 1) { - x = 0; - y++; - } else if (x > columns - 1) { - x--; - } - } else if (dy < 0) { - // Move up one grid cell, stop at the top. - if (y < 0) { - y = 0; - } - } else if (dy > 0) { - // Move down one grid cell, stop at the bottom. - if (y > Math.floor(colours.length / columns) - 1) { - y = Math.floor(colours.length / columns) - 1; - } - } - - // Move the highlight to the new coordinates. - const cell = - /** @type {!Element} */ (this.picker_.childNodes[y].childNodes[x]); - const index = (y * columns) + x; - this.setHighlightedCell_(cell, index); -}; - -/** - * Handle a mouse move event. Highlight the hovered colour. - * @param {!MouseEvent} e Mouse event. - * @private - */ -FieldColour.prototype.onMouseMove_ = function(e) { - const cell = /** @type {!Element} */ (e.target); - const index = cell && Number(cell.getAttribute('data-index')); - if (index !== null && index !== this.highlightedIndex_) { - this.setHighlightedCell_(cell, index); - } -}; - -/** - * Handle a mouse enter event. Focus the picker. - * @private - */ -FieldColour.prototype.onMouseEnter_ = function() { - this.picker_.focus({preventScroll: true}); -}; - -/** - * Handle a mouse leave event. Blur the picker and unhighlight - * the currently highlighted colour. - * @private - */ -FieldColour.prototype.onMouseLeave_ = function() { - this.picker_.blur(); - const highlighted = this.getHighlighted_(); - if (highlighted) { - dom.removeClass(highlighted, 'blocklyColourHighlighted'); - } -}; - -/** - * Returns the currently highlighted item (if any). - * @return {?HTMLElement} Highlighted item (null if none). - * @private - */ -FieldColour.prototype.getHighlighted_ = function() { - const columns = this.columns_ || FieldColour.COLUMNS; - const x = this.highlightedIndex_ % columns; - const y = Math.floor(this.highlightedIndex_ / columns); - const row = this.picker_.childNodes[y]; - if (!row) { - return null; - } - const col = /** @type {HTMLElement} */ (row.childNodes[x]); - return col; -}; - -/** - * Update the currently highlighted cell. - * @param {!Element} cell the new cell to highlight - * @param {number} index the index of the new cell - * @private - */ -FieldColour.prototype.setHighlightedCell_ = function(cell, index) { - // Unhighlight the current item. - const highlighted = this.getHighlighted_(); - if (highlighted) { - dom.removeClass(highlighted, 'blocklyColourHighlighted'); - } - // Highlight new item. - dom.addClass(cell, 'blocklyColourHighlighted'); - // Set new highlighted index. - this.highlightedIndex_ = index; - - // Update accessibility roles. - aria.setState( - /** @type {!Element} */ (this.picker_), aria.State.ACTIVEDESCENDANT, - cell.getAttribute('id')); -}; - -/** - * Create a colour picker dropdown editor. - * @private - */ -FieldColour.prototype.dropdownCreate_ = function() { - const columns = this.columns_ || FieldColour.COLUMNS; - const colours = this.colours_ || FieldColour.COLOURS; - const titles = this.titles_ || FieldColour.TITLES; - const selectedColour = this.getValue(); - // Create the palette. - const table = document.createElement('table'); - table.className = 'blocklyColourTable'; - table.tabIndex = 0; - table.dir = 'ltr'; - aria.setRole(table, aria.Role.GRID); - aria.setState(table, aria.State.EXPANDED, true); - aria.setState( - table, aria.State.ROWCOUNT, Math.floor(colours.length / columns)); - aria.setState(table, aria.State.COLCOUNT, columns); - let row; - for (let i = 0; i < colours.length; i++) { - if (i % columns === 0) { - row = document.createElement('tr'); - aria.setRole(row, aria.Role.ROW); - table.appendChild(row); - } - const cell = document.createElement('td'); - row.appendChild(cell); - cell.label = colours[i]; // This becomes the value, if clicked. - cell.title = titles[i] || colours[i]; - cell.id = idGenerator.getNextUniqueId(); - cell.setAttribute('data-index', i); - aria.setRole(cell, aria.Role.GRIDCELL); - aria.setState(cell, aria.State.LABEL, colours[i]); - aria.setState(cell, aria.State.SELECTED, colours[i] === selectedColour); - cell.style.backgroundColor = colours[i]; - if (colours[i] === selectedColour) { - cell.className = 'blocklyColourSelected'; - this.highlightedIndex_ = i; - } - } - - // Configure event handler on the table to listen for any event in a cell. - this.onClickWrapper_ = - browserEvents.conditionalBind(table, 'click', this, this.onClick_, true); - this.onMouseMoveWrapper_ = browserEvents.conditionalBind( - table, 'mousemove', this, this.onMouseMove_, true); - this.onMouseEnterWrapper_ = browserEvents.conditionalBind( - table, 'mouseenter', this, this.onMouseEnter_, true); - this.onMouseLeaveWrapper_ = browserEvents.conditionalBind( - table, 'mouseleave', this, this.onMouseLeave_, true); - this.onKeyDownWrapper_ = - browserEvents.conditionalBind(table, 'keydown', this, this.onKeyDown_); - - this.picker_ = table; -}; - -/** - * Disposes of events and DOM-references belonging to the colour editor. - * @private - */ -FieldColour.prototype.dropdownDispose_ = function() { - if (this.onClickWrapper_) { - browserEvents.unbind(this.onClickWrapper_); - this.onClickWrapper_ = null; - } - if (this.onMouseMoveWrapper_) { - browserEvents.unbind(this.onMouseMoveWrapper_); - this.onMouseMoveWrapper_ = null; - } - if (this.onMouseEnterWrapper_) { - browserEvents.unbind(this.onMouseEnterWrapper_); - this.onMouseEnterWrapper_ = null; - } - if (this.onMouseLeaveWrapper_) { - browserEvents.unbind(this.onMouseLeaveWrapper_); - this.onMouseLeaveWrapper_ = null; - } - if (this.onKeyDownWrapper_) { - browserEvents.unbind(this.onKeyDownWrapper_); - this.onKeyDownWrapper_ = null; - } - this.picker_ = null; - this.highlightedIndex_ = null; -}; - /** * CSS for colour picker. See css.js for use. */ diff --git a/core/field_dropdown.js b/core/field_dropdown.js index 618ecd7b6..307578db9 100644 --- a/core/field_dropdown.js +++ b/core/field_dropdown.js @@ -22,7 +22,6 @@ goog.module('Blockly.FieldDropdown'); const aria = goog.require('Blockly.utils.aria'); const dom = goog.require('Blockly.utils.dom'); const fieldRegistry = goog.require('Blockly.fieldRegistry'); -const object = goog.require('Blockly.utils.object'); const parsing = goog.require('Blockly.utils.parsing'); const userAgent = goog.require('Blockly.utils.userAgent'); const utilsString = goog.require('Blockly.utils.string'); @@ -31,111 +30,682 @@ const {DropDownDiv} = goog.require('Blockly.DropDownDiv'); const {Field} = goog.require('Blockly.Field'); const {MenuItem} = goog.require('Blockly.MenuItem'); const {Menu} = goog.require('Blockly.Menu'); +/* eslint-disable-next-line no-unused-vars */ +const {Sentinel} = goog.requireType('Blockly.utils.Sentinel'); const {Svg} = goog.require('Blockly.utils.Svg'); /** * Class for an editable dropdown field. - * @param {(!Array|!Function)} menuGenerator A non-empty array of - * options for a dropdown list, or a function which generates these options. - * @param {Function=} opt_validator A function that is called to validate - * changes to the field's value. Takes in a language-neutral dropdown - * option & returns a validated language-neutral dropdown option, or null to - * abort the change. - * @param {Object=} opt_config A map of options used to configure the field. - * See the [field creation documentation]{@link - * https://developers.google.com/blockly/guides/create-custom-blocks/fields/built-in-fields/dropdown#creation} - * for a list of properties this parameter supports. * @extends {Field} - * @constructor - * @throws {TypeError} If `menuGenerator` options are incorrectly structured. - * @alias Blockly.FieldDropdown */ -const FieldDropdown = function(menuGenerator, opt_validator, opt_config) { - if (typeof menuGenerator !== 'function') { - validateOptions(menuGenerator); +class FieldDropdown extends Field { + /** + * @param {(!Array|!Function|!Sentinel)} menuGenerator + * A non-empty array of options for a dropdown list, or a function which + * generates these options. + * Also accepts Field.SKIP_SETUP if you wish to skip setup (only used by + * subclasses that want to handle configuration and setting the field + * value after their own constructors have run). + * @param {Function=} opt_validator A function that is called to validate + * changes to the field's value. Takes in a language-neutral dropdown + * option & returns a validated language-neutral dropdown option, or null + * to abort the change. + * @param {Object=} opt_config A map of options used to configure the field. + * See the [field creation documentation]{@link + * https://developers.google.com/blockly/guides/create-custom-blocks/fields/built-in-fields/dropdown#creation} + * for a list of properties this parameter supports. + * @throws {TypeError} If `menuGenerator` options are incorrectly structured. + * @alias Blockly.FieldDropdown + */ + constructor(menuGenerator, opt_validator, opt_config) { + super(Field.SKIP_SETUP); + + /** + * A reference to the currently selected menu item. + * @type {?MenuItem} + * @private + */ + this.selectedMenuItem_ = null; + + /** + * The dropdown menu. + * @type {?Menu} + * @protected + */ + this.menu_ = null; + + /** + * SVG image element if currently selected option is an image, or null. + * @type {?SVGImageElement} + * @private + */ + this.imageElement_ = null; + + /** + * Tspan based arrow element. + * @type {?SVGTSpanElement} + * @private + */ + this.arrow_ = null; + + /** + * SVG based arrow element. + * @type {?SVGElement} + * @private + */ + this.svgArrow_ = null; + + /** + * Serializable fields are saved by the serializer, non-serializable fields + * are not. Editable fields should also be serializable. + * @type {boolean} + */ + this.SERIALIZABLE = true; + + /** + * Mouse cursor style when over the hotspot that initiates the editor. + * @type {string} + */ + this.CURSOR = 'default'; + + + // If we pass SKIP_SETUP, don't do *anything* with the menu generator. + if (menuGenerator === Field.SKIP_SETUP) return; + + if (Array.isArray(menuGenerator)) { + validateOptions(menuGenerator); + } + + /** + * An array of options for a dropdown list, + * or a function which generates these options. + * @type {(!Array|!function(this:FieldDropdown): !Array)} + * @protected + */ + this.menuGenerator_ = + /** + * @type {(!Array| + * !function(this:FieldDropdown):!Array)} + */ + (menuGenerator); + + /** + * A cache of the most recently generated options. + * @type {Array>} + * @private + */ + this.generatedOptions_ = null; + + /** + * The prefix field label, of common words set after options are trimmed. + * @type {?string} + * @package + */ + this.prefixField = null; + + /** + * The suffix field label, of common words set after options are trimmed. + * @type {?string} + * @package + */ + this.suffixField = null; + + this.trimOptions_(); + + /** + * The currently selected option. The field is initialized with the + * first option selected. + * @type {!Array} + * @private + */ + this.selectedOption_ = this.getOptions(false)[0]; + + if (opt_config) this.configure_(opt_config); + this.setValue(this.selectedOption_[1]); + if (opt_validator) this.setValidator(opt_validator); } /** - * An array of options for a dropdown list, - * or a function which generates these options. - * @type {(!Array| - * !function(this:FieldDropdown): !Array)} - * @protected - */ - this.menuGenerator_ = menuGenerator; - - /** - * A cache of the most recently generated options. - * @type {Array>} - * @private - */ - this.generatedOptions_ = null; - - /** - * The prefix field label, of common words set after options are trimmed. - * @type {?string} + * Sets the field's value based on the given XML element. Should only be + * called by Blockly.Xml. + * @param {!Element} fieldElement The element containing info about the + * field's state. * @package */ - this.prefixField = null; + fromXml(fieldElement) { + if (this.isOptionListDynamic()) { + this.getOptions(false); + } + this.setValue(fieldElement.textContent); + } /** - * The suffix field label, of common words set after options are trimmed. - * @type {?string} + * Sets the field's value based on the given state. + * @param {*} state The state to apply to the dropdown field. + * @override * @package */ - this.suffixField = null; - - this.trimOptions_(); + loadState(state) { + if (this.loadLegacyState(FieldDropdown, state)) { + return; + } + if (this.isOptionListDynamic()) { + this.getOptions(false); + } + this.setValue(state); + } /** - * The currently selected option. The field is initialized with the - * first option selected. - * @type {!Object} - * @private + * Create the block UI for this dropdown. + * @package */ - this.selectedOption_ = this.getOptions(false)[0]; + initView() { + if (this.shouldAddBorderRect_()) { + this.createBorderRect_(); + } else { + this.clickTarget_ = this.sourceBlock_.getSvgRoot(); + } + this.createTextElement_(); - // Call parent's constructor. - FieldDropdown.superClass_.constructor.call( - this, this.selectedOption_[1], opt_validator, opt_config); + this.imageElement_ = dom.createSvgElement(Svg.IMAGE, {}, this.fieldGroup_); + + if (this.getConstants().FIELD_DROPDOWN_SVG_ARROW) { + this.createSVGArrow_(); + } else { + this.createTextArrow_(); + } + + if (this.borderRect_) { + dom.addClass(this.borderRect_, 'blocklyDropdownRect'); + } + } /** - * A reference to the currently selected menu item. - * @type {?MenuItem} - * @private - */ - this.selectedMenuItem_ = null; - - /** - * The dropdown menu. - * @type {?Menu} + * Whether or not the dropdown should add a border rect. + * @return {boolean} True if the dropdown field should add a border rect. * @protected */ - this.menu_ = null; + shouldAddBorderRect_() { + return !this.getConstants().FIELD_DROPDOWN_NO_BORDER_RECT_SHADOW || + (this.getConstants().FIELD_DROPDOWN_NO_BORDER_RECT_SHADOW && + !this.sourceBlock_.isShadow()); + } /** - * SVG image element if currently selected option is an image, or null. - * @type {?SVGImageElement} - * @private + * Create a tspan based arrow. + * @protected */ - this.imageElement_ = null; + createTextArrow_() { + this.arrow_ = dom.createSvgElement(Svg.TSPAN, {}, this.textElement_); + this.arrow_.appendChild(document.createTextNode( + this.sourceBlock_.RTL ? FieldDropdown.ARROW_CHAR + ' ' : + ' ' + FieldDropdown.ARROW_CHAR)); + if (this.sourceBlock_.RTL) { + this.textElement_.insertBefore(this.arrow_, this.textContent_); + } else { + this.textElement_.appendChild(this.arrow_); + } + } /** - * Tspan based arrow element. - * @type {?SVGTSpanElement} - * @private + * Create an SVG based arrow. + * @protected */ - this.arrow_ = null; + createSVGArrow_() { + this.svgArrow_ = dom.createSvgElement( + Svg.IMAGE, { + 'height': this.getConstants().FIELD_DROPDOWN_SVG_ARROW_SIZE + 'px', + 'width': this.getConstants().FIELD_DROPDOWN_SVG_ARROW_SIZE + 'px', + }, + this.fieldGroup_); + this.svgArrow_.setAttributeNS( + dom.XLINK_NS, 'xlink:href', + this.getConstants().FIELD_DROPDOWN_SVG_ARROW_DATAURI); + } /** - * SVG based arrow element. - * @type {?SVGElement} + * Create a dropdown menu under the text. + * @param {Event=} opt_e Optional mouse event that triggered the field to + * open, or undefined if triggered programmatically. + * @protected + */ + showEditor_(opt_e) { + this.dropdownCreate_(); + if (opt_e && typeof opt_e.clientX === 'number') { + this.menu_.openingCoords = new Coordinate(opt_e.clientX, opt_e.clientY); + } else { + this.menu_.openingCoords = null; + } + + // Remove any pre-existing elements in the dropdown. + DropDownDiv.clearContent(); + // Element gets created in render. + this.menu_.render(DropDownDiv.getContentDiv()); + const menuElement = /** @type {!Element} */ (this.menu_.getElement()); + dom.addClass(menuElement, 'blocklyDropdownMenu'); + + if (this.getConstants().FIELD_DROPDOWN_COLOURED_DIV) { + const primaryColour = (this.sourceBlock_.isShadow()) ? + this.sourceBlock_.getParent().getColour() : + this.sourceBlock_.getColour(); + const borderColour = (this.sourceBlock_.isShadow()) ? + this.sourceBlock_.getParent().style.colourTertiary : + this.sourceBlock_.style.colourTertiary; + DropDownDiv.setColour(primaryColour, borderColour); + } + + DropDownDiv.showPositionedByField(this, this.dropdownDispose_.bind(this)); + + // Focusing needs to be handled after the menu is rendered and positioned. + // Otherwise it will cause a page scroll to get the misplaced menu in + // view. See issue #1329. + this.menu_.focus(); + + if (this.selectedMenuItem_) { + this.menu_.setHighlighted(this.selectedMenuItem_); + } + + this.applyColour(); + } + + /** + * Create the dropdown editor. * @private */ - this.svgArrow_ = null; -}; -object.inherits(FieldDropdown, Field); + dropdownCreate_() { + const menu = new Menu(); + menu.setRole(aria.Role.LISTBOX); + this.menu_ = menu; + + const options = this.getOptions(false); + this.selectedMenuItem_ = null; + for (let i = 0; i < options.length; i++) { + let content = options[i][0]; // Human-readable text or image. + const value = options[i][1]; // Language-neutral value. + if (typeof content === 'object') { + // An image, not text. + const image = new Image(content['width'], content['height']); + image.src = content['src']; + image.alt = content['alt'] || ''; + content = image; + } + const menuItem = new MenuItem(content, value); + menuItem.setRole(aria.Role.OPTION); + menuItem.setRightToLeft(this.sourceBlock_.RTL); + menuItem.setCheckable(true); + menu.addChild(menuItem); + menuItem.setChecked(value === this.value_); + if (value === this.value_) { + this.selectedMenuItem_ = menuItem; + } + menuItem.onAction(this.handleMenuActionEvent_, this); + } + } + + /** + * Disposes of events and DOM-references belonging to the dropdown editor. + * @private + */ + dropdownDispose_() { + if (this.menu_) { + this.menu_.dispose(); + } + this.menu_ = null; + this.selectedMenuItem_ = null; + this.applyColour(); + } + + /** + * Handle an action in the dropdown menu. + * @param {!MenuItem} menuItem The MenuItem selected within menu. + * @private + */ + handleMenuActionEvent_(menuItem) { + DropDownDiv.hideIfOwner(this, true); + this.onItemSelected_(/** @type {!Menu} */ (this.menu_), menuItem); + } + + /** + * Handle the selection of an item in the dropdown menu. + * @param {!Menu} menu The Menu component clicked. + * @param {!MenuItem} menuItem The MenuItem selected within menu. + * @protected + */ + onItemSelected_(menu, menuItem) { + this.setValue(menuItem.getValue()); + } + + /** + * Factor out common words in statically defined options. + * Create prefix and/or suffix labels. + * @private + */ + trimOptions_() { + const options = this.menuGenerator_; + if (!Array.isArray(options)) { + return; + } + let hasImages = false; + + // Localize label text and image alt text. + for (let i = 0; i < options.length; i++) { + const label = options[i][0]; + if (typeof label === 'string') { + options[i][0] = parsing.replaceMessageReferences(label); + } else { + if (label.alt !== null) { + options[i][0].alt = parsing.replaceMessageReferences(label.alt); + } + hasImages = true; + } + } + if (hasImages || options.length < 2) { + return; // Do nothing if too few items or at least one label is an image. + } + const strings = []; + for (let i = 0; i < options.length; i++) { + strings.push(options[i][0]); + } + const shortest = utilsString.shortestStringLength(strings); + const prefixLength = utilsString.commonWordPrefix(strings, shortest); + const suffixLength = utilsString.commonWordSuffix(strings, shortest); + if (!prefixLength && !suffixLength) { + return; + } + if (shortest <= prefixLength + suffixLength) { + // One or more strings will entirely vanish if we proceed. Abort. + return; + } + if (prefixLength) { + this.prefixField = strings[0].substring(0, prefixLength - 1); + } + if (suffixLength) { + this.suffixField = strings[0].substr(1 - suffixLength); + } + + this.menuGenerator_ = + FieldDropdown.applyTrim_(options, prefixLength, suffixLength); + } + + /** + * @return {boolean} True if the option list is generated by a function. + * Otherwise false. + */ + isOptionListDynamic() { + return typeof this.menuGenerator_ === 'function'; + } + + /** + * Return a list of the options for this dropdown. + * @param {boolean=} opt_useCache For dynamic options, whether or not to use + * the cached options or to re-generate them. + * @return {!Array} A non-empty array of option tuples: + * (human-readable text or image, language-neutral name). + * @throws {TypeError} If generated options are incorrectly structured. + */ + getOptions(opt_useCache) { + if (this.isOptionListDynamic()) { + if (!this.generatedOptions_ || !opt_useCache) { + this.generatedOptions_ = this.menuGenerator_.call(this); + validateOptions(this.generatedOptions_); + } + return this.generatedOptions_; + } + return /** @type {!Array>} */ (this.menuGenerator_); + } + + /** + * Ensure that the input value is a valid language-neutral option. + * @param {*=} opt_newValue The input value. + * @return {?string} A valid language-neutral option, or null if invalid. + * @protected + */ + doClassValidation_(opt_newValue) { + let isValueValid = false; + const options = this.getOptions(true); + for (let i = 0, option; (option = options[i]); i++) { + // Options are tuples of human-readable text and language-neutral values. + if (option[1] === opt_newValue) { + isValueValid = true; + break; + } + } + if (!isValueValid) { + if (this.sourceBlock_) { + console.warn( + 'Cannot set the dropdown\'s value to an unavailable option.' + + ' Block type: ' + this.sourceBlock_.type + + ', Field name: ' + this.name + ', Value: ' + opt_newValue); + } + return null; + } + return /** @type {string} */ (opt_newValue); + } + + /** + * Update the value of this dropdown field. + * @param {*} newValue The value to be saved. The default validator guarantees + * that this is one of the valid dropdown options. + * @protected + */ + doValueUpdate_(newValue) { + super.doValueUpdate_(newValue); + const options = this.getOptions(true); + for (let i = 0, option; (option = options[i]); i++) { + if (option[1] === this.value_) { + this.selectedOption_ = option; + } + } + } + + /** + * Updates the dropdown arrow to match the colour/style of the block. + * @package + */ + applyColour() { + if (this.borderRect_) { + this.borderRect_.setAttribute( + 'stroke', this.sourceBlock_.style.colourTertiary); + if (this.menu_) { + this.borderRect_.setAttribute( + 'fill', this.sourceBlock_.style.colourTertiary); + } else { + this.borderRect_.setAttribute('fill', 'transparent'); + } + } + // Update arrow's colour. + if (this.sourceBlock_ && this.arrow_) { + if (this.sourceBlock_.isShadow()) { + this.arrow_.style.fill = this.sourceBlock_.style.colourSecondary; + } else { + this.arrow_.style.fill = this.sourceBlock_.style.colourPrimary; + } + } + } + + /** + * Draws the border with the correct width. + * @protected + */ + render_() { + // Hide both elements. + this.textContent_.nodeValue = ''; + this.imageElement_.style.display = 'none'; + + // Show correct element. + const option = this.selectedOption_ && this.selectedOption_[0]; + if (option && typeof option === 'object') { + this.renderSelectedImage_( + /** @type {!ImageProperties} */ (option)); + } else { + this.renderSelectedText_(); + } + + this.positionBorderRect_(); + } + + /** + * Renders the selected option, which must be an image. + * @param {!ImageProperties} imageJson Selected + * option that must be an image. + * @private + */ + renderSelectedImage_(imageJson) { + this.imageElement_.style.display = ''; + this.imageElement_.setAttributeNS( + dom.XLINK_NS, 'xlink:href', imageJson.src); + this.imageElement_.setAttribute('height', imageJson.height); + this.imageElement_.setAttribute('width', imageJson.width); + + const imageHeight = Number(imageJson.height); + const imageWidth = Number(imageJson.width); + + // Height and width include the border rect. + const hasBorder = !!this.borderRect_; + const height = Math.max( + hasBorder ? this.getConstants().FIELD_DROPDOWN_BORDER_RECT_HEIGHT : 0, + imageHeight + IMAGE_Y_PADDING); + const xPadding = + hasBorder ? this.getConstants().FIELD_BORDER_RECT_X_PADDING : 0; + let arrowWidth = 0; + if (this.svgArrow_) { + arrowWidth = this.positionSVGArrow_( + imageWidth + xPadding, + height / 2 - this.getConstants().FIELD_DROPDOWN_SVG_ARROW_SIZE / 2); + } else { + arrowWidth = dom.getFastTextWidth( + /** @type {!SVGTSpanElement} */ (this.arrow_), + this.getConstants().FIELD_TEXT_FONTSIZE, + this.getConstants().FIELD_TEXT_FONTWEIGHT, + this.getConstants().FIELD_TEXT_FONTFAMILY); + } + this.size_.width = imageWidth + arrowWidth + xPadding * 2; + this.size_.height = height; + + let arrowX = 0; + if (this.sourceBlock_.RTL) { + const imageX = xPadding + arrowWidth; + this.imageElement_.setAttribute('x', imageX); + } else { + arrowX = imageWidth + arrowWidth; + this.textElement_.setAttribute('text-anchor', 'end'); + this.imageElement_.setAttribute('x', xPadding); + } + this.imageElement_.setAttribute('y', height / 2 - imageHeight / 2); + + this.positionTextElement_(arrowX + xPadding, imageWidth + arrowWidth); + } + + /** + * Renders the selected option, which must be text. + * @private + */ + renderSelectedText_() { + // Retrieves the selected option to display through getText_. + this.textContent_.nodeValue = this.getDisplayText_(); + dom.addClass( + /** @type {!Element} */ (this.textElement_), 'blocklyDropdownText'); + this.textElement_.setAttribute('text-anchor', 'start'); + + // Height and width include the border rect. + const hasBorder = !!this.borderRect_; + const height = Math.max( + hasBorder ? this.getConstants().FIELD_DROPDOWN_BORDER_RECT_HEIGHT : 0, + this.getConstants().FIELD_TEXT_HEIGHT); + const textWidth = dom.getFastTextWidth( + this.textElement_, this.getConstants().FIELD_TEXT_FONTSIZE, + this.getConstants().FIELD_TEXT_FONTWEIGHT, + this.getConstants().FIELD_TEXT_FONTFAMILY); + const xPadding = + hasBorder ? this.getConstants().FIELD_BORDER_RECT_X_PADDING : 0; + let arrowWidth = 0; + if (this.svgArrow_) { + arrowWidth = this.positionSVGArrow_( + textWidth + xPadding, + height / 2 - this.getConstants().FIELD_DROPDOWN_SVG_ARROW_SIZE / 2); + } + this.size_.width = textWidth + arrowWidth + xPadding * 2; + this.size_.height = height; + + this.positionTextElement_(xPadding, textWidth); + } + + /** + * Position a drop-down arrow at the appropriate location at render-time. + * @param {number} x X position the arrow is being rendered at, in px. + * @param {number} y Y position the arrow is being rendered at, in px. + * @return {number} Amount of space the arrow is taking up, in px. + * @private + */ + positionSVGArrow_(x, y) { + if (!this.svgArrow_) { + return 0; + } + const hasBorder = !!this.borderRect_; + const xPadding = + hasBorder ? this.getConstants().FIELD_BORDER_RECT_X_PADDING : 0; + const textPadding = this.getConstants().FIELD_DROPDOWN_SVG_ARROW_PADDING; + const svgArrowSize = this.getConstants().FIELD_DROPDOWN_SVG_ARROW_SIZE; + const arrowX = this.sourceBlock_.RTL ? xPadding : x + textPadding; + this.svgArrow_.setAttribute( + 'transform', 'translate(' + arrowX + ',' + y + ')'); + return svgArrowSize + textPadding; + } + + /** + * Use the `getText_` developer hook to override the field's text + * representation. Get the selected option text. If the selected option is an + * image we return the image alt text. + * @return {?string} Selected option text. + * @protected + * @override + */ + getText_() { + if (!this.selectedOption_) { + return null; + } + const option = this.selectedOption_[0]; + if (typeof option === 'object') { + return option['alt']; + } + return option; + } + + /** + * Construct a FieldDropdown from a JSON arg object. + * @param {!Object} options A JSON object with options (options). + * @return {!FieldDropdown} The new field instance. + * @package + * @nocollapse + */ + static fromJson(options) { + // `this` might be a subclass of FieldDropdown if that class doesn't + // override the static fromJson method. + return new this(options['options'], undefined, options); + } + + /** + * Use the calculated prefix and suffix lengths to trim all of the options in + * the given array. + * @param {!Array} options Array of option tuples: + * (human-readable text or image, language-neutral name). + * @param {number} prefixLength The length of the common prefix. + * @param {number} suffixLength The length of the common suffix + * @return {!Array} A new array with all of the option text trimmed. + */ + static applyTrim_(options, prefixLength, suffixLength) { + const newOptions = []; + // Remove the prefix and suffix from the options. + for (let i = 0; i < options.length; i++) { + let text = options[i][0]; + const value = options[i][1]; + text = text.substring(prefixLength, text.length - suffixLength); + newOptions[i] = [text, value]; + } + return newOptions; + } +} /** * Dropdown image properties. @@ -146,57 +716,7 @@ object.inherits(FieldDropdown, Field); * height:number * }} */ -FieldDropdown.ImageProperties; - -/** - * Construct a FieldDropdown from a JSON arg object. - * @param {!Object} options A JSON object with options (options). - * @return {!FieldDropdown} The new field instance. - * @package - * @nocollapse - */ -FieldDropdown.fromJson = function(options) { - // `this` might be a subclass of FieldDropdown if that class doesn't override - // the static fromJson method. - return new this(options['options'], undefined, options); -}; - -/** - * Sets the field's value based on the given XML element. Should only be - * called by Blockly.Xml. - * @param {!Element} fieldElement The element containing info about the - * field's state. - * @package - */ -FieldDropdown.prototype.fromXml = function(fieldElement) { - if (this.isOptionListDynamic()) { - this.getOptions(false); - } - this.setValue(fieldElement.textContent); -}; - -/** - * Sets the field's value based on the given state. - * @param {*} state The state to apply to the dropdown field. - * @override - * @package - */ -FieldDropdown.prototype.loadState = function(state) { - if (this.loadLegacyState(FieldDropdown, state)) { - return; - } - if (this.isOptionListDynamic()) { - this.getOptions(false); - } - this.setValue(state); -}; - -/** - * Serializable fields are saved by the XML renderer, non-serializable fields - * are not. Editable fields should also be serializable. - * @type {boolean} - */ -FieldDropdown.prototype.SERIALIZABLE = true; +let ImageProperties; // eslint-disable-line no-unused-vars /** * Horizontal distance that a checkmark overhangs the dropdown. @@ -228,507 +748,6 @@ const IMAGE_Y_PADDING = IMAGE_Y_OFFSET * 2; */ FieldDropdown.ARROW_CHAR = userAgent.ANDROID ? '\u25BC' : '\u25BE'; -/** - * Mouse cursor style when over the hotspot that initiates the editor. - */ -FieldDropdown.prototype.CURSOR = 'default'; - -/** - * Create the block UI for this dropdown. - * @package - */ -FieldDropdown.prototype.initView = function() { - if (this.shouldAddBorderRect_()) { - this.createBorderRect_(); - } else { - this.clickTarget_ = this.sourceBlock_.getSvgRoot(); - } - this.createTextElement_(); - - this.imageElement_ = dom.createSvgElement(Svg.IMAGE, {}, this.fieldGroup_); - - if (this.getConstants().FIELD_DROPDOWN_SVG_ARROW) { - this.createSVGArrow_(); - } else { - this.createTextArrow_(); - } - - if (this.borderRect_) { - dom.addClass(this.borderRect_, 'blocklyDropdownRect'); - } -}; - -/** - * Whether or not the dropdown should add a border rect. - * @return {boolean} True if the dropdown field should add a border rect. - * @protected - */ -FieldDropdown.prototype.shouldAddBorderRect_ = function() { - return !this.getConstants().FIELD_DROPDOWN_NO_BORDER_RECT_SHADOW || - (this.getConstants().FIELD_DROPDOWN_NO_BORDER_RECT_SHADOW && - !this.sourceBlock_.isShadow()); -}; - -/** - * Create a tspan based arrow. - * @protected - */ -FieldDropdown.prototype.createTextArrow_ = function() { - this.arrow_ = dom.createSvgElement(Svg.TSPAN, {}, this.textElement_); - this.arrow_.appendChild(document.createTextNode( - this.sourceBlock_.RTL ? FieldDropdown.ARROW_CHAR + ' ' : - ' ' + FieldDropdown.ARROW_CHAR)); - if (this.sourceBlock_.RTL) { - this.textElement_.insertBefore(this.arrow_, this.textContent_); - } else { - this.textElement_.appendChild(this.arrow_); - } -}; - -/** - * Create an SVG based arrow. - * @protected - */ -FieldDropdown.prototype.createSVGArrow_ = function() { - this.svgArrow_ = dom.createSvgElement( - Svg.IMAGE, { - 'height': this.getConstants().FIELD_DROPDOWN_SVG_ARROW_SIZE + 'px', - 'width': this.getConstants().FIELD_DROPDOWN_SVG_ARROW_SIZE + 'px', - }, - this.fieldGroup_); - this.svgArrow_.setAttributeNS( - dom.XLINK_NS, 'xlink:href', - this.getConstants().FIELD_DROPDOWN_SVG_ARROW_DATAURI); -}; - -/** - * Create a dropdown menu under the text. - * @param {Event=} opt_e Optional mouse event that triggered the field to open, - * or undefined if triggered programmatically. - * @protected - */ -FieldDropdown.prototype.showEditor_ = function(opt_e) { - this.dropdownCreate_(); - if (opt_e && typeof opt_e.clientX === 'number') { - this.menu_.openingCoords = new Coordinate(opt_e.clientX, opt_e.clientY); - } else { - this.menu_.openingCoords = null; - } - - // Remove any pre-existing elements in the dropdown. - DropDownDiv.clearContent(); - // Element gets created in render. - this.menu_.render(DropDownDiv.getContentDiv()); - const menuElement = /** @type {!Element} */ (this.menu_.getElement()); - dom.addClass(menuElement, 'blocklyDropdownMenu'); - - if (this.getConstants().FIELD_DROPDOWN_COLOURED_DIV) { - const primaryColour = (this.sourceBlock_.isShadow()) ? - this.sourceBlock_.getParent().getColour() : - this.sourceBlock_.getColour(); - const borderColour = (this.sourceBlock_.isShadow()) ? - this.sourceBlock_.getParent().style.colourTertiary : - this.sourceBlock_.style.colourTertiary; - DropDownDiv.setColour(primaryColour, borderColour); - } - - DropDownDiv.showPositionedByField(this, this.dropdownDispose_.bind(this)); - - // Focusing needs to be handled after the menu is rendered and positioned. - // Otherwise it will cause a page scroll to get the misplaced menu in - // view. See issue #1329. - this.menu_.focus(); - - if (this.selectedMenuItem_) { - this.menu_.setHighlighted(this.selectedMenuItem_); - } - - this.applyColour(); -}; - -/** - * Create the dropdown editor. - * @private - */ -FieldDropdown.prototype.dropdownCreate_ = function() { - const menu = new Menu(); - menu.setRole(aria.Role.LISTBOX); - this.menu_ = menu; - - const options = this.getOptions(false); - this.selectedMenuItem_ = null; - for (let i = 0; i < options.length; i++) { - let content = options[i][0]; // Human-readable text or image. - const value = options[i][1]; // Language-neutral value. - if (typeof content === 'object') { - // An image, not text. - const image = new Image(content['width'], content['height']); - image.src = content['src']; - image.alt = content['alt'] || ''; - content = image; - } - const menuItem = new MenuItem(content, value); - menuItem.setRole(aria.Role.OPTION); - menuItem.setRightToLeft(this.sourceBlock_.RTL); - menuItem.setCheckable(true); - menu.addChild(menuItem); - menuItem.setChecked(value === this.value_); - if (value === this.value_) { - this.selectedMenuItem_ = menuItem; - } - menuItem.onAction(this.handleMenuActionEvent_, this); - } -}; - -/** - * Disposes of events and DOM-references belonging to the dropdown editor. - * @private - */ -FieldDropdown.prototype.dropdownDispose_ = function() { - if (this.menu_) { - this.menu_.dispose(); - } - this.menu_ = null; - this.selectedMenuItem_ = null; - this.applyColour(); -}; - -/** - * Handle an action in the dropdown menu. - * @param {!MenuItem} menuItem The MenuItem selected within menu. - * @private - */ -FieldDropdown.prototype.handleMenuActionEvent_ = function(menuItem) { - DropDownDiv.hideIfOwner(this, true); - this.onItemSelected_(/** @type {!Menu} */ (this.menu_), menuItem); -}; - -/** - * Handle the selection of an item in the dropdown menu. - * @param {!Menu} menu The Menu component clicked. - * @param {!MenuItem} menuItem The MenuItem selected within menu. - * @protected - */ -FieldDropdown.prototype.onItemSelected_ = function(menu, menuItem) { - this.setValue(menuItem.getValue()); -}; - -/** - * Factor out common words in statically defined options. - * Create prefix and/or suffix labels. - * @private - */ -FieldDropdown.prototype.trimOptions_ = function() { - const options = this.menuGenerator_; - if (!Array.isArray(options)) { - return; - } - let hasImages = false; - - // Localize label text and image alt text. - for (let i = 0; i < options.length; i++) { - const label = options[i][0]; - if (typeof label === 'string') { - options[i][0] = parsing.replaceMessageReferences(label); - } else { - if (label.alt !== null) { - options[i][0].alt = parsing.replaceMessageReferences(label.alt); - } - hasImages = true; - } - } - if (hasImages || options.length < 2) { - return; // Do nothing if too few items or at least one label is an image. - } - const strings = []; - for (let i = 0; i < options.length; i++) { - strings.push(options[i][0]); - } - const shortest = utilsString.shortestStringLength(strings); - const prefixLength = utilsString.commonWordPrefix(strings, shortest); - const suffixLength = utilsString.commonWordSuffix(strings, shortest); - if (!prefixLength && !suffixLength) { - return; - } - if (shortest <= prefixLength + suffixLength) { - // One or more strings will entirely vanish if we proceed. Abort. - return; - } - if (prefixLength) { - this.prefixField = strings[0].substring(0, prefixLength - 1); - } - if (suffixLength) { - this.suffixField = strings[0].substr(1 - suffixLength); - } - - this.menuGenerator_ = - FieldDropdown.applyTrim_(options, prefixLength, suffixLength); -}; - -/** - * Use the calculated prefix and suffix lengths to trim all of the options in - * the given array. - * @param {!Array} options Array of option tuples: - * (human-readable text or image, language-neutral name). - * @param {number} prefixLength The length of the common prefix. - * @param {number} suffixLength The length of the common suffix - * @return {!Array} A new array with all of the option text trimmed. - */ -FieldDropdown.applyTrim_ = function(options, prefixLength, suffixLength) { - const newOptions = []; - // Remove the prefix and suffix from the options. - for (let i = 0; i < options.length; i++) { - let text = options[i][0]; - const value = options[i][1]; - text = text.substring(prefixLength, text.length - suffixLength); - newOptions[i] = [text, value]; - } - return newOptions; -}; - -/** - * @return {boolean} True if the option list is generated by a function. - * Otherwise false. - */ -FieldDropdown.prototype.isOptionListDynamic = function() { - return typeof this.menuGenerator_ === 'function'; -}; - -/** - * Return a list of the options for this dropdown. - * @param {boolean=} opt_useCache For dynamic options, whether or not to use the - * cached options or to re-generate them. - * @return {!Array} A non-empty array of option tuples: - * (human-readable text or image, language-neutral name). - * @throws {TypeError} If generated options are incorrectly structured. - */ -FieldDropdown.prototype.getOptions = function(opt_useCache) { - if (this.isOptionListDynamic()) { - if (!this.generatedOptions_ || !opt_useCache) { - this.generatedOptions_ = this.menuGenerator_.call(this); - validateOptions(this.generatedOptions_); - } - return this.generatedOptions_; - } - return /** @type {!Array>} */ (this.menuGenerator_); -}; - -/** - * Ensure that the input value is a valid language-neutral option. - * @param {*=} opt_newValue The input value. - * @return {?string} A valid language-neutral option, or null if invalid. - * @protected - */ -FieldDropdown.prototype.doClassValidation_ = function(opt_newValue) { - let isValueValid = false; - const options = this.getOptions(true); - for (let i = 0, option; (option = options[i]); i++) { - // Options are tuples of human-readable text and language-neutral values. - if (option[1] === opt_newValue) { - isValueValid = true; - break; - } - } - if (!isValueValid) { - if (this.sourceBlock_) { - console.warn( - 'Cannot set the dropdown\'s value to an unavailable option.' + - ' Block type: ' + this.sourceBlock_.type + - ', Field name: ' + this.name + ', Value: ' + opt_newValue); - } - return null; - } - return /** @type {string} */ (opt_newValue); -}; - -/** - * Update the value of this dropdown field. - * @param {*} newValue The value to be saved. The default validator guarantees - * that this is one of the valid dropdown options. - * @protected - */ -FieldDropdown.prototype.doValueUpdate_ = function(newValue) { - FieldDropdown.superClass_.doValueUpdate_.call(this, newValue); - const options = this.getOptions(true); - for (let i = 0, option; (option = options[i]); i++) { - if (option[1] === this.value_) { - this.selectedOption_ = option; - } - } -}; - -/** - * Updates the dropdown arrow to match the colour/style of the block. - * @package - */ -FieldDropdown.prototype.applyColour = function() { - if (this.borderRect_) { - this.borderRect_.setAttribute( - 'stroke', this.sourceBlock_.style.colourTertiary); - if (this.menu_) { - this.borderRect_.setAttribute( - 'fill', this.sourceBlock_.style.colourTertiary); - } else { - this.borderRect_.setAttribute('fill', 'transparent'); - } - } - // Update arrow's colour. - if (this.sourceBlock_ && this.arrow_) { - if (this.sourceBlock_.isShadow()) { - this.arrow_.style.fill = this.sourceBlock_.style.colourSecondary; - } else { - this.arrow_.style.fill = this.sourceBlock_.style.colourPrimary; - } - } -}; - -/** - * Draws the border with the correct width. - * @protected - */ -FieldDropdown.prototype.render_ = function() { - // Hide both elements. - this.textContent_.nodeValue = ''; - this.imageElement_.style.display = 'none'; - - // Show correct element. - const option = this.selectedOption_ && this.selectedOption_[0]; - if (option && typeof option === 'object') { - this.renderSelectedImage_( - /** @type {!FieldDropdown.ImageProperties} */ (option)); - } else { - this.renderSelectedText_(); - } - - this.positionBorderRect_(); -}; - -/** - * Renders the selected option, which must be an image. - * @param {!FieldDropdown.ImageProperties} imageJson Selected - * option that must be an image. - * @private - */ -FieldDropdown.prototype.renderSelectedImage_ = function(imageJson) { - this.imageElement_.style.display = ''; - this.imageElement_.setAttributeNS(dom.XLINK_NS, 'xlink:href', imageJson.src); - this.imageElement_.setAttribute('height', imageJson.height); - this.imageElement_.setAttribute('width', imageJson.width); - - const imageHeight = Number(imageJson.height); - const imageWidth = Number(imageJson.width); - - // Height and width include the border rect. - const hasBorder = !!this.borderRect_; - const height = Math.max( - hasBorder ? this.getConstants().FIELD_DROPDOWN_BORDER_RECT_HEIGHT : 0, - imageHeight + IMAGE_Y_PADDING); - const xPadding = - hasBorder ? this.getConstants().FIELD_BORDER_RECT_X_PADDING : 0; - let arrowWidth = 0; - if (this.svgArrow_) { - arrowWidth = this.positionSVGArrow_( - imageWidth + xPadding, - height / 2 - this.getConstants().FIELD_DROPDOWN_SVG_ARROW_SIZE / 2); - } else { - arrowWidth = dom.getFastTextWidth( - /** @type {!SVGTSpanElement} */ (this.arrow_), - this.getConstants().FIELD_TEXT_FONTSIZE, - this.getConstants().FIELD_TEXT_FONTWEIGHT, - this.getConstants().FIELD_TEXT_FONTFAMILY); - } - this.size_.width = imageWidth + arrowWidth + xPadding * 2; - this.size_.height = height; - - let arrowX = 0; - if (this.sourceBlock_.RTL) { - const imageX = xPadding + arrowWidth; - this.imageElement_.setAttribute('x', imageX); - } else { - arrowX = imageWidth + arrowWidth; - this.textElement_.setAttribute('text-anchor', 'end'); - this.imageElement_.setAttribute('x', xPadding); - } - this.imageElement_.setAttribute('y', height / 2 - imageHeight / 2); - - this.positionTextElement_(arrowX + xPadding, imageWidth + arrowWidth); -}; - -/** - * Renders the selected option, which must be text. - * @private - */ -FieldDropdown.prototype.renderSelectedText_ = function() { - // Retrieves the selected option to display through getText_. - this.textContent_.nodeValue = this.getDisplayText_(); - dom.addClass( - /** @type {!Element} */ (this.textElement_), 'blocklyDropdownText'); - this.textElement_.setAttribute('text-anchor', 'start'); - - // Height and width include the border rect. - const hasBorder = !!this.borderRect_; - const height = Math.max( - hasBorder ? this.getConstants().FIELD_DROPDOWN_BORDER_RECT_HEIGHT : 0, - this.getConstants().FIELD_TEXT_HEIGHT); - const textWidth = dom.getFastTextWidth( - this.textElement_, this.getConstants().FIELD_TEXT_FONTSIZE, - this.getConstants().FIELD_TEXT_FONTWEIGHT, - this.getConstants().FIELD_TEXT_FONTFAMILY); - const xPadding = - hasBorder ? this.getConstants().FIELD_BORDER_RECT_X_PADDING : 0; - let arrowWidth = 0; - if (this.svgArrow_) { - arrowWidth = this.positionSVGArrow_( - textWidth + xPadding, - height / 2 - this.getConstants().FIELD_DROPDOWN_SVG_ARROW_SIZE / 2); - } - this.size_.width = textWidth + arrowWidth + xPadding * 2; - this.size_.height = height; - - this.positionTextElement_(xPadding, textWidth); -}; - -/** - * Position a drop-down arrow at the appropriate location at render-time. - * @param {number} x X position the arrow is being rendered at, in px. - * @param {number} y Y position the arrow is being rendered at, in px. - * @return {number} Amount of space the arrow is taking up, in px. - * @private - */ -FieldDropdown.prototype.positionSVGArrow_ = function(x, y) { - if (!this.svgArrow_) { - return 0; - } - const hasBorder = !!this.borderRect_; - const xPadding = - hasBorder ? this.getConstants().FIELD_BORDER_RECT_X_PADDING : 0; - const textPadding = this.getConstants().FIELD_DROPDOWN_SVG_ARROW_PADDING; - const svgArrowSize = this.getConstants().FIELD_DROPDOWN_SVG_ARROW_SIZE; - const arrowX = this.sourceBlock_.RTL ? xPadding : x + textPadding; - this.svgArrow_.setAttribute( - 'transform', 'translate(' + arrowX + ',' + y + ')'); - return svgArrowSize + textPadding; -}; - -/** - * Use the `getText_` developer hook to override the field's text - * representation. Get the selected option text. If the selected option is an - * image we return the image alt text. - * @return {?string} Selected option text. - * @protected - * @override - */ -FieldDropdown.prototype.getText_ = function() { - if (!this.selectedOption_) { - return null; - } - const option = this.selectedOption_[0]; - if (typeof option === 'object') { - return option['alt']; - } - return option; -}; - /** * Validates the data structure to be processed as an options list. * @param {?} options The proposed dropdown options. diff --git a/core/field_image.js b/core/field_image.js index 25cf1c5d1..de44cfdae 100644 --- a/core/field_image.js +++ b/core/field_image.js @@ -17,108 +17,272 @@ goog.module('Blockly.FieldImage'); const dom = goog.require('Blockly.utils.dom'); const fieldRegistry = goog.require('Blockly.fieldRegistry'); -const object = goog.require('Blockly.utils.object'); const parsing = goog.require('Blockly.utils.parsing'); const {Field} = goog.require('Blockly.Field'); +/* eslint-disable-next-line no-unused-vars */ +const {Sentinel} = goog.requireType('Blockly.utils.Sentinel'); const {Size} = goog.require('Blockly.utils.Size'); const {Svg} = goog.require('Blockly.utils.Svg'); /** * Class for an image on a block. - * @param {string} src The URL of the image. - * @param {!(string|number)} width Width of the image. - * @param {!(string|number)} height Height of the image. - * @param {string=} opt_alt Optional alt text for when block is collapsed. - * @param {function(!FieldImage)=} opt_onClick Optional function to be - * called when the image is clicked. If opt_onClick is defined, opt_alt must - * also be defined. - * @param {boolean=} opt_flipRtl Whether to flip the icon in RTL. - * @param {Object=} opt_config A map of options used to configure the field. - * See the [field creation documentation]{@link - * https://developers.google.com/blockly/guides/create-custom-blocks/fields/built-in-fields/image#creation} - * for a list of properties this parameter supports. * @extends {Field} - * @constructor - * @alias Blockly.FieldImage */ -const FieldImage = function( - src, width, height, opt_alt, opt_onClick, opt_flipRtl, opt_config) { - // Return early. - if (!src) { - throw Error('Src value of an image field is required'); - } - src = parsing.replaceMessageReferences(src); - const imageHeight = Number(parsing.replaceMessageReferences(height)); - const imageWidth = Number(parsing.replaceMessageReferences(width)); - if (isNaN(imageHeight) || isNaN(imageWidth)) { - throw Error( - 'Height and width values of an image field must cast to' + - ' numbers.'); - } - if (imageHeight <= 0 || imageWidth <= 0) { - throw Error( - 'Height and width values of an image field must be greater' + - ' than 0.'); - } - - // Initialize configurable properties. +class FieldImage extends Field { /** - * Whether to flip this image in RTL. - * @type {boolean} - * @private + * @param {string|!Sentinel} src The URL of the image. + * Also accepts Field.SKIP_SETUP if you wish to skip setup (only used by + * subclasses that want to handle configuration and setting the field + * value after their own constructors have run). + * @param {!(string|number)} width Width of the image. + * @param {!(string|number)} height Height of the image. + * @param {string=} opt_alt Optional alt text for when block is collapsed. + * @param {function(!FieldImage)=} opt_onClick Optional function to be + * called when the image is clicked. If opt_onClick is defined, opt_alt + * must also be defined. + * @param {boolean=} opt_flipRtl Whether to flip the icon in RTL. + * @param {Object=} opt_config A map of options used to configure the field. + * See the [field creation documentation]{@link + * https://developers.google.com/blockly/guides/create-custom-blocks/fields/built-in-fields/image#creation} + * for a list of properties this parameter supports. + * @alias Blockly.FieldImage */ - this.flipRtl_ = false; + constructor( + src, width, height, opt_alt, opt_onClick, opt_flipRtl, opt_config) { + super(Field.SKIP_SETUP); - /** - * Alt text of this image. - * @type {string} - * @private - */ - this.altText_ = ''; + // Return early. + if (!src) { + throw Error('Src value of an image field is required'); + } + const imageHeight = Number(parsing.replaceMessageReferences(height)); + const imageWidth = Number(parsing.replaceMessageReferences(width)); + if (isNaN(imageHeight) || isNaN(imageWidth)) { + throw Error( + 'Height and width values of an image field must cast to' + + ' numbers.'); + } + if (imageHeight <= 0 || imageWidth <= 0) { + throw Error( + 'Height and width values of an image field must be greater' + + ' than 0.'); + } - FieldImage.superClass_.constructor.call(this, src, null, opt_config); + /** + * The size of the area rendered by the field. + * @type {Size} + * @protected + * @override + */ + this.size_ = new Size(imageWidth, imageHeight + FieldImage.Y_PADDING); - if (!opt_config) { // If the config wasn't passed, do old configuration. - this.flipRtl_ = !!opt_flipRtl; - this.altText_ = parsing.replaceMessageReferences(opt_alt) || ''; + /** + * Store the image height, since it is different from the field height. + * @type {number} + * @private + */ + this.imageHeight_ = imageHeight; + + /** + * The function to be called when this field is clicked. + * @type {?function(!FieldImage)} + * @private + */ + this.clickHandler_ = null; + + if (typeof opt_onClick === 'function') { + this.clickHandler_ = opt_onClick; + } + + /** + * The rendered field's image element. + * @type {SVGImageElement} + * @private + */ + this.imageElement_ = null; + + /** + * Editable fields usually show some sort of UI indicating they are + * editable. This field should not. + * @type {boolean} + * @const + */ + this.EDITABLE = false; + + /** + * Used to tell if the field needs to be rendered the next time the block is + * rendered. Image fields are statically sized, and only need to be + * rendered at initialization. + * @type {boolean} + * @protected + */ + this.isDirty_ = false; + + /** + * Whether to flip this image in RTL. + * @type {boolean} + * @private + */ + this.flipRtl_ = false; + + /** + * Alt text of this image. + * @type {string} + * @private + */ + this.altText_ = ''; + + if (src === Field.SKIP_SETUP) return; + + if (opt_config) { + this.configure_(opt_config); + } else { + this.flipRtl_ = !!opt_flipRtl; + this.altText_ = parsing.replaceMessageReferences(opt_alt) || ''; + } + this.setValue(parsing.replaceMessageReferences(src)); } - // Initialize other properties. /** - * The size of the area rendered by the field. - * @type {Size} + * Configure the field based on the given map of options. + * @param {!Object} config A map of options to configure the field based on. * @protected * @override */ - this.size_ = new Size(imageWidth, imageHeight + FieldImage.Y_PADDING); - - /** - * Store the image height, since it is different from the field height. - * @type {number} - * @private - */ - this.imageHeight_ = imageHeight; - - /** - * The function to be called when this field is clicked. - * @type {?function(!FieldImage)} - * @private - */ - this.clickHandler_ = null; - - if (typeof opt_onClick === 'function') { - this.clickHandler_ = opt_onClick; + configure_(config) { + super.configure_(config); + this.flipRtl_ = !!config['flipRtl']; + this.altText_ = parsing.replaceMessageReferences(config['alt']) || ''; } /** - * The rendered field's image element. - * @type {SVGImageElement} - * @private + * Create the block UI for this image. + * @package */ - this.imageElement_ = null; -}; -object.inherits(FieldImage, Field); + initView() { + this.imageElement_ = dom.createSvgElement( + Svg.IMAGE, { + 'height': this.imageHeight_ + 'px', + 'width': this.size_.width + 'px', + 'alt': this.altText_, + }, + this.fieldGroup_); + this.imageElement_.setAttributeNS( + dom.XLINK_NS, 'xlink:href', /** @type {string} */ (this.value_)); + + if (this.clickHandler_) { + this.imageElement_.style.cursor = 'pointer'; + } + } + + /** + * @override + */ + updateSize_() { + // NOP + } + + /** + * Ensure that the input value (the source URL) is a string. + * @param {*=} opt_newValue The input value. + * @return {?string} A string, or null if invalid. + * @protected + */ + doClassValidation_(opt_newValue) { + if (typeof opt_newValue !== 'string') { + return null; + } + return opt_newValue; + } + + /** + * Update the value of this image field, and update the displayed image. + * @param {*} newValue The value to be saved. The default validator guarantees + * that this is a string. + * @protected + */ + doValueUpdate_(newValue) { + this.value_ = newValue; + if (this.imageElement_) { + this.imageElement_.setAttributeNS( + dom.XLINK_NS, 'xlink:href', String(this.value_)); + } + } + + /** + * Get whether to flip this image in RTL + * @return {boolean} True if we should flip in RTL. + * @override + */ + getFlipRtl() { + return this.flipRtl_; + } + + /** + * Set the alt text of this image. + * @param {?string} alt New alt text. + * @public + */ + setAlt(alt) { + if (alt === this.altText_) { + return; + } + this.altText_ = alt || ''; + if (this.imageElement_) { + this.imageElement_.setAttribute('alt', this.altText_); + } + } + + /** + * If field click is called, and click handler defined, + * call the handler. + * @protected + */ + showEditor_() { + if (this.clickHandler_) { + this.clickHandler_(this); + } + } + + /** + * Set the function that is called when this image is clicked. + * @param {?function(!FieldImage)} func The function that is called + * when the image is clicked, or null to remove. + */ + setOnClickHandler(func) { + this.clickHandler_ = func; + } + + /** + * Use the `getText_` developer hook to override the field's text + * representation. + * Return the image alt text instead. + * @return {?string} The image alt text. + * @protected + * @override + */ + getText_() { + return this.altText_; + } + + /** + * Construct a FieldImage from a JSON arg object, + * dereferencing any string table references. + * @param {!Object} options A JSON object with options (src, width, height, + * alt, and flipRtl). + * @return {!FieldImage} The new field instance. + * @package + * @nocollapse + */ + static fromJson(options) { + // `this` might be a subclass of FieldImage if that class doesn't override + // the static fromJson method. + return new this( + options['src'], options['width'], options['height'], undefined, + undefined, undefined, options); + } +} /** * The default value for this field. @@ -127,23 +291,6 @@ object.inherits(FieldImage, Field); */ FieldImage.prototype.DEFAULT_VALUE = ''; -/** - * Construct a FieldImage from a JSON arg object, - * dereferencing any string table references. - * @param {!Object} options A JSON object with options (src, width, height, - * alt, and flipRtl). - * @return {!FieldImage} The new field instance. - * @package - * @nocollapse - */ -FieldImage.fromJson = function(options) { - // `this` might be a subclass of FieldImage if that class doesn't override - // the static fromJson method. - return new this( - options['src'], options['width'], options['height'], undefined, undefined, - undefined, options); -}; - /** * Vertical padding below the image, which is included in the reported height of * the field. @@ -152,144 +299,6 @@ FieldImage.fromJson = function(options) { */ FieldImage.Y_PADDING = 1; -/** - * Editable fields usually show some sort of UI indicating they are - * editable. This field should not. - * @type {boolean} - */ -FieldImage.prototype.EDITABLE = false; - -/** - * Used to tell if the field needs to be rendered the next time the block is - * rendered. Image fields are statically sized, and only need to be - * rendered at initialization. - * @type {boolean} - * @protected - */ -FieldImage.prototype.isDirty_ = false; - -/** - * Configure the field based on the given map of options. - * @param {!Object} config A map of options to configure the field based on. - * @protected - * @override - */ -FieldImage.prototype.configure_ = function(config) { - FieldImage.superClass_.configure_.call(this, config); - this.flipRtl_ = !!config['flipRtl']; - this.altText_ = parsing.replaceMessageReferences(config['alt']) || ''; -}; - -/** - * Create the block UI for this image. - * @package - */ -FieldImage.prototype.initView = function() { - this.imageElement_ = dom.createSvgElement( - Svg.IMAGE, { - 'height': this.imageHeight_ + 'px', - 'width': this.size_.width + 'px', - 'alt': this.altText_, - }, - this.fieldGroup_); - this.imageElement_.setAttributeNS( - dom.XLINK_NS, 'xlink:href', /** @type {string} */ (this.value_)); - - if (this.clickHandler_) { - this.imageElement_.style.cursor = 'pointer'; - } -}; - -/** - * @override - */ -FieldImage.prototype.updateSize_ = function() { - // NOP -}; - -/** - * Ensure that the input value (the source URL) is a string. - * @param {*=} opt_newValue The input value. - * @return {?string} A string, or null if invalid. - * @protected - */ -FieldImage.prototype.doClassValidation_ = function(opt_newValue) { - if (typeof opt_newValue !== 'string') { - return null; - } - return opt_newValue; -}; - -/** - * Update the value of this image field, and update the displayed image. - * @param {*} newValue The value to be saved. The default validator guarantees - * that this is a string. - * @protected - */ -FieldImage.prototype.doValueUpdate_ = function(newValue) { - this.value_ = newValue; - if (this.imageElement_) { - this.imageElement_.setAttributeNS( - dom.XLINK_NS, 'xlink:href', String(this.value_)); - } -}; - -/** - * Get whether to flip this image in RTL - * @return {boolean} True if we should flip in RTL. - * @override - */ -FieldImage.prototype.getFlipRtl = function() { - return this.flipRtl_; -}; - -/** - * Set the alt text of this image. - * @param {?string} alt New alt text. - * @public - */ -FieldImage.prototype.setAlt = function(alt) { - if (alt === this.altText_) { - return; - } - this.altText_ = alt || ''; - if (this.imageElement_) { - this.imageElement_.setAttribute('alt', this.altText_); - } -}; - -/** - * If field click is called, and click handler defined, - * call the handler. - * @protected - */ -FieldImage.prototype.showEditor_ = function() { - if (this.clickHandler_) { - this.clickHandler_(this); - } -}; - -/** - * Set the function that is called when this image is clicked. - * @param {?function(!FieldImage)} func The function that is called - * when the image is clicked, or null to remove. - */ -FieldImage.prototype.setOnClickHandler = function(func) { - this.clickHandler_ = func; -}; - -/** - * Use the `getText_` developer hook to override the field's text - * representation. - * Return the image alt text instead. - * @return {?string} The image alt text. - * @protected - * @override - */ -FieldImage.prototype.getText_ = function() { - return this.altText_; -}; - fieldRegistry.register('field_image', FieldImage); exports.FieldImage = FieldImage; diff --git a/core/field_label.js b/core/field_label.js index b9195d803..edbb2e100 100644 --- a/core/field_label.js +++ b/core/field_label.js @@ -19,39 +19,123 @@ goog.module('Blockly.FieldLabel'); const dom = goog.require('Blockly.utils.dom'); const fieldRegistry = goog.require('Blockly.fieldRegistry'); -const object = goog.require('Blockly.utils.object'); const parsing = goog.require('Blockly.utils.parsing'); const {Field} = goog.require('Blockly.Field'); +/* eslint-disable-next-line no-unused-vars */ +const {Sentinel} = goog.requireType('Blockly.utils.Sentinel'); /** * Class for a non-editable, non-serializable text field. - * @param {string=} opt_value The initial value of the field. Should cast to a - * string. Defaults to an empty string if null or undefined. - * @param {string=} opt_class Optional CSS class for the field's text. - * @param {Object=} opt_config A map of options used to configure the field. - * See the [field creation documentation]{@link - * https://developers.google.com/blockly/guides/create-custom-blocks/fields/built-in-fields/label#creation} - * for a list of properties this parameter supports. * @extends {Field} - * @constructor - * @alias Blockly.FieldLabel */ -const FieldLabel = function(opt_value, opt_class, opt_config) { +class FieldLabel extends Field { /** - * The html class name to use for this field. - * @type {?string} - * @private + * @param {(string|!Sentinel)=} opt_value The initial value of the + * field. Should cast to a string. Defaults to an empty string if null or + * undefined. + * Also accepts Field.SKIP_SETUP if you wish to skip setup (only used by + * subclasses that want to handle configuration and setting the field + * value after their own constructors have run). + * @param {string=} opt_class Optional CSS class for the field's text. + * @param {Object=} opt_config A map of options used to configure the field. + * See the [field creation documentation]{@link + * https://developers.google.com/blockly/guides/create-custom-blocks/fields/built-in-fields/label#creation} + * for a list of properties this parameter supports. + * @alias Blockly.FieldLabel */ - this.class_ = null; + constructor(opt_value, opt_class, opt_config) { + super(Field.SKIP_SETUP); - FieldLabel.superClass_.constructor.call(this, opt_value, null, opt_config); + /** + * The html class name to use for this field. + * @type {?string} + * @private + */ + this.class_ = null; - if (!opt_config) { // If the config was not passed use old configuration. - this.class_ = opt_class || null; + /** + * Editable fields usually show some sort of UI indicating they are + * editable. This field should not. + * @type {boolean} + */ + this.EDITABLE = false; + + if (opt_value === Field.SKIP_SETUP) return; + if (opt_config) { + this.configure_(opt_config); + } else { + this.class_ = opt_class || null; + } + this.setValue(opt_value); } -}; -object.inherits(FieldLabel, Field); + + /** + * @override + */ + configure_(config) { + super.configure_(config); + this.class_ = config['class']; + } + + /** + * Create block UI for this label. + * @package + */ + initView() { + this.createTextElement_(); + if (this.class_) { + dom.addClass( + /** @type {!SVGTextElement} */ (this.textElement_), this.class_); + } + } + + /** + * Ensure that the input value casts to a valid string. + * @param {*=} opt_newValue The input value. + * @return {?string} A valid string, or null if invalid. + * @protected + */ + doClassValidation_(opt_newValue) { + if (opt_newValue === null || opt_newValue === undefined) { + return null; + } + return String(opt_newValue); + } + + /** + * Set the CSS class applied to the field's textElement_. + * @param {?string} cssClass The new CSS class name, or null to remove. + */ + setClass(cssClass) { + if (this.textElement_) { + // This check isn't necessary, but it's faster than letting removeClass + // figure it out. + if (this.class_) { + dom.removeClass(this.textElement_, this.class_); + } + if (cssClass) { + dom.addClass(this.textElement_, cssClass); + } + } + this.class_ = cssClass; + } + + /** + * Construct a FieldLabel from a JSON arg object, + * dereferencing any string table references. + * @param {!Object} options A JSON object with options (text, and class). + * @return {!FieldLabel} The new field instance. + * @package + * @nocollapse + */ + static fromJson(options) { + const text = parsing.replaceMessageReferences(options['text']); + // `this` might be a subclass of FieldLabel if that class doesn't override + // the static fromJson method. + return new this(text, undefined, options); + } +} /** * The default value for this field. @@ -60,79 +144,6 @@ object.inherits(FieldLabel, Field); */ FieldLabel.prototype.DEFAULT_VALUE = ''; -/** - * Construct a FieldLabel from a JSON arg object, - * dereferencing any string table references. - * @param {!Object} options A JSON object with options (text, and class). - * @return {!FieldLabel} The new field instance. - * @package - * @nocollapse - */ -FieldLabel.fromJson = function(options) { - const text = parsing.replaceMessageReferences(options['text']); - // `this` might be a subclass of FieldLabel if that class doesn't override - // the static fromJson method. - return new this(text, undefined, options); -}; - -/** - * Editable fields usually show some sort of UI indicating they are - * editable. This field should not. - * @type {boolean} - */ -FieldLabel.prototype.EDITABLE = false; - -/** - * @override - */ -FieldLabel.prototype.configure_ = function(config) { - FieldLabel.superClass_.configure_.call(this, config); - this.class_ = config['class']; -}; - -/** - * Create block UI for this label. - * @package - */ -FieldLabel.prototype.initView = function() { - this.createTextElement_(); - if (this.class_) { - dom.addClass( - /** @type {!SVGTextElement} */ (this.textElement_), this.class_); - } -}; - -/** - * Ensure that the input value casts to a valid string. - * @param {*=} opt_newValue The input value. - * @return {?string} A valid string, or null if invalid. - * @protected - */ -FieldLabel.prototype.doClassValidation_ = function(opt_newValue) { - if (opt_newValue === null || opt_newValue === undefined) { - return null; - } - return String(opt_newValue); -}; - -/** - * Set the CSS class applied to the field's textElement_. - * @param {?string} cssClass The new CSS class name, or null to remove. - */ -FieldLabel.prototype.setClass = function(cssClass) { - if (this.textElement_) { - // This check isn't necessary, but it's faster than letting removeClass - // figure it out. - if (this.class_) { - dom.removeClass(this.textElement_, this.class_); - } - if (cssClass) { - dom.addClass(this.textElement_, cssClass); - } - } - this.class_ = cssClass; -}; - fieldRegistry.register('field_label', FieldLabel); exports.FieldLabel = FieldLabel; diff --git a/core/field_label_serializable.js b/core/field_label_serializable.js index b8d3e027a..d9e6109f0 100644 --- a/core/field_label_serializable.js +++ b/core/field_label_serializable.js @@ -30,19 +30,17 @@ const {FieldLabel} = goog.require('Blockly.FieldLabel'); */ class FieldLabelSerializable extends FieldLabel { /** - * @param {*} opt_value The initial value of the field. Should cast to a + * @param {string=} opt_value The initial value of the field. Should cast to a * string. Defaults to an empty string if null or undefined. * @param {string=} opt_class Optional CSS class for the field's text. * @param {Object=} opt_config A map of options used to configure the field. * See the [field creation documentation]{@link * https://developers.google.com/blockly/guides/create-custom-blocks/fields/built-in-fields/label-serializable#creation} * for a list of properties this parameter supports. - * * @alias Blockly.FieldLabelSerializable */ constructor(opt_value, opt_class, opt_config) { - const stringValue = opt_value == undefined ? '' : String(opt_value); - super(stringValue, opt_class, opt_config); + super(String(opt_value ?? ''), opt_class, opt_config); /** * Editable fields usually show some sort of UI indicating they are diff --git a/core/field_multilineinput.js b/core/field_multilineinput.js index b03dc2d2b..1b065cdd8 100644 --- a/core/field_multilineinput.js +++ b/core/field_multilineinput.js @@ -25,6 +25,8 @@ const userAgent = goog.require('Blockly.utils.userAgent'); const {FieldTextInput} = goog.require('Blockly.FieldTextInput'); const {Field} = goog.require('Blockly.Field'); const {KeyCodes} = goog.require('Blockly.utils.KeyCodes'); +/* eslint-disable-next-line no-unused-vars */ +const {Sentinel} = goog.requireType('Blockly.utils.Sentinel'); const {Svg} = goog.require('Blockly.utils.Svg'); @@ -34,22 +36,24 @@ const {Svg} = goog.require('Blockly.utils.Svg'); */ class FieldMultilineInput extends FieldTextInput { /** - * @param {string=} opt_value The initial content of the field. Should cast to - * a - * string. Defaults to an empty string if null or undefined. + * @param {(string|!Sentinel)=} opt_value The initial content of the + * field. Should cast to a string. Defaults to an empty string if null or + * undefined. + * Also accepts Field.SKIP_SETUP if you wish to skip setup (only used by + * subclasses that want to handle configuration and setting the field + * value after their own constructors have run). * @param {Function=} opt_validator An optional function that is called * to validate any constraints on what the user entered. Takes the new * text as an argument and returns either the accepted text, a replacement * text, or null to abort the change. * @param {Object=} opt_config A map of options used to configure the field. - * See the [field creation documentation]{@link - * https://developers.google.com/blockly/guides/create-custom-blocks/fields/built-in-fields/multiline-text-input#creation} - * for a list of properties this parameter supports. + * See the [field creation documentation]{@link + * https://developers.google.com/blockly/guides/create-custom-blocks/fields/built-in-fields/multiline-text-input#creation} + * for a list of properties this parameter supports. * @alias Blockly.FieldMultilineInput */ constructor(opt_value, opt_validator, opt_config) { - const stringValue = opt_value == undefined ? '' : String(opt_value); - super(stringValue, opt_validator, opt_config); + super(Field.SKIP_SETUP); /** * The SVG group element that will contain a text element for each text row @@ -73,17 +77,10 @@ class FieldMultilineInput extends FieldTextInput { */ this.isOverflowedY_ = false; - /** - * @type {boolean} - * @private - */ - this.isBeingEdited_ = false; - - /** - * @type {boolean} - * @private - */ - this.isTextValid_ = false; + if (opt_value === Field.SKIP_SETUP) return; + if (opt_config) this.configure_(opt_config); + this.setValue(opt_value); + if (opt_validator) this.setValidator(opt_validator); } /** diff --git a/core/field_number.js b/core/field_number.js index afa9ee89b..c1ceeadc7 100644 --- a/core/field_number.js +++ b/core/field_number.js @@ -17,67 +17,316 @@ goog.module('Blockly.FieldNumber'); const aria = goog.require('Blockly.utils.aria'); const fieldRegistry = goog.require('Blockly.fieldRegistry'); -const object = goog.require('Blockly.utils.object'); +const {Field} = goog.require('Blockly.Field'); const {FieldTextInput} = goog.require('Blockly.FieldTextInput'); +/* eslint-disable-next-line no-unused-vars */ +const {Sentinel} = goog.requireType('Blockly.utils.Sentinel'); /** * Class for an editable number field. - * @param {string|number=} opt_value The initial value of the field. Should cast - * to a number. Defaults to 0. - * @param {?(string|number)=} opt_min Minimum value. - * @param {?(string|number)=} opt_max Maximum value. - * @param {?(string|number)=} opt_precision Precision for value. - * @param {?Function=} opt_validator A function that is called to validate - * changes to the field's value. Takes in a number & returns a validated - * number, or null to abort the change. - * @param {Object=} opt_config A map of options used to configure the field. - * See the [field creation documentation]{@link - * https://developers.google.com/blockly/guides/create-custom-blocks/fields/built-in-fields/number#creation} - * for a list of properties this parameter supports. * @extends {FieldTextInput} - * @constructor - * @alias Blockly.FieldNumber */ -const FieldNumber = function( - opt_value, opt_min, opt_max, opt_precision, opt_validator, opt_config) { +class FieldNumber extends FieldTextInput { /** - * The minimum value this number field can contain. - * @type {number} - * @protected + * @param {(string|number|!Sentinel)=} opt_value The initial value of + * the field. Should cast to a number. Defaults to 0. + * Also accepts Field.SKIP_SETUP if you wish to skip setup (only used by + * subclasses that want to handle configuration and setting the field + * value after their own constructors have run). + * @param {?(string|number)=} opt_min Minimum value. Will only be used if + * opt_config is not provided. + * @param {?(string|number)=} opt_max Maximum value. Will only be used if + * opt_config is not provided. + * @param {?(string|number)=} opt_precision Precision for value. Will only be + * used if opt_config is not provided. + * @param {?Function=} opt_validator A function that is called to validate + * changes to the field's value. Takes in a number & returns a validated + * number, or null to abort the change. + * @param {Object=} opt_config A map of options used to configure the field. + * See the [field creation documentation]{@link + * https://developers.google.com/blockly/guides/create-custom-blocks/fields/built-in-fields/number#creation} + * for a list of properties this parameter supports. + * @alias Blockly.FieldNumber */ - this.min_ = -Infinity; + constructor( + opt_value, opt_min, opt_max, opt_precision, opt_validator, opt_config) { + // Pass SENTINEL so that we can define properties before value validation. + super(Field.SKIP_SETUP); + + /** + * The minimum value this number field can contain. + * @type {number} + * @protected + */ + this.min_ = -Infinity; + + /** + * The maximum value this number field can contain. + * @type {number} + * @protected + */ + this.max_ = Infinity; + + /** + * The multiple to which this fields value is rounded. + * @type {number} + * @protected + */ + this.precision_ = 0; + + /** + * The number of decimal places to allow, or null to allow any number of + * decimal digits. + * @type {?number} + * @private + */ + this.decimalPlaces_ = null; + + /** + * Serializable fields are saved by the serializer, non-serializable fields + * are not. Editable fields should also be serializable. + * @type {boolean} + */ + this.SERIALIZABLE = true; + + if (opt_value === Field.SKIP_SETUP) return; + if (opt_config) { + this.configure_(opt_config); + } else { + this.setConstraints(opt_min, opt_max, opt_precision); + } + this.setValue(opt_value); + if (opt_validator) this.setValidator(opt_validator); + } /** - * The maximum value this number field can contain. - * @type {number} + * Configure the field based on the given map of options. + * @param {!Object} config A map of options to configure the field based on. * @protected + * @override */ - this.max_ = Infinity; + configure_(config) { + super.configure_(config); + this.setMinInternal_(config['min']); + this.setMaxInternal_(config['max']); + this.setPrecisionInternal_(config['precision']); + } /** - * The multiple to which this fields value is rounded. - * @type {number} - * @protected + * Set the maximum, minimum and precision constraints on this field. + * Any of these properties may be undefined or NaN to be disabled. + * Setting precision (usually a power of 10) enforces a minimum step between + * values. That is, the user's value will rounded to the closest multiple of + * precision. The least significant digit place is inferred from the + * precision. Integers values can be enforces by choosing an integer + * precision. + * @param {?(number|string|undefined)} min Minimum value. + * @param {?(number|string|undefined)} max Maximum value. + * @param {?(number|string|undefined)} precision Precision for value. */ - this.precision_ = 0; + setConstraints(min, max, precision) { + this.setMinInternal_(min); + this.setMaxInternal_(max); + this.setPrecisionInternal_(precision); + this.setValue(this.getValue()); + } /** - * The number of decimal places to allow, or null to allow any number of - * decimal digits. - * @type {?number} + * Sets the minimum value this field can contain. Updates the value to + * reflect. + * @param {?(number|string|undefined)} min Minimum value. + */ + setMin(min) { + this.setMinInternal_(min); + this.setValue(this.getValue()); + } + + /** + * Sets the minimum value this field can contain. Called internally to avoid + * value updates. + * @param {?(number|string|undefined)} min Minimum value. * @private */ - this.decimalPlaces_ = null; - - FieldNumber.superClass_.constructor.call( - this, opt_value, opt_validator, opt_config); - - if (!opt_config) { // Only do one kind of configuration or the other. - this.setConstraints(opt_min, opt_max, opt_precision); + setMinInternal_(min) { + if (min == null) { + this.min_ = -Infinity; + } else { + min = Number(min); + if (!isNaN(min)) { + this.min_ = min; + } + } } -}; -object.inherits(FieldNumber, FieldTextInput); + + /** + * Returns the current minimum value this field can contain. Default is + * -Infinity. + * @return {number} The current minimum value this field can contain. + */ + getMin() { + return this.min_; + } + + /** + * Sets the maximum value this field can contain. Updates the value to + * reflect. + * @param {?(number|string|undefined)} max Maximum value. + */ + setMax(max) { + this.setMaxInternal_(max); + this.setValue(this.getValue()); + } + + /** + * Sets the maximum value this field can contain. Called internally to avoid + * value updates. + * @param {?(number|string|undefined)} max Maximum value. + * @private + */ + setMaxInternal_(max) { + if (max == null) { + this.max_ = Infinity; + } else { + max = Number(max); + if (!isNaN(max)) { + this.max_ = max; + } + } + } + + /** + * Returns the current maximum value this field can contain. Default is + * Infinity. + * @return {number} The current maximum value this field can contain. + */ + getMax() { + return this.max_; + } + + /** + * Sets the precision of this field's value, i.e. the number to which the + * value is rounded. Updates the field to reflect. + * @param {?(number|string|undefined)} precision The number to which the + * field's value is rounded. + */ + setPrecision(precision) { + this.setPrecisionInternal_(precision); + this.setValue(this.getValue()); + } + + /** + * Sets the precision of this field's value. Called internally to avoid + * value updates. + * @param {?(number|string|undefined)} precision The number to which the + * field's value is rounded. + * @private + */ + setPrecisionInternal_(precision) { + this.precision_ = Number(precision) || 0; + let precisionString = String(this.precision_); + if (precisionString.indexOf('e') !== -1) { + // String() is fast. But it turns .0000001 into '1e-7'. + // Use the much slower toLocaleString to access all the digits. + precisionString = + this.precision_.toLocaleString('en-US', {maximumFractionDigits: 20}); + } + const decimalIndex = precisionString.indexOf('.'); + if (decimalIndex === -1) { + // If the precision is 0 (float) allow any number of decimals, + // otherwise allow none. + this.decimalPlaces_ = precision ? 0 : null; + } else { + this.decimalPlaces_ = precisionString.length - decimalIndex - 1; + } + } + + /** + * Returns the current precision of this field. The precision being the + * number to which the field's value is rounded. A precision of 0 means that + * the value is not rounded. + * @return {number} The number to which this field's value is rounded. + */ + getPrecision() { + return this.precision_; + } + + /** + * Ensure that the input value is a valid number (must fulfill the + * constraints placed on the field). + * @param {*=} opt_newValue The input value. + * @return {?number} A valid number, or null if invalid. + * @protected + * @override + */ + doClassValidation_(opt_newValue) { + if (opt_newValue === null) { + return null; + } + // Clean up text. + let newValue = String(opt_newValue); + // TODO: Handle cases like 'ten', '1.203,14', etc. + // 'O' is sometimes mistaken for '0' by inexperienced users. + newValue = newValue.replace(/O/ig, '0'); + // Strip out thousands separators. + newValue = newValue.replace(/,/g, ''); + // Ignore case of 'Infinity'. + newValue = newValue.replace(/infinity/i, 'Infinity'); + + // Clean up number. + let n = Number(newValue || 0); + if (isNaN(n)) { + // Invalid number. + return null; + } + // Get the value in range. + n = Math.min(Math.max(n, this.min_), this.max_); + // Round to nearest multiple of precision. + if (this.precision_ && isFinite(n)) { + n = Math.round(n / this.precision_) * this.precision_; + } + // Clean up floating point errors. + if (this.decimalPlaces_ !== null) { + n = Number(n.toFixed(this.decimalPlaces_)); + } + return n; + } + + /** + * Create the number input editor widget. + * @return {!HTMLElement} The newly created number input editor. + * @protected + * @override + */ + widgetCreate_() { + const htmlInput = super.widgetCreate_(); + + // Set the accessibility state + if (this.min_ > -Infinity) { + aria.setState(htmlInput, aria.State.VALUEMIN, this.min_); + } + if (this.max_ < Infinity) { + aria.setState(htmlInput, aria.State.VALUEMAX, this.max_); + } + return htmlInput; + } + + /** + * Construct a FieldNumber from a JSON arg object. + * @param {!Object} options A JSON object with options (value, min, max, and + * precision). + * @return {!FieldNumber} The new field instance. + * @package + * @nocollapse + * @override + */ + static fromJson(options) { + // `this` might be a subclass of FieldNumber if that class doesn't override + // the static fromJson method. + return new this( + options['value'], undefined, undefined, undefined, undefined, options); + } +} /** * The default value for this field. @@ -86,236 +335,6 @@ object.inherits(FieldNumber, FieldTextInput); */ FieldNumber.prototype.DEFAULT_VALUE = 0; -/** - * Construct a FieldNumber from a JSON arg object. - * @param {!Object} options A JSON object with options (value, min, max, and - * precision). - * @return {!FieldNumber} The new field instance. - * @package - * @nocollapse - */ -FieldNumber.fromJson = function(options) { - // `this` might be a subclass of FieldNumber if that class doesn't override - // the static fromJson method. - return new this( - options['value'], undefined, undefined, undefined, undefined, options); -}; - -/** - * Serializable fields are saved by the XML renderer, non-serializable fields - * are not. Editable fields should also be serializable. - * @type {boolean} - */ -FieldNumber.prototype.SERIALIZABLE = true; - -/** - * Configure the field based on the given map of options. - * @param {!Object} config A map of options to configure the field based on. - * @protected - * @override - */ -FieldNumber.prototype.configure_ = function(config) { - FieldNumber.superClass_.configure_.call(this, config); - this.setMinInternal_(config['min']); - this.setMaxInternal_(config['max']); - this.setPrecisionInternal_(config['precision']); -}; - -/** - * Set the maximum, minimum and precision constraints on this field. - * Any of these properties may be undefined or NaN to be disabled. - * Setting precision (usually a power of 10) enforces a minimum step between - * values. That is, the user's value will rounded to the closest multiple of - * precision. The least significant digit place is inferred from the precision. - * Integers values can be enforces by choosing an integer precision. - * @param {?(number|string|undefined)} min Minimum value. - * @param {?(number|string|undefined)} max Maximum value. - * @param {?(number|string|undefined)} precision Precision for value. - */ -FieldNumber.prototype.setConstraints = function(min, max, precision) { - this.setMinInternal_(min); - this.setMaxInternal_(max); - this.setPrecisionInternal_(precision); - this.setValue(this.getValue()); -}; - -/** - * Sets the minimum value this field can contain. Updates the value to reflect. - * @param {?(number|string|undefined)} min Minimum value. - */ -FieldNumber.prototype.setMin = function(min) { - this.setMinInternal_(min); - this.setValue(this.getValue()); -}; - -/** - * Sets the minimum value this field can contain. Called internally to avoid - * value updates. - * @param {?(number|string|undefined)} min Minimum value. - * @private - */ -FieldNumber.prototype.setMinInternal_ = function(min) { - if (min == null) { - this.min_ = -Infinity; - } else { - min = Number(min); - if (!isNaN(min)) { - this.min_ = min; - } - } -}; - -/** - * Returns the current minimum value this field can contain. Default is - * -Infinity. - * @return {number} The current minimum value this field can contain. - */ -FieldNumber.prototype.getMin = function() { - return this.min_; -}; - -/** - * Sets the maximum value this field can contain. Updates the value to reflect. - * @param {?(number|string|undefined)} max Maximum value. - */ -FieldNumber.prototype.setMax = function(max) { - this.setMaxInternal_(max); - this.setValue(this.getValue()); -}; - -/** - * Sets the maximum value this field can contain. Called internally to avoid - * value updates. - * @param {?(number|string|undefined)} max Maximum value. - * @private - */ -FieldNumber.prototype.setMaxInternal_ = function(max) { - if (max == null) { - this.max_ = Infinity; - } else { - max = Number(max); - if (!isNaN(max)) { - this.max_ = max; - } - } -}; - -/** - * Returns the current maximum value this field can contain. Default is - * Infinity. - * @return {number} The current maximum value this field can contain. - */ -FieldNumber.prototype.getMax = function() { - return this.max_; -}; - -/** - * Sets the precision of this field's value, i.e. the number to which the - * value is rounded. Updates the field to reflect. - * @param {?(number|string|undefined)} precision The number to which the - * field's value is rounded. - */ -FieldNumber.prototype.setPrecision = function(precision) { - this.setPrecisionInternal_(precision); - this.setValue(this.getValue()); -}; - -/** - * Sets the precision of this field's value. Called internally to avoid - * value updates. - * @param {?(number|string|undefined)} precision The number to which the - * field's value is rounded. - * @private - */ -FieldNumber.prototype.setPrecisionInternal_ = function(precision) { - this.precision_ = Number(precision) || 0; - let precisionString = String(this.precision_); - if (precisionString.indexOf('e') !== -1) { - // String() is fast. But it turns .0000001 into '1e-7'. - // Use the much slower toLocaleString to access all the digits. - precisionString = - this.precision_.toLocaleString('en-US', {maximumFractionDigits: 20}); - } - const decimalIndex = precisionString.indexOf('.'); - if (decimalIndex === -1) { - // If the precision is 0 (float) allow any number of decimals, - // otherwise allow none. - this.decimalPlaces_ = precision ? 0 : null; - } else { - this.decimalPlaces_ = precisionString.length - decimalIndex - 1; - } -}; - -/** - * Returns the current precision of this field. The precision being the - * number to which the field's value is rounded. A precision of 0 means that - * the value is not rounded. - * @return {number} The number to which this field's value is rounded. - */ -FieldNumber.prototype.getPrecision = function() { - return this.precision_; -}; - -/** - * Ensure that the input value is a valid number (must fulfill the - * constraints placed on the field). - * @param {*=} opt_newValue The input value. - * @return {?number} A valid number, or null if invalid. - * @protected - * @override - */ -FieldNumber.prototype.doClassValidation_ = function(opt_newValue) { - if (opt_newValue === null) { - return null; - } - // Clean up text. - let newValue = String(opt_newValue); - // TODO: Handle cases like 'ten', '1.203,14', etc. - // 'O' is sometimes mistaken for '0' by inexperienced users. - newValue = newValue.replace(/O/ig, '0'); - // Strip out thousands separators. - newValue = newValue.replace(/,/g, ''); - // Ignore case of 'Infinity'. - newValue = newValue.replace(/infinity/i, 'Infinity'); - - // Clean up number. - let n = Number(newValue || 0); - if (isNaN(n)) { - // Invalid number. - return null; - } - // Get the value in range. - n = Math.min(Math.max(n, this.min_), this.max_); - // Round to nearest multiple of precision. - if (this.precision_ && isFinite(n)) { - n = Math.round(n / this.precision_) * this.precision_; - } - // Clean up floating point errors. - if (this.decimalPlaces_ !== null) { - n = Number(n.toFixed(this.decimalPlaces_)); - } - return n; -}; - -/** - * Create the number input editor widget. - * @return {!HTMLElement} The newly created number input editor. - * @protected - * @override - */ -FieldNumber.prototype.widgetCreate_ = function() { - const htmlInput = FieldNumber.superClass_.widgetCreate_.call(this); - - // Set the accessibility state - if (this.min_ > -Infinity) { - aria.setState(htmlInput, aria.State.VALUEMIN, this.min_); - } - if (this.max_ < Infinity) { - aria.setState(htmlInput, aria.State.VALUEMAX, this.max_); - } - return htmlInput; -}; - fieldRegistry.register('field_number', FieldNumber); exports.FieldNumber = FieldNumber; diff --git a/core/field_textinput.js b/core/field_textinput.js index dfb6f055f..ddda5e728 100644 --- a/core/field_textinput.js +++ b/core/field_textinput.js @@ -22,7 +22,6 @@ const dialog = goog.require('Blockly.dialog'); const dom = goog.require('Blockly.utils.dom'); const eventUtils = goog.require('Blockly.Events.utils'); const fieldRegistry = goog.require('Blockly.fieldRegistry'); -const object = goog.require('Blockly.utils.object'); const parsing = goog.require('Blockly.utils.parsing'); const userAgent = goog.require('Blockly.utils.userAgent'); /* eslint-disable-next-line no-unused-vars */ @@ -33,6 +32,8 @@ const {Field} = goog.require('Blockly.Field'); const {KeyCodes} = goog.require('Blockly.utils.KeyCodes'); const {Msg} = goog.require('Blockly.Msg'); /* eslint-disable-next-line no-unused-vars */ +const {Sentinel} = goog.requireType('Blockly.utils.Sentinel'); +/* eslint-disable-next-line no-unused-vars */ const {WorkspaceSvg} = goog.requireType('Blockly.WorkspaceSvg'); /** @suppress {extraRequire} */ goog.require('Blockly.Events.BlockChange'); @@ -40,65 +41,565 @@ goog.require('Blockly.Events.BlockChange'); /** * Class for an editable text field. - * @param {string=} opt_value The initial value of the field. Should cast to a - * string. Defaults to an empty string if null or undefined. - * @param {?Function=} opt_validator A function that is called to validate - * changes to the field's value. Takes in a string & returns a validated - * string, or null to abort the change. - * @param {Object=} opt_config A map of options used to configure the field. - * See the [field creation documentation]{@link - * https://developers.google.com/blockly/guides/create-custom-blocks/fields/built-in-fields/text-input#creation} - * for a list of properties this parameter supports. - * @extends {Field} - * @constructor - * @alias Blockly.FieldTextInput */ -const FieldTextInput = function(opt_value, opt_validator, opt_config) { +class FieldTextInput extends Field { /** - * Allow browser to spellcheck this field. - * @type {boolean} + * @param {(string|!Sentinel)=} opt_value The initial value of the + * field. Should cast to a string. Defaults to an empty string if null or + * undefined. + * Also accepts Field.SKIP_SETUP if you wish to skip setup (only used by + * subclasses that want to handle configuration and setting the field + * value after their own constructors have run). + * @param {?Function=} opt_validator A function that is called to validate + * changes to the field's value. Takes in a string & returns a validated + * string, or null to abort the change. + * @param {Object=} opt_config A map of options used to configure the field. + * See the [field creation documentation]{@link + * https://developers.google.com/blockly/guides/create-custom-blocks/fields/built-in-fields/text-input#creation} + * for a list of properties this parameter supports. + * @alias Blockly.FieldTextInput + */ + constructor(opt_value, opt_validator, opt_config) { + super(Field.SKIP_SETUP); + + /** + * Allow browser to spellcheck this field. + * @type {boolean} + * @protected + */ + this.spellcheck_ = true; + + /** + * The HTML input element. + * @type {HTMLElement} + * @protected + */ + this.htmlInput_ = null; + + /** + * True if the field's value is currently being edited via the UI. + * @type {boolean} + * @private + */ + this.isBeingEdited_ = false; + + /** + * True if the value currently displayed in the field's editory UI is valid. + * @type {boolean} + * @private + */ + this.isTextValid_ = false; + + /** + * Key down event data. + * @type {?browserEvents.Data} + * @private + */ + this.onKeyDownWrapper_ = null; + + /** + * Key input event data. + * @type {?browserEvents.Data} + * @private + */ + this.onKeyInputWrapper_ = null; + + /** + * Whether the field should consider the whole parent block to be its click + * target. + * @type {?boolean} + */ + this.fullBlockClickTarget_ = false; + + /** + * The workspace that this field belongs to. + * @type {?WorkspaceSvg} + * @protected + */ + this.workspace_ = null; + + /** + * Serializable fields are saved by the serializer, non-serializable fields + * are not. Editable fields should also be serializable. + * @type {boolean} + */ + this.SERIALIZABLE = true; + + /** + * Mouse cursor style when over the hotspot that initiates the editor. + * @type {string} + */ + this.CURSOR = 'text'; + + if (opt_value === Field.SKIP_SETUP) return; + if (opt_config) this.configure_(opt_config); + this.setValue(opt_value); + if (opt_validator) this.setValidator(opt_validator); + } + + /** + * @override + */ + configure_(config) { + super.configure_(config); + if (typeof config['spellcheck'] === 'boolean') { + this.spellcheck_ = config['spellcheck']; + } + } + + /** + * @override + */ + initView() { + if (this.getConstants().FULL_BLOCK_FIELDS) { + // Step one: figure out if this is the only field on this block. + // Rendering is quite different in that case. + let nFields = 0; + let nConnections = 0; + + // Count the number of fields, excluding text fields + for (let i = 0, input; (input = this.sourceBlock_.inputList[i]); i++) { + for (let j = 0; (input.fieldRow[j]); j++) { + nFields++; + } + if (input.connection) { + nConnections++; + } + } + // The special case is when this is the only non-label field on the block + // and it has an output but no inputs. + this.fullBlockClickTarget_ = + nFields <= 1 && this.sourceBlock_.outputConnection && !nConnections; + } else { + this.fullBlockClickTarget_ = false; + } + + if (this.fullBlockClickTarget_) { + this.clickTarget_ = this.sourceBlock_.getSvgRoot(); + } else { + this.createBorderRect_(); + } + this.createTextElement_(); + } + + /** + * Ensure that the input value casts to a valid string. + * @param {*=} opt_newValue The input value. + * @return {*} A valid string, or null if invalid. * @protected */ - this.spellcheck_ = true; - - FieldTextInput.superClass_.constructor.call( - this, opt_value, opt_validator, opt_config); + doClassValidation_(opt_newValue) { + if (opt_newValue === null || opt_newValue === undefined) { + return null; + } + return String(opt_newValue); + } /** - * The HTML input element. - * @type {HTMLElement} - */ - this.htmlInput_ = null; - - /** - * Key down event data. - * @type {?browserEvents.Data} - * @private - */ - this.onKeyDownWrapper_ = null; - - /** - * Key input event data. - * @type {?browserEvents.Data} - * @private - */ - this.onKeyInputWrapper_ = null; - - /** - * Whether the field should consider the whole parent block to be its click - * target. - * @type {?boolean} - */ - this.fullBlockClickTarget_ = false; - - /** - * The workspace that this field belongs to. - * @type {?WorkspaceSvg} + * Called by setValue if the text input is not valid. If the field is + * currently being edited it reverts value of the field to the previous + * value while allowing the display text to be handled by the htmlInput_. + * @param {*} _invalidValue The input value that was determined to be invalid. + * This is not used by the text input because its display value is stored + * on the htmlInput_. * @protected */ - this.workspace_ = null; -}; -object.inherits(FieldTextInput, Field); + doValueInvalid_(_invalidValue) { + if (this.isBeingEdited_) { + this.isTextValid_ = false; + const oldValue = this.value_; + // Revert value when the text becomes invalid. + this.value_ = this.htmlInput_.untypedDefaultValue_; + if (this.sourceBlock_ && eventUtils.isEnabled()) { + eventUtils.fire(new (eventUtils.get(eventUtils.BLOCK_CHANGE))( + this.sourceBlock_, 'field', this.name || null, oldValue, + this.value_)); + } + } + } + + /** + * Called by setValue if the text input is valid. Updates the value of the + * field, and updates the text of the field if it is not currently being + * edited (i.e. handled by the htmlInput_). + * @param {*} newValue The value to be saved. The default validator guarantees + * that this is a string. + * @protected + */ + doValueUpdate_(newValue) { + this.isTextValid_ = true; + this.value_ = newValue; + if (!this.isBeingEdited_) { + // This should only occur if setValue is triggered programmatically. + this.isDirty_ = true; + } + } + + /** + * Updates text field to match the colour/style of the block. + * @package + */ + applyColour() { + if (this.sourceBlock_ && this.getConstants().FULL_BLOCK_FIELDS) { + if (this.borderRect_) { + this.borderRect_.setAttribute( + 'stroke', this.sourceBlock_.style.colourTertiary); + } else { + this.sourceBlock_.pathObject.svgPath.setAttribute( + 'fill', this.getConstants().FIELD_BORDER_RECT_COLOUR); + } + } + } + + /** + * Updates the colour of the htmlInput given the current validity of the + * field's value. + * @protected + */ + render_() { + super.render_(); + // This logic is done in render_ rather than doValueInvalid_ or + // doValueUpdate_ so that the code is more centralized. + if (this.isBeingEdited_) { + this.resizeEditor_(); + const htmlInput = /** @type {!HTMLElement} */ (this.htmlInput_); + if (!this.isTextValid_) { + dom.addClass(htmlInput, 'blocklyInvalidInput'); + aria.setState(htmlInput, aria.State.INVALID, true); + } else { + dom.removeClass(htmlInput, 'blocklyInvalidInput'); + aria.setState(htmlInput, aria.State.INVALID, false); + } + } + } + + /** + * Set whether this field is spellchecked by the browser. + * @param {boolean} check True if checked. + */ + setSpellcheck(check) { + if (check === this.spellcheck_) { + return; + } + this.spellcheck_ = check; + if (this.htmlInput_) { + this.htmlInput_.setAttribute('spellcheck', this.spellcheck_); + } + } + + /** + * Show the inline free-text editor on top of the text. + * @param {Event=} _opt_e Optional mouse event that triggered the field to + * open, or undefined if triggered programmatically. + * @param {boolean=} opt_quietInput True if editor should be created without + * focus. Defaults to false. + * @protected + */ + showEditor_(_opt_e, opt_quietInput) { + this.workspace_ = (/** @type {!BlockSvg} */ (this.sourceBlock_)).workspace; + const quietInput = opt_quietInput || false; + if (!quietInput && + (userAgent.MOBILE || userAgent.ANDROID || userAgent.IPAD)) { + this.showPromptEditor_(); + } else { + this.showInlineEditor_(quietInput); + } + } + + /** + * Create and show a text input editor that is a prompt (usually a popup). + * Mobile browsers have issues with in-line textareas (focus and keyboards). + * @private + */ + showPromptEditor_() { + dialog.prompt(Msg['CHANGE_VALUE_TITLE'], this.getText(), function(text) { + // Text is null if user pressed cancel button. + if (text !== null) { + this.setValue(this.getValueFromEditorText_(text)); + } + }.bind(this)); + } + + /** + * Create and show a text input editor that sits directly over the text input. + * @param {boolean} quietInput True if editor should be created without + * focus. + * @private + */ + showInlineEditor_(quietInput) { + WidgetDiv.show(this, this.sourceBlock_.RTL, this.widgetDispose_.bind(this)); + this.htmlInput_ = this.widgetCreate_(); + this.isBeingEdited_ = true; + + if (!quietInput) { + this.htmlInput_.focus({preventScroll: true}); + this.htmlInput_.select(); + } + } + + /** + * Create the text input editor widget. + * @return {!HTMLElement} The newly created text input editor. + * @protected + */ + widgetCreate_() { + eventUtils.setGroup(true); + const div = WidgetDiv.getDiv(); + + dom.addClass(this.getClickTarget_(), 'editing'); + + const htmlInput = + /** @type {HTMLInputElement} */ (document.createElement('input')); + htmlInput.className = 'blocklyHtmlInput'; + htmlInput.setAttribute('spellcheck', this.spellcheck_); + const scale = this.workspace_.getScale(); + const fontSize = (this.getConstants().FIELD_TEXT_FONTSIZE * scale) + 'pt'; + div.style.fontSize = fontSize; + htmlInput.style.fontSize = fontSize; + let borderRadius = (FieldTextInput.BORDERRADIUS * scale) + 'px'; + + if (this.fullBlockClickTarget_) { + const bBox = this.getScaledBBox(); + + // Override border radius. + borderRadius = (bBox.bottom - bBox.top) / 2 + 'px'; + // Pull stroke colour from the existing shadow block + const strokeColour = this.sourceBlock_.getParent() ? + this.sourceBlock_.getParent().style.colourTertiary : + this.sourceBlock_.style.colourTertiary; + htmlInput.style.border = (1 * scale) + 'px solid ' + strokeColour; + div.style.borderRadius = borderRadius; + div.style.transition = 'box-shadow 0.25s ease 0s'; + if (this.getConstants().FIELD_TEXTINPUT_BOX_SHADOW) { + div.style.boxShadow = + 'rgba(255, 255, 255, 0.3) 0 0 0 ' + (4 * scale) + 'px'; + } + } + htmlInput.style.borderRadius = borderRadius; + + div.appendChild(htmlInput); + + htmlInput.value = htmlInput.defaultValue = this.getEditorText_(this.value_); + htmlInput.untypedDefaultValue_ = this.value_; + htmlInput.oldValue_ = null; + + this.resizeEditor_(); + + this.bindInputEvents_(htmlInput); + + return htmlInput; + } + + /** + * Closes the editor, saves the results, and disposes of any events or + * DOM-references belonging to the editor. + * @protected + */ + widgetDispose_() { + // Non-disposal related things that we do when the editor closes. + this.isBeingEdited_ = false; + this.isTextValid_ = true; + // Make sure the field's node matches the field's internal value. + this.forceRerender(); + this.onFinishEditing_(this.value_); + eventUtils.setGroup(false); + + // Actual disposal. + this.unbindInputEvents_(); + const style = WidgetDiv.getDiv().style; + style.width = 'auto'; + style.height = 'auto'; + style.fontSize = ''; + style.transition = ''; + style.boxShadow = ''; + this.htmlInput_ = null; + + dom.removeClass(this.getClickTarget_(), 'editing'); + } + + /** + * A callback triggered when the user is done editing the field via the UI. + * @param {*} _value The new value of the field. + */ + onFinishEditing_(_value) { + // NOP by default. + // TODO(#2496): Support people passing a func into the field. + } + + /** + * Bind handlers for user input on the text input field's editor. + * @param {!HTMLElement} htmlInput The htmlInput to which event + * handlers will be bound. + * @protected + */ + bindInputEvents_(htmlInput) { + // Trap Enter without IME and Esc to hide. + this.onKeyDownWrapper_ = browserEvents.conditionalBind( + htmlInput, 'keydown', this, this.onHtmlInputKeyDown_); + // Resize after every input change. + this.onKeyInputWrapper_ = browserEvents.conditionalBind( + htmlInput, 'input', this, this.onHtmlInputChange_); + } + + /** + * Unbind handlers for user input and workspace size changes. + * @protected + */ + unbindInputEvents_() { + if (this.onKeyDownWrapper_) { + browserEvents.unbind(this.onKeyDownWrapper_); + this.onKeyDownWrapper_ = null; + } + if (this.onKeyInputWrapper_) { + browserEvents.unbind(this.onKeyInputWrapper_); + this.onKeyInputWrapper_ = null; + } + } + + /** + * Handle key down to the editor. + * @param {!Event} e Keyboard event. + * @protected + */ + onHtmlInputKeyDown_(e) { + if (e.keyCode === KeyCodes.ENTER) { + WidgetDiv.hide(); + DropDownDiv.hideWithoutAnimation(); + } else if (e.keyCode === KeyCodes.ESC) { + this.setValue(this.htmlInput_.untypedDefaultValue_); + WidgetDiv.hide(); + DropDownDiv.hideWithoutAnimation(); + } else if (e.keyCode === KeyCodes.TAB) { + WidgetDiv.hide(); + DropDownDiv.hideWithoutAnimation(); + this.sourceBlock_.tab(this, !e.shiftKey); + e.preventDefault(); + } + } + + /** + * Handle a change to the editor. + * @param {!Event} _e Keyboard event. + * @private + */ + onHtmlInputChange_(_e) { + const text = this.htmlInput_.value; + if (text !== this.htmlInput_.oldValue_) { + this.htmlInput_.oldValue_ = text; + + const value = this.getValueFromEditorText_(text); + this.setValue(value); + this.forceRerender(); + this.resizeEditor_(); + } + } + + /** + * Set the HTML input value and the field's internal value. The difference + * between this and ``setValue`` is that this also updates the HTML input + * value whilst editing. + * @param {*} newValue New value. + * @protected + */ + setEditorValue_(newValue) { + this.isDirty_ = true; + if (this.isBeingEdited_) { + // In the case this method is passed an invalid value, we still + // pass it through the transformation method `getEditorText` to deal + // with. Otherwise, the internal field's state will be inconsistent + // with what's shown to the user. + this.htmlInput_.value = this.getEditorText_(newValue); + } + this.setValue(newValue); + } + + /** + * Resize the editor to fit the text. + * @protected + */ + resizeEditor_() { + const div = WidgetDiv.getDiv(); + const bBox = this.getScaledBBox(); + div.style.width = bBox.right - bBox.left + 'px'; + div.style.height = bBox.bottom - bBox.top + 'px'; + + // In RTL mode block fields and LTR input fields the left edge moves, + // whereas the right edge is fixed. Reposition the editor. + const x = this.sourceBlock_.RTL ? bBox.right - div.offsetWidth : bBox.left; + const xy = new Coordinate(x, bBox.top); + + div.style.left = xy.x + 'px'; + div.style.top = xy.y + 'px'; + } + + /** + * Returns whether or not the field is tab navigable. + * @return {boolean} True if the field is tab navigable. + * @override + */ + isTabNavigable() { + return true; + } + + /** + * Use the `getText_` developer hook to override the field's text + * representation. When we're currently editing, return the current HTML value + * instead. Otherwise, return null which tells the field to use the default + * behaviour (which is a string cast of the field's value). + * @return {?string} The HTML value if we're editing, otherwise null. + * @protected + * @override + */ + getText_() { + if (this.isBeingEdited_ && this.htmlInput_) { + // We are currently editing, return the HTML input value instead. + return this.htmlInput_.value; + } + return null; + } + + /** + * Transform the provided value into a text to show in the HTML input. + * Override this method if the field's HTML input representation is different + * than the field's value. This should be coupled with an override of + * `getValueFromEditorText_`. + * @param {*} value The value stored in this field. + * @return {string} The text to show on the HTML input. + * @protected + */ + getEditorText_(value) { + return String(value); + } + + /** + * Transform the text received from the HTML input into a value to store + * in this field. + * Override this method if the field's HTML input representation is different + * than the field's value. This should be coupled with an override of + * `getEditorText_`. + * @param {string} text Text received from the HTML input. + * @return {*} The value to store. + * @protected + */ + getValueFromEditorText_(text) { + return text; + } + + /** + * Construct a FieldTextInput from a JSON arg object, + * dereferencing any string table references. + * @param {!Object} options A JSON object with options (text, and spellcheck). + * @return {!FieldTextInput} The new field instance. + * @package + * @nocollapse + */ + static fromJson(options) { + const text = parsing.replaceMessageReferences(options['text']); + // `this` might be a subclass of FieldTextInput if that class doesn't + // override the static fromJson method. + return new this(text, undefined, options); + } +} /** * The default value for this field. @@ -107,481 +608,12 @@ object.inherits(FieldTextInput, Field); */ FieldTextInput.prototype.DEFAULT_VALUE = ''; -/** - * Construct a FieldTextInput from a JSON arg object, - * dereferencing any string table references. - * @param {!Object} options A JSON object with options (text, and spellcheck). - * @return {!FieldTextInput} The new field instance. - * @package - * @nocollapse - */ -FieldTextInput.fromJson = function(options) { - const text = parsing.replaceMessageReferences(options['text']); - // `this` might be a subclass of FieldTextInput if that class doesn't override - // the static fromJson method. - return new this(text, undefined, options); -}; - -/** - * Serializable fields are saved by the XML renderer, non-serializable fields - * are not. Editable fields should also be serializable. - * @type {boolean} - */ -FieldTextInput.prototype.SERIALIZABLE = true; - /** * Pixel size of input border radius. * Should match blocklyText's border-radius in CSS. */ FieldTextInput.BORDERRADIUS = 4; -/** - * Mouse cursor style when over the hotspot that initiates the editor. - */ -FieldTextInput.prototype.CURSOR = 'text'; - -/** - * @override - */ -FieldTextInput.prototype.configure_ = function(config) { - FieldTextInput.superClass_.configure_.call(this, config); - if (typeof config['spellcheck'] === 'boolean') { - this.spellcheck_ = config['spellcheck']; - } -}; - -/** - * @override - */ -FieldTextInput.prototype.initView = function() { - if (this.getConstants().FULL_BLOCK_FIELDS) { - // Step one: figure out if this is the only field on this block. - // Rendering is quite different in that case. - let nFields = 0; - let nConnections = 0; - - // Count the number of fields, excluding text fields - for (let i = 0, input; (input = this.sourceBlock_.inputList[i]); i++) { - for (let j = 0; (input.fieldRow[j]); j++) { - nFields++; - } - if (input.connection) { - nConnections++; - } - } - // The special case is when this is the only non-label field on the block - // and it has an output but no inputs. - this.fullBlockClickTarget_ = - nFields <= 1 && this.sourceBlock_.outputConnection && !nConnections; - } else { - this.fullBlockClickTarget_ = false; - } - - if (this.fullBlockClickTarget_) { - this.clickTarget_ = this.sourceBlock_.getSvgRoot(); - } else { - this.createBorderRect_(); - } - this.createTextElement_(); -}; - -/** - * Ensure that the input value casts to a valid string. - * @param {*=} opt_newValue The input value. - * @return {*} A valid string, or null if invalid. - * @protected - */ -FieldTextInput.prototype.doClassValidation_ = function(opt_newValue) { - if (opt_newValue === null || opt_newValue === undefined) { - return null; - } - return String(opt_newValue); -}; - -/** - * Called by setValue if the text input is not valid. If the field is - * currently being edited it reverts value of the field to the previous - * value while allowing the display text to be handled by the htmlInput_. - * @param {*} _invalidValue The input value that was determined to be invalid. - * This is not used by the text input because its display value is stored on - * the htmlInput_. - * @protected - */ -FieldTextInput.prototype.doValueInvalid_ = function(_invalidValue) { - if (this.isBeingEdited_) { - this.isTextValid_ = false; - const oldValue = this.value_; - // Revert value when the text becomes invalid. - this.value_ = this.htmlInput_.untypedDefaultValue_; - if (this.sourceBlock_ && eventUtils.isEnabled()) { - eventUtils.fire(new (eventUtils.get(eventUtils.BLOCK_CHANGE))( - this.sourceBlock_, 'field', this.name || null, oldValue, - this.value_)); - } - } -}; - -/** - * Called by setValue if the text input is valid. Updates the value of the - * field, and updates the text of the field if it is not currently being - * edited (i.e. handled by the htmlInput_). - * @param {*} newValue The value to be saved. The default validator guarantees - * that this is a string. - * @protected - */ -FieldTextInput.prototype.doValueUpdate_ = function(newValue) { - this.isTextValid_ = true; - this.value_ = newValue; - if (!this.isBeingEdited_) { - // This should only occur if setValue is triggered programmatically. - this.isDirty_ = true; - } -}; - -/** - * Updates text field to match the colour/style of the block. - * @package - */ -FieldTextInput.prototype.applyColour = function() { - if (this.sourceBlock_ && this.getConstants().FULL_BLOCK_FIELDS) { - if (this.borderRect_) { - this.borderRect_.setAttribute( - 'stroke', this.sourceBlock_.style.colourTertiary); - } else { - this.sourceBlock_.pathObject.svgPath.setAttribute( - 'fill', this.getConstants().FIELD_BORDER_RECT_COLOUR); - } - } -}; - -/** - * Updates the colour of the htmlInput given the current validity of the - * field's value. - * @protected - */ -FieldTextInput.prototype.render_ = function() { - FieldTextInput.superClass_.render_.call(this); - // This logic is done in render_ rather than doValueInvalid_ or - // doValueUpdate_ so that the code is more centralized. - if (this.isBeingEdited_) { - this.resizeEditor_(); - const htmlInput = /** @type {!HTMLElement} */ (this.htmlInput_); - if (!this.isTextValid_) { - dom.addClass(htmlInput, 'blocklyInvalidInput'); - aria.setState(htmlInput, aria.State.INVALID, true); - } else { - dom.removeClass(htmlInput, 'blocklyInvalidInput'); - aria.setState(htmlInput, aria.State.INVALID, false); - } - } -}; - -/** - * Set whether this field is spellchecked by the browser. - * @param {boolean} check True if checked. - */ -FieldTextInput.prototype.setSpellcheck = function(check) { - if (check === this.spellcheck_) { - return; - } - this.spellcheck_ = check; - if (this.htmlInput_) { - this.htmlInput_.setAttribute('spellcheck', this.spellcheck_); - } -}; - -/** - * Show the inline free-text editor on top of the text. - * @param {Event=} _opt_e Optional mouse event that triggered the field to open, - * or undefined if triggered programmatically. - * @param {boolean=} opt_quietInput True if editor should be created without - * focus. Defaults to false. - * @protected - */ -FieldTextInput.prototype.showEditor_ = function(_opt_e, opt_quietInput) { - this.workspace_ = (/** @type {!BlockSvg} */ (this.sourceBlock_)).workspace; - const quietInput = opt_quietInput || false; - if (!quietInput && - (userAgent.MOBILE || userAgent.ANDROID || userAgent.IPAD)) { - this.showPromptEditor_(); - } else { - this.showInlineEditor_(quietInput); - } -}; - -/** - * Create and show a text input editor that is a prompt (usually a popup). - * Mobile browsers have issues with in-line textareas (focus and keyboards). - * @private - */ -FieldTextInput.prototype.showPromptEditor_ = function() { - dialog.prompt(Msg['CHANGE_VALUE_TITLE'], this.getText(), function(text) { - // Text is null if user pressed cancel button. - if (text !== null) { - this.setValue(this.getValueFromEditorText_(text)); - } - }.bind(this)); -}; - -/** - * Create and show a text input editor that sits directly over the text input. - * @param {boolean} quietInput True if editor should be created without - * focus. - * @private - */ -FieldTextInput.prototype.showInlineEditor_ = function(quietInput) { - WidgetDiv.show(this, this.sourceBlock_.RTL, this.widgetDispose_.bind(this)); - this.htmlInput_ = this.widgetCreate_(); - this.isBeingEdited_ = true; - - if (!quietInput) { - this.htmlInput_.focus({preventScroll: true}); - this.htmlInput_.select(); - } -}; - -/** - * Create the text input editor widget. - * @return {!HTMLElement} The newly created text input editor. - * @protected - */ -FieldTextInput.prototype.widgetCreate_ = function() { - eventUtils.setGroup(true); - const div = WidgetDiv.getDiv(); - - dom.addClass(this.getClickTarget_(), 'editing'); - - const htmlInput = - /** @type {HTMLInputElement} */ (document.createElement('input')); - htmlInput.className = 'blocklyHtmlInput'; - htmlInput.setAttribute('spellcheck', this.spellcheck_); - const scale = this.workspace_.getScale(); - const fontSize = (this.getConstants().FIELD_TEXT_FONTSIZE * scale) + 'pt'; - div.style.fontSize = fontSize; - htmlInput.style.fontSize = fontSize; - let borderRadius = (FieldTextInput.BORDERRADIUS * scale) + 'px'; - - if (this.fullBlockClickTarget_) { - const bBox = this.getScaledBBox(); - - // Override border radius. - borderRadius = (bBox.bottom - bBox.top) / 2 + 'px'; - // Pull stroke colour from the existing shadow block - const strokeColour = this.sourceBlock_.getParent() ? - this.sourceBlock_.getParent().style.colourTertiary : - this.sourceBlock_.style.colourTertiary; - htmlInput.style.border = (1 * scale) + 'px solid ' + strokeColour; - div.style.borderRadius = borderRadius; - div.style.transition = 'box-shadow 0.25s ease 0s'; - if (this.getConstants().FIELD_TEXTINPUT_BOX_SHADOW) { - div.style.boxShadow = - 'rgba(255, 255, 255, 0.3) 0 0 0 ' + (4 * scale) + 'px'; - } - } - htmlInput.style.borderRadius = borderRadius; - - div.appendChild(htmlInput); - - htmlInput.value = htmlInput.defaultValue = this.getEditorText_(this.value_); - htmlInput.untypedDefaultValue_ = this.value_; - htmlInput.oldValue_ = null; - - this.resizeEditor_(); - - this.bindInputEvents_(htmlInput); - - return htmlInput; -}; - -/** - * Closes the editor, saves the results, and disposes of any events or - * DOM-references belonging to the editor. - * @protected - */ -FieldTextInput.prototype.widgetDispose_ = function() { - // Non-disposal related things that we do when the editor closes. - this.isBeingEdited_ = false; - this.isTextValid_ = true; - // Make sure the field's node matches the field's internal value. - this.forceRerender(); - // TODO(#2496): Make this less of a hack. - if (this.onFinishEditing_) { - this.onFinishEditing_(this.value_); - } - eventUtils.setGroup(false); - - // Actual disposal. - this.unbindInputEvents_(); - const style = WidgetDiv.getDiv().style; - style.width = 'auto'; - style.height = 'auto'; - style.fontSize = ''; - style.transition = ''; - style.boxShadow = ''; - this.htmlInput_ = null; - - dom.removeClass(this.getClickTarget_(), 'editing'); -}; - -/** - * Bind handlers for user input on the text input field's editor. - * @param {!HTMLElement} htmlInput The htmlInput to which event - * handlers will be bound. - * @protected - */ -FieldTextInput.prototype.bindInputEvents_ = function(htmlInput) { - // Trap Enter without IME and Esc to hide. - this.onKeyDownWrapper_ = browserEvents.conditionalBind( - htmlInput, 'keydown', this, this.onHtmlInputKeyDown_); - // Resize after every input change. - this.onKeyInputWrapper_ = browserEvents.conditionalBind( - htmlInput, 'input', this, this.onHtmlInputChange_); -}; - -/** - * Unbind handlers for user input and workspace size changes. - * @protected - */ -FieldTextInput.prototype.unbindInputEvents_ = function() { - if (this.onKeyDownWrapper_) { - browserEvents.unbind(this.onKeyDownWrapper_); - this.onKeyDownWrapper_ = null; - } - if (this.onKeyInputWrapper_) { - browserEvents.unbind(this.onKeyInputWrapper_); - this.onKeyInputWrapper_ = null; - } -}; - -/** - * Handle key down to the editor. - * @param {!Event} e Keyboard event. - * @protected - */ -FieldTextInput.prototype.onHtmlInputKeyDown_ = function(e) { - if (e.keyCode === KeyCodes.ENTER) { - WidgetDiv.hide(); - DropDownDiv.hideWithoutAnimation(); - } else if (e.keyCode === KeyCodes.ESC) { - this.setValue(this.htmlInput_.untypedDefaultValue_); - WidgetDiv.hide(); - DropDownDiv.hideWithoutAnimation(); - } else if (e.keyCode === KeyCodes.TAB) { - WidgetDiv.hide(); - DropDownDiv.hideWithoutAnimation(); - this.sourceBlock_.tab(this, !e.shiftKey); - e.preventDefault(); - } -}; - -/** - * Handle a change to the editor. - * @param {!Event} _e Keyboard event. - * @private - */ -FieldTextInput.prototype.onHtmlInputChange_ = function(_e) { - const text = this.htmlInput_.value; - if (text !== this.htmlInput_.oldValue_) { - this.htmlInput_.oldValue_ = text; - - const value = this.getValueFromEditorText_(text); - this.setValue(value); - this.forceRerender(); - this.resizeEditor_(); - } -}; - -/** - * Set the HTML input value and the field's internal value. The difference - * between this and ``setValue`` is that this also updates the HTML input - * value whilst editing. - * @param {*} newValue New value. - * @protected - */ -FieldTextInput.prototype.setEditorValue_ = function(newValue) { - this.isDirty_ = true; - if (this.isBeingEdited_) { - // In the case this method is passed an invalid value, we still - // pass it through the transformation method `getEditorText` to deal - // with. Otherwise, the internal field's state will be inconsistent - // with what's shown to the user. - this.htmlInput_.value = this.getEditorText_(newValue); - } - this.setValue(newValue); -}; - -/** - * Resize the editor to fit the text. - * @protected - */ -FieldTextInput.prototype.resizeEditor_ = function() { - const div = WidgetDiv.getDiv(); - const bBox = this.getScaledBBox(); - div.style.width = bBox.right - bBox.left + 'px'; - div.style.height = bBox.bottom - bBox.top + 'px'; - - // In RTL mode block fields and LTR input fields the left edge moves, - // whereas the right edge is fixed. Reposition the editor. - const x = this.sourceBlock_.RTL ? bBox.right - div.offsetWidth : bBox.left; - const xy = new Coordinate(x, bBox.top); - - div.style.left = xy.x + 'px'; - div.style.top = xy.y + 'px'; -}; - -/** - * Returns whether or not the field is tab navigable. - * @return {boolean} True if the field is tab navigable. - * @override - */ -FieldTextInput.prototype.isTabNavigable = function() { - return true; -}; - -/** - * Use the `getText_` developer hook to override the field's text - * representation. When we're currently editing, return the current HTML value - * instead. Otherwise, return null which tells the field to use the default - * behaviour (which is a string cast of the field's value). - * @return {?string} The HTML value if we're editing, otherwise null. - * @protected - * @override - */ -FieldTextInput.prototype.getText_ = function() { - if (this.isBeingEdited_ && this.htmlInput_) { - // We are currently editing, return the HTML input value instead. - return this.htmlInput_.value; - } - return null; -}; - -/** - * Transform the provided value into a text to show in the HTML input. - * Override this method if the field's HTML input representation is different - * than the field's value. This should be coupled with an override of - * `getValueFromEditorText_`. - * @param {*} value The value stored in this field. - * @return {string} The text to show on the HTML input. - * @protected - */ -FieldTextInput.prototype.getEditorText_ = function(value) { - return String(value); -}; - -/** - * Transform the text received from the HTML input into a value to store - * in this field. - * Override this method if the field's HTML input representation is different - * than the field's value. This should be coupled with an override of - * `getEditorText_`. - * @param {string} text Text received from the HTML input. - * @return {*} The value to store. - * @protected - */ -FieldTextInput.prototype.getValueFromEditorText_ = function(text) { - return text; -}; - fieldRegistry.register('field_input', FieldTextInput); exports.FieldTextInput = FieldTextInput; diff --git a/core/field_variable.js b/core/field_variable.js index af43f02a5..62cc09ed1 100644 --- a/core/field_variable.js +++ b/core/field_variable.js @@ -19,16 +19,18 @@ const Variables = goog.require('Blockly.Variables'); const Xml = goog.require('Blockly.Xml'); const fieldRegistry = goog.require('Blockly.fieldRegistry'); const internalConstants = goog.require('Blockly.internalConstants'); -const object = goog.require('Blockly.utils.object'); const parsing = goog.require('Blockly.utils.parsing'); /* eslint-disable-next-line no-unused-vars */ const {Block} = goog.requireType('Blockly.Block'); +const {Field} = goog.require('Blockly.Field'); const {FieldDropdown} = goog.require('Blockly.FieldDropdown'); /* eslint-disable-next-line no-unused-vars */ const {MenuItem} = goog.requireType('Blockly.MenuItem'); /* eslint-disable-next-line no-unused-vars */ const {Menu} = goog.requireType('Blockly.Menu'); const {Msg} = goog.require('Blockly.Msg'); +/* eslint-disable-next-line no-unused-vars */ +const {Sentinel} = goog.requireType('Blockly.utils.Sentinel'); const {Size} = goog.require('Blockly.utils.Size'); const {VariableModel} = goog.require('Blockly.VariableModel'); /** @suppress {extraRequire} */ @@ -37,483 +39,519 @@ goog.require('Blockly.Events.BlockChange'); /** * Class for a variable's dropdown field. - * @param {?string} varName The default name for the variable. If null, - * a unique variable name will be generated. - * @param {Function=} opt_validator A function that is called to validate - * changes to the field's value. Takes in a variable ID & returns a - * validated variable ID, or null to abort the change. - * @param {Array=} opt_variableTypes A list of the types of variables - * to include in the dropdown. - * @param {string=} opt_defaultType The type of variable to create if this - * field's value is not explicitly set. Defaults to ''. - * @param {Object=} opt_config A map of options used to configure the field. - * See the [field creation documentation]{@link - * https://developers.google.com/blockly/guides/create-custom-blocks/fields/built-in-fields/variable#creation} - * for a list of properties this parameter supports. * @extends {FieldDropdown} - * @constructor - * @alias Blockly.FieldVariable */ -const FieldVariable = function( - varName, opt_validator, opt_variableTypes, opt_defaultType, opt_config) { - // The FieldDropdown constructor expects the field's initial value to be - // the first entry in the menu generator, which it may or may not be. - // Just do the relevant parts of the constructor. +class FieldVariable extends FieldDropdown { + /** + * @param {?string|!Sentinel} varName The default name for the variable. + * If null, a unique variable name will be generated. + * Also accepts Field.SKIP_SETUP if you wish to skip setup (only used by + * subclasses that want to handle configuration and setting the field + * value after their own constructors have run). + * @param {Function=} opt_validator A function that is called to validate + * changes to the field's value. Takes in a variable ID & returns a + * validated variable ID, or null to abort the change. + * @param {Array=} opt_variableTypes A list of the types of variables + * to include in the dropdown. Will only be used if opt_config is not + * provided. + * @param {string=} opt_defaultType The type of variable to create if this + * field's value is not explicitly set. Defaults to ''. Will only be used + * if opt_config is not provided. + * @param {Object=} opt_config A map of options used to configure the field. + * See the [field creation documentation]{@link + * https://developers.google.com/blockly/guides/create-custom-blocks/fields/built-in-fields/variable#creation} + * for a list of properties this parameter supports. + * @alias Blockly.FieldVariable + */ + constructor( + varName, opt_validator, opt_variableTypes, opt_defaultType, opt_config) { + super(Field.SKIP_SETUP); + + /** + * An array of options for a dropdown list, + * or a function which generates these options. + * @type {(!Array| + * !function(this:FieldDropdown): !Array)} + * @protected + */ + this.menuGenerator_ = FieldVariable.dropdownCreate; + + /** + * The initial variable name passed to this field's constructor, or an + * empty string if a name wasn't provided. Used to create the initial + * variable. + * @type {string} + */ + this.defaultVariableName = typeof varName === 'string' ? varName : ''; + + /** + * The type of the default variable for this field. + * @type {string} + * @private + */ + this.defaultType_ = ''; + + /** + * All of the types of variables that will be available in this field's + * dropdown. + * @type {?Array} + */ + this.variableTypes = []; + + /** + * The size of the area rendered by the field. + * @type {Size} + * @protected + * @override + */ + this.size_ = new Size(0, 0); + + /** + * The variable model associated with this field. + * @type {?VariableModel} + * @private + */ + this.variable_ = null; + + /** + * Serializable fields are saved by the serializer, non-serializable fields + * are not. Editable fields should also be serializable. + * @type {boolean} + */ + this.SERIALIZABLE = true; + + if (varName === Field.SKIP_SETUP) return; + + if (opt_config) { + this.configure_(opt_config); + } else { + this.setTypes_(opt_variableTypes, opt_defaultType); + } + if (opt_validator) this.setValidator(opt_validator); + } /** - * An array of options for a dropdown list, - * or a function which generates these options. - * @type {(!Array| - * !function(this:FieldDropdown): !Array)} + * Configure the field based on the given map of options. + * @param {!Object} config A map of options to configure the field based on. * @protected */ - this.menuGenerator_ = FieldVariable.dropdownCreate; + configure_(config) { + super.configure_(config); + this.setTypes_(config['variableTypes'], config['defaultType']); + } /** - * The initial variable name passed to this field's constructor, or an - * empty string if a name wasn't provided. Used to create the initial - * variable. - * @type {string} + * Initialize the model for this field if it has not already been initialized. + * If the value has not been set to a variable by the first render, we make up + * a variable rather than let the value be invalid. + * @package */ - this.defaultVariableName = typeof varName === 'string' ? varName : ''; + initModel() { + if (this.variable_) { + return; // Initialization already happened. + } + const variable = Variables.getOrCreateVariablePackage( + this.sourceBlock_.workspace, null, this.defaultVariableName, + this.defaultType_); + + // Don't call setValue because we don't want to cause a rerender. + this.doValueUpdate_(variable.getId()); + } /** - * The size of the area rendered by the field. - * @type {Size} - * @protected * @override */ - this.size_ = new Size(0, 0); - - opt_config && this.configure_(opt_config); - opt_validator && this.setValidator(opt_validator); - - if (!opt_config) { // Only do one kind of configuration or the other. - this.setTypes_(opt_variableTypes, opt_defaultType); - } -}; -object.inherits(FieldVariable, FieldDropdown); - -/** - * Construct a FieldVariable from a JSON arg object, - * dereferencing any string table references. - * @param {!Object} options A JSON object with options (variable, - * variableTypes, and defaultType). - * @return {!FieldVariable} The new field instance. - * @package - * @nocollapse - */ -FieldVariable.fromJson = function(options) { - const varName = parsing.replaceMessageReferences(options['variable']); - // `this` might be a subclass of FieldVariable if that class doesn't override - // the static fromJson method. - return new this(varName, undefined, undefined, undefined, options); -}; - -/** - * Serializable fields are saved by the XML renderer, non-serializable fields - * are not. Editable fields should also be serializable. - * @type {boolean} - */ -FieldVariable.prototype.SERIALIZABLE = true; - -/** - * Configure the field based on the given map of options. - * @param {!Object} config A map of options to configure the field based on. - * @protected - */ -FieldVariable.prototype.configure_ = function(config) { - FieldVariable.superClass_.configure_.call(this, config); - this.setTypes_(config['variableTypes'], config['defaultType']); -}; - -/** - * Initialize the model for this field if it has not already been initialized. - * If the value has not been set to a variable by the first render, we make up a - * variable rather than let the value be invalid. - * @package - */ -FieldVariable.prototype.initModel = function() { - if (this.variable_) { - return; // Initialization already happened. - } - const variable = Variables.getOrCreateVariablePackage( - this.sourceBlock_.workspace, null, this.defaultVariableName, - this.defaultType_); - - // Don't call setValue because we don't want to cause a rerender. - this.doValueUpdate_(variable.getId()); -}; - -/** - * @override - */ -FieldVariable.prototype.shouldAddBorderRect_ = function() { - return FieldVariable.superClass_.shouldAddBorderRect_.call(this) && - (!this.getConstants().FIELD_DROPDOWN_NO_BORDER_RECT_SHADOW || - this.sourceBlock_.type !== 'variables_get'); -}; - -/** - * Initialize this field based on the given XML. - * @param {!Element} fieldElement The element containing information about the - * variable field's state. - */ -FieldVariable.prototype.fromXml = function(fieldElement) { - const id = fieldElement.getAttribute('id'); - const variableName = fieldElement.textContent; - // 'variabletype' should be lowercase, but until July 2019 it was sometimes - // recorded as 'variableType'. Thus we need to check for both. - const variableType = fieldElement.getAttribute('variabletype') || - fieldElement.getAttribute('variableType') || ''; - - const variable = Variables.getOrCreateVariablePackage( - this.sourceBlock_.workspace, id, variableName, variableType); - - // This should never happen :) - if (variableType !== null && variableType !== variable.type) { - throw Error( - 'Serialized variable type with id \'' + variable.getId() + - '\' had type ' + variable.type + ', and ' + - 'does not match variable field that references it: ' + - Xml.domToText(fieldElement) + '.'); + shouldAddBorderRect_() { + return super.shouldAddBorderRect_() && + (!this.getConstants().FIELD_DROPDOWN_NO_BORDER_RECT_SHADOW || + this.sourceBlock_.type !== 'variables_get'); } - this.setValue(variable.getId()); -}; + /** + * Initialize this field based on the given XML. + * @param {!Element} fieldElement The element containing information about the + * variable field's state. + */ + fromXml(fieldElement) { + const id = fieldElement.getAttribute('id'); + const variableName = fieldElement.textContent; + // 'variabletype' should be lowercase, but until July 2019 it was sometimes + // recorded as 'variableType'. Thus we need to check for both. + const variableType = fieldElement.getAttribute('variabletype') || + fieldElement.getAttribute('variableType') || ''; -/** - * Serialize this field to XML. - * @param {!Element} fieldElement The element to populate with info about the - * field's state. - * @return {!Element} The element containing info about the field's state. - */ -FieldVariable.prototype.toXml = function(fieldElement) { - // Make sure the variable is initialized. - this.initModel(); + const variable = Variables.getOrCreateVariablePackage( + this.sourceBlock_.workspace, id, variableName, variableType); - fieldElement.id = this.variable_.getId(); - fieldElement.textContent = this.variable_.name; - if (this.variable_.type) { - fieldElement.setAttribute('variabletype', this.variable_.type); - } - return fieldElement; -}; - -/** - * Saves this field's value. - * @param {boolean=} doFullSerialization If true, the variable field will - * serialize the full state of the field being referenced (ie ID, name, - * and type) rather than just a reference to it (ie ID). - * @return {*} The state of the variable field. - * @override - * @package - */ -FieldVariable.prototype.saveState = function(doFullSerialization) { - const legacyState = this.saveLegacyState(FieldVariable); - if (legacyState !== null) { - return legacyState; - } - // Make sure the variable is initialized. - this.initModel(); - const state = {'id': this.variable_.getId()}; - if (doFullSerialization) { - state['name'] = this.variable_.name; - state['type'] = this.variable_.type; - } - return state; -}; - -/** - * Sets the field's value based on the given state. - * @param {*} state The state of the variable to assign to this variable field. - * @override - * @package - */ -FieldVariable.prototype.loadState = function(state) { - if (this.loadLegacyState(FieldVariable, state)) { - return; - } - // This is necessary so that blocks in the flyout can have custom var names. - const variable = Variables.getOrCreateVariablePackage( - this.sourceBlock_.workspace, state['id'] || null, state['name'], - state['type'] || ''); - this.setValue(variable.getId()); -}; - -/** - * Attach this field to a block. - * @param {!Block} block The block containing this field. - */ -FieldVariable.prototype.setSourceBlock = function(block) { - if (block.isShadow()) { - throw Error('Variable fields are not allowed to exist on shadow blocks.'); - } - FieldVariable.superClass_.setSourceBlock.call(this, block); -}; - -/** - * Get the variable's ID. - * @return {string} Current variable's ID. - */ -FieldVariable.prototype.getValue = function() { - return this.variable_ ? this.variable_.getId() : null; -}; - -/** - * Get the text from this field, which is the selected variable's name. - * @return {string} The selected variable's name, or the empty string if no - * variable is selected. - */ -FieldVariable.prototype.getText = function() { - return this.variable_ ? this.variable_.name : ''; -}; - -/** - * Get the variable model for the selected variable. - * Not guaranteed to be in the variable map on the workspace (e.g. if accessed - * after the variable has been deleted). - * @return {?VariableModel} The selected variable, or null if none was - * selected. - * @package - */ -FieldVariable.prototype.getVariable = function() { - return this.variable_; -}; - -/** - * Gets the validation function for this field, or null if not set. - * Returns null if the variable is not set, because validators should not - * run on the initial setValue call, because the field won't be attached to - * a block and workspace at that point. - * @return {?Function} Validation function, or null. - */ -FieldVariable.prototype.getValidator = function() { - // Validators shouldn't operate on the initial setValue call. - // Normally this is achieved by calling setValidator after setValue, but - // this is not a possibility with variable fields. - if (this.variable_) { - return this.validator_; - } - return null; -}; - -/** - * Ensure that the ID belongs to a valid variable of an allowed type. - * @param {*=} opt_newValue The ID of the new variable to set. - * @return {?string} The validated ID, or null if invalid. - * @protected - */ -FieldVariable.prototype.doClassValidation_ = function(opt_newValue) { - if (opt_newValue === null) { - return null; - } - const newId = /** @type {string} */ (opt_newValue); - const variable = Variables.getVariable(this.sourceBlock_.workspace, newId); - if (!variable) { - console.warn( - 'Variable id doesn\'t point to a real variable! ' + - 'ID was ' + newId); - return null; - } - // Type Checks. - const type = variable.type; - if (!this.typeIsAllowed_(type)) { - console.warn('Variable type doesn\'t match this field! Type was ' + type); - return null; - } - return newId; -}; - -/** - * Update the value of this variable field, as well as its variable and text. - * - * The variable ID should be valid at this point, but if a variable field - * validator returns a bad ID, this could break. - * @param {*} newId The value to be saved. - * @protected - */ -FieldVariable.prototype.doValueUpdate_ = function(newId) { - this.variable_ = Variables.getVariable( - this.sourceBlock_.workspace, /** @type {string} */ (newId)); - FieldVariable.superClass_.doValueUpdate_.call(this, newId); -}; - -/** - * Check whether the given variable type is allowed on this field. - * @param {string} type The type to check. - * @return {boolean} True if the type is in the list of allowed types. - * @private - */ -FieldVariable.prototype.typeIsAllowed_ = function(type) { - const typeList = this.getVariableTypes_(); - if (!typeList) { - return true; // If it's null, all types are valid. - } - for (let i = 0; i < typeList.length; i++) { - if (type === typeList[i]) { - return true; + // This should never happen :) + if (variableType !== null && variableType !== variable.type) { + throw Error( + 'Serialized variable type with id \'' + variable.getId() + + '\' had type ' + variable.type + ', and ' + + 'does not match variable field that references it: ' + + Xml.domToText(fieldElement) + '.'); } - } - return false; -}; -/** - * Return a list of variable types to include in the dropdown. - * @return {!Array} Array of variable types. - * @throws {Error} if variableTypes is an empty array. - * @private - */ -FieldVariable.prototype.getVariableTypes_ = function() { - // TODO (#1513): Try to avoid calling this every time the field is edited. - let variableTypes = this.variableTypes; - if (variableTypes === null) { - // If variableTypes is null, return all variable types. - if (this.sourceBlock_ && this.sourceBlock_.workspace) { - return this.sourceBlock_.workspace.getVariableTypes(); + this.setValue(variable.getId()); + } + + /** + * Serialize this field to XML. + * @param {!Element} fieldElement The element to populate with info about the + * field's state. + * @return {!Element} The element containing info about the field's state. + */ + toXml(fieldElement) { + // Make sure the variable is initialized. + this.initModel(); + + fieldElement.id = this.variable_.getId(); + fieldElement.textContent = this.variable_.name; + if (this.variable_.type) { + fieldElement.setAttribute('variabletype', this.variable_.type); } + return fieldElement; } - variableTypes = variableTypes || ['']; - if (variableTypes.length === 0) { - // Throw an error if variableTypes is an empty list. - const name = this.getText(); - throw Error( - '\'variableTypes\' of field variable ' + name + ' was an empty list'); - } - return variableTypes; -}; -/** - * Parse the optional arguments representing the allowed variable types and the - * default variable type. - * @param {Array=} opt_variableTypes A list of the types of variables - * to include in the dropdown. If null or undefined, variables of all types - * will be displayed in the dropdown. - * @param {string=} opt_defaultType The type of the variable to create if this - * field's value is not explicitly set. Defaults to ''. - * @private - */ -FieldVariable.prototype.setTypes_ = function( - opt_variableTypes, opt_defaultType) { - // If you expected that the default type would be the same as the only entry - // in the variable types array, tell the Blockly team by commenting on #1499. - const defaultType = opt_defaultType || ''; - let variableTypes; - // Set the allowable variable types. Null means all types on the workspace. - if (opt_variableTypes === null || opt_variableTypes === undefined) { - variableTypes = null; - } else if (Array.isArray(opt_variableTypes)) { - variableTypes = opt_variableTypes; - // Make sure the default type is valid. - let isInArray = false; - for (let i = 0; i < variableTypes.length; i++) { - if (variableTypes[i] === defaultType) { - isInArray = true; + /** + * Saves this field's value. + * @param {boolean=} doFullSerialization If true, the variable field will + * serialize the full state of the field being referenced (ie ID, name, + * and type) rather than just a reference to it (ie ID). + * @return {*} The state of the variable field. + * @override + * @package + */ + saveState(doFullSerialization) { + const legacyState = this.saveLegacyState(FieldVariable); + if (legacyState !== null) { + return legacyState; + } + // Make sure the variable is initialized. + this.initModel(); + const state = {'id': this.variable_.getId()}; + if (doFullSerialization) { + state['name'] = this.variable_.name; + state['type'] = this.variable_.type; + } + return state; + } + + /** + * Sets the field's value based on the given state. + * @param {*} state The state of the variable to assign to this variable + * field. + * @override + * @package + */ + loadState(state) { + if (this.loadLegacyState(FieldVariable, state)) { + return; + } + // This is necessary so that blocks in the flyout can have custom var names. + const variable = Variables.getOrCreateVariablePackage( + this.sourceBlock_.workspace, state['id'] || null, state['name'], + state['type'] || ''); + this.setValue(variable.getId()); + } + + /** + * Attach this field to a block. + * @param {!Block} block The block containing this field. + */ + setSourceBlock(block) { + if (block.isShadow()) { + throw Error('Variable fields are not allowed to exist on shadow blocks.'); + } + super.setSourceBlock(block); + } + + /** + * Get the variable's ID. + * @return {?string} Current variable's ID. + */ + getValue() { + return this.variable_ ? this.variable_.getId() : null; + } + + /** + * Get the text from this field, which is the selected variable's name. + * @return {string} The selected variable's name, or the empty string if no + * variable is selected. + */ + getText() { + return this.variable_ ? this.variable_.name : ''; + } + + /** + * Get the variable model for the selected variable. + * Not guaranteed to be in the variable map on the workspace (e.g. if accessed + * after the variable has been deleted). + * @return {?VariableModel} The selected variable, or null if none was + * selected. + * @package + */ + getVariable() { + return this.variable_; + } + + /** + * Gets the validation function for this field, or null if not set. + * Returns null if the variable is not set, because validators should not + * run on the initial setValue call, because the field won't be attached to + * a block and workspace at that point. + * @return {?Function} Validation function, or null. + */ + getValidator() { + // Validators shouldn't operate on the initial setValue call. + // Normally this is achieved by calling setValidator after setValue, but + // this is not a possibility with variable fields. + if (this.variable_) { + return this.validator_; + } + return null; + } + + /** + * Ensure that the ID belongs to a valid variable of an allowed type. + * @param {*=} opt_newValue The ID of the new variable to set. + * @return {?string} The validated ID, or null if invalid. + * @protected + */ + doClassValidation_(opt_newValue) { + if (opt_newValue === null) { + return null; + } + const newId = /** @type {string} */ (opt_newValue); + const variable = Variables.getVariable(this.sourceBlock_.workspace, newId); + if (!variable) { + console.warn( + 'Variable id doesn\'t point to a real variable! ' + + 'ID was ' + newId); + return null; + } + // Type Checks. + const type = variable.type; + if (!this.typeIsAllowed_(type)) { + console.warn( + 'Variable type doesn\'t match this field! Type was ' + type); + return null; + } + return newId; + } + + /** + * Update the value of this variable field, as well as its variable and text. + * + * The variable ID should be valid at this point, but if a variable field + * validator returns a bad ID, this could break. + * @param {*} newId The value to be saved. + * @protected + */ + doValueUpdate_(newId) { + this.variable_ = Variables.getVariable( + this.sourceBlock_.workspace, /** @type {string} */ (newId)); + super.doValueUpdate_(newId); + } + + /** + * Check whether the given variable type is allowed on this field. + * @param {string} type The type to check. + * @return {boolean} True if the type is in the list of allowed types. + * @private + */ + typeIsAllowed_(type) { + const typeList = this.getVariableTypes_(); + if (!typeList) { + return true; // If it's null, all types are valid. + } + for (let i = 0; i < typeList.length; i++) { + if (type === typeList[i]) { + return true; } } - if (!isInArray) { + return false; + } + + /** + * Return a list of variable types to include in the dropdown. + * @return {!Array} Array of variable types. + * @throws {Error} if variableTypes is an empty array. + * @private + */ + getVariableTypes_() { + // TODO (#1513): Try to avoid calling this every time the field is edited. + let variableTypes = this.variableTypes; + if (variableTypes === null) { + // If variableTypes is null, return all variable types. + if (this.sourceBlock_ && this.sourceBlock_.workspace) { + return this.sourceBlock_.workspace.getVariableTypes(); + } + } + variableTypes = variableTypes || ['']; + if (variableTypes.length === 0) { + // Throw an error if variableTypes is an empty list. + const name = this.getText(); throw Error( - 'Invalid default type \'' + defaultType + '\' in ' + - 'the definition of a FieldVariable'); + '\'variableTypes\' of field variable ' + name + ' was an empty list'); } - } else { - throw Error( - '\'variableTypes\' was not an array in the definition of ' + - 'a FieldVariable'); + return variableTypes; } - // Only update the field once all checks pass. - this.defaultType_ = defaultType; - this.variableTypes = variableTypes; -}; -/** - * Refreshes the name of the variable by grabbing the name of the model. - * Used when a variable gets renamed, but the ID stays the same. Should only - * be called by the block. - * @package - */ -FieldVariable.prototype.refreshVariableName = function() { - this.forceRerender(); -}; - -/** - * Return a sorted list of variable names for variable dropdown menus. - * Include a special option at the end for creating a new variable name. - * @return {!Array} Array of variable names/id tuples. - * @this {FieldVariable} - */ -FieldVariable.dropdownCreate = function() { - if (!this.variable_) { - throw Error( - 'Tried to call dropdownCreate on a variable field with no' + - ' variable selected.'); - } - const name = this.getText(); - let variableModelList = []; - if (this.sourceBlock_ && this.sourceBlock_.workspace) { - const variableTypes = this.getVariableTypes_(); - // Get a copy of the list, so that adding rename and new variable options - // doesn't modify the workspace's list. - for (let i = 0; i < variableTypes.length; i++) { - const variableType = variableTypes[i]; - const variables = - this.sourceBlock_.workspace.getVariablesOfType(variableType); - variableModelList = variableModelList.concat(variables); + /** + * Parse the optional arguments representing the allowed variable types and + * the default variable type. + * @param {Array=} opt_variableTypes A list of the types of variables + * to include in the dropdown. If null or undefined, variables of all + * types will be displayed in the dropdown. + * @param {string=} opt_defaultType The type of the variable to create if this + * field's value is not explicitly set. Defaults to ''. + * @private + */ + setTypes_(opt_variableTypes, opt_defaultType) { + // If you expected that the default type would be the same as the only entry + // in the variable types array, tell the Blockly team by commenting on + // #1499. + const defaultType = opt_defaultType || ''; + let variableTypes; + // Set the allowable variable types. Null means all types on the workspace. + if (opt_variableTypes === null || opt_variableTypes === undefined) { + variableTypes = null; + } else if (Array.isArray(opt_variableTypes)) { + variableTypes = opt_variableTypes; + // Make sure the default type is valid. + let isInArray = false; + for (let i = 0; i < variableTypes.length; i++) { + if (variableTypes[i] === defaultType) { + isInArray = true; + } + } + if (!isInArray) { + throw Error( + 'Invalid default type \'' + defaultType + '\' in ' + + 'the definition of a FieldVariable'); + } + } else { + throw Error( + '\'variableTypes\' was not an array in the definition of ' + + 'a FieldVariable'); } - } - variableModelList.sort(VariableModel.compareByName); - - const options = []; - for (let i = 0; i < variableModelList.length; i++) { - // Set the UUID as the internal representation of the variable. - options[i] = [variableModelList[i].name, variableModelList[i].getId()]; - } - options.push([Msg['RENAME_VARIABLE'], internalConstants.RENAME_VARIABLE_ID]); - if (Msg['DELETE_VARIABLE']) { - options.push([ - Msg['DELETE_VARIABLE'].replace('%1', name), - internalConstants.DELETE_VARIABLE_ID, - ]); + // Only update the field once all checks pass. + this.defaultType_ = defaultType; + this.variableTypes = variableTypes; } - return options; -}; + /** + * Refreshes the name of the variable by grabbing the name of the model. + * Used when a variable gets renamed, but the ID stays the same. Should only + * be called by the block. + * @override + * @package + */ + refreshVariableName() { + this.forceRerender(); + } -/** - * Handle the selection of an item in the variable dropdown menu. - * Special case the 'Rename variable...' and 'Delete variable...' options. - * In the rename case, prompt the user for a new name. - * @param {!Menu} menu The Menu component clicked. - * @param {!MenuItem} menuItem The MenuItem selected within menu. - * @protected - */ -FieldVariable.prototype.onItemSelected_ = function(menu, menuItem) { - const id = menuItem.getValue(); - // Handle special cases. - if (this.sourceBlock_ && this.sourceBlock_.workspace) { - if (id === internalConstants.RENAME_VARIABLE_ID) { - // Rename variable. - Variables.renameVariable(this.sourceBlock_.workspace, this.variable_); - return; - } else if (id === internalConstants.DELETE_VARIABLE_ID) { - // Delete variable. - this.sourceBlock_.workspace.deleteVariableById(this.variable_.getId()); - return; + /** + * Handle the selection of an item in the variable dropdown menu. + * Special case the 'Rename variable...' and 'Delete variable...' options. + * In the rename case, prompt the user for a new name. + * @param {!Menu} menu The Menu component clicked. + * @param {!MenuItem} menuItem The MenuItem selected within menu. + * @protected + */ + onItemSelected_(menu, menuItem) { + const id = menuItem.getValue(); + // Handle special cases. + if (this.sourceBlock_ && this.sourceBlock_.workspace) { + if (id === internalConstants.RENAME_VARIABLE_ID) { + // Rename variable. + Variables.renameVariable( + this.sourceBlock_.workspace, + /** @type {!VariableModel} */ (this.variable_)); + return; + } else if (id === internalConstants.DELETE_VARIABLE_ID) { + // Delete variable. + this.sourceBlock_.workspace.deleteVariableById(this.variable_.getId()); + return; + } } + // Handle unspecial case. + this.setValue(id); } - // Handle unspecial case. - this.setValue(id); -}; -/** - * Overrides referencesVariables(), indicating this field refers to a variable. - * @return {boolean} True. - * @package - * @override - */ -FieldVariable.prototype.referencesVariables = function() { - return true; -}; + /** + * Overrides referencesVariables(), indicating this field refers to a + * variable. + * @return {boolean} True. + * @package + * @override + */ + referencesVariables() { + return true; + } + + /** + * Construct a FieldVariable from a JSON arg object, + * dereferencing any string table references. + * @param {!Object} options A JSON object with options (variable, + * variableTypes, and defaultType). + * @return {!FieldVariable} The new field instance. + * @package + * @nocollapse + * @override + */ + static fromJson(options) { + const varName = parsing.replaceMessageReferences(options['variable']); + // `this` might be a subclass of FieldVariable if that class doesn't + // override the static fromJson method. + return new this(varName, undefined, undefined, undefined, options); + } + + /** + * Return a sorted list of variable names for variable dropdown menus. + * Include a special option at the end for creating a new variable name. + * @return {!Array} Array of variable names/id tuples. + * @this {FieldVariable} + */ + static dropdownCreate() { + if (!this.variable_) { + throw Error( + 'Tried to call dropdownCreate on a variable field with no' + + ' variable selected.'); + } + const name = this.getText(); + let variableModelList = []; + if (this.sourceBlock_ && this.sourceBlock_.workspace) { + const variableTypes = this.getVariableTypes_(); + // Get a copy of the list, so that adding rename and new variable options + // doesn't modify the workspace's list. + for (let i = 0; i < variableTypes.length; i++) { + const variableType = variableTypes[i]; + const variables = + this.sourceBlock_.workspace.getVariablesOfType(variableType); + variableModelList = variableModelList.concat(variables); + } + } + variableModelList.sort(VariableModel.compareByName); + + const options = []; + for (let i = 0; i < variableModelList.length; i++) { + // Set the UUID as the internal representation of the variable. + options[i] = [variableModelList[i].name, variableModelList[i].getId()]; + } + options.push( + [Msg['RENAME_VARIABLE'], internalConstants.RENAME_VARIABLE_ID]); + if (Msg['DELETE_VARIABLE']) { + options.push([ + Msg['DELETE_VARIABLE'].replace('%1', name), + internalConstants.DELETE_VARIABLE_ID, + ]); + } + + return options; + } +} fieldRegistry.register('field_variable', FieldVariable); diff --git a/core/utils/sentinel.js b/core/utils/sentinel.js new file mode 100644 index 000000000..66fa48e68 --- /dev/null +++ b/core/utils/sentinel.js @@ -0,0 +1,24 @@ +/** + * @license + * Copyright 2022 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ + +/** + * @fileoverview A type used to create flag values (e.g. SKIP_SETUP). + */ +'use strict'; + +/** + * A type used to create flag values. + * @class + */ +goog.module('Blockly.utils.Sentinel'); + + +/** + * A type used to create flag values. + */ +class Sentinel {} + +exports.Sentinel = Sentinel; diff --git a/scripts/gulpfiles/chunks.json b/scripts/gulpfiles/chunks.json index 79331823a..72c0d27c8 100644 --- a/scripts/gulpfiles/chunks.json +++ b/scripts/gulpfiles/chunks.json @@ -1,6 +1,6 @@ { "chunk": [ - "blockly:259", + "blockly:260", "blocks:10:blockly", "all:11:blockly", "all1:11:blockly", @@ -21,7 +21,6 @@ "./core/field_number.js", "./core/field_multilineinput.js", "./core/field_label_serializable.js", - "./core/field_dropdown.js", "./core/field_colour.js", "./core/field_checkbox.js", "./core/field_angle.js", @@ -57,8 +56,6 @@ "./core/contextmenu_items.js", "./core/widgetdiv.js", "./core/clipboard.js", - "./core/menuitem.js", - "./core/menu.js", "./core/contextmenu.js", "./core/utils/global.js", "./core/utils/useragent.js", @@ -80,16 +77,23 @@ "./core/utils/math.js", "./core/utils/array.js", "./core/workspace.js", - "./core/keyboard_nav/basic_cursor.js", - "./core/keyboard_nav/tab_navigate_cursor.js", - "./core/warning.js", - "./core/comment.js", + "./core/menu.js", + "./core/menuitem.js", + "./core/interfaces/i_registrable_field.js", + "./core/shortcut_registry.js", + "./core/interfaces/i_keyboard_accessible.js", "./core/events/events_block_drag.js", - "./core/events/events_block_move.js", "./core/bump_objects.js", "./core/block_dragger.js", "./core/workspace_dragger.js", "./core/interfaces/i_block_dragger.js", + "./core/bubble_dragger.js", + "./core/keyboard_nav/basic_cursor.js", + "./core/keyboard_nav/tab_navigate_cursor.js", + "./core/mutator.js", + "./core/warning.js", + "./core/comment.js", + "./core/events/events_block_move.js", "./core/events/events_viewport.js", "./core/events/events_theme_change.js", "./core/events/events_block_create.js", @@ -119,10 +123,12 @@ "./core/theme_manager.js", "./core/scrollbar_pair.js", "./core/options.js", + "./core/marker_manager.js", "./core/interfaces/i_bounded_element.js", "./core/grid.js", "./core/css.js", "./core/flyout_button.js", + "./core/keyboard_nav/cursor.js", "./core/contextmenu_registry.js", "./core/theme/classic.js", "./core/blockly_options.js", @@ -134,7 +140,8 @@ "./core/renderers/zelos/path_object.js", "./core/renderers/zelos/drawer.js", "./core/renderers/zelos/renderer.js", - "./core/utils/aria.js", + "./core/utils/keycodes.js", + "./core/dropdowndiv.js", "./core/field_textinput.js", "./core/field_image.js", "./core/renderers/zelos/constants.js", @@ -145,6 +152,13 @@ "./core/renderers/measurables/spacer_row.js", "./core/renderers/measurables/round_corner.js", "./core/renderers/common/path_object.js", + "./core/events/events_marker_move.js", + "./core/keyboard_nav/marker.js", + "./core/interfaces/i_ast_node_location_svg.js", + "./core/interfaces/i_ast_node_location.js", + "./core/interfaces/i_ast_node_location_with_block.js", + "./core/keyboard_nav/ast_node.js", + "./core/renderers/common/marker_svg.js", "./core/interfaces/i_positionable.js", "./core/interfaces/i_drag_target.js", "./core/interfaces/i_delete_area.js", @@ -166,6 +180,7 @@ "./core/interfaces/i_toolbox.js", "./core/utils/metrics.js", "./core/interfaces/i_metrics_manager.js", + "./core/interfaces/i_registrable.js", "./core/interfaces/i_flyout.js", "./core/metrics_manager.js", "./core/interfaces/i_deletable.js", @@ -181,6 +196,10 @@ "./core/renderers/common/info.js", "./core/renderers/measurables/field.js", "./core/renderers/common/debugger.js", + "./core/utils/sentinel.js", + "./core/field_label.js", + "./core/input_types.js", + "./core/input.js", "./core/renderers/measurables/input_connection.js", "./core/renderers/measurables/in_row_spacer.js", "./core/renderers/measurables/row.js", @@ -188,42 +207,23 @@ "./core/renderers/measurables/base.js", "./core/renderers/measurables/connection.js", "./core/renderers/measurables/next_connection.js", - "./core/renderers/measurables/bottom_row.js", - "./core/renderers/common/debug.js", - "./core/renderers/common/block_rendering.js", - "./core/variables_dynamic.js", - "./core/events/events_var_rename.js", - "./core/events/events_var_delete.js", - "./core/variable_map.js", - "./core/names.js", - "./core/events/events_marker_move.js", - "./core/renderers/common/marker_svg.js", - "./core/keyboard_nav/marker.js", - "./core/keyboard_nav/ast_node.js", - "./core/keyboard_nav/cursor.js", - "./core/marker_manager.js", - "./core/field_label.js", - "./core/input_types.js", - "./core/interfaces/i_registrable_field.js", - "./core/field_registry.js", - "./core/input.js", - "./core/interfaces/i_registrable.js", - "./core/utils/keycodes.js", - "./core/shortcut_registry.js", - "./core/interfaces/i_keyboard_accessible.js", - "./core/interfaces/i_ast_node_location_with_block.js", - "./core/interfaces/i_ast_node_location.js", - "./core/interfaces/i_ast_node_location_svg.js", - "./core/dropdowndiv.js", "./core/theme.js", - "./core/constants.js", "./core/interfaces/i_connection_checker.js", "./core/connection_db.js", "./core/config.js", "./core/rendered_connection.js", "./core/utils/svg_paths.js", "./core/renderers/common/constants.js", - "./core/field.js", + "./core/renderers/measurables/bottom_row.js", + "./core/renderers/common/debug.js", + "./core/renderers/common/block_rendering.js", + "./core/variables_dynamic.js", + "./core/events/events_block_base.js", + "./core/events/events_block_change.js", + "./core/events/events_var_rename.js", + "./core/events/events_var_delete.js", + "./core/variable_map.js", + "./core/names.js", "./core/events/events_ui_base.js", "./core/events/events_bubble_open.js", "./core/procedures.js", @@ -234,31 +234,32 @@ "./core/utils/style.js", "./core/utils/deprecation.js", "./core/utils/svg_math.js", - "./core/bubble_dragger.js", "./core/connection_type.js", "./core/internal_constants.js", + "./core/constants.js", + "./core/block_svg.js", "./core/block_animations.js", "./core/gesture.js", "./core/touch.js", "./core/browser_events.js", "./core/tooltip.js", - "./core/block_svg.js", - "./core/events/events_block_base.js", - "./core/events/events_block_change.js", - "./core/utils/xml.js", - "./core/mutator.js", + "./core/field.js", + "./core/field_registry.js", + "./core/utils/aria.js", + "./core/field_dropdown.js", "./core/msg.js", "./core/utils/colour.js", "./core/utils/parsing.js", "./core/extensions.js", "./core/block.js", "./core/utils/string.js", + "./core/utils/object.js", "./core/dialog.js", + "./core/utils/xml.js", "./core/events/events_var_base.js", "./core/events/events_var_create.js", "./core/variable_model.js", "./core/variables.js", - "./core/utils/object.js", "./core/events/events_abstract.js", "./core/registry.js", "./core/events/utils.js", diff --git a/tests/deps.js b/tests/deps.js index 96699e744..3d6cad703 100644 --- a/tests/deps.js +++ b/tests/deps.js @@ -67,20 +67,20 @@ goog.addDependency('../../core/events/events_var_rename.js', ['Blockly.Events.Va goog.addDependency('../../core/events/events_viewport.js', ['Blockly.Events.ViewportChange'], ['Blockly.Events.UiBase', 'Blockly.Events.utils', 'Blockly.registry'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/events/utils.js', ['Blockly.Events.utils'], ['Blockly.registry', 'Blockly.utils.idGenerator'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/events/workspace_events.js', ['Blockly.Events.FinishedLoading'], ['Blockly.Events.Abstract', 'Blockly.Events.utils', 'Blockly.registry'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/extensions.js', ['Blockly.Extensions'], ['Blockly.utils.parsing'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/field.js', ['Blockly.Field'], ['Blockly.DropDownDiv', 'Blockly.Events.BlockChange', 'Blockly.Events.utils', 'Blockly.Gesture', 'Blockly.IASTNodeLocationSvg', 'Blockly.IASTNodeLocationWithBlock', 'Blockly.IKeyboardAccessible', 'Blockly.IRegistrable', 'Blockly.MarkerManager', 'Blockly.Tooltip', 'Blockly.WidgetDiv', 'Blockly.Xml', 'Blockly.browserEvents', 'Blockly.utils.Rect', 'Blockly.utils.Size', 'Blockly.utils.Svg', 'Blockly.utils.dom', 'Blockly.utils.parsing', 'Blockly.utils.style', 'Blockly.utils.userAgent', 'Blockly.utils.xml'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/field_angle.js', ['Blockly.FieldAngle'], ['Blockly.Css', 'Blockly.DropDownDiv', 'Blockly.FieldTextInput', 'Blockly.WidgetDiv', 'Blockly.browserEvents', 'Blockly.fieldRegistry', 'Blockly.utils.KeyCodes', 'Blockly.utils.Svg', 'Blockly.utils.dom', 'Blockly.utils.math', 'Blockly.utils.object', 'Blockly.utils.userAgent'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/field_checkbox.js', ['Blockly.FieldCheckbox'], ['Blockly.Events.BlockChange', 'Blockly.Field', 'Blockly.fieldRegistry', 'Blockly.utils.dom', 'Blockly.utils.object'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/field_colour.js', ['Blockly.FieldColour'], ['Blockly.Css', 'Blockly.DropDownDiv', 'Blockly.Events.BlockChange', 'Blockly.Field', 'Blockly.browserEvents', 'Blockly.fieldRegistry', 'Blockly.utils.KeyCodes', 'Blockly.utils.Size', 'Blockly.utils.aria', 'Blockly.utils.colour', 'Blockly.utils.dom', 'Blockly.utils.idGenerator', 'Blockly.utils.object'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/field_dropdown.js', ['Blockly.FieldDropdown'], ['Blockly.DropDownDiv', 'Blockly.Field', 'Blockly.Menu', 'Blockly.MenuItem', 'Blockly.fieldRegistry', 'Blockly.utils.Coordinate', 'Blockly.utils.Svg', 'Blockly.utils.aria', 'Blockly.utils.dom', 'Blockly.utils.object', 'Blockly.utils.parsing', 'Blockly.utils.string', 'Blockly.utils.userAgent'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/field_image.js', ['Blockly.FieldImage'], ['Blockly.Field', 'Blockly.fieldRegistry', 'Blockly.utils.Size', 'Blockly.utils.Svg', 'Blockly.utils.dom', 'Blockly.utils.object', 'Blockly.utils.parsing'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/field_label.js', ['Blockly.FieldLabel'], ['Blockly.Field', 'Blockly.fieldRegistry', 'Blockly.utils.dom', 'Blockly.utils.object', 'Blockly.utils.parsing'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/field_label_serializable.js', ['Blockly.FieldLabelSerializable'], ['Blockly.FieldLabel', 'Blockly.fieldRegistry', 'Blockly.utils.parsing'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/extensions.js', ['Blockly.Extensions'], ['Blockly.FieldDropdown', 'Blockly.utils.parsing'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/field.js', ['Blockly.Field'], ['Blockly.DropDownDiv', 'Blockly.Events.BlockChange', 'Blockly.Events.utils', 'Blockly.Gesture', 'Blockly.IASTNodeLocationSvg', 'Blockly.IASTNodeLocationWithBlock', 'Blockly.IKeyboardAccessible', 'Blockly.IRegistrable', 'Blockly.MarkerManager', 'Blockly.Tooltip', 'Blockly.WidgetDiv', 'Blockly.Xml', 'Blockly.browserEvents', 'Blockly.utils.Rect', 'Blockly.utils.Sentinel', 'Blockly.utils.Size', 'Blockly.utils.Svg', 'Blockly.utils.dom', 'Blockly.utils.parsing', 'Blockly.utils.style', 'Blockly.utils.userAgent', 'Blockly.utils.xml'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/field_angle.js', ['Blockly.FieldAngle'], ['Blockly.Css', 'Blockly.DropDownDiv', 'Blockly.Field', 'Blockly.FieldTextInput', 'Blockly.WidgetDiv', 'Blockly.browserEvents', 'Blockly.fieldRegistry', 'Blockly.utils.KeyCodes', 'Blockly.utils.Svg', 'Blockly.utils.dom', 'Blockly.utils.math', 'Blockly.utils.userAgent'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/field_checkbox.js', ['Blockly.FieldCheckbox'], ['Blockly.Events.BlockChange', 'Blockly.Field', 'Blockly.fieldRegistry', 'Blockly.utils.dom'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/field_colour.js', ['Blockly.FieldColour'], ['Blockly.Css', 'Blockly.DropDownDiv', 'Blockly.Events.BlockChange', 'Blockly.Field', 'Blockly.browserEvents', 'Blockly.fieldRegistry', 'Blockly.utils.KeyCodes', 'Blockly.utils.Size', 'Blockly.utils.aria', 'Blockly.utils.colour', 'Blockly.utils.dom', 'Blockly.utils.idGenerator'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/field_dropdown.js', ['Blockly.FieldDropdown'], ['Blockly.DropDownDiv', 'Blockly.Field', 'Blockly.Menu', 'Blockly.MenuItem', 'Blockly.fieldRegistry', 'Blockly.utils.Coordinate', 'Blockly.utils.Svg', 'Blockly.utils.aria', 'Blockly.utils.dom', 'Blockly.utils.parsing', 'Blockly.utils.string', 'Blockly.utils.userAgent'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/field_image.js', ['Blockly.FieldImage'], ['Blockly.Field', 'Blockly.fieldRegistry', 'Blockly.utils.Size', 'Blockly.utils.Svg', 'Blockly.utils.dom', 'Blockly.utils.parsing'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/field_label.js', ['Blockly.FieldLabel'], ['Blockly.Field', 'Blockly.fieldRegistry', 'Blockly.utils.dom', 'Blockly.utils.parsing'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/field_label_serializable.js', ['Blockly.FieldLabelSerializable'], ['Blockly.FieldLabel', 'Blockly.fieldRegistry', 'Blockly.utils.parsing'], {'lang': 'es_2020', 'module': 'goog'}); goog.addDependency('../../core/field_multilineinput.js', ['Blockly.FieldMultilineInput'], ['Blockly.Css', 'Blockly.Field', 'Blockly.FieldTextInput', 'Blockly.WidgetDiv', 'Blockly.fieldRegistry', 'Blockly.utils.KeyCodes', 'Blockly.utils.Svg', 'Blockly.utils.aria', 'Blockly.utils.dom', 'Blockly.utils.parsing', 'Blockly.utils.userAgent'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/field_number.js', ['Blockly.FieldNumber'], ['Blockly.FieldTextInput', 'Blockly.fieldRegistry', 'Blockly.utils.aria', 'Blockly.utils.object'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/field_number.js', ['Blockly.FieldNumber'], ['Blockly.Field', 'Blockly.FieldTextInput', 'Blockly.fieldRegistry', 'Blockly.utils.aria'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/field_registry.js', ['Blockly.fieldRegistry'], ['Blockly.registry'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/field_textinput.js', ['Blockly.FieldTextInput'], ['Blockly.DropDownDiv', 'Blockly.Events.BlockChange', 'Blockly.Events.utils', 'Blockly.Field', 'Blockly.Msg', 'Blockly.WidgetDiv', 'Blockly.browserEvents', 'Blockly.dialog', 'Blockly.fieldRegistry', 'Blockly.utils.Coordinate', 'Blockly.utils.KeyCodes', 'Blockly.utils.aria', 'Blockly.utils.dom', 'Blockly.utils.object', 'Blockly.utils.parsing', 'Blockly.utils.userAgent'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/field_variable.js', ['Blockly.FieldVariable'], ['Blockly.Events.BlockChange', 'Blockly.FieldDropdown', 'Blockly.Msg', 'Blockly.VariableModel', 'Blockly.Variables', 'Blockly.Xml', 'Blockly.fieldRegistry', 'Blockly.internalConstants', 'Blockly.utils.Size', 'Blockly.utils.object', 'Blockly.utils.parsing'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/field_textinput.js', ['Blockly.FieldTextInput'], ['Blockly.DropDownDiv', 'Blockly.Events.BlockChange', 'Blockly.Events.utils', 'Blockly.Field', 'Blockly.Msg', 'Blockly.WidgetDiv', 'Blockly.browserEvents', 'Blockly.dialog', 'Blockly.fieldRegistry', 'Blockly.utils.Coordinate', 'Blockly.utils.KeyCodes', 'Blockly.utils.aria', 'Blockly.utils.dom', 'Blockly.utils.parsing', 'Blockly.utils.userAgent'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/field_variable.js', ['Blockly.FieldVariable'], ['Blockly.Events.BlockChange', 'Blockly.Field', 'Blockly.FieldDropdown', 'Blockly.Msg', 'Blockly.VariableModel', 'Blockly.Variables', 'Blockly.Xml', 'Blockly.fieldRegistry', 'Blockly.internalConstants', 'Blockly.utils.Size', 'Blockly.utils.parsing'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/flyout_base.js', ['Blockly.Flyout'], ['Blockly.ComponentManager', 'Blockly.DeleteArea', 'Blockly.Events.BlockCreate', 'Blockly.Events.VarCreate', 'Blockly.Events.utils', 'Blockly.FlyoutMetricsManager', 'Blockly.Gesture', 'Blockly.IFlyout', 'Blockly.ScrollbarPair', 'Blockly.Tooltip', 'Blockly.Touch', 'Blockly.Variables', 'Blockly.WorkspaceSvg', 'Blockly.Xml', 'Blockly.blockRendering', 'Blockly.browserEvents', 'Blockly.common', 'Blockly.serialization.blocks', 'Blockly.utils.Coordinate', 'Blockly.utils.Rect', 'Blockly.utils.Svg', 'Blockly.utils.dom', 'Blockly.utils.idGenerator', 'Blockly.utils.toolbox'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/flyout_button.js', ['Blockly.FlyoutButton'], ['Blockly.Css', 'Blockly.browserEvents', 'Blockly.utils.Coordinate', 'Blockly.utils.Svg', 'Blockly.utils.dom', 'Blockly.utils.parsing', 'Blockly.utils.style'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/flyout_horizontal.js', ['Blockly.HorizontalFlyout'], ['Blockly.DropDownDiv', 'Blockly.Flyout', 'Blockly.Scrollbar', 'Blockly.WidgetDiv', 'Blockly.browserEvents', 'Blockly.registry', 'Blockly.utils.Rect', 'Blockly.utils.toolbox'], {'lang': 'es6', 'module': 'goog'}); @@ -242,6 +242,7 @@ goog.addDependency('../../core/utils/metrics.js', ['Blockly.utils.Metrics'], [], goog.addDependency('../../core/utils/object.js', ['Blockly.utils.object'], [], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/utils/parsing.js', ['Blockly.utils.parsing'], ['Blockly.Msg', 'Blockly.utils.colour', 'Blockly.utils.string'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/utils/rect.js', ['Blockly.utils.Rect'], [], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/utils/sentinel.js', ['Blockly.utils.Sentinel'], [], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/utils/size.js', ['Blockly.utils.Size'], [], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/utils/string.js', ['Blockly.utils.string'], [], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/utils/style.js', ['Blockly.utils.style'], ['Blockly.utils.Coordinate', 'Blockly.utils.Size'], {'lang': 'es6', 'module': 'goog'}); diff --git a/tests/mocha/field_registry_test.js b/tests/mocha/field_registry_test.js index 0e49b5620..0df2f6bd0 100644 --- a/tests/mocha/field_registry_test.js +++ b/tests/mocha/field_registry_test.js @@ -10,13 +10,15 @@ const {createDeprecationWarningStub, sharedTestSetup, sharedTestTeardown} = goog suite('Field Registry', function() { - function CustomFieldType(value) { - CustomFieldType.superClass_.constructor.call(this, value); + class CustomFieldType extends Blockly.Field { + constructor(value) { + super(value); + } + + static fromJson(options) { + return new CustomFieldType(options['value']); + } } - Blockly.utils.object.inherits(CustomFieldType, Blockly.Field); - CustomFieldType.fromJson = function(options) { - return new CustomFieldType(options['value']); - }; setup(function() { sharedTestSetup.call(this); diff --git a/tests/mocha/field_test.js b/tests/mocha/field_test.js index 6ef1cbf24..0ba6a9e98 100644 --- a/tests/mocha/field_test.js +++ b/tests/mocha/field_test.js @@ -20,29 +20,40 @@ suite('Abstract Fields', function() { suite('Is Serializable', function() { // Both EDITABLE and SERIALIZABLE are default. - function FieldDefault() { - this.name = 'NAME'; + class FieldDefault extends Blockly.Field { + constructor() { + super(); + this.name = 'NAME'; + } } - FieldDefault.prototype = Object.create(Blockly.Field.prototype); + // EDITABLE is false and SERIALIZABLE is default. - function FieldFalseDefault() { - this.name = 'NAME'; + class FieldFalseDefault extends Blockly.Field { + constructor() { + super(); + this.name = 'NAME'; + this.EDITABLE = false; + } } - FieldFalseDefault.prototype = Object.create(Blockly.Field.prototype); - FieldFalseDefault.prototype.EDITABLE = false; + // EDITABLE is default and SERIALIZABLE is true. - function FieldDefaultTrue() { - this.name = 'NAME'; + class FieldDefaultTrue extends Blockly.Field { + constructor() { + super(); + this.name = 'NAME'; + this.SERIALIZABLE = true; + } } - FieldDefaultTrue.prototype = Object.create(Blockly.Field.prototype); - FieldDefaultTrue.prototype.SERIALIZABLE = true; + // EDITABLE is false and SERIALIZABLE is true. - function FieldFalseTrue() { - this.name = 'NAME'; + class FieldFalseTrue extends Blockly.Field { + constructor() { + super(); + this.name = 'NAME'; + this.EDITABLE = false; + this.SERIALIZABLE = true; + } } - FieldFalseTrue.prototype = Object.create(Blockly.Field.prototype); - FieldFalseTrue.prototype.EDITABLE = false; - FieldFalseTrue.prototype.SERIALIZABLE = true; /* Test Backwards Compatibility */ test('Editable Default(true), Serializable Default(false)', function() { @@ -585,14 +596,15 @@ suite('Abstract Fields', function() { suite('Customization', function() { // All this field does is wrap the abstract field. - function CustomField(opt_config) { - CustomField.superClass_.constructor.call( - this, 'value', null, opt_config); + class CustomField extends Blockly.Field { + constructor(opt_config) { + super('value', null, opt_config); + } + + static fromJson(options) { + return new CustomField(options); + } } - Blockly.utils.object.inherits(CustomField, Blockly.Field); - CustomField.fromJson = function(options) { - return new CustomField(options); - }; suite('Tooltip', function() { test('JS Constructor', function() { From fa14e9d6de5e22f204acf5055e7612889ca8ffdf Mon Sep 17 00:00:00 2001 From: Beka Westberg Date: Mon, 28 Feb 2022 09:48:37 -0800 Subject: [PATCH 089/128] refactor: convert blocksvg and block to ES6 classes (#5952) * refact: move super call to top of block svg * refact: run conversion script on block svg and block * fix: make debug build happy * fix: tests * style: format * fix: cleanup from rebase * fix: use new.target instead of a new parameter * fix: add more overridden casted methods to BlockSvg * style: fix typos * style: move override tags to the end of JSDoc * fix: cleanup from rebase --- core/block.js | 4179 ++++++++++++------------ core/block_dragger.js | 3 +- core/block_svg.js | 3421 +++++++++---------- core/comment.js | 1 - core/contextmenu.js | 5 +- core/contextmenu_items.js | 3 +- core/events/events_block_change.js | 7 +- core/extensions.js | 4 +- core/flyout_base.js | 10 +- core/flyout_horizontal.js | 4 +- core/flyout_vertical.js | 4 +- core/mutator.js | 6 +- core/procedures.js | 28 +- core/rendered_connection.js | 28 +- core/renderers/common/i_path_object.js | 4 +- core/renderers/common/path_object.js | 4 +- core/serialization/blocks.js | 19 +- core/workspace_svg.js | 14 +- core/xml.js | 25 +- scripts/gulpfiles/chunks.json | 2 +- tests/deps.js | 2 +- tests/mocha/extensions_test.js | 4 +- 22 files changed, 3987 insertions(+), 3790 deletions(-) diff --git a/core/block.js b/core/block.js index 3c6a75414..134ce88ab 100644 --- a/core/block.js +++ b/core/block.js @@ -64,306 +64,2146 @@ goog.require('Blockly.Events.BlockMove'); /** * Class for one block. * Not normally called directly, workspace.newBlock() is preferred. - * @param {!Workspace} workspace The block's workspace. - * @param {!string} prototypeName Name of the language object containing - * type-specific functions for this block. - * @param {string=} opt_id Optional ID. Use this ID if provided, otherwise - * create a new ID. - * @constructor * @implements {IASTNodeLocation} * @implements {IDeletable} - * @throws When the prototypeName is not valid or not allowed. - * @alias Blockly.Block + * @unrestricted */ -const Block = function(workspace, prototypeName, opt_id) { - const {Generator} = goog.module.get('Blockly.Generator'); - if (Generator && typeof Generator.prototype[prototypeName] !== 'undefined') { - // Occluding Generator class members is not allowed. - throw Error( - 'Block prototypeName "' + prototypeName + - '" conflicts with Blockly.Generator members.'); - } - +class Block { /** - * Optional text data that round-trips between blocks and XML. - * Has no effect. May be used by 3rd parties for meta information. - * @type {?string} + * @param {!Workspace} workspace The block's workspace. + * @param {!string} prototypeName Name of the language object containing + * type-specific functions for this block. + * @param {string=} opt_id Optional ID. Use this ID if provided, otherwise + * create a new ID. + * @throws When the prototypeName is not valid or not allowed. + * @alias Blockly.Block */ - this.data = null; - - /** - * Has this block been disposed of? - * @type {boolean} - * @package - */ - this.disposed = false; - - /** - * Colour of the block as HSV hue value (0-360) - * This may be null if the block colour was not set via a hue number. - * @type {?number} - * @private - */ - this.hue_ = null; - - /** - * Colour of the block in '#RRGGBB' format. - * @type {string} - * @protected - */ - this.colour_ = '#000000'; - - /** - * Name of the block style. - * @type {string} - * @protected - */ - this.styleName_ = ''; - - /** - * An optional method called during initialization. - * @type {undefined|?function()} - */ - this.init = undefined; - - /** - * An optional serialization method for defining how to serialize the - * mutation state to XML. This must be coupled with defining `domToMutation`. - * @type {undefined|?function(...):!Element} - */ - this.mutationToDom = undefined; - - /** - * An optional deserialization method for defining how to deserialize the - * mutation state from XML. This must be coupled with defining - * `mutationToDom`. - * @type {undefined|?function(!Element)} - */ - this.domToMutation = undefined; - - /** - * An optional serialization method for defining how to serialize the block's - * extra state (eg mutation state) to something JSON compatible. This must be - * coupled with defining `loadExtraState`. - * @type {undefined|?function(): *} - */ - this.saveExtraState = undefined; - - /** - * An optional serialization method for defining how to deserialize the - * block's extra state (eg mutation state) from something JSON compatible. - * This must be coupled with defining `saveExtraState`. - * @type {undefined|?function(*)} - */ - this.loadExtraState = undefined; - - /** - * An optional property for suppressing adding STATEMENT_PREFIX and - * STATEMENT_SUFFIX to generated code. - * @type {?boolean} - */ - this.suppressPrefixSuffix = false; - - /** - * An optional property for declaring developer variables. Return a list of - * variable names for use by generators. Developer variables are never shown - * to the user, but are declared as global variables in the generated code. - * @type {undefined|?function():!Array} - */ - this.getDeveloperVariables = undefined; - - /** @type {string} */ - this.id = (opt_id && !workspace.getBlockById(opt_id)) ? opt_id : - idGenerator.genUid(); - workspace.setBlockById(this.id, this); - /** @type {Connection} */ - this.outputConnection = null; - /** @type {Connection} */ - this.nextConnection = null; - /** @type {Connection} */ - this.previousConnection = null; - /** @type {!Array} */ - this.inputList = []; - /** @type {boolean|undefined} */ - this.inputsInline = undefined; - /** - * @type {boolean} - * @private - */ - this.disabled = false; - /** @type {!Tooltip.TipInfo} */ - this.tooltip = ''; - /** @type {boolean} */ - this.contextMenu = true; - - /** - * @type {Block} - * @protected - */ - this.parentBlock_ = null; - - /** - * @type {!Array} - * @protected - */ - this.childBlocks_ = []; - - /** - * @type {boolean} - * @private - */ - this.deletable_ = true; - - /** - * @type {boolean} - * @private - */ - this.movable_ = true; - - /** - * @type {boolean} - * @private - */ - this.editable_ = true; - - /** - * @type {boolean} - * @private - */ - this.isShadow_ = false; - - /** - * @type {boolean} - * @protected - */ - this.collapsed_ = false; - - /** - * @type {?number} - * @protected - */ - this.outputShape_ = null; - - /** - * A string representing the comment attached to this block. - * @type {string|Comment} - * @deprecated August 2019. Use getCommentText instead. - */ - this.comment = null; - - /** - * A model of the comment attached to this block. - * @type {!Block.CommentModel} - * @package - */ - this.commentModel = {text: null, pinned: false, size: new Size(160, 80)}; - - /** - * The block's position in workspace units. (0, 0) is at the workspace's - * origin; scale does not change this value. - * @type {!Coordinate} - * @private - */ - this.xy_ = new Coordinate(0, 0); - - /** @type {!Workspace} */ - this.workspace = workspace; - /** @type {boolean} */ - this.isInFlyout = workspace.isFlyout; - /** @type {boolean} */ - this.isInMutator = workspace.isMutator; - - /** @type {boolean} */ - this.RTL = workspace.RTL; - - /** - * True if this block is an insertion marker. - * @type {boolean} - * @protected - */ - this.isInsertionMarker_ = false; - - /** - * Name of the type of hat. - * @type {string|undefined} - */ - this.hat = undefined; - - /** @type {?boolean} */ - this.rendered = null; - - /** - * String for block help, or function that returns a URL. Null for no help. - * @type {string|Function} - */ - this.helpUrl = null; - - /** - * A bound callback function to use when the parent workspace changes. - * @type {?function(Abstract)} - * @private - */ - this.onchangeWrapper_ = null; - - /** - * A count of statement inputs on the block. - * @type {number} - * @package - */ - this.statementInputCount = 0; - - // Copy the type-specific functions and data from the prototype. - if (prototypeName) { - /** @type {string} */ - this.type = prototypeName; - const prototype = Blocks[prototypeName]; - if (!prototype || typeof prototype !== 'object') { - throw TypeError('Invalid block definition for type: ' + prototypeName); + constructor(workspace, prototypeName, opt_id) { + const {Generator} = goog.module.get('Blockly.Generator'); + if (Generator && + typeof Generator.prototype[prototypeName] !== 'undefined') { + // Occluding Generator class members is not allowed. + throw Error( + 'Block prototypeName "' + prototypeName + + '" conflicts with Blockly.Generator members.'); } - object.mixin(this, prototype); + + /** + * Optional text data that round-trips between blocks and XML. + * Has no effect. May be used by 3rd parties for meta information. + * @type {?string} + */ + this.data = null; + + /** + * Has this block been disposed of? + * @type {boolean} + * @package + */ + this.disposed = false; + + /** + * Colour of the block as HSV hue value (0-360) + * This may be null if the block colour was not set via a hue number. + * @type {?number} + * @private + */ + this.hue_ = null; + + /** + * Colour of the block in '#RRGGBB' format. + * @type {string} + * @protected + */ + this.colour_ = '#000000'; + + /** + * Name of the block style. + * @type {string} + * @protected + */ + this.styleName_ = ''; + + /** + * An optional method called during initialization. + * @type {undefined|?function()} + */ + this.init = undefined; + + /** + * An optional serialization method for defining how to serialize the + * mutation state to XML. This must be coupled with defining + * `domToMutation`. + * @type {undefined|?function(...):!Element} + */ + this.mutationToDom = undefined; + + /** + * An optional deserialization method for defining how to deserialize the + * mutation state from XML. This must be coupled with defining + * `mutationToDom`. + * @type {undefined|?function(!Element)} + */ + this.domToMutation = undefined; + + /** + * An optional serialization method for defining how to serialize the + * block's extra state (eg mutation state) to something JSON compatible. + * This must be coupled with defining `loadExtraState`. + * @type {undefined|?function(): *} + */ + this.saveExtraState = undefined; + + /** + * An optional serialization method for defining how to deserialize the + * block's extra state (eg mutation state) from something JSON compatible. + * This must be coupled with defining `saveExtraState`. + * @type {undefined|?function(*)} + */ + this.loadExtraState = undefined; + + /** + * An optional method called by the default mutator UI which allows the + * block to "explode" itself into smaller sub blocks. This function should + * return a "top block" which is the main block in the mutator workspace + * that sub-blocks connect to. + * @type {undefined|?function():!Block} + */ + this.decompose = undefined; + + /** + * An optional method called by the deafult mutator UI which allows the + * block to configure itself based on the configuration of sub-blocks in + * the mutator workspace. This function should accept the "top block" which + * was returned by `decompose` as a paramter. + * @type {undefined|?function(!Block)} + */ + this.compose = undefined; + + /** + * An optional method called by the default mutator UI which gives the block + * a chance to save information about what child blocks are connected to + * what mutated connections. + * @type {undefined|?function(!Block)} + */ + this.saveConnections = undefined; + + /** + * An optional property for suppressing adding STATEMENT_PREFIX and + * STATEMENT_SUFFIX to generated code. + * @type {?boolean} + */ + this.suppressPrefixSuffix = false; + + /** + * An optional property for declaring developer variables. Return a list of + * variable names for use by generators. Developer variables are never + * shown to the user, but are declared as global variables in the generated + * code. + * @type {undefined|?function():!Array} + */ + this.getDeveloperVariables = undefined; + + /** @type {string} */ + this.id = (opt_id && !workspace.getBlockById(opt_id)) ? + opt_id : + idGenerator.genUid(); + workspace.setBlockById(this.id, this); + /** @type {Connection} */ + this.outputConnection = null; + /** @type {Connection} */ + this.nextConnection = null; + /** @type {Connection} */ + this.previousConnection = null; + /** @type {!Array} */ + this.inputList = []; + /** @type {boolean|undefined} */ + this.inputsInline = undefined; + /** + * @type {boolean} + * @private + */ + this.disabled = false; + /** @type {!Tooltip.TipInfo} */ + this.tooltip = ''; + /** @type {boolean} */ + this.contextMenu = true; + + /** + * @type {Block} + * @protected + */ + this.parentBlock_ = null; + + /** + * @type {!Array} + * @protected + */ + this.childBlocks_ = []; + + /** + * @type {boolean} + * @private + */ + this.deletable_ = true; + + /** + * @type {boolean} + * @private + */ + this.movable_ = true; + + /** + * @type {boolean} + * @private + */ + this.editable_ = true; + + /** + * @type {boolean} + * @private + */ + this.isShadow_ = false; + + /** + * @type {boolean} + * @protected + */ + this.collapsed_ = false; + + /** + * @type {?number} + * @protected + */ + this.outputShape_ = null; + + /** + * A string representing the comment attached to this block. + * @type {string|Comment} + * @deprecated August 2019. Use getCommentText instead. + */ + this.comment = null; + + /** + * A model of the comment attached to this block. + * @type {!Block.CommentModel} + * @package + */ + this.commentModel = {text: null, pinned: false, size: new Size(160, 80)}; + + /** + * The block's position in workspace units. (0, 0) is at the workspace's + * origin; scale does not change this value. + * @type {!Coordinate} + * @private + */ + this.xy_ = new Coordinate(0, 0); + + /** @type {!Workspace} */ + this.workspace = workspace; + /** @type {boolean} */ + this.isInFlyout = workspace.isFlyout; + /** @type {boolean} */ + this.isInMutator = workspace.isMutator; + + /** @type {boolean} */ + this.RTL = workspace.RTL; + + /** + * True if this block is an insertion marker. + * @type {boolean} + * @protected + */ + this.isInsertionMarker_ = false; + + /** + * Name of the type of hat. + * @type {string|undefined} + */ + this.hat = undefined; + + /** @type {?boolean} */ + this.rendered = null; + + /** + * String for block help, or function that returns a URL. Null for no help. + * @type {string|Function} + */ + this.helpUrl = null; + + /** + * A bound callback function to use when the parent workspace changes. + * @type {?function(Abstract)} + * @private + */ + this.onchangeWrapper_ = null; + + /** + * A count of statement inputs on the block. + * @type {number} + * @package + */ + this.statementInputCount = 0; + + // Copy the type-specific functions and data from the prototype. + if (prototypeName) { + /** @type {string} */ + this.type = prototypeName; + const prototype = Blocks[prototypeName]; + if (!prototype || typeof prototype !== 'object') { + throw TypeError('Invalid block definition for type: ' + prototypeName); + } + object.mixin(this, prototype); + } + + workspace.addTopBlock(this); + workspace.addTypedBlock(this); + + if (new.target === Block) this.doInit_(); } - workspace.addTopBlock(this); - workspace.addTypedBlock(this); + /** + * Calls the init() function and handles associated event firing, etc. + * @protected + */ + doInit_() { + // All events fired should be part of the same group. + // Any events fired during init should not be undoable, + // so that block creation is atomic. + const existingGroup = eventUtils.getGroup(); + if (!existingGroup) { + eventUtils.setGroup(true); + } + const initialUndoFlag = eventUtils.getRecordUndo(); - // All events fired should be part of the same group. - // Any events fired during init should not be undoable, - // so that block creation is atomic. - const existingGroup = eventUtils.getGroup(); - if (!existingGroup) { - eventUtils.setGroup(true); - } - const initialUndoFlag = eventUtils.getRecordUndo(); + try { + // Call an initialization function, if it exists. + if (typeof this.init === 'function') { + eventUtils.setRecordUndo(false); + this.init(); + eventUtils.setRecordUndo(initialUndoFlag); + } - try { - // Call an initialization function, if it exists. - if (typeof this.init === 'function') { - eventUtils.setRecordUndo(false); - this.init(); + // Fire a create event. + if (eventUtils.isEnabled()) { + eventUtils.fire(new (eventUtils.get(eventUtils.BLOCK_CREATE))(this)); + } + } finally { + if (!existingGroup) { + eventUtils.setGroup(false); + } + // In case init threw, recordUndo flag should still be reset. eventUtils.setRecordUndo(initialUndoFlag); } - // Fire a create event. + // Record initial inline state. + /** @type {boolean|undefined} */ + this.inputsInlineDefault = this.inputsInline; + + // Bind an onchange function, if it exists. + if (typeof this.onchange === 'function') { + this.setOnChange(this.onchange); + } + } + + /** + * Dispose of this block. + * @param {boolean} healStack If true, then try to heal any gap by connecting + * the next statement with the previous statement. Otherwise, dispose of + * all children of this block. + * @param {boolean=} _animate If true, show a disposal animation and sound. + * @suppress {checkTypes} + */ + dispose(healStack, _animate) { + if (!this.workspace) { + // Already deleted. + return; + } + // Terminate onchange event calls. + if (this.onchangeWrapper_) { + this.workspace.removeChangeListener(this.onchangeWrapper_); + } + + this.unplug(healStack); if (eventUtils.isEnabled()) { - eventUtils.fire(new (eventUtils.get(eventUtils.BLOCK_CREATE))(this)); + eventUtils.fire(new (eventUtils.get(eventUtils.BLOCK_DELETE))(this)); } - } finally { - if (!existingGroup) { - eventUtils.setGroup(false); + eventUtils.disable(); + + try { + // This block is now at the top of the workspace. + // Remove this block from the workspace's list of top-most blocks. + if (this.workspace) { + this.workspace.removeTopBlock(this); + this.workspace.removeTypedBlock(this); + // Remove from block database. + this.workspace.removeBlockById(this.id); + this.workspace = null; + } + + // Just deleting this block from the DOM would result in a memory leak as + // well as corruption of the connection database. Therefore we must + // methodically step through the blocks and carefully disassemble them. + + if (common.getSelected() === this) { + common.setSelected(null); + } + + // First, dispose of all my children. + for (let i = this.childBlocks_.length - 1; i >= 0; i--) { + this.childBlocks_[i].dispose(false); + } + // Then dispose of myself. + // Dispose of all inputs and their fields. + for (let i = 0, input; (input = this.inputList[i]); i++) { + input.dispose(); + } + this.inputList.length = 0; + // Dispose of any remaining connections (next/previous/output). + const connections = this.getConnections_(true); + for (let i = 0, connection; (connection = connections[i]); i++) { + connection.dispose(); + } + } finally { + eventUtils.enable(); + this.disposed = true; } - // In case init threw, recordUndo flag should still be reset. - eventUtils.setRecordUndo(initialUndoFlag); } - // Record initial inline state. - /** @type {boolean|undefined} */ - this.inputsInlineDefault = this.inputsInline; - - // Bind an onchange function, if it exists. - if (typeof this.onchange === 'function') { - this.setOnChange(this.onchange); + /** + * Call initModel on all fields on the block. + * May be called more than once. + * Either initModel or initSvg must be called after creating a block and + * before the first interaction with it. Interactions include UI actions + * (e.g. clicking and dragging) and firing events (e.g. create, delete, and + * change). + * @public + */ + initModel() { + for (let i = 0, input; (input = this.inputList[i]); i++) { + for (let j = 0, field; (field = input.fieldRow[j]); j++) { + if (field.initModel) { + field.initModel(); + } + } + } } -}; + + /** + * Unplug this block from its superior block. If this block is a statement, + * optionally reconnect the block underneath with the block on top. + * @param {boolean=} opt_healStack Disconnect child statement and reconnect + * stack. Defaults to false. + */ + unplug(opt_healStack) { + if (this.outputConnection) { + this.unplugFromRow_(opt_healStack); + } + if (this.previousConnection) { + this.unplugFromStack_(opt_healStack); + } + } + + /** + * Unplug this block's output from an input on another block. Optionally + * reconnect the block's parent to the only child block, if possible. + * @param {boolean=} opt_healStack Disconnect right-side block and connect to + * left-side block. Defaults to false. + * @private + */ + unplugFromRow_(opt_healStack) { + let parentConnection = null; + if (this.outputConnection.isConnected()) { + parentConnection = this.outputConnection.targetConnection; + // Disconnect from any superior block. + this.outputConnection.disconnect(); + } + + // Return early in obvious cases. + if (!parentConnection || !opt_healStack) { + return; + } + + const thisConnection = this.getOnlyValueConnection_(); + if (!thisConnection || !thisConnection.isConnected() || + thisConnection.targetBlock().isShadow()) { + // Too many or too few possible connections on this block, or there's + // nothing on the other side of this connection. + return; + } + + const childConnection = thisConnection.targetConnection; + // Disconnect the child block. + childConnection.disconnect(); + // Connect child to the parent if possible, otherwise bump away. + if (this.workspace.connectionChecker.canConnect( + childConnection, parentConnection, false)) { + parentConnection.connect(childConnection); + } else { + childConnection.onFailedConnect(parentConnection); + } + } + + /** + * Returns the connection on the value input that is connected to another + * block. When an insertion marker is connected to a connection with a block + * already attached, the connected block is attached to the insertion marker. + * Since only one block can be displaced and attached to the insertion marker + * this should only ever return one connection. + * + * @return {?Connection} The connection on the value input, or null. + * @private + */ + getOnlyValueConnection_() { + let connection = null; + for (let i = 0; i < this.inputList.length; i++) { + const thisConnection = this.inputList[i].connection; + if (thisConnection && + thisConnection.type === ConnectionType.INPUT_VALUE && + thisConnection.targetConnection) { + if (connection) { + return null; // More than one value input found. + } + connection = thisConnection; + } + } + return connection; + } + + /** + * Unplug this statement block from its superior block. Optionally reconnect + * the block underneath with the block on top. + * @param {boolean=} opt_healStack Disconnect child statement and reconnect + * stack. Defaults to false. + * @private + */ + unplugFromStack_(opt_healStack) { + let previousTarget = null; + if (this.previousConnection.isConnected()) { + // Remember the connection that any next statements need to connect to. + previousTarget = this.previousConnection.targetConnection; + // Detach this block from the parent's tree. + this.previousConnection.disconnect(); + } + const nextBlock = this.getNextBlock(); + if (opt_healStack && nextBlock && !nextBlock.isShadow()) { + // Disconnect the next statement. + const nextTarget = this.nextConnection.targetConnection; + nextTarget.disconnect(); + if (previousTarget && + this.workspace.connectionChecker.canConnect( + previousTarget, nextTarget, false)) { + // Attach the next statement to the previous statement. + previousTarget.connect(nextTarget); + } + } + } + + /** + * Returns all connections originating from this block. + * @param {boolean} _all If true, return all connections even hidden ones. + * @return {!Array} Array of connections. + * @package + */ + getConnections_(_all) { + const myConnections = []; + if (this.outputConnection) { + myConnections.push(this.outputConnection); + } + if (this.previousConnection) { + myConnections.push(this.previousConnection); + } + if (this.nextConnection) { + myConnections.push(this.nextConnection); + } + for (let i = 0, input; (input = this.inputList[i]); i++) { + if (input.connection) { + myConnections.push(input.connection); + } + } + return myConnections; + } + + /** + * Walks down a stack of blocks and finds the last next connection on the + * stack. + * @param {boolean} ignoreShadows If true,the last connection on a non-shadow + * block will be returned. If false, this will follow shadows to find the + * last connection. + * @return {?Connection} The last next connection on the stack, or null. + * @package + */ + lastConnectionInStack(ignoreShadows) { + let nextConnection = this.nextConnection; + while (nextConnection) { + const nextBlock = nextConnection.targetBlock(); + if (!nextBlock || (ignoreShadows && nextBlock.isShadow())) { + return nextConnection; + } + nextConnection = nextBlock.nextConnection; + } + return null; + } + + /** + * Bump unconnected blocks out of alignment. Two blocks which aren't actually + * connected should not coincidentally line up on screen. + */ + bumpNeighbours() { + // noop. + } + + /** + * Return the parent block or null if this block is at the top level. The + * parent block is either the block connected to the previous connection (for + * a statement block) or the block connected to the output connection (for a + * value block). + * @return {?Block} The block (if any) that holds the current block. + */ + getParent() { + return this.parentBlock_; + } + + /** + * Return the input that connects to the specified block. + * @param {!Block} block A block connected to an input on this block. + * @return {?Input} The input (if any) that connects to the specified + * block. + */ + getInputWithBlock(block) { + for (let i = 0, input; (input = this.inputList[i]); i++) { + if (input.connection && input.connection.targetBlock() === block) { + return input; + } + } + return null; + } + + /** + * Return the parent block that surrounds the current block, or null if this + * block has no surrounding block. A parent block might just be the previous + * statement, whereas the surrounding block is an if statement, while loop, + * etc. + * @return {?Block} The block (if any) that surrounds the current block. + */ + getSurroundParent() { + let block = this; + let prevBlock; + do { + prevBlock = block; + block = block.getParent(); + if (!block) { + // Ran off the top. + return null; + } + } while (block.getNextBlock() === prevBlock); + // This block is an enclosing parent, not just a statement in a stack. + return block; + } + + /** + * Return the next statement block directly connected to this block. + * @return {?Block} The next statement block or null. + */ + getNextBlock() { + return this.nextConnection && this.nextConnection.targetBlock(); + } + + /** + * Returns the block connected to the previous connection. + * @return {?Block} The previous statement block or null. + */ + getPreviousBlock() { + return this.previousConnection && this.previousConnection.targetBlock(); + } + + /** + * Return the connection on the first statement input on this block, or null + * if there are none. + * @return {?Connection} The first statement connection or null. + * @package + */ + getFirstStatementConnection() { + for (let i = 0, input; (input = this.inputList[i]); i++) { + if (input.connection && + input.connection.type === ConnectionType.NEXT_STATEMENT) { + return input.connection; + } + } + return null; + } + + /** + * Return the top-most block in this block's tree. + * This will return itself if this block is at the top level. + * @return {!Block} The root block. + */ + getRootBlock() { + let rootBlock; + let block = this; + do { + rootBlock = block; + block = rootBlock.parentBlock_; + } while (block); + return rootBlock; + } + + /** + * Walk up from the given block up through the stack of blocks to find + * the top block of the sub stack. If we are nested in a statement input only + * find the top-most nested block. Do not go all the way to the root block. + * @return {!Block} The top block in a stack. + * @package + */ + getTopStackBlock() { + let block = this; + let previous; + do { + previous = block.getPreviousBlock(); + } while (previous && previous.getNextBlock() === block && + (block = previous)); + return block; + } + + /** + * Find all the blocks that are directly nested inside this one. + * Includes value and statement inputs, as well as any following statement. + * Excludes any connection on an output tab or any preceding statement. + * Blocks are optionally sorted by position; top to bottom. + * @param {boolean} ordered Sort the list if true. + * @return {!Array} Array of blocks. + */ + getChildren(ordered) { + if (!ordered) { + return this.childBlocks_; + } + const blocks = []; + for (let i = 0, input; (input = this.inputList[i]); i++) { + if (input.connection) { + const child = input.connection.targetBlock(); + if (child) { + blocks.push(child); + } + } + } + const next = this.getNextBlock(); + if (next) { + blocks.push(next); + } + return blocks; + } + + /** + * Set parent of this block to be a new block or null. + * @param {Block} newParent New parent block. + * @package + */ + setParent(newParent) { + if (newParent === this.parentBlock_) { + return; + } + + // Check that block is connected to new parent if new parent is not null and + // that block is not connected to superior one if new parent is null. + const targetBlock = + (this.previousConnection && this.previousConnection.targetBlock()) || + (this.outputConnection && this.outputConnection.targetBlock()); + const isConnected = !!targetBlock; + + if (isConnected && newParent && targetBlock !== newParent) { + throw Error('Block connected to superior one that is not new parent.'); + } else if (!isConnected && newParent) { + throw Error('Block not connected to new parent.'); + } else if (isConnected && !newParent) { + throw Error( + 'Cannot set parent to null while block is still connected to' + + ' superior block.'); + } + + if (this.parentBlock_) { + // Remove this block from the old parent's child list. + arrayUtils.removeElem(this.parentBlock_.childBlocks_, this); + + // This block hasn't actually moved on-screen, so there's no need to + // update + // its connection locations. + } else { + // New parent must be non-null so remove this block from the workspace's + // list of top-most blocks. + this.workspace.removeTopBlock(this); + } + + this.parentBlock_ = newParent; + if (newParent) { + // Add this block to the new parent's child list. + newParent.childBlocks_.push(this); + } else { + this.workspace.addTopBlock(this); + } + } + + /** + * Find all the blocks that are directly or indirectly nested inside this one. + * Includes this block in the list. + * Includes value and statement inputs, as well as any following statements. + * Excludes any connection on an output tab or any preceding statements. + * Blocks are optionally sorted by position; top to bottom. + * @param {boolean} ordered Sort the list if true. + * @return {!Array} Flattened array of blocks. + */ + getDescendants(ordered) { + const blocks = [this]; + const childBlocks = this.getChildren(ordered); + for (let child, i = 0; (child = childBlocks[i]); i++) { + blocks.push.apply(blocks, child.getDescendants(ordered)); + } + return blocks; + } + + /** + * Get whether this block is deletable or not. + * @return {boolean} True if deletable. + */ + isDeletable() { + return this.deletable_ && !this.isShadow_ && + !(this.workspace && this.workspace.options.readOnly); + } + + /** + * Set whether this block is deletable or not. + * @param {boolean} deletable True if deletable. + */ + setDeletable(deletable) { + this.deletable_ = deletable; + } + + /** + * Get whether this block is movable or not. + * @return {boolean} True if movable. + */ + isMovable() { + return this.movable_ && !this.isShadow_ && + !(this.workspace && this.workspace.options.readOnly); + } + + /** + * Set whether this block is movable or not. + * @param {boolean} movable True if movable. + */ + setMovable(movable) { + this.movable_ = movable; + } + + /** + * Get whether is block is duplicatable or not. If duplicating this block and + * descendants will put this block over the workspace's capacity this block is + * not duplicatable. If duplicating this block and descendants will put any + * type over their maxInstances this block is not duplicatable. + * @return {boolean} True if duplicatable. + */ + isDuplicatable() { + if (!this.workspace.hasBlockLimits()) { + return true; + } + return this.workspace.isCapacityAvailable( + common.getBlockTypeCounts(this, true)); + } + + /** + * Get whether this block is a shadow block or not. + * @return {boolean} True if a shadow. + */ + isShadow() { + return this.isShadow_; + } + + /** + * Set whether this block is a shadow block or not. + * @param {boolean} shadow True if a shadow. + * @package + */ + setShadow(shadow) { + this.isShadow_ = shadow; + } + + /** + * Get whether this block is an insertion marker block or not. + * @return {boolean} True if an insertion marker. + */ + isInsertionMarker() { + return this.isInsertionMarker_; + } + + /** + * Set whether this block is an insertion marker block or not. + * Once set this cannot be unset. + * @param {boolean} insertionMarker True if an insertion marker. + * @package + */ + setInsertionMarker(insertionMarker) { + this.isInsertionMarker_ = insertionMarker; + } + + /** + * Get whether this block is editable or not. + * @return {boolean} True if editable. + */ + isEditable() { + return this.editable_ && + !(this.workspace && this.workspace.options.readOnly); + } + + /** + * Set whether this block is editable or not. + * @param {boolean} editable True if editable. + */ + setEditable(editable) { + this.editable_ = editable; + for (let i = 0, input; (input = this.inputList[i]); i++) { + for (let j = 0, field; (field = input.fieldRow[j]); j++) { + field.updateEditable(); + } + } + } + + /** + * Returns if this block has been disposed of / deleted. + * @return {boolean} True if this block has been disposed of / deleted. + */ + isDisposed() { + return this.disposed; + } + + /** + * Find the connection on this block that corresponds to the given connection + * on the other block. + * Used to match connections between a block and its insertion marker. + * @param {!Block} otherBlock The other block to match against. + * @param {!Connection} conn The other connection to match. + * @return {?Connection} The matching connection on this block, or null. + * @package + */ + getMatchingConnection(otherBlock, conn) { + const connections = this.getConnections_(true); + const otherConnections = otherBlock.getConnections_(true); + if (connections.length !== otherConnections.length) { + throw Error('Connection lists did not match in length.'); + } + for (let i = 0; i < otherConnections.length; i++) { + if (otherConnections[i] === conn) { + return connections[i]; + } + } + return null; + } + + /** + * Set the URL of this block's help page. + * @param {string|Function} url URL string for block help, or function that + * returns a URL. Null for no help. + */ + setHelpUrl(url) { + this.helpUrl = url; + } + + /** + * Sets the tooltip for this block. + * @param {!Tooltip.TipInfo} newTip The text for the tooltip, a function + * that returns the text for the tooltip, or a parent object whose tooltip + * will be used. To not display a tooltip pass the empty string. + */ + setTooltip(newTip) { + this.tooltip = newTip; + } + + /** + * Returns the tooltip text for this block. + * @return {!string} The tooltip text for this block. + */ + getTooltip() { + return Tooltip.getTooltipOfObject(this); + } + + /** + * Get the colour of a block. + * @return {string} #RRGGBB string. + */ + getColour() { + return this.colour_; + } + + /** + * Get the name of the block style. + * @return {string} Name of the block style. + */ + getStyleName() { + return this.styleName_; + } + + /** + * Get the HSV hue value of a block. Null if hue not set. + * @return {?number} Hue value (0-360). + */ + getHue() { + return this.hue_; + } + + /** + * Change the colour of a block. + * @param {number|string} colour HSV hue value (0 to 360), #RRGGBB string, + * or a message reference string pointing to one of those two values. + */ + setColour(colour) { + const parsed = parsing.parseBlockColour(colour); + this.hue_ = parsed.hue; + this.colour_ = parsed.hex; + } + + /** + * Set the style and colour values of a block. + * @param {string} blockStyleName Name of the block style. + */ + setStyle(blockStyleName) { + this.styleName_ = blockStyleName; + } + + /** + * Sets a callback function to use whenever the block's parent workspace + * changes, replacing any prior onchange handler. This is usually only called + * from the constructor, the block type initializer function, or an extension + * initializer function. + * @param {function(Abstract)} onchangeFn The callback to call + * when the block's workspace changes. + * @throws {Error} if onchangeFn is not falsey and not a function. + */ + setOnChange(onchangeFn) { + if (onchangeFn && typeof onchangeFn !== 'function') { + throw Error('onchange must be a function.'); + } + if (this.onchangeWrapper_) { + this.workspace.removeChangeListener(this.onchangeWrapper_); + } + this.onchange = onchangeFn; + if (this.onchange) { + this.onchangeWrapper_ = onchangeFn.bind(this); + this.workspace.addChangeListener(this.onchangeWrapper_); + } + } + + /** + * Returns the named field from a block. + * @param {string} name The name of the field. + * @return {?Field} Named field, or null if field does not exist. + */ + getField(name) { + if (typeof name !== 'string') { + throw TypeError( + 'Block.prototype.getField expects a string ' + + 'with the field name but received ' + + (name === undefined ? 'nothing' : name + ' of type ' + typeof name) + + ' instead'); + } + for (let i = 0, input; (input = this.inputList[i]); i++) { + for (let j = 0, field; (field = input.fieldRow[j]); j++) { + if (field.name === name) { + return field; + } + } + } + return null; + } + + /** + * Return all variables referenced by this block. + * @return {!Array} List of variable ids. + */ + getVars() { + const vars = []; + for (let i = 0, input; (input = this.inputList[i]); i++) { + for (let j = 0, field; (field = input.fieldRow[j]); j++) { + if (field.referencesVariables()) { + vars.push(field.getValue()); + } + } + } + return vars; + } + + /** + * Return all variables referenced by this block. + * @return {!Array} List of variable models. + * @package + */ + getVarModels() { + const vars = []; + for (let i = 0, input; (input = this.inputList[i]); i++) { + for (let j = 0, field; (field = input.fieldRow[j]); j++) { + if (field.referencesVariables()) { + const model = this.workspace.getVariableById( + /** @type {string} */ (field.getValue())); + // Check if the variable actually exists (and isn't just a potential + // variable). + if (model) { + vars.push(model); + } + } + } + } + return vars; + } + + /** + * Notification that a variable is renaming but keeping the same ID. If the + * variable is in use on this block, rerender to show the new name. + * @param {!VariableModel} variable The variable being renamed. + * @package + */ + updateVarName(variable) { + for (let i = 0, input; (input = this.inputList[i]); i++) { + for (let j = 0, field; (field = input.fieldRow[j]); j++) { + if (field.referencesVariables() && + variable.getId() === field.getValue()) { + field.refreshVariableName(); + } + } + } + } + + /** + * Notification that a variable is renaming. + * If the ID matches one of this block's variables, rename it. + * @param {string} oldId ID of variable to rename. + * @param {string} newId ID of new variable. May be the same as oldId, but + * with an updated name. + */ + renameVarById(oldId, newId) { + for (let i = 0, input; (input = this.inputList[i]); i++) { + for (let j = 0, field; (field = input.fieldRow[j]); j++) { + if (field.referencesVariables() && oldId === field.getValue()) { + field.setValue(newId); + } + } + } + } + + /** + * Returns the language-neutral value of the given field. + * @param {string} name The name of the field. + * @return {*} Value of the field or null if field does not exist. + */ + getFieldValue(name) { + const field = this.getField(name); + if (field) { + return field.getValue(); + } + return null; + } + + /** + * Sets the value of the given field for this block. + * @param {*} newValue The value to set. + * @param {string} name The name of the field to set the value of. + */ + setFieldValue(newValue, name) { + const field = this.getField(name); + if (!field) { + throw Error('Field "' + name + '" not found.'); + } + field.setValue(newValue); + } + + /** + * Set whether this block can chain onto the bottom of another block. + * @param {boolean} newBoolean True if there can be a previous statement. + * @param {(string|Array|null)=} opt_check Statement type or + * list of statement types. Null/undefined if any type could be + * connected. + */ + setPreviousStatement(newBoolean, opt_check) { + if (newBoolean) { + if (opt_check === undefined) { + opt_check = null; + } + if (!this.previousConnection) { + this.previousConnection = + this.makeConnection_(ConnectionType.PREVIOUS_STATEMENT); + } + this.previousConnection.setCheck(opt_check); + } else { + if (this.previousConnection) { + if (this.previousConnection.isConnected()) { + throw Error( + 'Must disconnect previous statement before removing ' + + 'connection.'); + } + this.previousConnection.dispose(); + this.previousConnection = null; + } + } + } + + /** + * Set whether another block can chain onto the bottom of this block. + * @param {boolean} newBoolean True if there can be a next statement. + * @param {(string|Array|null)=} opt_check Statement type or + * list of statement types. Null/undefined if any type could be + * connected. + */ + setNextStatement(newBoolean, opt_check) { + if (newBoolean) { + if (opt_check === undefined) { + opt_check = null; + } + if (!this.nextConnection) { + this.nextConnection = + this.makeConnection_(ConnectionType.NEXT_STATEMENT); + } + this.nextConnection.setCheck(opt_check); + } else { + if (this.nextConnection) { + if (this.nextConnection.isConnected()) { + throw Error( + 'Must disconnect next statement before removing ' + + 'connection.'); + } + this.nextConnection.dispose(); + this.nextConnection = null; + } + } + } + + /** + * Set whether this block returns a value. + * @param {boolean} newBoolean True if there is an output. + * @param {(string|Array|null)=} opt_check Returned type or list + * of returned types. Null or undefined if any type could be returned + * (e.g. variable get). + */ + setOutput(newBoolean, opt_check) { + if (newBoolean) { + if (opt_check === undefined) { + opt_check = null; + } + if (!this.outputConnection) { + this.outputConnection = + this.makeConnection_(ConnectionType.OUTPUT_VALUE); + } + this.outputConnection.setCheck(opt_check); + } else { + if (this.outputConnection) { + if (this.outputConnection.isConnected()) { + throw Error( + 'Must disconnect output value before removing connection.'); + } + this.outputConnection.dispose(); + this.outputConnection = null; + } + } + } + + /** + * Set whether value inputs are arranged horizontally or vertically. + * @param {boolean} newBoolean True if inputs are horizontal. + */ + setInputsInline(newBoolean) { + if (this.inputsInline !== newBoolean) { + eventUtils.fire(new (eventUtils.get(eventUtils.BLOCK_CHANGE))( + this, 'inline', null, this.inputsInline, newBoolean)); + this.inputsInline = newBoolean; + } + } + + /** + * Get whether value inputs are arranged horizontally or vertically. + * @return {boolean} True if inputs are horizontal. + */ + getInputsInline() { + if (this.inputsInline !== undefined) { + // Set explicitly. + return this.inputsInline; + } + // Not defined explicitly. Figure out what would look best. + for (let i = 1; i < this.inputList.length; i++) { + if (this.inputList[i - 1].type === inputTypes.DUMMY && + this.inputList[i].type === inputTypes.DUMMY) { + // Two dummy inputs in a row. Don't inline them. + return false; + } + } + for (let i = 1; i < this.inputList.length; i++) { + if (this.inputList[i - 1].type === inputTypes.VALUE && + this.inputList[i].type === inputTypes.DUMMY) { + // Dummy input after a value input. Inline them. + return true; + } + } + return false; + } + + /** + * Set the block's output shape. + * @param {?number} outputShape Value representing an output shape. + */ + setOutputShape(outputShape) { + this.outputShape_ = outputShape; + } + + /** + * Get the block's output shape. + * @return {?number} Value representing output shape if one exists. + */ + getOutputShape() { + return this.outputShape_; + } + + /** + * Get whether this block is enabled or not. + * @return {boolean} True if enabled. + */ + isEnabled() { + return !this.disabled; + } + + /** + * Set whether the block is enabled or not. + * @param {boolean} enabled True if enabled. + */ + setEnabled(enabled) { + if (this.isEnabled() !== enabled) { + const oldValue = this.disabled; + this.disabled = !enabled; + eventUtils.fire(new (eventUtils.get(eventUtils.BLOCK_CHANGE))( + this, 'disabled', null, oldValue, !enabled)); + } + } + + /** + * Get whether the block is disabled or not due to parents. + * The block's own disabled property is not considered. + * @return {boolean} True if disabled. + */ + getInheritedDisabled() { + let ancestor = this.getSurroundParent(); + while (ancestor) { + if (ancestor.disabled) { + return true; + } + ancestor = ancestor.getSurroundParent(); + } + // Ran off the top. + return false; + } + + /** + * Get whether the block is collapsed or not. + * @return {boolean} True if collapsed. + */ + isCollapsed() { + return this.collapsed_; + } + + /** + * Set whether the block is collapsed or not. + * @param {boolean} collapsed True if collapsed. + */ + setCollapsed(collapsed) { + if (this.collapsed_ !== collapsed) { + eventUtils.fire(new (eventUtils.get(eventUtils.BLOCK_CHANGE))( + this, 'collapsed', null, this.collapsed_, collapsed)); + this.collapsed_ = collapsed; + } + } + + /** + * Create a human-readable text representation of this block and any children. + * @param {number=} opt_maxLength Truncate the string to this length. + * @param {string=} opt_emptyToken The placeholder string used to denote an + * empty field. If not specified, '?' is used. + * @return {string} Text of block. + */ + toString(opt_maxLength, opt_emptyToken) { + let text = []; + const emptyFieldPlaceholder = opt_emptyToken || '?'; + + // Temporarily set flag to navigate to all fields. + const prevNavigateFields = ASTNode.NAVIGATE_ALL_FIELDS; + ASTNode.NAVIGATE_ALL_FIELDS = true; + + let node = ASTNode.createBlockNode(this); + const rootNode = node; + + /** + * Whether or not to add parentheses around an input. + * @param {!Connection} connection The connection. + * @return {boolean} True if we should add parentheses around the input. + */ + function shouldAddParentheses(connection) { + let checks = connection.getCheck(); + if (!checks && connection.targetConnection) { + checks = connection.targetConnection.getCheck(); + } + return !!checks && + (checks.indexOf('Boolean') !== -1 || checks.indexOf('Number') !== -1); + } + + /** + * Check that we haven't circled back to the original root node. + */ + function checkRoot() { + if (node && node.getType() === rootNode.getType() && + node.getLocation() === rootNode.getLocation()) { + node = null; + } + } + + // Traverse the AST building up our text string. + while (node) { + switch (node.getType()) { + case ASTNode.types.INPUT: { + const connection = /** @type {!Connection} */ (node.getLocation()); + if (!node.in()) { + text.push(emptyFieldPlaceholder); + } else if (shouldAddParentheses(connection)) { + text.push('('); + } + break; + } + case ASTNode.types.FIELD: { + const field = /** @type {Field} */ (node.getLocation()); + if (field.name !== constants.COLLAPSED_FIELD_NAME) { + text.push(field.getText()); + } + break; + } + } + + const current = node; + node = current.in() || current.next(); + if (!node) { + // Can't go in or next, keep going out until we can go next. + node = current.out(); + checkRoot(); + while (node && !node.next()) { + node = node.out(); + checkRoot(); + // If we hit an input on the way up, possibly close out parentheses. + if (node && node.getType() === ASTNode.types.INPUT && + shouldAddParentheses( + /** @type {!Connection} */ (node.getLocation()))) { + text.push(')'); + } + } + if (node) { + node = node.next(); + } + } + } + + // Restore state of NAVIGATE_ALL_FIELDS. + ASTNode.NAVIGATE_ALL_FIELDS = prevNavigateFields; + + // Run through our text array and simplify expression to remove parentheses + // around single field blocks. + // E.g. ['repeat', '(', '10', ')', 'times', 'do', '?'] + for (let i = 2; i < text.length; i++) { + if (text[i - 2] === '(' && text[i] === ')') { + text[i - 2] = text[i - 1]; + text.splice(i - 1, 2); + } + } + + // Join the text array, removing spaces around added parentheses. + text = text.reduce(function(acc, value) { + return acc + ((acc.substr(-1) === '(' || value === ')') ? '' : ' ') + + value; + }, ''); + text = text.trim() || '???'; + if (opt_maxLength) { + // TODO: Improve truncation so that text from this block is given + // priority. E.g. "1+2+3+4+5+6+7+8+9=0" should be "...6+7+8+9=0", not + // "1+2+3+4+5...". E.g. "1+2+3+4+5=6+7+8+9+0" should be "...4+5=6+7...". + if (text.length > opt_maxLength) { + text = text.substring(0, opt_maxLength - 3) + '...'; + } + } + return text; + } + + /** + * Shortcut for appending a value input row. + * @param {string} name Language-neutral identifier which may used to find + * this input again. Should be unique to this block. + * @return {!Input} The input object created. + */ + appendValueInput(name) { + return this.appendInput_(inputTypes.VALUE, name); + } + + /** + * Shortcut for appending a statement input row. + * @param {string} name Language-neutral identifier which may used to find + * this input again. Should be unique to this block. + * @return {!Input} The input object created. + */ + appendStatementInput(name) { + return this.appendInput_(inputTypes.STATEMENT, name); + } + + /** + * Shortcut for appending a dummy input row. + * @param {string=} opt_name Language-neutral identifier which may used to + * find this input again. Should be unique to this block. + * @return {!Input} The input object created. + */ + appendDummyInput(opt_name) { + return this.appendInput_(inputTypes.DUMMY, opt_name || ''); + } + + /** + * Initialize this block using a cross-platform, internationalization-friendly + * JSON description. + * @param {!Object} json Structured data describing the block. + */ + jsonInit(json) { + const warningPrefix = json['type'] ? 'Block "' + json['type'] + '": ' : ''; + + // Validate inputs. + if (json['output'] && json['previousStatement']) { + throw Error( + warningPrefix + + 'Must not have both an output and a previousStatement.'); + } + + // Set basic properties of block. + // Makes styles backward compatible with old way of defining hat style. + if (json['style'] && json['style'].hat) { + this.hat = json['style'].hat; + // Must set to null so it doesn't error when checking for style and + // colour. + json['style'] = null; + } + + if (json['style'] && json['colour']) { + throw Error(warningPrefix + 'Must not have both a colour and a style.'); + } else if (json['style']) { + this.jsonInitStyle_(json, warningPrefix); + } else { + this.jsonInitColour_(json, warningPrefix); + } + + // Interpolate the message blocks. + let i = 0; + while (json['message' + i] !== undefined) { + this.interpolate_( + json['message' + i], json['args' + i] || [], + json['lastDummyAlign' + i], warningPrefix); + i++; + } + + if (json['inputsInline'] !== undefined) { + this.setInputsInline(json['inputsInline']); + } + // Set output and previous/next connections. + if (json['output'] !== undefined) { + this.setOutput(true, json['output']); + } + if (json['outputShape'] !== undefined) { + this.setOutputShape(json['outputShape']); + } + if (json['previousStatement'] !== undefined) { + this.setPreviousStatement(true, json['previousStatement']); + } + if (json['nextStatement'] !== undefined) { + this.setNextStatement(true, json['nextStatement']); + } + if (json['tooltip'] !== undefined) { + const rawValue = json['tooltip']; + const localizedText = parsing.replaceMessageReferences(rawValue); + this.setTooltip(localizedText); + } + if (json['enableContextMenu'] !== undefined) { + this.contextMenu = !!json['enableContextMenu']; + } + if (json['suppressPrefixSuffix'] !== undefined) { + this.suppressPrefixSuffix = !!json['suppressPrefixSuffix']; + } + if (json['helpUrl'] !== undefined) { + const rawValue = json['helpUrl']; + const localizedValue = parsing.replaceMessageReferences(rawValue); + this.setHelpUrl(localizedValue); + } + if (typeof json['extensions'] === 'string') { + console.warn( + warningPrefix + + 'JSON attribute \'extensions\' should be an array of' + + ' strings. Found raw string in JSON for \'' + json['type'] + + '\' block.'); + json['extensions'] = [json['extensions']]; // Correct and continue. + } + + // Add the mutator to the block. + if (json['mutator'] !== undefined) { + Extensions.apply(json['mutator'], this, true); + } + + const extensionNames = json['extensions']; + if (Array.isArray(extensionNames)) { + for (let j = 0; j < extensionNames.length; j++) { + Extensions.apply(extensionNames[j], this, false); + } + } + } + + /** + * Initialize the colour of this block from the JSON description. + * @param {!Object} json Structured data describing the block. + * @param {string} warningPrefix Warning prefix string identifying block. + * @private + */ + jsonInitColour_(json, warningPrefix) { + if ('colour' in json) { + if (json['colour'] === undefined) { + console.warn(warningPrefix + 'Undefined colour value.'); + } else { + const rawValue = json['colour']; + try { + this.setColour(rawValue); + } catch (e) { + console.warn(warningPrefix + 'Illegal colour value: ', rawValue); + } + } + } + } + + /** + * Initialize the style of this block from the JSON description. + * @param {!Object} json Structured data describing the block. + * @param {string} warningPrefix Warning prefix string identifying block. + * @private + */ + jsonInitStyle_(json, warningPrefix) { + const blockStyleName = json['style']; + try { + this.setStyle(blockStyleName); + } catch (styleError) { + console.warn(warningPrefix + 'Style does not exist: ', blockStyleName); + } + } + + /** + * Add key/values from mixinObj to this block object. By default, this method + * will check that the keys in mixinObj will not overwrite existing values in + * the block, including prototype values. This provides some insurance against + * mixin / extension incompatibilities with future block features. This check + * can be disabled by passing true as the second argument. + * @param {!Object} mixinObj The key/values pairs to add to this block object. + * @param {boolean=} opt_disableCheck Option flag to disable overwrite checks. + */ + mixin(mixinObj, opt_disableCheck) { + if (opt_disableCheck !== undefined && + typeof opt_disableCheck !== 'boolean') { + throw Error('opt_disableCheck must be a boolean if provided'); + } + if (!opt_disableCheck) { + const overwrites = []; + for (const key in mixinObj) { + if (this[key] !== undefined) { + overwrites.push(key); + } + } + if (overwrites.length) { + throw Error( + 'Mixin will overwrite block members: ' + + JSON.stringify(overwrites)); + } + } + object.mixin(this, mixinObj); + } + + /** + * Interpolate a message description onto the block. + * @param {string} message Text contains interpolation tokens (%1, %2, ...) + * that match with fields or inputs defined in the args array. + * @param {!Array} args Array of arguments to be interpolated. + * @param {string|undefined} lastDummyAlign If a dummy input is added at the + * end, how should it be aligned? + * @param {string} warningPrefix Warning prefix string identifying block. + * @private + */ + interpolate_(message, args, lastDummyAlign, warningPrefix) { + const tokens = parsing.tokenizeInterpolation(message); + this.validateTokens_(tokens, args.length); + const elements = this.interpolateArguments_(tokens, args, lastDummyAlign); + + // An array of [field, fieldName] tuples. + const fieldStack = []; + for (let i = 0, element; (element = elements[i]); i++) { + if (this.isInputKeyword_(element['type'])) { + const input = this.inputFromJson_(element, warningPrefix); + // Should never be null, but just in case. + if (input) { + for (let j = 0, tuple; (tuple = fieldStack[j]); j++) { + input.appendField(tuple[0], tuple[1]); + } + fieldStack.length = 0; + } + } else { + // All other types, including ones starting with 'input_' get routed + // here. + const field = this.fieldFromJson_(element); + if (field) { + fieldStack.push([field, element['name']]); + } + } + } + } + + /** + * Validates that the tokens are within the correct bounds, with no + * duplicates, and that all of the arguments are referred to. Throws errors if + * any of these things are not true. + * @param {!Array} tokens An array of tokens to validate + * @param {number} argsCount The number of args that need to be referred to. + * @private + */ + validateTokens_(tokens, argsCount) { + const visitedArgsHash = []; + let visitedArgsCount = 0; + for (let i = 0; i < tokens.length; i++) { + const token = tokens[i]; + if (typeof token !== 'number') { + continue; + } + if (token < 1 || token > argsCount) { + throw Error( + 'Block "' + this.type + '": ' + + 'Message index %' + token + ' out of range.'); + } + if (visitedArgsHash[token]) { + throw Error( + 'Block "' + this.type + '": ' + + 'Message index %' + token + ' duplicated.'); + } + visitedArgsHash[token] = true; + visitedArgsCount++; + } + if (visitedArgsCount !== argsCount) { + throw Error( + 'Block "' + this.type + '": ' + + 'Message does not reference all ' + argsCount + ' arg(s).'); + } + } + + /** + * Inserts args in place of numerical tokens. String args are converted to + * JSON that defines a label field. If necessary an extra dummy input is added + * to the end of the elements. + * @param {!Array} tokens The tokens to interpolate + * @param {!Array} args The arguments to insert. + * @param {string|undefined} lastDummyAlign The alignment the added dummy + * input should have, if we are required to add one. + * @return {!Array} The JSON definitions of field and inputs to add + * to the block. + * @private + */ + interpolateArguments_(tokens, args, lastDummyAlign) { + const elements = []; + for (let i = 0; i < tokens.length; i++) { + let element = tokens[i]; + if (typeof element === 'number') { + element = args[element - 1]; + } + // Args can be strings, which is why this isn't elseif. + if (typeof element === 'string') { + element = this.stringToFieldJson_(element); + if (!element) { + continue; + } + } + elements.push(element); + } + + const length = elements.length; + if (length && !this.isInputKeyword_(elements[length - 1]['type'])) { + const dummyInput = {'type': 'input_dummy'}; + if (lastDummyAlign) { + dummyInput['align'] = lastDummyAlign; + } + elements.push(dummyInput); + } + + return elements; + } + + /** + * Creates a field from the JSON definition of a field. If a field with the + * given type cannot be found, this attempts to create a different field using + * the 'alt' property of the JSON definition (if it exists). + * @param {{alt:(string|undefined)}} element The element to try to turn into a + * field. + * @return {?Field} The field defined by the JSON, or null if one + * couldn't be created. + * @private + */ + fieldFromJson_(element) { + const field = fieldRegistry.fromJson(element); + if (!field && element['alt']) { + if (typeof element['alt'] === 'string') { + const json = this.stringToFieldJson_(element['alt']); + return json ? this.fieldFromJson_(json) : null; + } + return this.fieldFromJson_(element['alt']); + } + return field; + } + + /** + * Creates an input from the JSON definition of an input. Sets the input's + * check and alignment if they are provided. + * @param {!Object} element The JSON to turn into an input. + * @param {string} warningPrefix The prefix to add to warnings to help the + * developer debug. + * @return {?Input} The input that has been created, or null if one + * could not be created for some reason (should never happen). + * @private + */ + inputFromJson_(element, warningPrefix) { + const alignmentLookup = { + 'LEFT': Align.LEFT, + 'RIGHT': Align.RIGHT, + 'CENTRE': Align.CENTRE, + 'CENTER': Align.CENTRE, + }; + + let input = null; + switch (element['type']) { + case 'input_value': + input = this.appendValueInput(element['name']); + break; + case 'input_statement': + input = this.appendStatementInput(element['name']); + break; + case 'input_dummy': + input = this.appendDummyInput(element['name']); + break; + } + // Should never be hit because of interpolate_'s checks, but just in case. + if (!input) { + return null; + } + + if (element['check']) { + input.setCheck(element['check']); + } + if (element['align']) { + const alignment = alignmentLookup[element['align'].toUpperCase()]; + if (alignment === undefined) { + console.warn(warningPrefix + 'Illegal align value: ', element['align']); + } else { + input.setAlign(alignment); + } + } + return input; + } + + /** + * Returns true if the given string matches one of the input keywords. + * @param {string} str The string to check. + * @return {boolean} True if the given string matches one of the input + * keywords, false otherwise. + * @private + */ + isInputKeyword_(str) { + return str === 'input_value' || str === 'input_statement' || + str === 'input_dummy'; + } + + /** + * Turns a string into the JSON definition of a label field. If the string + * becomes an empty string when trimmed, this returns null. + * @param {string} str String to turn into the JSON definition of a label + * field. + * @return {?{text: string, type: string}} The JSON definition or null. + * @private + */ + stringToFieldJson_(str) { + str = str.trim(); + if (str) { + return { + 'type': 'field_label', + 'text': str, + }; + } + return null; + } + + /** + * Add a value input, statement input or local variable to this block. + * @param {number} type One of Blockly.inputTypes. + * @param {string} name Language-neutral identifier which may used to find + * this input again. Should be unique to this block. + * @return {!Input} The input object created. + * @protected + */ + appendInput_(type, name) { + let connection = null; + if (type === inputTypes.VALUE || type === inputTypes.STATEMENT) { + connection = this.makeConnection_(type); + } + if (type === inputTypes.STATEMENT) { + this.statementInputCount++; + } + const input = new Input(type, name, this, connection); + // Append input to list. + this.inputList.push(input); + return input; + } + + /** + * Move a named input to a different location on this block. + * @param {string} name The name of the input to move. + * @param {?string} refName Name of input that should be after the moved + * input, + * or null to be the input at the end. + */ + moveInputBefore(name, refName) { + if (name === refName) { + return; + } + // Find both inputs. + let inputIndex = -1; + let refIndex = refName ? -1 : this.inputList.length; + for (let i = 0, input; (input = this.inputList[i]); i++) { + if (input.name === name) { + inputIndex = i; + if (refIndex !== -1) { + break; + } + } else if (refName && input.name === refName) { + refIndex = i; + if (inputIndex !== -1) { + break; + } + } + } + if (inputIndex === -1) { + throw Error('Named input "' + name + '" not found.'); + } + if (refIndex === -1) { + throw Error('Reference input "' + refName + '" not found.'); + } + this.moveNumberedInputBefore(inputIndex, refIndex); + } + + /** + * Move a numbered input to a different location on this block. + * @param {number} inputIndex Index of the input to move. + * @param {number} refIndex Index of input that should be after the moved + * input. + */ + moveNumberedInputBefore(inputIndex, refIndex) { + // Validate arguments. + if (inputIndex === refIndex) { + throw Error('Can\'t move input to itself.'); + } + if (inputIndex >= this.inputList.length) { + throw RangeError('Input index ' + inputIndex + ' out of bounds.'); + } + if (refIndex > this.inputList.length) { + throw RangeError('Reference input ' + refIndex + ' out of bounds.'); + } + // Remove input. + const input = this.inputList[inputIndex]; + this.inputList.splice(inputIndex, 1); + if (inputIndex < refIndex) { + refIndex--; + } + // Reinsert input. + this.inputList.splice(refIndex, 0, input); + } + + /** + * Remove an input from this block. + * @param {string} name The name of the input. + * @param {boolean=} opt_quiet True to prevent an error if input is not + * present. + * @return {boolean} True if operation succeeds, false if input is not present + * and opt_quiet is true. + * @throws {Error} if the input is not present and opt_quiet is not true. + */ + removeInput(name, opt_quiet) { + for (let i = 0, input; (input = this.inputList[i]); i++) { + if (input.name === name) { + if (input.type === inputTypes.STATEMENT) { + this.statementInputCount--; + } + input.dispose(); + this.inputList.splice(i, 1); + return true; + } + } + if (opt_quiet) { + return false; + } + throw Error('Input not found: ' + name); + } + + /** + * Fetches the named input object. + * @param {string} name The name of the input. + * @return {?Input} The input object, or null if input does not exist. + */ + getInput(name) { + for (let i = 0, input; (input = this.inputList[i]); i++) { + if (input.name === name) { + return input; + } + } + // This input does not exist. + return null; + } + + /** + * Fetches the block attached to the named input. + * @param {string} name The name of the input. + * @return {?Block} The attached value block, or null if the input is + * either disconnected or if the input does not exist. + */ + getInputTargetBlock(name) { + const input = this.getInput(name); + return input && input.connection && input.connection.targetBlock(); + } + + /** + * Returns the comment on this block (or null if there is no comment). + * @return {?string} Block's comment. + */ + getCommentText() { + return this.commentModel.text; + } + + /** + * Set this block's comment text. + * @param {?string} text The text, or null to delete. + */ + setCommentText(text) { + if (this.commentModel.text === text) { + return; + } + eventUtils.fire(new (eventUtils.get(eventUtils.BLOCK_CHANGE))( + this, 'comment', null, this.commentModel.text, text)); + this.commentModel.text = text; + this.comment = text; // For backwards compatibility. + } + + /** + * Set this block's warning text. + * @param {?string} _text The text, or null to delete. + * @param {string=} _opt_id An optional ID for the warning text to be able to + * maintain multiple warnings. + */ + setWarningText(_text, _opt_id) { + // NOP. + } + + /** + * Give this block a mutator dialog. + * @param {Mutator} _mutator A mutator dialog instance or null to + * remove. + */ + setMutator(_mutator) { + // NOP. + } + + /** + * Return the coordinates of the top-left corner of this block relative to the + * drawing surface's origin (0,0), in workspace units. + * @return {!Coordinate} Object with .x and .y properties. + */ + getRelativeToSurfaceXY() { + return this.xy_; + } + + /** + * Move a block by a relative offset. + * @param {number} dx Horizontal offset, in workspace units. + * @param {number} dy Vertical offset, in workspace units. + */ + moveBy(dx, dy) { + if (this.parentBlock_) { + throw Error('Block has parent.'); + } + const event = /** @type {!BlockMove} */ ( + new (eventUtils.get(eventUtils.BLOCK_MOVE))(this)); + this.xy_.translate(dx, dy); + event.recordNew(); + eventUtils.fire(event); + } + + /** + * Create a connection of the specified type. + * @param {number} type The type of the connection to create. + * @return {!Connection} A new connection of the specified type. + * @protected + */ + makeConnection_(type) { + return new Connection(this, type); + } + + /** + * Recursively checks whether all statement and value inputs are filled with + * blocks. Also checks all following statement blocks in this stack. + * @param {boolean=} opt_shadowBlocksAreFilled An optional argument + * controlling whether shadow blocks are counted as filled. Defaults to + * true. + * @return {boolean} True if all inputs are filled, false otherwise. + */ + allInputsFilled(opt_shadowBlocksAreFilled) { + // Account for the shadow block filledness toggle. + if (opt_shadowBlocksAreFilled === undefined) { + opt_shadowBlocksAreFilled = true; + } + if (!opt_shadowBlocksAreFilled && this.isShadow()) { + return false; + } + + // Recursively check each input block of the current block. + for (let i = 0, input; (input = this.inputList[i]); i++) { + if (!input.connection) { + continue; + } + const target = input.connection.targetBlock(); + if (!target || !target.allInputsFilled(opt_shadowBlocksAreFilled)) { + return false; + } + } + + // Recursively check the next block after the current block. + const next = this.getNextBlock(); + if (next) { + return next.allInputsFilled(opt_shadowBlocksAreFilled); + } + + return true; + } + + /** + * This method returns a string describing this Block in developer terms (type + * name and ID; English only). + * + * Intended to on be used in console logs and errors. If you need a string + * that uses the user's native language (including block text, field values, + * and child blocks), use [toString()]{@link Block#toString}. + * @return {string} The description. + */ + toDevString() { + let msg = this.type ? '"' + this.type + '" block' : 'Block'; + if (this.id) { + msg += ' (id="' + this.id + '")'; + } + return msg; + } +} /** * @typedef {{ @@ -394,1781 +2234,4 @@ Block.COLLAPSED_INPUT_NAME = constants.COLLAPSED_INPUT_NAME; */ Block.COLLAPSED_FIELD_NAME = constants.COLLAPSED_FIELD_NAME; -/** - * Dispose of this block. - * @param {boolean} healStack If true, then try to heal any gap by connecting - * the next statement with the previous statement. Otherwise, dispose of - * all children of this block. - * @param {boolean=} _animate If true, show a disposal animation and sound. - * @suppress {checkTypes} - */ -Block.prototype.dispose = function(healStack, _animate) { - if (!this.workspace) { - // Already deleted. - return; - } - // Terminate onchange event calls. - if (this.onchangeWrapper_) { - this.workspace.removeChangeListener(this.onchangeWrapper_); - } - - this.unplug(healStack); - if (eventUtils.isEnabled()) { - eventUtils.fire(new (eventUtils.get(eventUtils.BLOCK_DELETE))(this)); - } - eventUtils.disable(); - - try { - // This block is now at the top of the workspace. - // Remove this block from the workspace's list of top-most blocks. - if (this.workspace) { - this.workspace.removeTopBlock(this); - this.workspace.removeTypedBlock(this); - // Remove from block database. - this.workspace.removeBlockById(this.id); - this.workspace = null; - } - - // Just deleting this block from the DOM would result in a memory leak as - // well as corruption of the connection database. Therefore we must - // methodically step through the blocks and carefully disassemble them. - - if (common.getSelected() === this) { - common.setSelected(null); - } - - // First, dispose of all my children. - for (let i = this.childBlocks_.length - 1; i >= 0; i--) { - this.childBlocks_[i].dispose(false); - } - // Then dispose of myself. - // Dispose of all inputs and their fields. - for (let i = 0, input; (input = this.inputList[i]); i++) { - input.dispose(); - } - this.inputList.length = 0; - // Dispose of any remaining connections (next/previous/output). - const connections = this.getConnections_(true); - for (let i = 0, connection; (connection = connections[i]); i++) { - connection.dispose(); - } - } finally { - eventUtils.enable(); - this.disposed = true; - } -}; - -/** - * Call initModel on all fields on the block. - * May be called more than once. - * Either initModel or initSvg must be called after creating a block and before - * the first interaction with it. Interactions include UI actions - * (e.g. clicking and dragging) and firing events (e.g. create, delete, and - * change). - * @public - */ -Block.prototype.initModel = function() { - for (let i = 0, input; (input = this.inputList[i]); i++) { - for (let j = 0, field; (field = input.fieldRow[j]); j++) { - if (field.initModel) { - field.initModel(); - } - } - } -}; - -/** - * Unplug this block from its superior block. If this block is a statement, - * optionally reconnect the block underneath with the block on top. - * @param {boolean=} opt_healStack Disconnect child statement and reconnect - * stack. Defaults to false. - */ -Block.prototype.unplug = function(opt_healStack) { - if (this.outputConnection) { - this.unplugFromRow_(opt_healStack); - } - if (this.previousConnection) { - this.unplugFromStack_(opt_healStack); - } -}; - -/** - * Unplug this block's output from an input on another block. Optionally - * reconnect the block's parent to the only child block, if possible. - * @param {boolean=} opt_healStack Disconnect right-side block and connect to - * left-side block. Defaults to false. - * @private - */ -Block.prototype.unplugFromRow_ = function(opt_healStack) { - let parentConnection = null; - if (this.outputConnection.isConnected()) { - parentConnection = this.outputConnection.targetConnection; - // Disconnect from any superior block. - this.outputConnection.disconnect(); - } - - // Return early in obvious cases. - if (!parentConnection || !opt_healStack) { - return; - } - - const thisConnection = this.getOnlyValueConnection_(); - if (!thisConnection || !thisConnection.isConnected() || - thisConnection.targetBlock().isShadow()) { - // Too many or too few possible connections on this block, or there's - // nothing on the other side of this connection. - return; - } - - const childConnection = thisConnection.targetConnection; - // Disconnect the child block. - childConnection.disconnect(); - // Connect child to the parent if possible, otherwise bump away. - if (this.workspace.connectionChecker.canConnect( - childConnection, parentConnection, false)) { - parentConnection.connect(childConnection); - } else { - childConnection.onFailedConnect(parentConnection); - } -}; - -/** - * Returns the connection on the value input that is connected to another block. - * When an insertion marker is connected to a connection with a block already - * attached, the connected block is attached to the insertion marker. - * Since only one block can be displaced and attached to the insertion marker - * this should only ever return one connection. - * - * @return {?Connection} The connection on the value input, or null. - * @private - */ -Block.prototype.getOnlyValueConnection_ = function() { - let connection = null; - for (let i = 0; i < this.inputList.length; i++) { - const thisConnection = this.inputList[i].connection; - if (thisConnection && thisConnection.type === ConnectionType.INPUT_VALUE && - thisConnection.targetConnection) { - if (connection) { - return null; // More than one value input found. - } - connection = thisConnection; - } - } - return connection; -}; - -/** - * Unplug this statement block from its superior block. Optionally reconnect - * the block underneath with the block on top. - * @param {boolean=} opt_healStack Disconnect child statement and reconnect - * stack. Defaults to false. - * @private - */ -Block.prototype.unplugFromStack_ = function(opt_healStack) { - let previousTarget = null; - if (this.previousConnection.isConnected()) { - // Remember the connection that any next statements need to connect to. - previousTarget = this.previousConnection.targetConnection; - // Detach this block from the parent's tree. - this.previousConnection.disconnect(); - } - const nextBlock = this.getNextBlock(); - if (opt_healStack && nextBlock && !nextBlock.isShadow()) { - // Disconnect the next statement. - const nextTarget = this.nextConnection.targetConnection; - nextTarget.disconnect(); - if (previousTarget && - this.workspace.connectionChecker.canConnect( - previousTarget, nextTarget, false)) { - // Attach the next statement to the previous statement. - previousTarget.connect(nextTarget); - } - } -}; - -/** - * Returns all connections originating from this block. - * @param {boolean} _all If true, return all connections even hidden ones. - * @return {!Array} Array of connections. - * @package - */ -Block.prototype.getConnections_ = function(_all) { - const myConnections = []; - if (this.outputConnection) { - myConnections.push(this.outputConnection); - } - if (this.previousConnection) { - myConnections.push(this.previousConnection); - } - if (this.nextConnection) { - myConnections.push(this.nextConnection); - } - for (let i = 0, input; (input = this.inputList[i]); i++) { - if (input.connection) { - myConnections.push(input.connection); - } - } - return myConnections; -}; - -/** - * Walks down a stack of blocks and finds the last next connection on the stack. - * @param {boolean} ignoreShadows If true,the last connection on a non-shadow - * block will be returned. If false, this will follow shadows to find the - * last connection. - * @return {?Connection} The last next connection on the stack, or null. - * @package - */ -Block.prototype.lastConnectionInStack = function(ignoreShadows) { - let nextConnection = this.nextConnection; - while (nextConnection) { - const nextBlock = nextConnection.targetBlock(); - if (!nextBlock || (ignoreShadows && nextBlock.isShadow())) { - return nextConnection; - } - nextConnection = nextBlock.nextConnection; - } - return null; -}; - -/** - * Bump unconnected blocks out of alignment. Two blocks which aren't actually - * connected should not coincidentally line up on screen. - */ -Block.prototype.bumpNeighbours = function() { - // noop. -}; - -/** - * Return the parent block or null if this block is at the top level. The parent - * block is either the block connected to the previous connection (for a - * statement block) or the block connected to the output connection (for a value - * block). - * @return {?Block} The block (if any) that holds the current block. - */ -Block.prototype.getParent = function() { - return this.parentBlock_; -}; - -/** - * Return the input that connects to the specified block. - * @param {!Block} block A block connected to an input on this block. - * @return {?Input} The input (if any) that connects to the specified - * block. - */ -Block.prototype.getInputWithBlock = function(block) { - for (let i = 0, input; (input = this.inputList[i]); i++) { - if (input.connection && input.connection.targetBlock() === block) { - return input; - } - } - return null; -}; - -/** - * Return the parent block that surrounds the current block, or null if this - * block has no surrounding block. A parent block might just be the previous - * statement, whereas the surrounding block is an if statement, while loop, etc. - * @return {?Block} The block (if any) that surrounds the current block. - */ -Block.prototype.getSurroundParent = function() { - let block = this; - let prevBlock; - do { - prevBlock = block; - block = block.getParent(); - if (!block) { - // Ran off the top. - return null; - } - } while (block.getNextBlock() === prevBlock); - // This block is an enclosing parent, not just a statement in a stack. - return block; -}; - -/** - * Return the next statement block directly connected to this block. - * @return {?Block} The next statement block or null. - */ -Block.prototype.getNextBlock = function() { - return this.nextConnection && this.nextConnection.targetBlock(); -}; - -/** - * Returns the block connected to the previous connection. - * @return {?Block} The previous statement block or null. - */ -Block.prototype.getPreviousBlock = function() { - return this.previousConnection && this.previousConnection.targetBlock(); -}; - -/** - * Return the connection on the first statement input on this block, or null if - * there are none. - * @return {?Connection} The first statement connection or null. - * @package - */ -Block.prototype.getFirstStatementConnection = function() { - for (let i = 0, input; (input = this.inputList[i]); i++) { - if (input.connection && - input.connection.type === ConnectionType.NEXT_STATEMENT) { - return input.connection; - } - } - return null; -}; - -/** - * Return the top-most block in this block's tree. - * This will return itself if this block is at the top level. - * @return {!Block} The root block. - */ -Block.prototype.getRootBlock = function() { - let rootBlock; - let block = this; - do { - rootBlock = block; - block = rootBlock.parentBlock_; - } while (block); - return rootBlock; -}; - -/** - * Walk up from the given block up through the stack of blocks to find - * the top block of the sub stack. If we are nested in a statement input only - * find the top-most nested block. Do not go all the way to the root block. - * @return {!Block} The top block in a stack. - * @package - */ -Block.prototype.getTopStackBlock = function() { - let block = this; - let previous; - do { - previous = block.getPreviousBlock(); - } while (previous && previous.getNextBlock() === block && (block = previous)); - return block; -}; - -/** - * Find all the blocks that are directly nested inside this one. - * Includes value and statement inputs, as well as any following statement. - * Excludes any connection on an output tab or any preceding statement. - * Blocks are optionally sorted by position; top to bottom. - * @param {boolean} ordered Sort the list if true. - * @return {!Array} Array of blocks. - */ -Block.prototype.getChildren = function(ordered) { - if (!ordered) { - return this.childBlocks_; - } - const blocks = []; - for (let i = 0, input; (input = this.inputList[i]); i++) { - if (input.connection) { - const child = input.connection.targetBlock(); - if (child) { - blocks.push(child); - } - } - } - const next = this.getNextBlock(); - if (next) { - blocks.push(next); - } - return blocks; -}; - -/** - * Set parent of this block to be a new block or null. - * @param {Block} newParent New parent block. - * @package - */ -Block.prototype.setParent = function(newParent) { - if (newParent === this.parentBlock_) { - return; - } - - // Check that block is connected to new parent if new parent is not null and - // that block is not connected to superior one if new parent is null. - const targetBlock = - (this.previousConnection && this.previousConnection.targetBlock()) || - (this.outputConnection && this.outputConnection.targetBlock()); - const isConnected = !!targetBlock; - - if (isConnected && newParent && targetBlock !== newParent) { - throw Error('Block connected to superior one that is not new parent.'); - } else if (!isConnected && newParent) { - throw Error('Block not connected to new parent.'); - } else if (isConnected && !newParent) { - throw Error( - 'Cannot set parent to null while block is still connected to' + - ' superior block.'); - } - - if (this.parentBlock_) { - // Remove this block from the old parent's child list. - arrayUtils.removeElem(this.parentBlock_.childBlocks_, this); - - // This block hasn't actually moved on-screen, so there's no need to update - // its connection locations. - } else { - // New parent must be non-null so remove this block from the workspace's - // list of top-most blocks. - this.workspace.removeTopBlock(this); - } - - this.parentBlock_ = newParent; - if (newParent) { - // Add this block to the new parent's child list. - newParent.childBlocks_.push(this); - } else { - this.workspace.addTopBlock(this); - } -}; - -/** - * Find all the blocks that are directly or indirectly nested inside this one. - * Includes this block in the list. - * Includes value and statement inputs, as well as any following statements. - * Excludes any connection on an output tab or any preceding statements. - * Blocks are optionally sorted by position; top to bottom. - * @param {boolean} ordered Sort the list if true. - * @return {!Array} Flattened array of blocks. - */ -Block.prototype.getDescendants = function(ordered) { - const blocks = [this]; - const childBlocks = this.getChildren(ordered); - for (let child, i = 0; (child = childBlocks[i]); i++) { - blocks.push.apply(blocks, child.getDescendants(ordered)); - } - return blocks; -}; - -/** - * Get whether this block is deletable or not. - * @return {boolean} True if deletable. - */ -Block.prototype.isDeletable = function() { - return this.deletable_ && !this.isShadow_ && - !(this.workspace && this.workspace.options.readOnly); -}; - -/** - * Set whether this block is deletable or not. - * @param {boolean} deletable True if deletable. - */ -Block.prototype.setDeletable = function(deletable) { - this.deletable_ = deletable; -}; - -/** - * Get whether this block is movable or not. - * @return {boolean} True if movable. - */ -Block.prototype.isMovable = function() { - return this.movable_ && !this.isShadow_ && - !(this.workspace && this.workspace.options.readOnly); -}; - -/** - * Set whether this block is movable or not. - * @param {boolean} movable True if movable. - */ -Block.prototype.setMovable = function(movable) { - this.movable_ = movable; -}; - -/** - * Get whether is block is duplicatable or not. If duplicating this block and - * descendants will put this block over the workspace's capacity this block is - * not duplicatable. If duplicating this block and descendants will put any - * type over their maxInstances this block is not duplicatable. - * @return {boolean} True if duplicatable. - */ -Block.prototype.isDuplicatable = function() { - if (!this.workspace.hasBlockLimits()) { - return true; - } - return this.workspace.isCapacityAvailable( - common.getBlockTypeCounts(this, true)); -}; - -/** - * Get whether this block is a shadow block or not. - * @return {boolean} True if a shadow. - */ -Block.prototype.isShadow = function() { - return this.isShadow_; -}; - -/** - * Set whether this block is a shadow block or not. - * @param {boolean} shadow True if a shadow. - * @package - */ -Block.prototype.setShadow = function(shadow) { - this.isShadow_ = shadow; -}; - -/** - * Get whether this block is an insertion marker block or not. - * @return {boolean} True if an insertion marker. - */ -Block.prototype.isInsertionMarker = function() { - return this.isInsertionMarker_; -}; - -/** - * Set whether this block is an insertion marker block or not. - * Once set this cannot be unset. - * @param {boolean} insertionMarker True if an insertion marker. - * @package - */ -Block.prototype.setInsertionMarker = function(insertionMarker) { - this.isInsertionMarker_ = insertionMarker; -}; - -/** - * Get whether this block is editable or not. - * @return {boolean} True if editable. - */ -Block.prototype.isEditable = function() { - return this.editable_ && !(this.workspace && this.workspace.options.readOnly); -}; - -/** - * Set whether this block is editable or not. - * @param {boolean} editable True if editable. - */ -Block.prototype.setEditable = function(editable) { - this.editable_ = editable; - for (let i = 0, input; (input = this.inputList[i]); i++) { - for (let j = 0, field; (field = input.fieldRow[j]); j++) { - field.updateEditable(); - } - } -}; - -/** - * Returns if this block has been disposed of / deleted. - * @return {boolean} True if this block has been disposed of / deleted. - */ -Block.prototype.isDisposed = function() { - return this.disposed; -}; - -/** - * Find the connection on this block that corresponds to the given connection - * on the other block. - * Used to match connections between a block and its insertion marker. - * @param {!Block} otherBlock The other block to match against. - * @param {!Connection} conn The other connection to match. - * @return {?Connection} The matching connection on this block, or null. - * @package - */ -Block.prototype.getMatchingConnection = function(otherBlock, conn) { - const connections = this.getConnections_(true); - const otherConnections = otherBlock.getConnections_(true); - if (connections.length !== otherConnections.length) { - throw Error('Connection lists did not match in length.'); - } - for (let i = 0; i < otherConnections.length; i++) { - if (otherConnections[i] === conn) { - return connections[i]; - } - } - return null; -}; - -/** - * Set the URL of this block's help page. - * @param {string|Function} url URL string for block help, or function that - * returns a URL. Null for no help. - */ -Block.prototype.setHelpUrl = function(url) { - this.helpUrl = url; -}; - -/** - * Sets the tooltip for this block. - * @param {!Tooltip.TipInfo} newTip The text for the tooltip, a function - * that returns the text for the tooltip, or a parent object whose tooltip - * will be used. To not display a tooltip pass the empty string. - */ -Block.prototype.setTooltip = function(newTip) { - this.tooltip = newTip; -}; - -/** - * Returns the tooltip text for this block. - * @return {!string} The tooltip text for this block. - */ -Block.prototype.getTooltip = function() { - return Tooltip.getTooltipOfObject(this); -}; - -/** - * Get the colour of a block. - * @return {string} #RRGGBB string. - */ -Block.prototype.getColour = function() { - return this.colour_; -}; - -/** - * Get the name of the block style. - * @return {string} Name of the block style. - */ -Block.prototype.getStyleName = function() { - return this.styleName_; -}; - -/** - * Get the HSV hue value of a block. Null if hue not set. - * @return {?number} Hue value (0-360). - */ -Block.prototype.getHue = function() { - return this.hue_; -}; - -/** - * Change the colour of a block. - * @param {number|string} colour HSV hue value (0 to 360), #RRGGBB string, - * or a message reference string pointing to one of those two values. - */ -Block.prototype.setColour = function(colour) { - const parsed = parsing.parseBlockColour(colour); - this.hue_ = parsed.hue; - this.colour_ = parsed.hex; -}; - -/** - * Set the style and colour values of a block. - * @param {string} blockStyleName Name of the block style. - */ -Block.prototype.setStyle = function(blockStyleName) { - this.styleName_ = blockStyleName; -}; - -/** - * Sets a callback function to use whenever the block's parent workspace - * changes, replacing any prior onchange handler. This is usually only called - * from the constructor, the block type initializer function, or an extension - * initializer function. - * @param {function(Abstract)} onchangeFn The callback to call - * when the block's workspace changes. - * @throws {Error} if onchangeFn is not falsey and not a function. - */ -Block.prototype.setOnChange = function(onchangeFn) { - if (onchangeFn && typeof onchangeFn !== 'function') { - throw Error('onchange must be a function.'); - } - if (this.onchangeWrapper_) { - this.workspace.removeChangeListener(this.onchangeWrapper_); - } - this.onchange = onchangeFn; - if (this.onchange) { - this.onchangeWrapper_ = onchangeFn.bind(this); - this.workspace.addChangeListener(this.onchangeWrapper_); - } -}; - -/** - * Returns the named field from a block. - * @param {string} name The name of the field. - * @return {?Field} Named field, or null if field does not exist. - */ -Block.prototype.getField = function(name) { - if (typeof name !== 'string') { - throw TypeError( - 'Block.prototype.getField expects a string ' + - 'with the field name but received ' + - (name === undefined ? 'nothing' : name + ' of type ' + typeof name) + - ' instead'); - } - for (let i = 0, input; (input = this.inputList[i]); i++) { - for (let j = 0, field; (field = input.fieldRow[j]); j++) { - if (field.name === name) { - return field; - } - } - } - return null; -}; - -/** - * Return all variables referenced by this block. - * @return {!Array} List of variable ids. - */ -Block.prototype.getVars = function() { - const vars = []; - for (let i = 0, input; (input = this.inputList[i]); i++) { - for (let j = 0, field; (field = input.fieldRow[j]); j++) { - if (field.referencesVariables()) { - vars.push(field.getValue()); - } - } - } - return vars; -}; - -/** - * Return all variables referenced by this block. - * @return {!Array} List of variable models. - * @package - */ -Block.prototype.getVarModels = function() { - const vars = []; - for (let i = 0, input; (input = this.inputList[i]); i++) { - for (let j = 0, field; (field = input.fieldRow[j]); j++) { - if (field.referencesVariables()) { - const model = this.workspace.getVariableById( - /** @type {string} */ (field.getValue())); - // Check if the variable actually exists (and isn't just a potential - // variable). - if (model) { - vars.push(model); - } - } - } - } - return vars; -}; - -/** - * Notification that a variable is renaming but keeping the same ID. If the - * variable is in use on this block, rerender to show the new name. - * @param {!VariableModel} variable The variable being renamed. - * @package - */ -Block.prototype.updateVarName = function(variable) { - for (let i = 0, input; (input = this.inputList[i]); i++) { - for (let j = 0, field; (field = input.fieldRow[j]); j++) { - if (field.referencesVariables() && - variable.getId() === field.getValue()) { - field.refreshVariableName(); - } - } - } -}; - -/** - * Notification that a variable is renaming. - * If the ID matches one of this block's variables, rename it. - * @param {string} oldId ID of variable to rename. - * @param {string} newId ID of new variable. May be the same as oldId, but with - * an updated name. - */ -Block.prototype.renameVarById = function(oldId, newId) { - for (let i = 0, input; (input = this.inputList[i]); i++) { - for (let j = 0, field; (field = input.fieldRow[j]); j++) { - if (field.referencesVariables() && oldId === field.getValue()) { - field.setValue(newId); - } - } - } -}; - -/** - * Returns the language-neutral value of the given field. - * @param {string} name The name of the field. - * @return {*} Value of the field or null if field does not exist. - */ -Block.prototype.getFieldValue = function(name) { - const field = this.getField(name); - if (field) { - return field.getValue(); - } - return null; -}; - -/** - * Sets the value of the given field for this block. - * @param {*} newValue The value to set. - * @param {string} name The name of the field to set the value of. - */ -Block.prototype.setFieldValue = function(newValue, name) { - const field = this.getField(name); - if (!field) { - throw Error('Field "' + name + '" not found.'); - } - field.setValue(newValue); -}; - -/** - * Set whether this block can chain onto the bottom of another block. - * @param {boolean} newBoolean True if there can be a previous statement. - * @param {(string|Array|null)=} opt_check Statement type or - * list of statement types. Null/undefined if any type could be connected. - */ -Block.prototype.setPreviousStatement = function(newBoolean, opt_check) { - if (newBoolean) { - if (opt_check === undefined) { - opt_check = null; - } - if (!this.previousConnection) { - this.previousConnection = - this.makeConnection_(ConnectionType.PREVIOUS_STATEMENT); - } - this.previousConnection.setCheck(opt_check); - } else { - if (this.previousConnection) { - if (this.previousConnection.isConnected()) { - throw Error( - 'Must disconnect previous statement before removing ' + - 'connection.'); - } - this.previousConnection.dispose(); - this.previousConnection = null; - } - } -}; - -/** - * Set whether another block can chain onto the bottom of this block. - * @param {boolean} newBoolean True if there can be a next statement. - * @param {(string|Array|null)=} opt_check Statement type or - * list of statement types. Null/undefined if any type could be connected. - */ -Block.prototype.setNextStatement = function(newBoolean, opt_check) { - if (newBoolean) { - if (opt_check === undefined) { - opt_check = null; - } - if (!this.nextConnection) { - this.nextConnection = this.makeConnection_(ConnectionType.NEXT_STATEMENT); - } - this.nextConnection.setCheck(opt_check); - } else { - if (this.nextConnection) { - if (this.nextConnection.isConnected()) { - throw Error( - 'Must disconnect next statement before removing ' + - 'connection.'); - } - this.nextConnection.dispose(); - this.nextConnection = null; - } - } -}; - -/** - * Set whether this block returns a value. - * @param {boolean} newBoolean True if there is an output. - * @param {(string|Array|null)=} opt_check Returned type or list - * of returned types. Null or undefined if any type could be returned - * (e.g. variable get). - */ -Block.prototype.setOutput = function(newBoolean, opt_check) { - if (newBoolean) { - if (opt_check === undefined) { - opt_check = null; - } - if (!this.outputConnection) { - this.outputConnection = this.makeConnection_(ConnectionType.OUTPUT_VALUE); - } - this.outputConnection.setCheck(opt_check); - } else { - if (this.outputConnection) { - if (this.outputConnection.isConnected()) { - throw Error('Must disconnect output value before removing connection.'); - } - this.outputConnection.dispose(); - this.outputConnection = null; - } - } -}; - -/** - * Set whether value inputs are arranged horizontally or vertically. - * @param {boolean} newBoolean True if inputs are horizontal. - */ -Block.prototype.setInputsInline = function(newBoolean) { - if (this.inputsInline !== newBoolean) { - eventUtils.fire(new (eventUtils.get(eventUtils.BLOCK_CHANGE))( - this, 'inline', null, this.inputsInline, newBoolean)); - this.inputsInline = newBoolean; - } -}; - -/** - * Get whether value inputs are arranged horizontally or vertically. - * @return {boolean} True if inputs are horizontal. - */ -Block.prototype.getInputsInline = function() { - if (this.inputsInline !== undefined) { - // Set explicitly. - return this.inputsInline; - } - // Not defined explicitly. Figure out what would look best. - for (let i = 1; i < this.inputList.length; i++) { - if (this.inputList[i - 1].type === inputTypes.DUMMY && - this.inputList[i].type === inputTypes.DUMMY) { - // Two dummy inputs in a row. Don't inline them. - return false; - } - } - for (let i = 1; i < this.inputList.length; i++) { - if (this.inputList[i - 1].type === inputTypes.VALUE && - this.inputList[i].type === inputTypes.DUMMY) { - // Dummy input after a value input. Inline them. - return true; - } - } - return false; -}; - -/** - * Set the block's output shape. - * @param {?number} outputShape Value representing an output shape. - */ -Block.prototype.setOutputShape = function(outputShape) { - this.outputShape_ = outputShape; -}; - -/** - * Get the block's output shape. - * @return {?number} Value representing output shape if one exists. - */ -Block.prototype.getOutputShape = function() { - return this.outputShape_; -}; - -/** - * Get whether this block is enabled or not. - * @return {boolean} True if enabled. - */ -Block.prototype.isEnabled = function() { - return !this.disabled; -}; - -/** - * Set whether the block is enabled or not. - * @param {boolean} enabled True if enabled. - */ -Block.prototype.setEnabled = function(enabled) { - if (this.isEnabled() !== enabled) { - const oldValue = this.disabled; - this.disabled = !enabled; - eventUtils.fire(new (eventUtils.get(eventUtils.BLOCK_CHANGE))( - this, 'disabled', null, oldValue, !enabled)); - } -}; - -/** - * Get whether the block is disabled or not due to parents. - * The block's own disabled property is not considered. - * @return {boolean} True if disabled. - */ -Block.prototype.getInheritedDisabled = function() { - let ancestor = this.getSurroundParent(); - while (ancestor) { - if (ancestor.disabled) { - return true; - } - ancestor = ancestor.getSurroundParent(); - } - // Ran off the top. - return false; -}; - -/** - * Get whether the block is collapsed or not. - * @return {boolean} True if collapsed. - */ -Block.prototype.isCollapsed = function() { - return this.collapsed_; -}; - -/** - * Set whether the block is collapsed or not. - * @param {boolean} collapsed True if collapsed. - */ -Block.prototype.setCollapsed = function(collapsed) { - if (this.collapsed_ !== collapsed) { - eventUtils.fire(new (eventUtils.get(eventUtils.BLOCK_CHANGE))( - this, 'collapsed', null, this.collapsed_, collapsed)); - this.collapsed_ = collapsed; - } -}; - -/** - * Create a human-readable text representation of this block and any children. - * @param {number=} opt_maxLength Truncate the string to this length. - * @param {string=} opt_emptyToken The placeholder string used to denote an - * empty field. If not specified, '?' is used. - * @return {string} Text of block. - */ -Block.prototype.toString = function(opt_maxLength, opt_emptyToken) { - let text = []; - const emptyFieldPlaceholder = opt_emptyToken || '?'; - - // Temporarily set flag to navigate to all fields. - const prevNavigateFields = ASTNode.NAVIGATE_ALL_FIELDS; - ASTNode.NAVIGATE_ALL_FIELDS = true; - - let node = ASTNode.createBlockNode(this); - const rootNode = node; - - /** - * Whether or not to add parentheses around an input. - * @param {!Connection} connection The connection. - * @return {boolean} True if we should add parentheses around the input. - */ - function shouldAddParentheses(connection) { - let checks = connection.getCheck(); - if (!checks && connection.targetConnection) { - checks = connection.targetConnection.getCheck(); - } - return !!checks && - (checks.indexOf('Boolean') !== -1 || checks.indexOf('Number') !== -1); - } - - /** - * Check that we haven't circled back to the original root node. - */ - function checkRoot() { - if (node && node.getType() === rootNode.getType() && - node.getLocation() === rootNode.getLocation()) { - node = null; - } - } - - // Traverse the AST building up our text string. - while (node) { - switch (node.getType()) { - case ASTNode.types.INPUT: { - const connection = /** @type {!Connection} */ (node.getLocation()); - if (!node.in()) { - text.push(emptyFieldPlaceholder); - } else if (shouldAddParentheses(connection)) { - text.push('('); - } - break; - } - case ASTNode.types.FIELD: { - const field = /** @type {Field} */ (node.getLocation()); - if (field.name !== constants.COLLAPSED_FIELD_NAME) { - text.push(field.getText()); - } - break; - } - } - - const current = node; - node = current.in() || current.next(); - if (!node) { - // Can't go in or next, keep going out until we can go next. - node = current.out(); - checkRoot(); - while (node && !node.next()) { - node = node.out(); - checkRoot(); - // If we hit an input on the way up, possibly close out parentheses. - if (node && node.getType() === ASTNode.types.INPUT && - shouldAddParentheses( - /** @type {!Connection} */ (node.getLocation()))) { - text.push(')'); - } - } - if (node) { - node = node.next(); - } - } - } - - // Restore state of NAVIGATE_ALL_FIELDS. - ASTNode.NAVIGATE_ALL_FIELDS = prevNavigateFields; - - // Run through our text array and simplify expression to remove parentheses - // around single field blocks. - // E.g. ['repeat', '(', '10', ')', 'times', 'do', '?'] - for (let i = 2; i < text.length; i++) { - if (text[i - 2] === '(' && text[i] === ')') { - text[i - 2] = text[i - 1]; - text.splice(i - 1, 2); - } - } - - // Join the text array, removing spaces around added parentheses. - text = text.reduce(function(acc, value) { - return acc + ((acc.substr(-1) === '(' || value === ')') ? '' : ' ') + value; - }, ''); - text = text.trim() || '???'; - if (opt_maxLength) { - // TODO: Improve truncation so that text from this block is given priority. - // E.g. "1+2+3+4+5+6+7+8+9=0" should be "...6+7+8+9=0", not "1+2+3+4+5...". - // E.g. "1+2+3+4+5=6+7+8+9+0" should be "...4+5=6+7...". - if (text.length > opt_maxLength) { - text = text.substring(0, opt_maxLength - 3) + '...'; - } - } - return text; -}; - -/** - * Shortcut for appending a value input row. - * @param {string} name Language-neutral identifier which may used to find this - * input again. Should be unique to this block. - * @return {!Input} The input object created. - */ -Block.prototype.appendValueInput = function(name) { - return this.appendInput_(inputTypes.VALUE, name); -}; - -/** - * Shortcut for appending a statement input row. - * @param {string} name Language-neutral identifier which may used to find this - * input again. Should be unique to this block. - * @return {!Input} The input object created. - */ -Block.prototype.appendStatementInput = function(name) { - return this.appendInput_(inputTypes.STATEMENT, name); -}; - -/** - * Shortcut for appending a dummy input row. - * @param {string=} opt_name Language-neutral identifier which may used to find - * this input again. Should be unique to this block. - * @return {!Input} The input object created. - */ -Block.prototype.appendDummyInput = function(opt_name) { - return this.appendInput_(inputTypes.DUMMY, opt_name || ''); -}; - -/** - * Initialize this block using a cross-platform, internationalization-friendly - * JSON description. - * @param {!Object} json Structured data describing the block. - */ -Block.prototype.jsonInit = function(json) { - const warningPrefix = json['type'] ? 'Block "' + json['type'] + '": ' : ''; - - // Validate inputs. - if (json['output'] && json['previousStatement']) { - throw Error( - warningPrefix + - 'Must not have both an output and a previousStatement.'); - } - - // Set basic properties of block. - // Makes styles backward compatible with old way of defining hat style. - if (json['style'] && json['style'].hat) { - this.hat = json['style'].hat; - // Must set to null so it doesn't error when checking for style and colour. - json['style'] = null; - } - - if (json['style'] && json['colour']) { - throw Error(warningPrefix + 'Must not have both a colour and a style.'); - } else if (json['style']) { - this.jsonInitStyle_(json, warningPrefix); - } else { - this.jsonInitColour_(json, warningPrefix); - } - - // Interpolate the message blocks. - let i = 0; - while (json['message' + i] !== undefined) { - this.interpolate_( - json['message' + i], json['args' + i] || [], json['lastDummyAlign' + i], - warningPrefix); - i++; - } - - if (json['inputsInline'] !== undefined) { - this.setInputsInline(json['inputsInline']); - } - // Set output and previous/next connections. - if (json['output'] !== undefined) { - this.setOutput(true, json['output']); - } - if (json['outputShape'] !== undefined) { - this.setOutputShape(json['outputShape']); - } - if (json['previousStatement'] !== undefined) { - this.setPreviousStatement(true, json['previousStatement']); - } - if (json['nextStatement'] !== undefined) { - this.setNextStatement(true, json['nextStatement']); - } - if (json['tooltip'] !== undefined) { - const rawValue = json['tooltip']; - const localizedText = parsing.replaceMessageReferences(rawValue); - this.setTooltip(localizedText); - } - if (json['enableContextMenu'] !== undefined) { - this.contextMenu = !!json['enableContextMenu']; - } - if (json['suppressPrefixSuffix'] !== undefined) { - this.suppressPrefixSuffix = !!json['suppressPrefixSuffix']; - } - if (json['helpUrl'] !== undefined) { - const rawValue = json['helpUrl']; - const localizedValue = parsing.replaceMessageReferences(rawValue); - this.setHelpUrl(localizedValue); - } - if (typeof json['extensions'] === 'string') { - console.warn( - warningPrefix + 'JSON attribute \'extensions\' should be an array of' + - ' strings. Found raw string in JSON for \'' + json['type'] + - '\' block.'); - json['extensions'] = [json['extensions']]; // Correct and continue. - } - - // Add the mutator to the block. - if (json['mutator'] !== undefined) { - Extensions.apply(json['mutator'], this, true); - } - - const extensionNames = json['extensions']; - if (Array.isArray(extensionNames)) { - for (let j = 0; j < extensionNames.length; j++) { - Extensions.apply(extensionNames[j], this, false); - } - } -}; - -/** - * Initialize the colour of this block from the JSON description. - * @param {!Object} json Structured data describing the block. - * @param {string} warningPrefix Warning prefix string identifying block. - * @private - */ -Block.prototype.jsonInitColour_ = function(json, warningPrefix) { - if ('colour' in json) { - if (json['colour'] === undefined) { - console.warn(warningPrefix + 'Undefined colour value.'); - } else { - const rawValue = json['colour']; - try { - this.setColour(rawValue); - } catch (e) { - console.warn(warningPrefix + 'Illegal colour value: ', rawValue); - } - } - } -}; - -/** - * Initialize the style of this block from the JSON description. - * @param {!Object} json Structured data describing the block. - * @param {string} warningPrefix Warning prefix string identifying block. - * @private - */ -Block.prototype.jsonInitStyle_ = function(json, warningPrefix) { - const blockStyleName = json['style']; - try { - this.setStyle(blockStyleName); - } catch (styleError) { - console.warn(warningPrefix + 'Style does not exist: ', blockStyleName); - } -}; - -/** - * Add key/values from mixinObj to this block object. By default, this method - * will check that the keys in mixinObj will not overwrite existing values in - * the block, including prototype values. This provides some insurance against - * mixin / extension incompatibilities with future block features. This check - * can be disabled by passing true as the second argument. - * @param {!Object} mixinObj The key/values pairs to add to this block object. - * @param {boolean=} opt_disableCheck Option flag to disable overwrite checks. - */ -Block.prototype.mixin = function(mixinObj, opt_disableCheck) { - if (opt_disableCheck !== undefined && typeof opt_disableCheck !== 'boolean') { - throw Error('opt_disableCheck must be a boolean if provided'); - } - if (!opt_disableCheck) { - const overwrites = []; - for (const key in mixinObj) { - if (this[key] !== undefined) { - overwrites.push(key); - } - } - if (overwrites.length) { - throw Error( - 'Mixin will overwrite block members: ' + JSON.stringify(overwrites)); - } - } - object.mixin(this, mixinObj); -}; - -/** - * Interpolate a message description onto the block. - * @param {string} message Text contains interpolation tokens (%1, %2, ...) - * that match with fields or inputs defined in the args array. - * @param {!Array} args Array of arguments to be interpolated. - * @param {string|undefined} lastDummyAlign If a dummy input is added at the - * end, how should it be aligned? - * @param {string} warningPrefix Warning prefix string identifying block. - * @private - */ -Block.prototype.interpolate_ = function( - message, args, lastDummyAlign, warningPrefix) { - const tokens = parsing.tokenizeInterpolation(message); - this.validateTokens_(tokens, args.length); - const elements = this.interpolateArguments_(tokens, args, lastDummyAlign); - - // An array of [field, fieldName] tuples. - const fieldStack = []; - for (let i = 0, element; (element = elements[i]); i++) { - if (this.isInputKeyword_(element['type'])) { - const input = this.inputFromJson_(element, warningPrefix); - // Should never be null, but just in case. - if (input) { - for (let j = 0, tuple; (tuple = fieldStack[j]); j++) { - input.appendField(tuple[0], tuple[1]); - } - fieldStack.length = 0; - } - } else { - // All other types, including ones starting with 'input_' get routed here. - const field = this.fieldFromJson_(element); - if (field) { - fieldStack.push([field, element['name']]); - } - } - } -}; - -/** - * Validates that the tokens are within the correct bounds, with no duplicates, - * and that all of the arguments are referred to. Throws errors if any of these - * things are not true. - * @param {!Array} tokens An array of tokens to validate - * @param {number} argsCount The number of args that need to be referred to. - * @private - */ -Block.prototype.validateTokens_ = function(tokens, argsCount) { - const visitedArgsHash = []; - let visitedArgsCount = 0; - for (let i = 0; i < tokens.length; i++) { - const token = tokens[i]; - if (typeof token !== 'number') { - continue; - } - if (token < 1 || token > argsCount) { - throw Error( - 'Block "' + this.type + '": ' + - 'Message index %' + token + ' out of range.'); - } - if (visitedArgsHash[token]) { - throw Error( - 'Block "' + this.type + '": ' + - 'Message index %' + token + ' duplicated.'); - } - visitedArgsHash[token] = true; - visitedArgsCount++; - } - if (visitedArgsCount !== argsCount) { - throw Error( - 'Block "' + this.type + '": ' + - 'Message does not reference all ' + argsCount + ' arg(s).'); - } -}; - -/** - * Inserts args in place of numerical tokens. String args are converted to JSON - * that defines a label field. If necessary an extra dummy input is added to - * the end of the elements. - * @param {!Array} tokens The tokens to interpolate - * @param {!Array} args The arguments to insert. - * @param {string|undefined} lastDummyAlign The alignment the added dummy input - * should have, if we are required to add one. - * @return {!Array} The JSON definitions of field and inputs to add - * to the block. - * @private - */ -Block.prototype.interpolateArguments_ = function(tokens, args, lastDummyAlign) { - const elements = []; - for (let i = 0; i < tokens.length; i++) { - let element = tokens[i]; - if (typeof element === 'number') { - element = args[element - 1]; - } - // Args can be strings, which is why this isn't elseif. - if (typeof element === 'string') { - element = this.stringToFieldJson_(element); - if (!element) { - continue; - } - } - elements.push(element); - } - - const length = elements.length; - if (length && !this.isInputKeyword_(elements[length - 1]['type'])) { - const dummyInput = {'type': 'input_dummy'}; - if (lastDummyAlign) { - dummyInput['align'] = lastDummyAlign; - } - elements.push(dummyInput); - } - - return elements; -}; - -/** - * Creates a field from the JSON definition of a field. If a field with the - * given type cannot be found, this attempts to create a different field using - * the 'alt' property of the JSON definition (if it exists). - * @param {{alt:(string|undefined)}} element The element to try to turn into a - * field. - * @return {?Field} The field defined by the JSON, or null if one - * couldn't be created. - * @private - */ -Block.prototype.fieldFromJson_ = function(element) { - const field = fieldRegistry.fromJson(element); - if (!field && element['alt']) { - if (typeof element['alt'] === 'string') { - const json = this.stringToFieldJson_(element['alt']); - return json ? this.fieldFromJson_(json) : null; - } - return this.fieldFromJson_(element['alt']); - } - return field; -}; - -/** - * Creates an input from the JSON definition of an input. Sets the input's check - * and alignment if they are provided. - * @param {!Object} element The JSON to turn into an input. - * @param {string} warningPrefix The prefix to add to warnings to help the - * developer debug. - * @return {?Input} The input that has been created, or null if one - * could not be created for some reason (should never happen). - * @private - */ -Block.prototype.inputFromJson_ = function(element, warningPrefix) { - const alignmentLookup = { - 'LEFT': Align.LEFT, - 'RIGHT': Align.RIGHT, - 'CENTRE': Align.CENTRE, - 'CENTER': Align.CENTRE, - }; - - let input = null; - switch (element['type']) { - case 'input_value': - input = this.appendValueInput(element['name']); - break; - case 'input_statement': - input = this.appendStatementInput(element['name']); - break; - case 'input_dummy': - input = this.appendDummyInput(element['name']); - break; - } - // Should never be hit because of interpolate_'s checks, but just in case. - if (!input) { - return null; - } - - if (element['check']) { - input.setCheck(element['check']); - } - if (element['align']) { - const alignment = alignmentLookup[element['align'].toUpperCase()]; - if (alignment === undefined) { - console.warn(warningPrefix + 'Illegal align value: ', element['align']); - } else { - input.setAlign(alignment); - } - } - return input; -}; - -/** - * Returns true if the given string matches one of the input keywords. - * @param {string} str The string to check. - * @return {boolean} True if the given string matches one of the input keywords, - * false otherwise. - * @private - */ -Block.prototype.isInputKeyword_ = function(str) { - return str === 'input_value' || str === 'input_statement' || - str === 'input_dummy'; -}; - -/** - * Turns a string into the JSON definition of a label field. If the string - * becomes an empty string when trimmed, this returns null. - * @param {string} str String to turn into the JSON definition of a label field. - * @return {?{text: string, type: string}} The JSON definition or null. - * @private - */ -Block.prototype.stringToFieldJson_ = function(str) { - str = str.trim(); - if (str) { - return { - 'type': 'field_label', - 'text': str, - }; - } - return null; -}; - -/** - * Add a value input, statement input or local variable to this block. - * @param {number} type One of Blockly.inputTypes. - * @param {string} name Language-neutral identifier which may used to find this - * input again. Should be unique to this block. - * @return {!Input} The input object created. - * @protected - */ -Block.prototype.appendInput_ = function(type, name) { - let connection = null; - if (type === inputTypes.VALUE || type === inputTypes.STATEMENT) { - connection = this.makeConnection_(type); - } - if (type === inputTypes.STATEMENT) { - this.statementInputCount++; - } - const input = new Input(type, name, this, connection); - // Append input to list. - this.inputList.push(input); - return input; -}; - -/** - * Move a named input to a different location on this block. - * @param {string} name The name of the input to move. - * @param {?string} refName Name of input that should be after the moved input, - * or null to be the input at the end. - */ -Block.prototype.moveInputBefore = function(name, refName) { - if (name === refName) { - return; - } - // Find both inputs. - let inputIndex = -1; - let refIndex = refName ? -1 : this.inputList.length; - for (let i = 0, input; (input = this.inputList[i]); i++) { - if (input.name === name) { - inputIndex = i; - if (refIndex !== -1) { - break; - } - } else if (refName && input.name === refName) { - refIndex = i; - if (inputIndex !== -1) { - break; - } - } - } - if (inputIndex === -1) { - throw Error('Named input "' + name + '" not found.'); - } - if (refIndex === -1) { - throw Error('Reference input "' + refName + '" not found.'); - } - this.moveNumberedInputBefore(inputIndex, refIndex); -}; - -/** - * Move a numbered input to a different location on this block. - * @param {number} inputIndex Index of the input to move. - * @param {number} refIndex Index of input that should be after the moved input. - */ -Block.prototype.moveNumberedInputBefore = function(inputIndex, refIndex) { - // Validate arguments. - if (inputIndex === refIndex) { - throw Error('Can\'t move input to itself.'); - } - if (inputIndex >= this.inputList.length) { - throw RangeError('Input index ' + inputIndex + ' out of bounds.'); - } - if (refIndex > this.inputList.length) { - throw RangeError('Reference input ' + refIndex + ' out of bounds.'); - } - // Remove input. - const input = this.inputList[inputIndex]; - this.inputList.splice(inputIndex, 1); - if (inputIndex < refIndex) { - refIndex--; - } - // Reinsert input. - this.inputList.splice(refIndex, 0, input); -}; - -/** - * Remove an input from this block. - * @param {string} name The name of the input. - * @param {boolean=} opt_quiet True to prevent an error if input is not present. - * @return {boolean} True if operation succeeds, false if input is not present - * and opt_quiet is true. - * @throws {Error} if the input is not present and opt_quiet is not true. - */ -Block.prototype.removeInput = function(name, opt_quiet) { - for (let i = 0, input; (input = this.inputList[i]); i++) { - if (input.name === name) { - if (input.type === inputTypes.STATEMENT) { - this.statementInputCount--; - } - input.dispose(); - this.inputList.splice(i, 1); - return true; - } - } - if (opt_quiet) { - return false; - } - throw Error('Input not found: ' + name); -}; - -/** - * Fetches the named input object. - * @param {string} name The name of the input. - * @return {?Input} The input object, or null if input does not exist. - */ -Block.prototype.getInput = function(name) { - for (let i = 0, input; (input = this.inputList[i]); i++) { - if (input.name === name) { - return input; - } - } - // This input does not exist. - return null; -}; - -/** - * Fetches the block attached to the named input. - * @param {string} name The name of the input. - * @return {?Block} The attached value block, or null if the input is - * either disconnected or if the input does not exist. - */ -Block.prototype.getInputTargetBlock = function(name) { - const input = this.getInput(name); - return input && input.connection && input.connection.targetBlock(); -}; - -/** - * Returns the comment on this block (or null if there is no comment). - * @return {?string} Block's comment. - */ -Block.prototype.getCommentText = function() { - return this.commentModel.text; -}; - -/** - * Set this block's comment text. - * @param {?string} text The text, or null to delete. - */ -Block.prototype.setCommentText = function(text) { - if (this.commentModel.text === text) { - return; - } - eventUtils.fire(new (eventUtils.get(eventUtils.BLOCK_CHANGE))( - this, 'comment', null, this.commentModel.text, text)); - this.commentModel.text = text; - this.comment = text; // For backwards compatibility. -}; - -/** - * Set this block's warning text. - * @param {?string} _text The text, or null to delete. - * @param {string=} _opt_id An optional ID for the warning text to be able to - * maintain multiple warnings. - */ -Block.prototype.setWarningText = function(_text, _opt_id) { - // NOP. -}; - -/** - * Give this block a mutator dialog. - * @param {Mutator} _mutator A mutator dialog instance or null to - * remove. - */ -Block.prototype.setMutator = function(_mutator) { - // NOP. -}; - -/** - * Return the coordinates of the top-left corner of this block relative to the - * drawing surface's origin (0,0), in workspace units. - * @return {!Coordinate} Object with .x and .y properties. - */ -Block.prototype.getRelativeToSurfaceXY = function() { - return this.xy_; -}; - -/** - * Move a block by a relative offset. - * @param {number} dx Horizontal offset, in workspace units. - * @param {number} dy Vertical offset, in workspace units. - */ -Block.prototype.moveBy = function(dx, dy) { - if (this.parentBlock_) { - throw Error('Block has parent.'); - } - const event = /** @type {!BlockMove} */ ( - new (eventUtils.get(eventUtils.BLOCK_MOVE))(this)); - this.xy_.translate(dx, dy); - event.recordNew(); - eventUtils.fire(event); -}; - -/** - * Create a connection of the specified type. - * @param {number} type The type of the connection to create. - * @return {!Connection} A new connection of the specified type. - * @protected - */ -Block.prototype.makeConnection_ = function(type) { - return new Connection(this, type); -}; - -/** - * Recursively checks whether all statement and value inputs are filled with - * blocks. Also checks all following statement blocks in this stack. - * @param {boolean=} opt_shadowBlocksAreFilled An optional argument controlling - * whether shadow blocks are counted as filled. Defaults to true. - * @return {boolean} True if all inputs are filled, false otherwise. - */ -Block.prototype.allInputsFilled = function(opt_shadowBlocksAreFilled) { - // Account for the shadow block filledness toggle. - if (opt_shadowBlocksAreFilled === undefined) { - opt_shadowBlocksAreFilled = true; - } - if (!opt_shadowBlocksAreFilled && this.isShadow()) { - return false; - } - - // Recursively check each input block of the current block. - for (let i = 0, input; (input = this.inputList[i]); i++) { - if (!input.connection) { - continue; - } - const target = input.connection.targetBlock(); - if (!target || !target.allInputsFilled(opt_shadowBlocksAreFilled)) { - return false; - } - } - - // Recursively check the next block after the current block. - const next = this.getNextBlock(); - if (next) { - return next.allInputsFilled(opt_shadowBlocksAreFilled); - } - - return true; -}; - -/** - * This method returns a string describing this Block in developer terms (type - * name and ID; English only). - * - * Intended to on be used in console logs and errors. If you need a string that - * uses the user's native language (including block text, field values, and - * child blocks), use [toString()]{@link Block#toString}. - * @return {string} The description. - */ -Block.prototype.toDevString = function() { - let msg = this.type ? '"' + this.type + '" block' : 'Block'; - if (this.id) { - msg += ' (id="' + this.id + '")'; - } - return msg; -}; - exports.Block = Block; diff --git a/core/block_dragger.js b/core/block_dragger.js index 88c1a177d..896f099f7 100644 --- a/core/block_dragger.js +++ b/core/block_dragger.js @@ -460,7 +460,8 @@ const BlockDragger = class { const initIconData = function(block) { // Build a list of icons that need to be moved and where they started. const dragIconData = []; - const descendants = block.getDescendants(false); + const descendants = + /** @type {!Array} */ (block.getDescendants(false)); for (let i = 0, descendant; (descendant = descendants[i]); i++) { const icons = descendant.getIcons(); diff --git a/core/block_svg.js b/core/block_svg.js index ffd6eb48f..3b81d63f8 100644 --- a/core/block_svg.js +++ b/core/block_svg.js @@ -25,7 +25,6 @@ const constants = goog.require('Blockly.constants'); const dom = goog.require('Blockly.utils.dom'); const eventUtils = goog.require('Blockly.Events.utils'); const internalConstants = goog.require('Blockly.internalConstants'); -const object = goog.require('Blockly.utils.object'); const svgMath = goog.require('Blockly.utils.svgMath'); const userAgent = goog.require('Blockly.utils.userAgent'); const {ASTNode} = goog.require('Blockly.ASTNode'); @@ -84,175 +83,1789 @@ goog.require('Blockly.Touch'); /** * Class for a block's SVG representation. * Not normally called directly, workspace.newBlock() is preferred. - * @param {!WorkspaceSvg} workspace The block's workspace. - * @param {?string} prototypeName Name of the language object containing - * type-specific functions for this block. - * @param {string=} opt_id Optional ID. Use this ID if provided, otherwise - * create a new ID. * @extends {Block} * @implements {IASTNodeLocationSvg} * @implements {IBoundedElement} * @implements {ICopyable} * @implements {IDraggable} - * @constructor - * @alias Blockly.BlockSvg */ -const BlockSvg = function(workspace, prototypeName, opt_id) { +class BlockSvg extends Block { /** - * An optional method called when a mutator dialog is first opened. - * This function must create and initialize a top-level block for the mutator - * dialog, and return it. This function should also populate this top-level - * block with any sub-blocks which are appropriate. This method must also be - * coupled with defining a `compose` method for the default mutation dialog - * button and UI to appear. - * @type {undefined|?function(WorkspaceSvg):!BlockSvg} + * @param {!WorkspaceSvg} workspace The block's workspace. + * @param {string} prototypeName Name of the language object containing + * type-specific functions for this block. + * @param {string=} opt_id Optional ID. Use this ID if provided, otherwise + * create a new ID. + * @alias Blockly.BlockSvg */ - this.decompose = undefined; + constructor(workspace, prototypeName, opt_id) { + super(workspace, prototypeName, opt_id); - /** - * An optional method called when a mutator dialog saves its content. - * This function is called to modify the original block according to new - * settings. This method must also be coupled with defining a `decompose` - * method for the default mutation dialog button and UI to appear. - * @type {undefined|?function(!BlockSvg)} - */ - this.compose = undefined; + /** + * An optional method called when a mutator dialog is first opened. + * This function must create and initialize a top-level block for the + * mutator dialog, and return it. This function should also populate this + * top-level block with any sub-blocks which are appropriate. This method + * must also be coupled with defining a `compose` method for the default + * mutation dialog button and UI to appear. + * @type {undefined|?function(WorkspaceSvg):!BlockSvg} + */ + this.decompose = undefined; - /** - * An optional method for defining custom block context menu items. - * @type {undefined|?function(!Array)} - */ - this.customContextMenu = undefined; + /** + * An optional method called when a mutator dialog saves its content. + * This function is called to modify the original block according to new + * settings. This method must also be coupled with defining a `decompose` + * method for the default mutation dialog button and UI to appear. + * @type {undefined|?function(!BlockSvg)} + */ + this.compose = undefined; - /** - * An property used internally to reference the block's rendering debugger. - * @type {?BlockRenderingDebug} - * @package - */ - this.renderingDebugger = null; + /** + * An optional method for defining custom block context menu items. + * @type {undefined|?function(!Array)} + */ + this.customContextMenu = undefined; - /** - * Height of this block, not including any statement blocks above or below. - * Height is in workspace units. - * @type {number} - */ - this.height = 0; + /** + * An property used internally to reference the block's rendering debugger. + * @type {?BlockRenderingDebug} + * @package + */ + this.renderingDebugger = null; - /** - * Width of this block, including any connected value blocks. - * Width is in workspace units. - * @type {number} - */ - this.width = 0; + /** + * Height of this block, not including any statement blocks above or below. + * Height is in workspace units. + * @type {number} + */ + this.height = 0; - /** - * Map from IDs for warnings text to PIDs of functions to apply them. - * Used to be able to maintain multiple warnings. - * @type {Object} - * @private - */ - this.warningTextDb_ = null; + /** + * Width of this block, including any connected value blocks. + * Width is in workspace units. + * @type {number} + */ + this.width = 0; - /** - * Block's mutator icon (if any). - * @type {?Mutator} - */ - this.mutator = null; + /** + * Map from IDs for warnings text to PIDs of functions to apply them. + * Used to be able to maintain multiple warnings. + * @type {Object} + * @private + */ + this.warningTextDb_ = null; - /** - * Block's comment icon (if any). - * @type {?Comment} - * @deprecated August 2019. Use getCommentIcon instead. - */ - this.comment = null; + /** + * Block's mutator icon (if any). + * @type {?Mutator} + */ + this.mutator = null; - /** - * Block's comment icon (if any). - * @type {?Comment} - * @private - */ - this.commentIcon_ = null; + /** + * Block's comment icon (if any). + * @type {?Comment} + * @deprecated August 2019. Use getCommentIcon instead. + */ + this.comment = null; - /** - * Block's warning icon (if any). - * @type {?Warning} - */ - this.warning = null; + /** + * Block's comment icon (if any). + * @type {?Comment} + * @private + */ + this.commentIcon_ = null; + /** + * Block's warning icon (if any). + * @type {?Warning} + */ + this.warning = null; - // Create core elements for the block. - /** - * @type {!SVGGElement} - * @private - */ - this.svgGroup_ = dom.createSvgElement(Svg.G, {}, null); - this.svgGroup_.translate_ = ''; + // Create core elements for the block. + /** + * @type {!SVGGElement} + * @private + */ + this.svgGroup_ = dom.createSvgElement(Svg.G, {}, null); + this.svgGroup_.translate_ = ''; - /** - * A block style object. - * @type {!Theme.BlockStyle} - */ - this.style = workspace.getRenderer().getConstants().getBlockStyle(null); + /** + * A block style object. + * @type {!Theme.BlockStyle} + */ + this.style = workspace.getRenderer().getConstants().getBlockStyle(null); - /** - * The renderer's path object. - * @type {IPathObject} - * @package - */ - this.pathObject = - workspace.getRenderer().makePathObject(this.svgGroup_, this.style); + /** + * The renderer's path object. + * @type {IPathObject} + * @package + */ + this.pathObject = + workspace.getRenderer().makePathObject(this.svgGroup_, this.style); - /** @type {boolean} */ - this.rendered = false; - /** - * Is this block currently rendering? Used to stop recursive render calls - * from actually triggering a re-render. - * @type {boolean} - * @private - */ - this.renderIsInProgress_ = false; + /** @type {boolean} */ + this.rendered = false; + /** + * Is this block currently rendering? Used to stop recursive render calls + * from actually triggering a re-render. + * @type {boolean} + * @private + */ + this.renderIsInProgress_ = false; - /** - * Whether mousedown events have been bound yet. - * @type {boolean} - * @private - */ - this.eventsInit_ = false; + /** + * Whether mousedown events have been bound yet. + * @type {boolean} + * @private + */ + this.eventsInit_ = false; - /** @type {!WorkspaceSvg} */ - this.workspace = workspace; + /** @type {!WorkspaceSvg} */ + this.workspace; + /** @type {RenderedConnection} */ + this.outputConnection; + /** @type {RenderedConnection} */ + this.nextConnection; + /** @type {RenderedConnection} */ + this.previousConnection; - /** @type {RenderedConnection} */ - this.outputConnection = null; - /** @type {RenderedConnection} */ - this.nextConnection = null; - /** @type {RenderedConnection} */ - this.previousConnection = null; + /** + * Whether to move the block to the drag surface when it is dragged. + * True if it should move, false if it should be translated directly. + * @type {boolean} + * @private + */ + this.useDragSurface_ = + svgMath.is3dSupported() && !!workspace.getBlockDragSurface(); - /** - * Whether to move the block to the drag surface when it is dragged. - * True if it should move, false if it should be translated directly. - * @type {boolean} - * @private - */ - this.useDragSurface_ = - svgMath.is3dSupported() && !!workspace.getBlockDragSurface(); + const svgPath = this.pathObject.svgPath; + svgPath.tooltip = this; + Tooltip.bindMouseEvents(svgPath); - const svgPath = this.pathObject.svgPath; - svgPath.tooltip = this; - Tooltip.bindMouseEvents(svgPath); - BlockSvg.superClass_.constructor.call(this, workspace, prototypeName, opt_id); + // Expose this block's ID on its top-level SVG group. + if (this.svgGroup_.dataset) { + this.svgGroup_.dataset['id'] = this.id; + } else if (userAgent.IE) { + // SVGElement.dataset is not available on IE11, but data-* properties + // can be set with setAttribute(). + this.svgGroup_.setAttribute('data-id', this.id); + } - // Expose this block's ID on its top-level SVG group. - if (this.svgGroup_.dataset) { - this.svgGroup_.dataset['id'] = this.id; - } else if (userAgent.IE) { - // SVGElement.dataset is not available on IE11, but data-* properties - // can be set with setAttribute(). - this.svgGroup_.setAttribute('data-id', this.id); + this.doInit_(); } -}; -object.inherits(BlockSvg, Block); + + /** + * Create and initialize the SVG representation of the block. + * May be called more than once. + */ + initSvg() { + if (!this.workspace.rendered) { + throw TypeError('Workspace is headless.'); + } + for (let i = 0, input; (input = this.inputList[i]); i++) { + input.init(); + } + const icons = this.getIcons(); + for (let i = 0; i < icons.length; i++) { + icons[i].createIcon(); + } + this.applyColour(); + this.pathObject.updateMovable(this.isMovable()); + const svg = this.getSvgRoot(); + if (!this.workspace.options.readOnly && !this.eventsInit_ && svg) { + browserEvents.conditionalBind(svg, 'mousedown', this, this.onMouseDown_); + } + this.eventsInit_ = true; + + if (!svg.parentNode) { + this.workspace.getCanvas().appendChild(svg); + } + } + + /** + * Get the secondary colour of a block. + * @return {?string} #RRGGBB string. + */ + getColourSecondary() { + return this.style.colourSecondary; + } + + /** + * Get the tertiary colour of a block. + * @return {?string} #RRGGBB string. + */ + getColourTertiary() { + return this.style.colourTertiary; + } + + /** + * Selects this block. Highlights the block visually and fires a select event + * if the block is not already selected. + */ + select() { + if (this.isShadow() && this.getParent()) { + // Shadow blocks should not be selected. + this.getParent().select(); + return; + } + if (common.getSelected() === this) { + return; + } + let oldId = null; + if (common.getSelected()) { + oldId = common.getSelected().id; + // Unselect any previously selected block. + eventUtils.disable(); + try { + common.getSelected().unselect(); + } finally { + eventUtils.enable(); + } + } + const event = new (eventUtils.get(eventUtils.SELECTED))( + oldId, this.id, this.workspace.id); + eventUtils.fire(event); + common.setSelected(this); + this.addSelect(); + } + + /** + * Unselects this block. Unhighlights the block and fires a select (false) + * event if the block is currently selected. + */ + unselect() { + if (common.getSelected() !== this) { + return; + } + const event = new (eventUtils.get(eventUtils.SELECTED))( + this.id, null, this.workspace.id); + event.workspaceId = this.workspace.id; + eventUtils.fire(event); + common.setSelected(null); + this.removeSelect(); + } + + /** + * Returns a list of mutator, comment, and warning icons. + * @return {!Array} List of icons. + */ + getIcons() { + const icons = []; + if (this.mutator) { + icons.push(this.mutator); + } + if (this.commentIcon_) { + icons.push(this.commentIcon_); + } + if (this.warning) { + icons.push(this.warning); + } + return icons; + } + + /** + * Sets the parent of this block to be a new block or null. + * @param {?Block} newParent New parent block. + * @package + * @override + */ + setParent(newParent) { + const oldParent = this.parentBlock_; + if (newParent === oldParent) { + return; + } + + dom.startTextWidthCache(); + super.setParent(newParent); + dom.stopTextWidthCache(); + + const svgRoot = this.getSvgRoot(); + + // Bail early if workspace is clearing, or we aren't rendered. + // We won't need to reattach ourselves anywhere. + if (this.workspace.isClearing || !svgRoot) { + return; + } + + const oldXY = this.getRelativeToSurfaceXY(); + if (newParent) { + (/** @type {!BlockSvg} */ (newParent)).getSvgRoot().appendChild(svgRoot); + const newXY = this.getRelativeToSurfaceXY(); + // Move the connections to match the child's new position. + this.moveConnections(newXY.x - oldXY.x, newXY.y - oldXY.y); + } else if (oldParent) { + // If we are losing a parent, we want to move our DOM element to the + // root of the workspace. + this.workspace.getCanvas().appendChild(svgRoot); + this.translate(oldXY.x, oldXY.y); + } + + this.applyColour(); + } + + /** + * Return the coordinates of the top-left corner of this block relative to the + * drawing surface's origin (0,0), in workspace units. + * If the block is on the workspace, (0, 0) is the origin of the workspace + * coordinate system. + * This does not change with workspace scale. + * @return {!Coordinate} Object with .x and .y properties in + * workspace coordinates. + */ + getRelativeToSurfaceXY() { + let x = 0; + let y = 0; + + const dragSurfaceGroup = this.useDragSurface_ ? + this.workspace.getBlockDragSurface().getGroup() : + null; + + let element = this.getSvgRoot(); + if (element) { + do { + // Loop through this block and every parent. + const xy = svgMath.getRelativeXY(element); + x += xy.x; + y += xy.y; + // If this element is the current element on the drag surface, include + // the translation of the drag surface itself. + if (this.useDragSurface_ && + this.workspace.getBlockDragSurface().getCurrentBlock() === + element) { + const surfaceTranslation = + this.workspace.getBlockDragSurface().getSurfaceTranslation(); + x += surfaceTranslation.x; + y += surfaceTranslation.y; + } + element = /** @type {!SVGElement} */ (element.parentNode); + } while (element && element !== this.workspace.getCanvas() && + element !== dragSurfaceGroup); + } + return new Coordinate(x, y); + } + + /** + * Move a block by a relative offset. + * @param {number} dx Horizontal offset in workspace units. + * @param {number} dy Vertical offset in workspace units. + */ + moveBy(dx, dy) { + if (this.parentBlock_) { + throw Error('Block has parent.'); + } + const eventsEnabled = eventUtils.isEnabled(); + let event; + if (eventsEnabled) { + event = /** @type {!BlockMove} */ + (new (eventUtils.get(eventUtils.BLOCK_MOVE))(this)); + } + const xy = this.getRelativeToSurfaceXY(); + this.translate(xy.x + dx, xy.y + dy); + this.moveConnections(dx, dy); + if (eventsEnabled) { + event.recordNew(); + eventUtils.fire(event); + } + this.workspace.resizeContents(); + } + + /** + * Transforms a block by setting the translation on the transform attribute + * of the block's SVG. + * @param {number} x The x coordinate of the translation in workspace units. + * @param {number} y The y coordinate of the translation in workspace units. + */ + translate(x, y) { + this.getSvgRoot().setAttribute( + 'transform', 'translate(' + x + ',' + y + ')'); + } + + /** + * Move this block to its workspace's drag surface, accounting for + * positioning. Generally should be called at the same time as + * setDragging_(true). Does nothing if useDragSurface_ is false. + * @package + */ + moveToDragSurface() { + if (!this.useDragSurface_) { + return; + } + // The translation for drag surface blocks, + // is equal to the current relative-to-surface position, + // to keep the position in sync as it move on/off the surface. + // This is in workspace coordinates. + const xy = this.getRelativeToSurfaceXY(); + this.clearTransformAttributes_(); + this.workspace.getBlockDragSurface().translateSurface(xy.x, xy.y); + // Execute the move on the top-level SVG component + const svg = this.getSvgRoot(); + if (svg) { + this.workspace.getBlockDragSurface().setBlocksAndShow(svg); + } + } + + /** + * Move a block to a position. + * @param {Coordinate} xy The position to move to in workspace units. + */ + moveTo(xy) { + const curXY = this.getRelativeToSurfaceXY(); + this.moveBy(xy.x - curXY.x, xy.y - curXY.y); + } + + /** + * Move this block back to the workspace block canvas. + * Generally should be called at the same time as setDragging_(false). + * Does nothing if useDragSurface_ is false. + * @param {!Coordinate} newXY The position the block should take on + * on the workspace canvas, in workspace coordinates. + * @package + */ + moveOffDragSurface(newXY) { + if (!this.useDragSurface_) { + return; + } + // Translate to current position, turning off 3d. + this.translate(newXY.x, newXY.y); + this.workspace.getBlockDragSurface().clearAndHide( + this.workspace.getCanvas()); + } + + /** + * Move this block during a drag, taking into account whether we are using a + * drag surface to translate blocks. + * This block must be a top-level block. + * @param {!Coordinate} newLoc The location to translate to, in + * workspace coordinates. + * @package + */ + moveDuringDrag(newLoc) { + if (this.useDragSurface_) { + this.workspace.getBlockDragSurface().translateSurface(newLoc.x, newLoc.y); + } else { + this.svgGroup_.translate_ = + 'translate(' + newLoc.x + ',' + newLoc.y + ')'; + this.svgGroup_.setAttribute( + 'transform', this.svgGroup_.translate_ + this.svgGroup_.skew_); + } + } + + /** + * Clear the block of transform="..." attributes. + * Used when the block is switching from 3d to 2d transform or vice versa. + * @private + */ + clearTransformAttributes_() { + this.getSvgRoot().removeAttribute('transform'); + } + + /** + * Snap this block to the nearest grid point. + */ + snapToGrid() { + if (!this.workspace) { + return; // Deleted block. + } + if (this.workspace.isDragging()) { + return; // Don't bump blocks during a drag. + } + if (this.getParent()) { + return; // Only snap top-level blocks. + } + if (this.isInFlyout) { + return; // Don't move blocks around in a flyout. + } + const grid = this.workspace.getGrid(); + if (!grid || !grid.shouldSnap()) { + return; // Config says no snapping. + } + const spacing = grid.getSpacing(); + const half = spacing / 2; + const xy = this.getRelativeToSurfaceXY(); + const dx = + Math.round(Math.round((xy.x - half) / spacing) * spacing + half - xy.x); + const dy = + Math.round(Math.round((xy.y - half) / spacing) * spacing + half - xy.y); + if (dx || dy) { + this.moveBy(dx, dy); + } + } + + /** + * Returns the coordinates of a bounding box describing the dimensions of this + * block and any blocks stacked below it. + * Coordinate system: workspace coordinates. + * @return {!Rect} Object with coordinates of the bounding box. + */ + getBoundingRectangle() { + const blockXY = this.getRelativeToSurfaceXY(); + const blockBounds = this.getHeightWidth(); + let left; + let right; + if (this.RTL) { + left = blockXY.x - blockBounds.width; + right = blockXY.x; + } else { + left = blockXY.x; + right = blockXY.x + blockBounds.width; + } + return new Rect(blockXY.y, blockXY.y + blockBounds.height, left, right); + } + + /** + * Notify every input on this block to mark its fields as dirty. + * A dirty field is a field that needs to be re-rendered. + */ + markDirty() { + this.pathObject.constants = (/** @type {!WorkspaceSvg} */ (this.workspace)) + .getRenderer() + .getConstants(); + for (let i = 0, input; (input = this.inputList[i]); i++) { + input.markDirty(); + } + } + + /** + * Set whether the block is collapsed or not. + * @param {boolean} collapsed True if collapsed. + */ + setCollapsed(collapsed) { + if (this.collapsed_ === collapsed) { + return; + } + super.setCollapsed(collapsed); + if (!collapsed) { + this.updateCollapsed_(); + } else if (this.rendered) { + this.render(); + // Don't bump neighbours. Users like to store collapsed functions together + // and bumping makes them go out of alignment. + } + } + + /** + * Makes sure that when the block is collapsed, it is rendered correctly + * for that state. + * @private + */ + updateCollapsed_() { + const collapsed = this.isCollapsed(); + const collapsedInputName = constants.COLLAPSED_INPUT_NAME; + const collapsedFieldName = constants.COLLAPSED_FIELD_NAME; + + for (let i = 0, input; (input = this.inputList[i]); i++) { + if (input.name !== collapsedInputName) { + input.setVisible(!collapsed); + } + } + + if (!collapsed) { + this.updateDisabled(); + this.removeInput(collapsedInputName); + return; + } + + const icons = this.getIcons(); + for (let i = 0, icon; (icon = icons[i]); i++) { + icon.setVisible(false); + } + + const text = this.toString(internalConstants.COLLAPSE_CHARS); + const field = this.getField(collapsedFieldName); + if (field) { + field.setValue(text); + return; + } + const input = this.getInput(collapsedInputName) || + this.appendDummyInput(collapsedInputName); + input.appendField(new FieldLabel(text), collapsedFieldName); + } + + /** + * Open the next (or previous) FieldTextInput. + * @param {!Field} start Current field. + * @param {boolean} forward If true go forward, otherwise backward. + */ + tab(start, forward) { + const tabCursor = new TabNavigateCursor(); + tabCursor.setCurNode(ASTNode.createFieldNode(start)); + const currentNode = tabCursor.getCurNode(); + + if (forward) { + tabCursor.next(); + } else { + tabCursor.prev(); + } + + const nextNode = tabCursor.getCurNode(); + if (nextNode && nextNode !== currentNode) { + const nextField = /** @type {!Field} */ (nextNode.getLocation()); + nextField.showEditor(); + + // Also move the cursor if we're in keyboard nav mode. + if (this.workspace.keyboardAccessibilityMode) { + this.workspace.getCursor().setCurNode(nextNode); + } + } + } + + /** + * Handle a mouse-down on an SVG block. + * @param {!Event} e Mouse down event or touch start event. + * @private + */ + onMouseDown_(e) { + const gesture = this.workspace && this.workspace.getGesture(e); + if (gesture) { + gesture.handleBlockStart(e, this); + } + } + + /** + * Load the block's help page in a new window. + * @package + */ + showHelp() { + const url = + (typeof this.helpUrl === 'function') ? this.helpUrl() : this.helpUrl; + if (url) { + window.open(url); + } + } + + /** + * Generate the context menu for this block. + * @return {?Array} Context menu options or null if no menu. + * @protected + */ + generateContextMenu() { + if (this.workspace.options.readOnly || !this.contextMenu) { + return null; + } + const menuOptions = ContextMenuRegistry.registry.getContextMenuOptions( + ContextMenuRegistry.ScopeType.BLOCK, {block: this}); + + // Allow the block to add or modify menuOptions. + if (this.customContextMenu) { + this.customContextMenu(menuOptions); + } + + return menuOptions; + } + + /** + * Show the context menu for this block. + * @param {!Event} e Mouse event. + * @package + */ + showContextMenu(e) { + const menuOptions = this.generateContextMenu(); + + if (menuOptions && menuOptions.length) { + ContextMenu.show(e, menuOptions, this.RTL); + ContextMenu.setCurrentBlock(this); + } + } + + /** + * Move the connections for this block and all blocks attached under it. + * Also update any attached bubbles. + * @param {number} dx Horizontal offset from current location, in workspace + * units. + * @param {number} dy Vertical offset from current location, in workspace + * units. + * @package + */ + moveConnections(dx, dy) { + if (!this.rendered) { + // Rendering is required to lay out the blocks. + // This is probably an invisible block attached to a collapsed block. + return; + } + const myConnections = this.getConnections_(false); + for (let i = 0; i < myConnections.length; i++) { + myConnections[i].moveBy(dx, dy); + } + const icons = this.getIcons(); + for (let i = 0; i < icons.length; i++) { + icons[i].computeIconLocation(); + } + + // Recurse through all blocks attached under this one. + for (let i = 0; i < this.childBlocks_.length; i++) { + (/** @type {!BlockSvg} */ (this.childBlocks_[i])).moveConnections(dx, dy); + } + } + + /** + * Recursively adds or removes the dragging class to this node and its + * children. + * @param {boolean} adding True if adding, false if removing. + * @package + */ + setDragging(adding) { + if (adding) { + const group = this.getSvgRoot(); + group.translate_ = ''; + group.skew_ = ''; + common.draggingConnections.push(...this.getConnections_(true)); + dom.addClass( + /** @type {!Element} */ (this.svgGroup_), 'blocklyDragging'); + } else { + common.draggingConnections.length = 0; + dom.removeClass( + /** @type {!Element} */ (this.svgGroup_), 'blocklyDragging'); + } + // Recurse through all blocks attached under this one. + for (let i = 0; i < this.childBlocks_.length; i++) { + (/** @type {!BlockSvg} */ (this.childBlocks_[i])).setDragging(adding); + } + } + + /** + * Set whether this block is movable or not. + * @param {boolean} movable True if movable. + */ + setMovable(movable) { + super.setMovable(movable); + this.pathObject.updateMovable(movable); + } + + /** + * Set whether this block is editable or not. + * @param {boolean} editable True if editable. + */ + setEditable(editable) { + super.setEditable(editable); + const icons = this.getIcons(); + for (let i = 0; i < icons.length; i++) { + icons[i].updateEditable(); + } + } + + /** + * Sets whether this block is a shadow block or not. + * @param {boolean} shadow True if a shadow. + * @package + */ + setShadow(shadow) { + super.setShadow(shadow); + this.applyColour(); + } + + /** + * Set whether this block is an insertion marker block or not. + * Once set this cannot be unset. + * @param {boolean} insertionMarker True if an insertion marker. + * @package + */ + setInsertionMarker(insertionMarker) { + if (this.isInsertionMarker_ === insertionMarker) { + return; // No change. + } + this.isInsertionMarker_ = insertionMarker; + if (this.isInsertionMarker_) { + this.setColour( + this.workspace.getRenderer().getConstants().INSERTION_MARKER_COLOUR); + this.pathObject.updateInsertionMarker(true); + } + } + + /** + * Return the root node of the SVG or null if none exists. + * @return {!SVGGElement} The root SVG node (probably a group). + */ + getSvgRoot() { + return this.svgGroup_; + } + + /** + * Dispose of this block. + * @param {boolean=} healStack If true, then try to heal any gap by connecting + * the next statement with the previous statement. Otherwise, dispose of + * all children of this block. + * @param {boolean=} animate If true, show a disposal animation and sound. + * @suppress {checkTypes} + */ + dispose(healStack, animate) { + if (!this.workspace) { + // The block has already been deleted. + return; + } + Tooltip.dispose(); + Tooltip.unbindMouseEvents(this.pathObject.svgPath); + dom.startTextWidthCache(); + // Save the block's workspace temporarily so we can resize the + // contents once the block is disposed. + const blockWorkspace = this.workspace; + // If this block is being dragged, unlink the mouse events. + if (common.getSelected() === this) { + this.unselect(); + this.workspace.cancelCurrentGesture(); + } + // If this block has a context menu open, close it. + if (ContextMenu.getCurrentBlock() === this) { + ContextMenu.hide(); + } + + if (animate && this.rendered) { + this.unplug(healStack); + blockAnimations.disposeUiEffect(this); + } + // Stop rerendering. + this.rendered = false; + + // Clear pending warnings. + if (this.warningTextDb_) { + for (const n in this.warningTextDb_) { + clearTimeout(this.warningTextDb_[n]); + } + this.warningTextDb_ = null; + } + + const icons = this.getIcons(); + for (let i = 0; i < icons.length; i++) { + icons[i].dispose(); + } + super.dispose(!!healStack); + + dom.removeNode(this.svgGroup_); + blockWorkspace.resizeContents(); + // Sever JavaScript to DOM connections. + this.svgGroup_ = null; + dom.stopTextWidthCache(); + } + + /** + * Delete a block and hide chaff when doing so. The block will not be deleted + * if it's in a flyout. This is called from the context menu and keyboard + * shortcuts as the full delete action. If you are disposing of a block from + * the workspace and don't need to perform flyout checks, handle event + * grouping, or hide chaff, then use `block.dispose()` directly. + */ + checkAndDelete() { + if (this.workspace.isFlyout) { + return; + } + eventUtils.setGroup(true); + this.workspace.hideChaff(); + if (this.outputConnection) { + // Do not attempt to heal rows + // (https://github.com/google/blockly/issues/4832) + this.dispose(false, true); + } else { + this.dispose(/* heal */ true, true); + } + eventUtils.setGroup(false); + } + + /** + * Encode a block for copying. + * @return {?ICopyable.CopyData} Copy metadata, or null if the block is + * an insertion marker. + * @package + */ + toCopyData() { + if (this.isInsertionMarker_) { + return null; + } + return { + saveInfo: /** @type {!blocks.State} */ ( + blocks.save(this, {addCoordinates: true, addNextBlocks: false})), + source: this.workspace, + typeCounts: common.getBlockTypeCounts(this, true), + }; + } + + /** + * Updates the colour of the block to match the block's state. + * @package + */ + applyColour() { + this.pathObject.applyColour(this); + + const icons = this.getIcons(); + for (let i = 0; i < icons.length; i++) { + icons[i].applyColour(); + } + + for (let x = 0, input; (input = this.inputList[x]); x++) { + for (let y = 0, field; (field = input.fieldRow[y]); y++) { + field.applyColour(); + } + } + } + + /** + * Updates the color of the block (and children) to match the current disabled + * state. + * @package + */ + updateDisabled() { + const children = + /** @type {!Array} */ (this.getChildren(false)); + this.applyColour(); + if (this.isCollapsed()) { + return; + } + for (let i = 0, child; (child = children[i]); i++) { + if (child.rendered) { + child.updateDisabled(); + } + } + } + + /** + * Get the comment icon attached to this block, or null if the block has no + * comment. + * @return {?Comment} The comment icon attached to this block, or null. + */ + getCommentIcon() { + return this.commentIcon_; + } + + /** + * Set this block's comment text. + * @param {?string} text The text, or null to delete. + */ + setCommentText(text) { + const {Comment} = goog.module.get('Blockly.Comment'); + if (!Comment) { + throw Error('Missing require for Blockly.Comment'); + } + if (this.commentModel.text === text) { + return; + } + super.setCommentText(text); + + const shouldHaveComment = text !== null; + if (!!this.commentIcon_ === shouldHaveComment) { + // If the comment's state of existence is correct, but the text is new + // that means we're just updating a comment. + this.commentIcon_.updateText(); + return; + } + if (shouldHaveComment) { + this.commentIcon_ = new Comment(this); + this.comment = this.commentIcon_; // For backwards compatibility. + } else { + this.commentIcon_.dispose(); + this.commentIcon_ = null; + this.comment = null; // For backwards compatibility. + } + if (this.rendered) { + this.render(); + // Adding or removing a comment icon will cause the block to change shape. + this.bumpNeighbours(); + } + } + + /** + * Set this block's warning text. + * @param {?string} text The text, or null to delete. + * @param {string=} opt_id An optional ID for the warning text to be able to + * maintain multiple warnings. + */ + setWarningText(text, opt_id) { + const {Warning} = goog.module.get('Blockly.Warning'); + if (!Warning) { + throw Error('Missing require for Blockly.Warning'); + } + if (!this.warningTextDb_) { + // Create a database of warning PIDs. + // Only runs once per block (and only those with warnings). + this.warningTextDb_ = Object.create(null); + } + const id = opt_id || ''; + if (!id) { + // Kill all previous pending processes, this edit supersedes them all. + for (const n of Object.keys(this.warningTextDb_)) { + clearTimeout(this.warningTextDb_[n]); + delete this.warningTextDb_[n]; + } + } else if (this.warningTextDb_[id]) { + // Only queue up the latest change. Kill any earlier pending process. + clearTimeout(this.warningTextDb_[id]); + delete this.warningTextDb_[id]; + } + if (this.workspace.isDragging()) { + // Don't change the warning text during a drag. + // Wait until the drag finishes. + const thisBlock = this; + this.warningTextDb_[id] = setTimeout(function() { + if (thisBlock.workspace) { // Check block wasn't deleted. + delete thisBlock.warningTextDb_[id]; + thisBlock.setWarningText(text, id); + } + }, 100); + return; + } + if (this.isInFlyout) { + text = null; + } + + let changedState = false; + if (typeof text === 'string') { + // Bubble up to add a warning on top-most collapsed block. + let parent = this.getSurroundParent(); + let collapsedParent = null; + while (parent) { + if (parent.isCollapsed()) { + collapsedParent = parent; + } + parent = parent.getSurroundParent(); + } + if (collapsedParent) { + collapsedParent.setWarningText( + Msg['COLLAPSED_WARNINGS_WARNING'], BlockSvg.COLLAPSED_WARNING_ID); + } + + if (!this.warning) { + this.warning = new Warning(this); + changedState = true; + } + this.warning.setText(/** @type {string} */ (text), id); + } else { + // Dispose all warnings if no ID is given. + if (this.warning && !id) { + this.warning.dispose(); + changedState = true; + } else if (this.warning) { + const oldText = this.warning.getText(); + this.warning.setText('', id); + const newText = this.warning.getText(); + if (!newText) { + this.warning.dispose(); + } + changedState = oldText !== newText; + } + } + if (changedState && this.rendered) { + this.render(); + // Adding or removing a warning icon will cause the block to change shape. + this.bumpNeighbours(); + } + } + + /** + * Give this block a mutator dialog. + * @param {?Mutator} mutator A mutator dialog instance or null to remove. + */ + setMutator(mutator) { + if (this.mutator && this.mutator !== mutator) { + this.mutator.dispose(); + } + if (mutator) { + mutator.setBlock(this); + this.mutator = mutator; + mutator.createIcon(); + } + if (this.rendered) { + this.render(); + // Adding or removing a mutator icon will cause the block to change shape. + this.bumpNeighbours(); + } + } + + /** + * Set whether the block is enabled or not. + * @param {boolean} enabled True if enabled. + */ + setEnabled(enabled) { + if (this.isEnabled() !== enabled) { + super.setEnabled(enabled); + if (this.rendered && !this.getInheritedDisabled()) { + this.updateDisabled(); + } + } + } + + /** + * Set whether the block is highlighted or not. Block highlighting is + * often used to visually mark blocks currently being executed. + * @param {boolean} highlighted True if highlighted. + */ + setHighlighted(highlighted) { + if (!this.rendered) { + return; + } + this.pathObject.updateHighlighted(highlighted); + } + + /** + * Adds the visual "select" effect to the block, but does not actually select + * it or fire an event. + * @see BlockSvg#select + */ + addSelect() { + this.pathObject.updateSelected(true); + } + + /** + * Removes the visual "select" effect from the block, but does not actually + * unselect it or fire an event. + * @see BlockSvg#unselect + */ + removeSelect() { + this.pathObject.updateSelected(false); + } + + /** + * Update the cursor over this block by adding or removing a class. + * @param {boolean} enable True if the delete cursor should be shown, false + * otherwise. + * @package + */ + setDeleteStyle(enable) { + this.pathObject.updateDraggingDelete(enable); + } + + // Overrides of functions on Blockly.Block that take into account whether the + + // block has been rendered. + + /** + * Get the colour of a block. + * @return {string} #RRGGBB string. + */ + getColour() { + return this.style.colourPrimary; + } + + /** + * Change the colour of a block. + * @param {number|string} colour HSV hue value, or #RRGGBB string. + */ + setColour(colour) { + super.setColour(colour); + const styleObj = + this.workspace.getRenderer().getConstants().getBlockStyleForColour( + this.colour_); + + this.pathObject.setStyle(styleObj.style); + this.style = styleObj.style; + this.styleName_ = styleObj.name; + + this.applyColour(); + } + + /** + * Set the style and colour values of a block. + * @param {string} blockStyleName Name of the block style. + * @throws {Error} if the block style does not exist. + */ + setStyle(blockStyleName) { + const blockStyle = + this.workspace.getRenderer().getConstants().getBlockStyle( + blockStyleName); + this.styleName_ = blockStyleName; + + if (blockStyle) { + this.hat = blockStyle.hat; + this.pathObject.setStyle(blockStyle); + // Set colour to match Block. + this.colour_ = blockStyle.colourPrimary; + this.style = blockStyle; + + this.applyColour(); + } else { + throw Error('Invalid style name: ' + blockStyleName); + } + } + + /** + * Move this block to the front of the visible workspace. + * tags do not respect z-index so SVG renders them in the + * order that they are in the DOM. By placing this block first within the + * block group's , it will render on top of any other blocks. + * @package + */ + bringToFront() { + let block = this; + do { + const root = block.getSvgRoot(); + const parent = root.parentNode; + const childNodes = parent.childNodes; + // Avoid moving the block if it's already at the bottom. + if (childNodes[childNodes.length - 1] !== root) { + parent.appendChild(root); + } + block = block.getParent(); + } while (block); + } + + /** + * Set whether this block can chain onto the bottom of another block. + * @param {boolean} newBoolean True if there can be a previous statement. + * @param {(string|Array|null)=} opt_check Statement type or + * list of statement types. Null/undefined if any type could be + * connected. + */ + setPreviousStatement(newBoolean, opt_check) { + super.setPreviousStatement(newBoolean, opt_check); + + if (this.rendered) { + this.render(); + this.bumpNeighbours(); + } + } + + /** + * Set whether another block can chain onto the bottom of this block. + * @param {boolean} newBoolean True if there can be a next statement. + * @param {(string|Array|null)=} opt_check Statement type or + * list of statement types. Null/undefined if any type could be + * connected. + */ + setNextStatement(newBoolean, opt_check) { + super.setNextStatement(newBoolean, opt_check); + + if (this.rendered) { + this.render(); + this.bumpNeighbours(); + } + } + + /** + * Set whether this block returns a value. + * @param {boolean} newBoolean True if there is an output. + * @param {(string|Array|null)=} opt_check Returned type or list + * of returned types. Null or undefined if any type could be returned + * (e.g. variable get). + */ + setOutput(newBoolean, opt_check) { + super.setOutput(newBoolean, opt_check); + + if (this.rendered) { + this.render(); + this.bumpNeighbours(); + } + } + + /** + * Set whether value inputs are arranged horizontally or vertically. + * @param {boolean} newBoolean True if inputs are horizontal. + */ + setInputsInline(newBoolean) { + super.setInputsInline(newBoolean); + + if (this.rendered) { + this.render(); + this.bumpNeighbours(); + } + } + + /** + * Remove an input from this block. + * @param {string} name The name of the input. + * @param {boolean=} opt_quiet True to prevent error if input is not present. + * @return {boolean} True if operation succeeds, false if input is not present + * and opt_quiet is true + * @throws {Error} if the input is not present and opt_quiet is not true. + */ + removeInput(name, opt_quiet) { + const removed = super.removeInput(name, opt_quiet); + + if (this.rendered) { + this.render(); + // Removing an input will cause the block to change shape. + this.bumpNeighbours(); + } + + return removed; + } + + /** + * Move a numbered input to a different location on this block. + * @param {number} inputIndex Index of the input to move. + * @param {number} refIndex Index of input that should be after the moved + * input. + */ + moveNumberedInputBefore(inputIndex, refIndex) { + super.moveNumberedInputBefore(inputIndex, refIndex); + + if (this.rendered) { + this.render(); + // Moving an input will cause the block to change shape. + this.bumpNeighbours(); + } + } + + /** + * Add a value input, statement input or local variable to this block. + * @param {number} type One of Blockly.inputTypes. + * @param {string} name Language-neutral identifier which may used to find + * this input again. Should be unique to this block. + * @return {!Input} The input object created. + * @protected + * @override + */ + appendInput_(type, name) { + const input = super.appendInput_(type, name); + + if (this.rendered) { + this.render(); + // Adding an input will cause the block to change shape. + this.bumpNeighbours(); + } + return input; + } + + /** + * Sets whether this block's connections are tracked in the database or not. + * + * Used by the deserializer to be more efficient. Setting a connection's + * tracked_ value to false keeps it from adding itself to the db when it + * gets its first moveTo call, saving expensive ops for later. + * @param {boolean} track If true, start tracking. If false, stop tracking. + * @package + */ + setConnectionTracking(track) { + if (this.previousConnection) { + /** @type {!RenderedConnection} */ (this.previousConnection) + .setTracking(track); + } + if (this.outputConnection) { + /** @type {!RenderedConnection} */ (this.outputConnection) + .setTracking(track); + } + if (this.nextConnection) { + /** @type {!RenderedConnection} */ (this.nextConnection) + .setTracking(track); + const child = + /** @type {!RenderedConnection} */ (this.nextConnection) + .targetBlock(); + if (child) { + child.setConnectionTracking(track); + } + } + + if (this.collapsed_) { + // When track is true, we don't want to start tracking collapsed + // connections. When track is false, we're already not tracking + // collapsed connections, so no need to update. + return; + } + + for (let i = 0; i < this.inputList.length; i++) { + const conn = + /** @type {!RenderedConnection} */ (this.inputList[i].connection); + if (conn) { + conn.setTracking(track); + + // Pass tracking on down the chain. + const block = conn.targetBlock(); + if (block) { + block.setConnectionTracking(track); + } + } + } + } + + /** + * Returns connections originating from this block. + * @param {boolean} all If true, return all connections even hidden ones. + * Otherwise, for a non-rendered block return an empty list, and for a + * collapsed block don't return inputs connections. + * @return {!Array} Array of connections. + * @package + */ + getConnections_(all) { + const myConnections = []; + if (all || this.rendered) { + if (this.outputConnection) { + myConnections.push(this.outputConnection); + } + if (this.previousConnection) { + myConnections.push(this.previousConnection); + } + if (this.nextConnection) { + myConnections.push(this.nextConnection); + } + if (all || !this.collapsed_) { + for (let i = 0, input; (input = this.inputList[i]); i++) { + if (input.connection) { + myConnections.push(input.connection); + } + } + } + } + return myConnections; + } + + /** + * Walks down a stack of blocks and finds the last next connection on the + * stack. + * @param {boolean} ignoreShadows If true,the last connection on a non-shadow + * block will be returned. If false, this will follow shadows to find the + * last connection. + * @return {?RenderedConnection} The last next connection on the stack, + * or null. + * @package + * @override + */ + lastConnectionInStack(ignoreShadows) { + return /** @type {RenderedConnection} */ ( + super.lastConnectionInStack(ignoreShadows)); + } + + /** + * Find the connection on this block that corresponds to the given connection + * on the other block. + * Used to match connections between a block and its insertion marker. + * @param {!Block} otherBlock The other block to match against. + * @param {!Connection} conn The other connection to match. + * @return {?RenderedConnection} The matching connection on this block, + * or null. + * @package + * @override + */ + getMatchingConnection(otherBlock, conn) { + return /** @type {RenderedConnection} */ ( + super.getMatchingConnection(otherBlock, conn)); + } + + /** + * Create a connection of the specified type. + * @param {number} type The type of the connection to create. + * @return {!RenderedConnection} A new connection of the specified type. + * @protected + */ + makeConnection_(type) { + return new RenderedConnection(this, type); + } + + /** + * Bump unconnected blocks out of alignment. Two blocks which aren't actually + * connected should not coincidentally line up on screen. + */ + bumpNeighbours() { + if (!this.workspace) { + return; // Deleted block. + } + if (this.workspace.isDragging()) { + return; // Don't bump blocks during a drag. + } + const rootBlock = this.getRootBlock(); + if (rootBlock.isInFlyout) { + return; // Don't move blocks around in a flyout. + } + // Loop through every connection on this block. + const myConnections = this.getConnections_(false); + for (let i = 0, connection; (connection = myConnections[i]); i++) { + const renderedConn = /** @type {!RenderedConnection} */ (connection); + // Spider down from this block bumping all sub-blocks. + if (renderedConn.isConnected() && renderedConn.isSuperior()) { + renderedConn.targetBlock().bumpNeighbours(); + } + + const neighbours = connection.neighbours(config.snapRadius); + for (let j = 0, otherConnection; (otherConnection = neighbours[j]); j++) { + const renderedOther = + /** @type {!RenderedConnection} */ (otherConnection); + // If both connections are connected, that's probably fine. But if + // either one of them is unconnected, then there could be confusion. + if (!renderedConn.isConnected() || !renderedOther.isConnected()) { + // Only bump blocks if they are from different tree structures. + if (renderedOther.getSourceBlock().getRootBlock() !== rootBlock) { + // Always bump the inferior block. + if (renderedConn.isSuperior()) { + renderedOther.bumpAwayFrom(renderedConn); + } else { + renderedConn.bumpAwayFrom(renderedOther); + } + } + } + } + } + } + + /** + * Schedule snapping to grid and bumping neighbours to occur after a brief + * delay. + * @package + */ + scheduleSnapAndBump() { + const block = this; + // Ensure that any snap and bump are part of this move's event group. + const group = eventUtils.getGroup(); + + setTimeout(function() { + eventUtils.setGroup(group); + block.snapToGrid(); + eventUtils.setGroup(false); + }, config.bumpDelay / 2); + + setTimeout(function() { + eventUtils.setGroup(group); + block.bumpNeighbours(); + eventUtils.setGroup(false); + }, config.bumpDelay); + } + + /** + * Position a block so that it doesn't move the target block when connected. + * The block to position is usually either the first block in a dragged stack + * or an insertion marker. + * @param {!RenderedConnection} sourceConnection The connection on the + * moving block's stack. + * @param {!RenderedConnection} targetConnection The connection that + * should stay stationary as this block is positioned. + * @package + */ + positionNearConnection(sourceConnection, targetConnection) { + // We only need to position the new block if it's before the existing one, + // otherwise its position is set by the previous block. + if (sourceConnection.type === ConnectionType.NEXT_STATEMENT || + sourceConnection.type === ConnectionType.INPUT_VALUE) { + const dx = targetConnection.x - sourceConnection.x; + const dy = targetConnection.y - sourceConnection.y; + + this.moveBy(dx, dy); + } + } + + /** + * Return the parent block or null if this block is at the top level. + * @return {?BlockSvg} The block (if any) that holds the current block. + * @override + */ + getParent() { + return /** @type {?BlockSvg} */ (super.getParent()); + } + + /** + * @return {?BlockSvg} The block (if any) that surrounds the current block. + * @override + */ + getSurroundParent() { + return /** @type {?BlockSvg} */ (super.getSurroundParent()); + } + + /** + * @return {?BlockSvg} The next statement block or null. + * @override + */ + getNextBlock() { + return /** @type {?BlockSvg} */ (super.getNextBlock()); + } + + /** + * @return {?BlockSvg} The previou statement block or null. + * @override + */ + getPreviousBlock() { + return /** @type {?BlockSvg} */ (super.getPreviousBlock()); + } + + /** + * @return {?RenderedConnection} The first statement connection or null. + * @package + * @override + */ + getFirstStatementConnection() { + return /** @type {?RenderedConnection} */ ( + super.getFirstStatementConnection()); + } + + /** + * @return {!BlockSvg} The top block in a stack. + * @override + */ + getTopStackBlock() { + return /** @type {!BlockSvg} */ (super.getTopStackBlock()); + } + + /** + * @param {boolean} ordered Sort the list if true. + * @return {!Array} Children of this block. + * @override + */ + getChildren(ordered) { + return /** @type {!Array} */ (super.getChildren(ordered)); + } + + /** + * @param {boolean} ordered Sort the list if true. + * @return {!Array} Descendants of this block. + * @override + */ + getDescendants(ordered) { + return /** @type {!Array} */ (super.getDescendants(ordered)); + } + + /** + * @param {string} name The name of the input. + * @return {?BlockSvg} The attached value block, or null if the input is + * either disconnected or if the input does not exist. + * @override + */ + getInputTargetBlock(name) { + return /** @type {?BlockSvg} */ (super.getInputTargetBlock(name)); + } + + /** + * Return the top-most block in this block's tree. + * This will return itself if this block is at the top level. + * @return {!BlockSvg} The root block. + * @override + */ + getRootBlock() { + return /** @type {!BlockSvg} */ (super.getRootBlock()); + } + + /** + * Lays out and reflows a block based on its contents and settings. + * @param {boolean=} opt_bubble If false, just render this block. + * If true, also render block's parent, grandparent, etc. Defaults to true. + */ + render(opt_bubble) { + if (this.renderIsInProgress_) { + return; // Don't allow recursive renders. + } + this.renderIsInProgress_ = true; + try { + this.rendered = true; + dom.startTextWidthCache(); + + if (this.isCollapsed()) { + this.updateCollapsed_(); + } + this.workspace.getRenderer().render(this); + this.updateConnectionLocations_(); + + if (opt_bubble !== false) { + const parentBlock = this.getParent(); + if (parentBlock) { + parentBlock.render(true); + } else { + // Top-most block. Fire an event to allow scrollbars to resize. + this.workspace.resizeContents(); + } + } + + dom.stopTextWidthCache(); + this.updateMarkers_(); + } finally { + this.renderIsInProgress_ = false; + } + } + + /** + * Redraw any attached marker or cursor svgs if needed. + * @protected + */ + updateMarkers_() { + if (this.workspace.keyboardAccessibilityMode && this.pathObject.cursorSvg) { + this.workspace.getCursor().draw(); + } + if (this.workspace.keyboardAccessibilityMode && this.pathObject.markerSvg) { + // TODO(#4592): Update all markers on the block. + this.workspace.getMarker(MarkerManager.LOCAL_MARKER).draw(); + } + } + + /** + * Update all of the connections on this block with the new locations + * calculated during rendering. Also move all of the connected blocks based + * on the new connection locations. + * @private + */ + updateConnectionLocations_() { + const blockTL = this.getRelativeToSurfaceXY(); + // Don't tighten previous or output connections because they are inferior + // connections. + if (this.previousConnection) { + this.previousConnection.moveToOffset(blockTL); + } + if (this.outputConnection) { + this.outputConnection.moveToOffset(blockTL); + } + + for (let i = 0; i < this.inputList.length; i++) { + const conn = + /** @type {!RenderedConnection} */ (this.inputList[i].connection); + if (conn) { + conn.moveToOffset(blockTL); + if (conn.isConnected()) { + conn.tighten(); + } + } + } + + if (this.nextConnection) { + this.nextConnection.moveToOffset(blockTL); + if (this.nextConnection.isConnected()) { + this.nextConnection.tighten(); + } + } + } + + /** + * Add the cursor SVG to this block's SVG group. + * @param {SVGElement} cursorSvg The SVG root of the cursor to be added to the + * block SVG group. + * @package + */ + setCursorSvg(cursorSvg) { + this.pathObject.setCursorSvg(cursorSvg); + } + + /** + * Add the marker SVG to this block's SVG group. + * @param {SVGElement} markerSvg The SVG root of the marker to be added to the + * block SVG group. + * @package + */ + setMarkerSvg(markerSvg) { + this.pathObject.setMarkerSvg(markerSvg); + } + + /** + * Returns a bounding box describing the dimensions of this block + * and any blocks stacked below it. + * @return {!{height: number, width: number}} Object with height and width + * properties in workspace units. + * @package + */ + getHeightWidth() { + let height = this.height; + let width = this.width; + // Recursively add size of subsequent blocks. + const nextBlock = this.getNextBlock(); + if (nextBlock) { + const nextHeightWidth = nextBlock.getHeightWidth(); + const workspace = /** @type {!WorkspaceSvg} */ (this.workspace); + const tabHeight = workspace.getRenderer().getConstants().NOTCH_HEIGHT; + height += nextHeightWidth.height - tabHeight; + width = Math.max(width, nextHeightWidth.width); + } + return {height: height, width: width}; + } + + /** + * Visual effect to show that if the dragging block is dropped, this block + * will be replaced. If a shadow block, it will disappear. Otherwise it will + * bump. + * @param {boolean} add True if highlighting should be added. + * @package + */ + fadeForReplacement(add) { + this.pathObject.updateReplacementFade(add); + } + + /** + * Visual effect to show that if the dragging block is dropped it will connect + * to this input. + * @param {Connection} conn The connection on the input to highlight. + * @param {boolean} add True if highlighting should be added. + * @package + */ + highlightShapeForInput(conn, add) { + this.pathObject.updateShapeForInputHighlight(conn, add); + } +} /** * Constant for identifying rows that are to be rendered inline. @@ -270,1532 +1883,4 @@ BlockSvg.INLINE = -1; */ BlockSvg.COLLAPSED_WARNING_ID = 'TEMP_COLLAPSED_WARNING_'; -/** - * Create and initialize the SVG representation of the block. - * May be called more than once. - */ -BlockSvg.prototype.initSvg = function() { - if (!this.workspace.rendered) { - throw TypeError('Workspace is headless.'); - } - for (let i = 0, input; (input = this.inputList[i]); i++) { - input.init(); - } - const icons = this.getIcons(); - for (let i = 0; i < icons.length; i++) { - icons[i].createIcon(); - } - this.applyColour(); - this.pathObject.updateMovable(this.isMovable()); - const svg = this.getSvgRoot(); - if (!this.workspace.options.readOnly && !this.eventsInit_ && svg) { - browserEvents.conditionalBind(svg, 'mousedown', this, this.onMouseDown_); - } - this.eventsInit_ = true; - - if (!svg.parentNode) { - this.workspace.getCanvas().appendChild(svg); - } -}; - -/** - * Get the secondary colour of a block. - * @return {?string} #RRGGBB string. - */ -BlockSvg.prototype.getColourSecondary = function() { - return this.style.colourSecondary; -}; - -/** - * Get the tertiary colour of a block. - * @return {?string} #RRGGBB string. - */ -BlockSvg.prototype.getColourTertiary = function() { - return this.style.colourTertiary; -}; - -/** - * Selects this block. Highlights the block visually and fires a select event - * if the block is not already selected. - */ -BlockSvg.prototype.select = function() { - if (this.isShadow() && this.getParent()) { - // Shadow blocks should not be selected. - this.getParent().select(); - return; - } - if (common.getSelected() === this) { - return; - } - let oldId = null; - if (common.getSelected()) { - oldId = common.getSelected().id; - // Unselect any previously selected block. - eventUtils.disable(); - try { - common.getSelected().unselect(); - } finally { - eventUtils.enable(); - } - } - const event = new (eventUtils.get(eventUtils.SELECTED))( - oldId, this.id, this.workspace.id); - eventUtils.fire(event); - common.setSelected(this); - this.addSelect(); -}; - -/** - * Unselects this block. Unhighlights the block and fires a select (false) event - * if the block is currently selected. - */ -BlockSvg.prototype.unselect = function() { - if (common.getSelected() !== this) { - return; - } - const event = new (eventUtils.get(eventUtils.SELECTED))( - this.id, null, this.workspace.id); - event.workspaceId = this.workspace.id; - eventUtils.fire(event); - common.setSelected(null); - this.removeSelect(); -}; - -/** - * Returns a list of mutator, comment, and warning icons. - * @return {!Array} List of icons. - */ -BlockSvg.prototype.getIcons = function() { - const icons = []; - if (this.mutator) { - icons.push(this.mutator); - } - if (this.commentIcon_) { - icons.push(this.commentIcon_); - } - if (this.warning) { - icons.push(this.warning); - } - return icons; -}; - -/** - * Sets the parent of this block to be a new block or null. - * @param {?Block} newParent New parent block. - * @package - * @override - */ -BlockSvg.prototype.setParent = function(newParent) { - const oldParent = this.parentBlock_; - if (newParent === oldParent) { - return; - } - - dom.startTextWidthCache(); - BlockSvg.superClass_.setParent.call(this, newParent); - dom.stopTextWidthCache(); - - const svgRoot = this.getSvgRoot(); - - // Bail early if workspace is clearing, or we aren't rendered. - // We won't need to reattach ourselves anywhere. - if (this.workspace.isClearing || !svgRoot) { - return; - } - - const oldXY = this.getRelativeToSurfaceXY(); - if (newParent) { - newParent.getSvgRoot().appendChild(svgRoot); - const newXY = this.getRelativeToSurfaceXY(); - // Move the connections to match the child's new position. - this.moveConnections(newXY.x - oldXY.x, newXY.y - oldXY.y); - } else if (oldParent) { - // If we are losing a parent, we want to move our DOM element to the - // root of the workspace. - this.workspace.getCanvas().appendChild(svgRoot); - this.translate(oldXY.x, oldXY.y); - } - - this.applyColour(); -}; - -/** - * Return the coordinates of the top-left corner of this block relative to the - * drawing surface's origin (0,0), in workspace units. - * If the block is on the workspace, (0, 0) is the origin of the workspace - * coordinate system. - * This does not change with workspace scale. - * @return {!Coordinate} Object with .x and .y properties in - * workspace coordinates. - */ -BlockSvg.prototype.getRelativeToSurfaceXY = function() { - let x = 0; - let y = 0; - - const dragSurfaceGroup = this.useDragSurface_ ? - this.workspace.getBlockDragSurface().getGroup() : - null; - - let element = this.getSvgRoot(); - if (element) { - do { - // Loop through this block and every parent. - const xy = svgMath.getRelativeXY(element); - x += xy.x; - y += xy.y; - // If this element is the current element on the drag surface, include - // the translation of the drag surface itself. - if (this.useDragSurface_ && - this.workspace.getBlockDragSurface().getCurrentBlock() === element) { - const surfaceTranslation = - this.workspace.getBlockDragSurface().getSurfaceTranslation(); - x += surfaceTranslation.x; - y += surfaceTranslation.y; - } - element = /** @type {!SVGElement} */ (element.parentNode); - } while (element && element !== this.workspace.getCanvas() && - element !== dragSurfaceGroup); - } - return new Coordinate(x, y); -}; - -/** - * Move a block by a relative offset. - * @param {number} dx Horizontal offset in workspace units. - * @param {number} dy Vertical offset in workspace units. - */ -BlockSvg.prototype.moveBy = function(dx, dy) { - if (this.parentBlock_) { - throw Error('Block has parent.'); - } - const eventsEnabled = eventUtils.isEnabled(); - let event; - if (eventsEnabled) { - event = /** @type {!BlockMove} */ - (new (eventUtils.get(eventUtils.BLOCK_MOVE))(this)); - } - const xy = this.getRelativeToSurfaceXY(); - this.translate(xy.x + dx, xy.y + dy); - this.moveConnections(dx, dy); - if (eventsEnabled) { - event.recordNew(); - eventUtils.fire(event); - } - this.workspace.resizeContents(); -}; - -/** - * Transforms a block by setting the translation on the transform attribute - * of the block's SVG. - * @param {number} x The x coordinate of the translation in workspace units. - * @param {number} y The y coordinate of the translation in workspace units. - */ -BlockSvg.prototype.translate = function(x, y) { - this.getSvgRoot().setAttribute('transform', 'translate(' + x + ',' + y + ')'); -}; - -/** - * Move this block to its workspace's drag surface, accounting for positioning. - * Generally should be called at the same time as setDragging_(true). - * Does nothing if useDragSurface_ is false. - * @package - */ -BlockSvg.prototype.moveToDragSurface = function() { - if (!this.useDragSurface_) { - return; - } - // The translation for drag surface blocks, - // is equal to the current relative-to-surface position, - // to keep the position in sync as it move on/off the surface. - // This is in workspace coordinates. - const xy = this.getRelativeToSurfaceXY(); - this.clearTransformAttributes_(); - this.workspace.getBlockDragSurface().translateSurface(xy.x, xy.y); - // Execute the move on the top-level SVG component - const svg = this.getSvgRoot(); - if (svg) { - this.workspace.getBlockDragSurface().setBlocksAndShow(svg); - } -}; - -/** - * Move a block to a position. - * @param {Coordinate} xy The position to move to in workspace units. - */ -BlockSvg.prototype.moveTo = function(xy) { - const curXY = this.getRelativeToSurfaceXY(); - this.moveBy(xy.x - curXY.x, xy.y - curXY.y); -}; - -/** - * Move this block back to the workspace block canvas. - * Generally should be called at the same time as setDragging_(false). - * Does nothing if useDragSurface_ is false. - * @param {!Coordinate} newXY The position the block should take on - * on the workspace canvas, in workspace coordinates. - * @package - */ -BlockSvg.prototype.moveOffDragSurface = function(newXY) { - if (!this.useDragSurface_) { - return; - } - // Translate to current position, turning off 3d. - this.translate(newXY.x, newXY.y); - this.workspace.getBlockDragSurface().clearAndHide(this.workspace.getCanvas()); -}; - -/** - * Move this block during a drag, taking into account whether we are using a - * drag surface to translate blocks. - * This block must be a top-level block. - * @param {!Coordinate} newLoc The location to translate to, in - * workspace coordinates. - * @package - */ -BlockSvg.prototype.moveDuringDrag = function(newLoc) { - if (this.useDragSurface_) { - this.workspace.getBlockDragSurface().translateSurface(newLoc.x, newLoc.y); - } else { - this.svgGroup_.translate_ = 'translate(' + newLoc.x + ',' + newLoc.y + ')'; - this.svgGroup_.setAttribute( - 'transform', this.svgGroup_.translate_ + this.svgGroup_.skew_); - } -}; - -/** - * Clear the block of transform="..." attributes. - * Used when the block is switching from 3d to 2d transform or vice versa. - * @private - */ -BlockSvg.prototype.clearTransformAttributes_ = function() { - this.getSvgRoot().removeAttribute('transform'); -}; - -/** - * Snap this block to the nearest grid point. - */ -BlockSvg.prototype.snapToGrid = function() { - if (!this.workspace) { - return; // Deleted block. - } - if (this.workspace.isDragging()) { - return; // Don't bump blocks during a drag. - } - if (this.getParent()) { - return; // Only snap top-level blocks. - } - if (this.isInFlyout) { - return; // Don't move blocks around in a flyout. - } - const grid = this.workspace.getGrid(); - if (!grid || !grid.shouldSnap()) { - return; // Config says no snapping. - } - const spacing = grid.getSpacing(); - const half = spacing / 2; - const xy = this.getRelativeToSurfaceXY(); - const dx = - Math.round(Math.round((xy.x - half) / spacing) * spacing + half - xy.x); - const dy = - Math.round(Math.round((xy.y - half) / spacing) * spacing + half - xy.y); - if (dx || dy) { - this.moveBy(dx, dy); - } -}; - -/** - * Returns the coordinates of a bounding box describing the dimensions of this - * block and any blocks stacked below it. - * Coordinate system: workspace coordinates. - * @return {!Rect} Object with coordinates of the bounding box. - */ -BlockSvg.prototype.getBoundingRectangle = function() { - const blockXY = this.getRelativeToSurfaceXY(); - const blockBounds = this.getHeightWidth(); - let left; - let right; - if (this.RTL) { - left = blockXY.x - blockBounds.width; - right = blockXY.x; - } else { - left = blockXY.x; - right = blockXY.x + blockBounds.width; - } - return new Rect(blockXY.y, blockXY.y + blockBounds.height, left, right); -}; - -/** - * Notify every input on this block to mark its fields as dirty. - * A dirty field is a field that needs to be re-rendered. - */ -BlockSvg.prototype.markDirty = function() { - this.pathObject.constants = (/** @type {!WorkspaceSvg} */ (this.workspace)) - .getRenderer() - .getConstants(); - for (let i = 0, input; (input = this.inputList[i]); i++) { - input.markDirty(); - } -}; - -/** - * Set whether the block is collapsed or not. - * @param {boolean} collapsed True if collapsed. - */ -BlockSvg.prototype.setCollapsed = function(collapsed) { - if (this.collapsed_ === collapsed) { - return; - } - BlockSvg.superClass_.setCollapsed.call(this, collapsed); - if (!collapsed) { - this.updateCollapsed_(); - } else if (this.rendered) { - this.render(); - // Don't bump neighbours. Users like to store collapsed functions together - // and bumping makes them go out of alignment. - } -}; - -/** - * Makes sure that when the block is collapsed, it is rendered correctly - * for that state. - * @private - */ -BlockSvg.prototype.updateCollapsed_ = function() { - const collapsed = this.isCollapsed(); - const collapsedInputName = constants.COLLAPSED_INPUT_NAME; - const collapsedFieldName = constants.COLLAPSED_FIELD_NAME; - - for (let i = 0, input; (input = this.inputList[i]); i++) { - if (input.name !== collapsedInputName) { - input.setVisible(!collapsed); - } - } - - if (!collapsed) { - this.updateDisabled(); - this.removeInput(collapsedInputName); - return; - } - - const icons = this.getIcons(); - for (let i = 0, icon; (icon = icons[i]); i++) { - icon.setVisible(false); - } - - const text = this.toString(internalConstants.COLLAPSE_CHARS); - const field = this.getField(collapsedFieldName); - if (field) { - field.setValue(text); - return; - } - const input = this.getInput(collapsedInputName) || - this.appendDummyInput(collapsedInputName); - input.appendField(new FieldLabel(text), collapsedFieldName); -}; - -/** - * Open the next (or previous) FieldTextInput. - * @param {!Field} start Current field. - * @param {boolean} forward If true go forward, otherwise backward. - */ -BlockSvg.prototype.tab = function(start, forward) { - const tabCursor = new TabNavigateCursor(); - tabCursor.setCurNode(ASTNode.createFieldNode(start)); - const currentNode = tabCursor.getCurNode(); - - if (forward) { - tabCursor.next(); - } else { - tabCursor.prev(); - } - - const nextNode = tabCursor.getCurNode(); - if (nextNode && nextNode !== currentNode) { - const nextField = /** @type {!Field} */ (nextNode.getLocation()); - nextField.showEditor(); - - // Also move the cursor if we're in keyboard nav mode. - if (this.workspace.keyboardAccessibilityMode) { - this.workspace.getCursor().setCurNode(nextNode); - } - } -}; - -/** - * Handle a mouse-down on an SVG block. - * @param {!Event} e Mouse down event or touch start event. - * @private - */ -BlockSvg.prototype.onMouseDown_ = function(e) { - const gesture = this.workspace && this.workspace.getGesture(e); - if (gesture) { - gesture.handleBlockStart(e, this); - } -}; - -/** - * Load the block's help page in a new window. - * @package - */ -BlockSvg.prototype.showHelp = function() { - const url = - (typeof this.helpUrl === 'function') ? this.helpUrl() : this.helpUrl; - if (url) { - window.open(url); - } -}; - -/** - * Generate the context menu for this block. - * @return {?Array} Context menu options or null if no menu. - * @protected - */ -BlockSvg.prototype.generateContextMenu = function() { - if (this.workspace.options.readOnly || !this.contextMenu) { - return null; - } - const menuOptions = ContextMenuRegistry.registry.getContextMenuOptions( - ContextMenuRegistry.ScopeType.BLOCK, {block: this}); - - // Allow the block to add or modify menuOptions. - if (this.customContextMenu) { - this.customContextMenu(menuOptions); - } - - return menuOptions; -}; - -/** - * Show the context menu for this block. - * @param {!Event} e Mouse event. - * @package - */ -BlockSvg.prototype.showContextMenu = function(e) { - const menuOptions = this.generateContextMenu(); - - if (menuOptions && menuOptions.length) { - ContextMenu.show(e, menuOptions, this.RTL); - ContextMenu.setCurrentBlock(this); - } -}; - -/** - * Move the connections for this block and all blocks attached under it. - * Also update any attached bubbles. - * @param {number} dx Horizontal offset from current location, in workspace - * units. - * @param {number} dy Vertical offset from current location, in workspace - * units. - * @package - */ -BlockSvg.prototype.moveConnections = function(dx, dy) { - if (!this.rendered) { - // Rendering is required to lay out the blocks. - // This is probably an invisible block attached to a collapsed block. - return; - } - const myConnections = this.getConnections_(false); - for (let i = 0; i < myConnections.length; i++) { - myConnections[i].moveBy(dx, dy); - } - const icons = this.getIcons(); - for (let i = 0; i < icons.length; i++) { - icons[i].computeIconLocation(); - } - - // Recurse through all blocks attached under this one. - for (let i = 0; i < this.childBlocks_.length; i++) { - this.childBlocks_[i].moveConnections(dx, dy); - } -}; - -/** - * Recursively adds or removes the dragging class to this node and its children. - * @param {boolean} adding True if adding, false if removing. - * @package - */ -BlockSvg.prototype.setDragging = function(adding) { - if (adding) { - const group = this.getSvgRoot(); - group.translate_ = ''; - group.skew_ = ''; - common.draggingConnections.push(...this.getConnections_(true)); - dom.addClass( - /** @type {!Element} */ (this.svgGroup_), 'blocklyDragging'); - } else { - common.draggingConnections.length = 0; - dom.removeClass( - /** @type {!Element} */ (this.svgGroup_), 'blocklyDragging'); - } - // Recurse through all blocks attached under this one. - for (let i = 0; i < this.childBlocks_.length; i++) { - this.childBlocks_[i].setDragging(adding); - } -}; - -/** - * Set whether this block is movable or not. - * @param {boolean} movable True if movable. - */ -BlockSvg.prototype.setMovable = function(movable) { - BlockSvg.superClass_.setMovable.call(this, movable); - this.pathObject.updateMovable(movable); -}; - -/** - * Set whether this block is editable or not. - * @param {boolean} editable True if editable. - */ -BlockSvg.prototype.setEditable = function(editable) { - BlockSvg.superClass_.setEditable.call(this, editable); - const icons = this.getIcons(); - for (let i = 0; i < icons.length; i++) { - icons[i].updateEditable(); - } -}; - -/** - * Sets whether this block is a shadow block or not. - * @param {boolean} shadow True if a shadow. - * @package - */ -BlockSvg.prototype.setShadow = function(shadow) { - BlockSvg.superClass_.setShadow.call(this, shadow); - this.applyColour(); -}; - -/** - * Set whether this block is an insertion marker block or not. - * Once set this cannot be unset. - * @param {boolean} insertionMarker True if an insertion marker. - * @package - */ -BlockSvg.prototype.setInsertionMarker = function(insertionMarker) { - if (this.isInsertionMarker_ === insertionMarker) { - return; // No change. - } - this.isInsertionMarker_ = insertionMarker; - if (this.isInsertionMarker_) { - this.setColour( - this.workspace.getRenderer().getConstants().INSERTION_MARKER_COLOUR); - this.pathObject.updateInsertionMarker(true); - } -}; - -/** - * Return the root node of the SVG or null if none exists. - * @return {!SVGGElement} The root SVG node (probably a group). - */ -BlockSvg.prototype.getSvgRoot = function() { - return this.svgGroup_; -}; - -/** - * Dispose of this block. - * @param {boolean=} healStack If true, then try to heal any gap by connecting - * the next statement with the previous statement. Otherwise, dispose of - * all children of this block. - * @param {boolean=} animate If true, show a disposal animation and sound. - * @suppress {checkTypes} - */ -BlockSvg.prototype.dispose = function(healStack, animate) { - if (!this.workspace) { - // The block has already been deleted. - return; - } - Tooltip.dispose(); - Tooltip.unbindMouseEvents(this.pathObject.svgPath); - dom.startTextWidthCache(); - // Save the block's workspace temporarily so we can resize the - // contents once the block is disposed. - const blockWorkspace = this.workspace; - // If this block is being dragged, unlink the mouse events. - if (common.getSelected() === this) { - this.unselect(); - this.workspace.cancelCurrentGesture(); - } - // If this block has a context menu open, close it. - if (ContextMenu.getCurrentBlock() === this) { - ContextMenu.hide(); - } - - if (animate && this.rendered) { - this.unplug(healStack); - blockAnimations.disposeUiEffect(this); - } - // Stop rerendering. - this.rendered = false; - - // Clear pending warnings. - if (this.warningTextDb_) { - for (const n in this.warningTextDb_) { - clearTimeout(this.warningTextDb_[n]); - } - this.warningTextDb_ = null; - } - - const icons = this.getIcons(); - for (let i = 0; i < icons.length; i++) { - icons[i].dispose(); - } - BlockSvg.superClass_.dispose.call(this, !!healStack); - - dom.removeNode(this.svgGroup_); - blockWorkspace.resizeContents(); - // Sever JavaScript to DOM connections. - this.svgGroup_ = null; - dom.stopTextWidthCache(); -}; - -/** - * Delete a block and hide chaff when doing so. The block will not be deleted if - * it's in a flyout. This is called from the context menu and keyboard shortcuts - * as the full delete action. If you are disposing of a block from the workspace - * and don't need to perform flyout checks, handle event grouping, or hide - * chaff, then use `block.dispose()` directly. - */ -BlockSvg.prototype.checkAndDelete = function() { - if (this.workspace.isFlyout) { - return; - } - eventUtils.setGroup(true); - this.workspace.hideChaff(); - if (this.outputConnection) { - // Do not attempt to heal rows - // (https://github.com/google/blockly/issues/4832) - this.dispose(false, true); - } else { - this.dispose(/* heal */ true, true); - } - eventUtils.setGroup(false); -}; - -/** - * Encode a block for copying. - * @return {?ICopyable.CopyData} Copy metadata, or null if the block is - * an insertion marker. - * @package - */ -BlockSvg.prototype.toCopyData = function() { - if (this.isInsertionMarker_) { - return null; - } - return { - saveInfo: /** @type {!blocks.State} */ ( - blocks.save(this, {addCoordinates: true, addNextBlocks: false})), - source: this.workspace, - typeCounts: common.getBlockTypeCounts(this, true), - }; -}; - -/** - * Updates the colour of the block to match the block's state. - * @package - */ -BlockSvg.prototype.applyColour = function() { - this.pathObject.applyColour(this); - - const icons = this.getIcons(); - for (let i = 0; i < icons.length; i++) { - icons[i].applyColour(); - } - - for (let x = 0, input; (input = this.inputList[x]); x++) { - for (let y = 0, field; (field = input.fieldRow[y]); y++) { - field.applyColour(); - } - } -}; - -/** - * Updates the color of the block (and children) to match the current disabled - * state. - * @package - */ -BlockSvg.prototype.updateDisabled = function() { - const children = this.getChildren(false); - this.applyColour(); - if (this.isCollapsed()) { - return; - } - for (let i = 0, child; (child = children[i]); i++) { - if (child.rendered) { - child.updateDisabled(); - } - } -}; - -/** - * Get the comment icon attached to this block, or null if the block has no - * comment. - * @return {?Comment} The comment icon attached to this block, or null. - */ -BlockSvg.prototype.getCommentIcon = function() { - return this.commentIcon_; -}; - -/** - * Set this block's comment text. - * @param {?string} text The text, or null to delete. - */ -BlockSvg.prototype.setCommentText = function(text) { - const {Comment} = goog.module.get('Blockly.Comment'); - if (!Comment) { - throw Error('Missing require for Blockly.Comment'); - } - if (this.commentModel.text === text) { - return; - } - BlockSvg.superClass_.setCommentText.call(this, text); - - const shouldHaveComment = text !== null; - if (!!this.commentIcon_ === shouldHaveComment) { - // If the comment's state of existence is correct, but the text is new - // that means we're just updating a comment. - this.commentIcon_.updateText(); - return; - } - if (shouldHaveComment) { - this.commentIcon_ = new Comment(this); - this.comment = this.commentIcon_; // For backwards compatibility. - } else { - this.commentIcon_.dispose(); - this.commentIcon_ = null; - this.comment = null; // For backwards compatibility. - } - if (this.rendered) { - this.render(); - // Adding or removing a comment icon will cause the block to change shape. - this.bumpNeighbours(); - } -}; - -/** - * Set this block's warning text. - * @param {?string} text The text, or null to delete. - * @param {string=} opt_id An optional ID for the warning text to be able to - * maintain multiple warnings. - */ -BlockSvg.prototype.setWarningText = function(text, opt_id) { - const {Warning} = goog.module.get('Blockly.Warning'); - if (!Warning) { - throw Error('Missing require for Blockly.Warning'); - } - if (!this.warningTextDb_) { - // Create a database of warning PIDs. - // Only runs once per block (and only those with warnings). - this.warningTextDb_ = Object.create(null); - } - const id = opt_id || ''; - if (!id) { - // Kill all previous pending processes, this edit supersedes them all. - for (const n of Object.keys(this.warningTextDb_)) { - clearTimeout(this.warningTextDb_[n]); - delete this.warningTextDb_[n]; - } - } else if (this.warningTextDb_[id]) { - // Only queue up the latest change. Kill any earlier pending process. - clearTimeout(this.warningTextDb_[id]); - delete this.warningTextDb_[id]; - } - if (this.workspace.isDragging()) { - // Don't change the warning text during a drag. - // Wait until the drag finishes. - const thisBlock = this; - this.warningTextDb_[id] = setTimeout(function() { - if (thisBlock.workspace) { // Check block wasn't deleted. - delete thisBlock.warningTextDb_[id]; - thisBlock.setWarningText(text, id); - } - }, 100); - return; - } - if (this.isInFlyout) { - text = null; - } - - let changedState = false; - if (typeof text === 'string') { - // Bubble up to add a warning on top-most collapsed block. - let parent = this.getSurroundParent(); - let collapsedParent = null; - while (parent) { - if (parent.isCollapsed()) { - collapsedParent = parent; - } - parent = parent.getSurroundParent(); - } - if (collapsedParent) { - collapsedParent.setWarningText( - Msg['COLLAPSED_WARNINGS_WARNING'], BlockSvg.COLLAPSED_WARNING_ID); - } - - if (!this.warning) { - this.warning = new Warning(this); - changedState = true; - } - this.warning.setText(/** @type {string} */ (text), id); - } else { - // Dispose all warnings if no ID is given. - if (this.warning && !id) { - this.warning.dispose(); - changedState = true; - } else if (this.warning) { - const oldText = this.warning.getText(); - this.warning.setText('', id); - const newText = this.warning.getText(); - if (!newText) { - this.warning.dispose(); - } - changedState = oldText !== newText; - } - } - if (changedState && this.rendered) { - this.render(); - // Adding or removing a warning icon will cause the block to change shape. - this.bumpNeighbours(); - } -}; - -/** - * Give this block a mutator dialog. - * @param {?Mutator} mutator A mutator dialog instance or null to remove. - */ -BlockSvg.prototype.setMutator = function(mutator) { - if (this.mutator && this.mutator !== mutator) { - this.mutator.dispose(); - } - if (mutator) { - mutator.setBlock(this); - this.mutator = mutator; - mutator.createIcon(); - } - if (this.rendered) { - this.render(); - // Adding or removing a mutator icon will cause the block to change shape. - this.bumpNeighbours(); - } -}; - -/** - * Set whether the block is enabled or not. - * @param {boolean} enabled True if enabled. - */ -BlockSvg.prototype.setEnabled = function(enabled) { - if (this.isEnabled() !== enabled) { - BlockSvg.superClass_.setEnabled.call(this, enabled); - if (this.rendered && !this.getInheritedDisabled()) { - this.updateDisabled(); - } - } -}; - -/** - * Set whether the block is highlighted or not. Block highlighting is - * often used to visually mark blocks currently being executed. - * @param {boolean} highlighted True if highlighted. - */ -BlockSvg.prototype.setHighlighted = function(highlighted) { - if (!this.rendered) { - return; - } - this.pathObject.updateHighlighted(highlighted); -}; - -/** - * Adds the visual "select" effect to the block, but does not actually select - * it or fire an event. - * @see BlockSvg#select - */ -BlockSvg.prototype.addSelect = function() { - this.pathObject.updateSelected(true); -}; - -/** - * Removes the visual "select" effect from the block, but does not actually - * unselect it or fire an event. - * @see BlockSvg#unselect - */ -BlockSvg.prototype.removeSelect = function() { - this.pathObject.updateSelected(false); -}; - -/** - * Update the cursor over this block by adding or removing a class. - * @param {boolean} enable True if the delete cursor should be shown, false - * otherwise. - * @package - */ -BlockSvg.prototype.setDeleteStyle = function(enable) { - this.pathObject.updateDraggingDelete(enable); -}; - - -// Overrides of functions on Blockly.Block that take into account whether the -// block has been rendered. -/** - * Get the colour of a block. - * @return {string} #RRGGBB string. - */ -BlockSvg.prototype.getColour = function() { - return this.style.colourPrimary; -}; - -/** - * Change the colour of a block. - * @param {number|string} colour HSV hue value, or #RRGGBB string. - */ -BlockSvg.prototype.setColour = function(colour) { - BlockSvg.superClass_.setColour.call(this, colour); - const styleObj = - this.workspace.getRenderer().getConstants().getBlockStyleForColour( - this.colour_); - - this.pathObject.setStyle(styleObj.style); - this.style = styleObj.style; - this.styleName_ = styleObj.name; - - this.applyColour(); -}; - -/** - * Set the style and colour values of a block. - * @param {string} blockStyleName Name of the block style. - * @throws {Error} if the block style does not exist. - */ -BlockSvg.prototype.setStyle = function(blockStyleName) { - const blockStyle = - this.workspace.getRenderer().getConstants().getBlockStyle(blockStyleName); - this.styleName_ = blockStyleName; - - if (blockStyle) { - this.hat = blockStyle.hat; - this.pathObject.setStyle(blockStyle); - // Set colour to match Block. - this.colour_ = blockStyle.colourPrimary; - this.style = blockStyle; - - this.applyColour(); - } else { - throw Error('Invalid style name: ' + blockStyleName); - } -}; - -/** - * Move this block to the front of the visible workspace. - * tags do not respect z-index so SVG renders them in the - * order that they are in the DOM. By placing this block first within the - * block group's , it will render on top of any other blocks. - * @package - */ -BlockSvg.prototype.bringToFront = function() { - let block = this; - do { - const root = block.getSvgRoot(); - const parent = root.parentNode; - const childNodes = parent.childNodes; - // Avoid moving the block if it's already at the bottom. - if (childNodes[childNodes.length - 1] !== root) { - parent.appendChild(root); - } - block = block.getParent(); - } while (block); -}; - -/** - * Set whether this block can chain onto the bottom of another block. - * @param {boolean} newBoolean True if there can be a previous statement. - * @param {(string|Array|null)=} opt_check Statement type or - * list of statement types. Null/undefined if any type could be connected. - */ -BlockSvg.prototype.setPreviousStatement = function(newBoolean, opt_check) { - BlockSvg.superClass_.setPreviousStatement.call(this, newBoolean, opt_check); - - if (this.rendered) { - this.render(); - this.bumpNeighbours(); - } -}; - -/** - * Set whether another block can chain onto the bottom of this block. - * @param {boolean} newBoolean True if there can be a next statement. - * @param {(string|Array|null)=} opt_check Statement type or - * list of statement types. Null/undefined if any type could be connected. - */ -BlockSvg.prototype.setNextStatement = function(newBoolean, opt_check) { - BlockSvg.superClass_.setNextStatement.call(this, newBoolean, opt_check); - - if (this.rendered) { - this.render(); - this.bumpNeighbours(); - } -}; - -/** - * Set whether this block returns a value. - * @param {boolean} newBoolean True if there is an output. - * @param {(string|Array|null)=} opt_check Returned type or list - * of returned types. Null or undefined if any type could be returned - * (e.g. variable get). - */ -BlockSvg.prototype.setOutput = function(newBoolean, opt_check) { - BlockSvg.superClass_.setOutput.call(this, newBoolean, opt_check); - - if (this.rendered) { - this.render(); - this.bumpNeighbours(); - } -}; - -/** - * Set whether value inputs are arranged horizontally or vertically. - * @param {boolean} newBoolean True if inputs are horizontal. - */ -BlockSvg.prototype.setInputsInline = function(newBoolean) { - BlockSvg.superClass_.setInputsInline.call(this, newBoolean); - - if (this.rendered) { - this.render(); - this.bumpNeighbours(); - } -}; - -/** - * Remove an input from this block. - * @param {string} name The name of the input. - * @param {boolean=} opt_quiet True to prevent error if input is not present. - * @return {boolean} True if operation succeeds, false if input is not present - * and opt_quiet is true - * @throws {Error} if the input is not present and opt_quiet is not true. - */ -BlockSvg.prototype.removeInput = function(name, opt_quiet) { - const removed = BlockSvg.superClass_.removeInput.call(this, name, opt_quiet); - - if (this.rendered) { - this.render(); - // Removing an input will cause the block to change shape. - this.bumpNeighbours(); - } - - return removed; -}; - -/** - * Move a numbered input to a different location on this block. - * @param {number} inputIndex Index of the input to move. - * @param {number} refIndex Index of input that should be after the moved input. - */ -BlockSvg.prototype.moveNumberedInputBefore = function(inputIndex, refIndex) { - BlockSvg.superClass_.moveNumberedInputBefore.call(this, inputIndex, refIndex); - - if (this.rendered) { - this.render(); - // Moving an input will cause the block to change shape. - this.bumpNeighbours(); - } -}; - -/** - * Add a value input, statement input or local variable to this block. - * @param {number} type One of Blockly.inputTypes. - * @param {string} name Language-neutral identifier which may used to find this - * input again. Should be unique to this block. - * @return {!Input} The input object created. - * @protected - * @override - */ -BlockSvg.prototype.appendInput_ = function(type, name) { - const input = BlockSvg.superClass_.appendInput_.call(this, type, name); - - if (this.rendered) { - this.render(); - // Adding an input will cause the block to change shape. - this.bumpNeighbours(); - } - return input; -}; - -/** - * Sets whether this block's connections are tracked in the database or not. - * - * Used by the deserializer to be more efficient. Setting a connection's - * tracked_ value to false keeps it from adding itself to the db when it - * gets its first moveTo call, saving expensive ops for later. - * @param {boolean} track If true, start tracking. If false, stop tracking. - * @package - */ -BlockSvg.prototype.setConnectionTracking = function(track) { - if (this.previousConnection) { - /** @type {!RenderedConnection} */ (this.previousConnection) - .setTracking(track); - } - if (this.outputConnection) { - /** @type {!RenderedConnection} */ (this.outputConnection) - .setTracking(track); - } - if (this.nextConnection) { - /** @type {!RenderedConnection} */ (this.nextConnection).setTracking(track); - const child = - /** @type {!RenderedConnection} */ (this.nextConnection).targetBlock(); - if (child) { - child.setConnectionTracking(track); - } - } - - if (this.collapsed_) { - // When track is true, we don't want to start tracking collapsed - // connections. When track is false, we're already not tracking - // collapsed connections, so no need to update. - return; - } - - for (let i = 0; i < this.inputList.length; i++) { - const conn = - /** @type {!RenderedConnection} */ (this.inputList[i].connection); - if (conn) { - conn.setTracking(track); - - // Pass tracking on down the chain. - const block = conn.targetBlock(); - if (block) { - block.setConnectionTracking(track); - } - } - } -}; - -/** - * Returns connections originating from this block. - * @param {boolean} all If true, return all connections even hidden ones. - * Otherwise, for a non-rendered block return an empty list, and for a - * collapsed block don't return inputs connections. - * @return {!Array} Array of connections. - * @package - */ -BlockSvg.prototype.getConnections_ = function(all) { - const myConnections = []; - if (all || this.rendered) { - if (this.outputConnection) { - myConnections.push(this.outputConnection); - } - if (this.previousConnection) { - myConnections.push(this.previousConnection); - } - if (this.nextConnection) { - myConnections.push(this.nextConnection); - } - if (all || !this.collapsed_) { - for (let i = 0, input; (input = this.inputList[i]); i++) { - if (input.connection) { - myConnections.push(input.connection); - } - } - } - } - return myConnections; -}; - -/** - * Walks down a stack of blocks and finds the last next connection on the stack. - * @param {boolean} ignoreShadows If true,the last connection on a non-shadow - * block will be returned. If false, this will follow shadows to find the - * last connection. - * @return {?RenderedConnection} The last next connection on the stack, - * or null. - * @package - * @override - */ -BlockSvg.prototype.lastConnectionInStack = function(ignoreShadows) { - return /** @type {RenderedConnection} */ ( - BlockSvg.superClass_.lastConnectionInStack.call(this, ignoreShadows)); -}; - -/** - * Find the connection on this block that corresponds to the given connection - * on the other block. - * Used to match connections between a block and its insertion marker. - * @param {!Block} otherBlock The other block to match against. - * @param {!Connection} conn The other connection to match. - * @return {?RenderedConnection} The matching connection on this block, - * or null. - * @package - * @override - */ -BlockSvg.prototype.getMatchingConnection = function(otherBlock, conn) { - return /** @type {RenderedConnection} */ ( - BlockSvg.superClass_.getMatchingConnection.call(this, otherBlock, conn)); -}; - -/** - * Create a connection of the specified type. - * @param {number} type The type of the connection to create. - * @return {!RenderedConnection} A new connection of the specified type. - * @protected - */ -BlockSvg.prototype.makeConnection_ = function(type) { - return new RenderedConnection(this, type); -}; - -/** - * Bump unconnected blocks out of alignment. Two blocks which aren't actually - * connected should not coincidentally line up on screen. - */ -BlockSvg.prototype.bumpNeighbours = function() { - if (!this.workspace) { - return; // Deleted block. - } - if (this.workspace.isDragging()) { - return; // Don't bump blocks during a drag. - } - const rootBlock = this.getRootBlock(); - if (rootBlock.isInFlyout) { - return; // Don't move blocks around in a flyout. - } - // Loop through every connection on this block. - const myConnections = this.getConnections_(false); - for (let i = 0, connection; (connection = myConnections[i]); i++) { - const renderedConn = /** @type {!RenderedConnection} */ (connection); - // Spider down from this block bumping all sub-blocks. - if (renderedConn.isConnected() && renderedConn.isSuperior()) { - renderedConn.targetBlock().bumpNeighbours(); - } - - const neighbours = connection.neighbours(config.snapRadius); - for (let j = 0, otherConnection; (otherConnection = neighbours[j]); j++) { - const renderedOther = - /** @type {!RenderedConnection} */ (otherConnection); - // If both connections are connected, that's probably fine. But if - // either one of them is unconnected, then there could be confusion. - if (!renderedConn.isConnected() || !renderedOther.isConnected()) { - // Only bump blocks if they are from different tree structures. - if (renderedOther.getSourceBlock().getRootBlock() !== rootBlock) { - // Always bump the inferior block. - if (renderedConn.isSuperior()) { - renderedOther.bumpAwayFrom(renderedConn); - } else { - renderedConn.bumpAwayFrom(renderedOther); - } - } - } - } - } -}; - -/** - * Schedule snapping to grid and bumping neighbours to occur after a brief - * delay. - * @package - */ -BlockSvg.prototype.scheduleSnapAndBump = function() { - const block = this; - // Ensure that any snap and bump are part of this move's event group. - const group = eventUtils.getGroup(); - - setTimeout(function() { - eventUtils.setGroup(group); - block.snapToGrid(); - eventUtils.setGroup(false); - }, config.bumpDelay / 2); - - setTimeout(function() { - eventUtils.setGroup(group); - block.bumpNeighbours(); - eventUtils.setGroup(false); - }, config.bumpDelay); -}; - -/** - * Position a block so that it doesn't move the target block when connected. - * The block to position is usually either the first block in a dragged stack or - * an insertion marker. - * @param {!RenderedConnection} sourceConnection The connection on the - * moving block's stack. - * @param {!RenderedConnection} targetConnection The connection that - * should stay stationary as this block is positioned. - * @package - */ -BlockSvg.prototype.positionNearConnection = function( - sourceConnection, targetConnection) { - // We only need to position the new block if it's before the existing one, - // otherwise its position is set by the previous block. - if (sourceConnection.type === ConnectionType.NEXT_STATEMENT || - sourceConnection.type === ConnectionType.INPUT_VALUE) { - const dx = targetConnection.x - sourceConnection.x; - const dy = targetConnection.y - sourceConnection.y; - - this.moveBy(dx, dy); - } -}; - -/** - * Return the parent block or null if this block is at the top level. - * @return {?BlockSvg} The block (if any) that holds the current block. - * @override - */ -BlockSvg.prototype.getParent = function() { - return /** @type {!BlockSvg} */ (BlockSvg.superClass_.getParent.call(this)); -}; - -/** - * Return the top-most block in this block's tree. - * This will return itself if this block is at the top level. - * @return {!BlockSvg} The root block. - * @override - */ -BlockSvg.prototype.getRootBlock = function() { - return /** @type {!BlockSvg} */ ( - BlockSvg.superClass_.getRootBlock.call(this)); -}; - -/** - * Lays out and reflows a block based on its contents and settings. - * @param {boolean=} opt_bubble If false, just render this block. - * If true, also render block's parent, grandparent, etc. Defaults to true. - */ -BlockSvg.prototype.render = function(opt_bubble) { - if (this.renderIsInProgress_) { - return; // Don't allow recursive renders. - } - this.renderIsInProgress_ = true; - try { - this.rendered = true; - dom.startTextWidthCache(); - - if (this.isCollapsed()) { - this.updateCollapsed_(); - } - this.workspace.getRenderer().render(this); - this.updateConnectionLocations_(); - - if (opt_bubble !== false) { - const parentBlock = this.getParent(); - if (parentBlock) { - parentBlock.render(true); - } else { - // Top-most block. Fire an event to allow scrollbars to resize. - this.workspace.resizeContents(); - } - } - - dom.stopTextWidthCache(); - this.updateMarkers_(); - } finally { - this.renderIsInProgress_ = false; - } -}; - -/** - * Redraw any attached marker or cursor svgs if needed. - * @protected - */ -BlockSvg.prototype.updateMarkers_ = function() { - if (this.workspace.keyboardAccessibilityMode && this.pathObject.cursorSvg) { - this.workspace.getCursor().draw(); - } - if (this.workspace.keyboardAccessibilityMode && this.pathObject.markerSvg) { - // TODO(#4592): Update all markers on the block. - this.workspace.getMarker(MarkerManager.LOCAL_MARKER).draw(); - } -}; - -/** - * Update all of the connections on this block with the new locations calculated - * during rendering. Also move all of the connected blocks based on the new - * connection locations. - * @private - */ -BlockSvg.prototype.updateConnectionLocations_ = function() { - const blockTL = this.getRelativeToSurfaceXY(); - // Don't tighten previous or output connections because they are inferior - // connections. - if (this.previousConnection) { - this.previousConnection.moveToOffset(blockTL); - } - if (this.outputConnection) { - this.outputConnection.moveToOffset(blockTL); - } - - for (let i = 0; i < this.inputList.length; i++) { - const conn = - /** @type {!RenderedConnection} */ (this.inputList[i].connection); - if (conn) { - conn.moveToOffset(blockTL); - if (conn.isConnected()) { - conn.tighten(); - } - } - } - - if (this.nextConnection) { - this.nextConnection.moveToOffset(blockTL); - if (this.nextConnection.isConnected()) { - this.nextConnection.tighten(); - } - } -}; - -/** - * Add the cursor SVG to this block's SVG group. - * @param {SVGElement} cursorSvg The SVG root of the cursor to be added to the - * block SVG group. - * @package - */ -BlockSvg.prototype.setCursorSvg = function(cursorSvg) { - this.pathObject.setCursorSvg(cursorSvg); -}; - -/** - * Add the marker SVG to this block's SVG group. - * @param {SVGElement} markerSvg The SVG root of the marker to be added to the - * block SVG group. - * @package - */ -BlockSvg.prototype.setMarkerSvg = function(markerSvg) { - this.pathObject.setMarkerSvg(markerSvg); -}; - -/** - * Returns a bounding box describing the dimensions of this block - * and any blocks stacked below it. - * @return {!{height: number, width: number}} Object with height and width - * properties in workspace units. - * @package - */ -BlockSvg.prototype.getHeightWidth = function() { - let height = this.height; - let width = this.width; - // Recursively add size of subsequent blocks. - const nextBlock = this.getNextBlock(); - if (nextBlock) { - const nextHeightWidth = nextBlock.getHeightWidth(); - const workspace = /** @type {!WorkspaceSvg} */ (this.workspace); - const tabHeight = workspace.getRenderer().getConstants().NOTCH_HEIGHT; - height += nextHeightWidth.height - tabHeight; - width = Math.max(width, nextHeightWidth.width); - } - return {height: height, width: width}; -}; - -/** - * Visual effect to show that if the dragging block is dropped, this block will - * be replaced. If a shadow block, it will disappear. Otherwise it will bump. - * @param {boolean} add True if highlighting should be added. - * @package - */ -BlockSvg.prototype.fadeForReplacement = function(add) { - this.pathObject.updateReplacementFade(add); -}; - -/** - * Visual effect to show that if the dragging block is dropped it will connect - * to this input. - * @param {Connection} conn The connection on the input to highlight. - * @param {boolean} add True if highlighting should be added. - * @package - */ -BlockSvg.prototype.highlightShapeForInput = function(conn, add) { - this.pathObject.updateShapeForInputHighlight(conn, add); -}; - exports.BlockSvg = BlockSvg; diff --git a/core/comment.js b/core/comment.js index 8f1efbe93..0502057bf 100644 --- a/core/comment.js +++ b/core/comment.js @@ -120,7 +120,6 @@ class Comment extends Icon { */ this.paragraphElement_ = null; - this.createIcon(); } diff --git a/core/contextmenu.js b/core/contextmenu.js index 6508ff3c9..907f24389 100644 --- a/core/contextmenu.js +++ b/core/contextmenu.js @@ -27,6 +27,8 @@ const userAgent = goog.require('Blockly.utils.userAgent'); const svgMath = goog.require('Blockly.utils.svgMath'); /* eslint-disable-next-line no-unused-vars */ const {Block} = goog.requireType('Blockly.Block'); +/* eslint-disable-next-line no-unused-vars */ +const {BlockSvg} = goog.requireType('Blockly.BlockSvg'); const {config} = goog.require('Blockly.config'); const {Coordinate} = goog.require('Blockly.utils.Coordinate'); const {MenuItem} = goog.require('Blockly.MenuItem'); @@ -262,7 +264,8 @@ const callbackFactory = function(block, xml) { eventUtils.disable(); let newBlock; try { - newBlock = Xml.domToBlock(xml, block.workspace); + newBlock = + /** @type {!BlockSvg} */ (Xml.domToBlock(xml, block.workspace)); // Move the new block next to the old block. const xy = block.getRelativeToSurfaceXY(); if (block.RTL) { diff --git a/core/contextmenu_items.js b/core/contextmenu_items.js index aa0abbf5d..0d0696f42 100644 --- a/core/contextmenu_items.js +++ b/core/contextmenu_items.js @@ -239,8 +239,7 @@ const addDeletableBlocks_ = function(block, deleteList) { if (block.isDeletable()) { Array.prototype.push.apply(deleteList, block.getDescendants(false)); } else { - const children = /* eslint-disable-next-line indent */ - /** @type {!Array} */ (block.getChildren(false)); + const children = block.getChildren(false); for (let i = 0; i < children.length; i++) { addDeletableBlocks_(children[i], deleteList); } diff --git a/core/events/events_block_change.js b/core/events/events_block_change.js index cf8b6d0e9..305ed4488 100644 --- a/core/events/events_block_change.js +++ b/core/events/events_block_change.js @@ -103,9 +103,12 @@ class BlockChange extends BlockBase { console.warn('Can\'t change non-existent block: ' + this.blockId); return; } - if (block.mutator) { + + // Assume the block is rendered so that then we can check. + const blockSvg = /** @type {!BlockSvg} */ (block); + if (blockSvg.mutator) { // Close the mutator (if open) since we don't want to update it. - block.mutator.setVisible(false); + blockSvg.mutator.setVisible(false); } const value = forward ? this.newValue : this.oldValue; switch (this.element) { diff --git a/core/extensions.js b/core/extensions.js index 4043ba95c..a05e05d61 100644 --- a/core/extensions.js +++ b/core/extensions.js @@ -513,11 +513,11 @@ exports.buildTooltipWithFieldText = buildTooltipWithFieldText; * @this {Block} */ const extensionParentTooltip = function() { - this.tooltipWhenNotConnected = this.tooltip; + const tooltipWhenNotConnected = this.tooltip; this.setTooltip(function() { const parent = this.getParent(); return (parent && parent.getInputsInline() && parent.tooltip) || - this.tooltipWhenNotConnected; + tooltipWhenNotConnected; }.bind(this)); }; register('parent_tooltip_when_inline', extensionParentTooltip); diff --git a/core/flyout_base.js b/core/flyout_base.js index 4490617e0..89bb628e7 100644 --- a/core/flyout_base.js +++ b/core/flyout_base.js @@ -206,6 +206,14 @@ class Flyout extends DeleteArea { */ this.containerVisible_ = true; + /** + * A map from blocks to the rects which are beneath them to act as input + * targets. + * @type {!WeakMap} + * @private + */ + this.rectMap_ = new WeakMap(); + /** * Corner radius of the flyout background. * @type {number} @@ -1045,7 +1053,7 @@ class Flyout extends DeleteArea { // Add the rectangles under the blocks, so that the blocks' tooltips work. this.workspace_.getCanvas().insertBefore(rect, block.getSvgRoot()); - block.flyoutRect_ = rect; + this.rectMap_.set(block, rect); this.mats_[index] = rect; return rect; } diff --git a/core/flyout_horizontal.js b/core/flyout_horizontal.js index e09ced7f9..56c25e9ce 100644 --- a/core/flyout_horizontal.js +++ b/core/flyout_horizontal.js @@ -360,8 +360,8 @@ class HorizontalFlyout extends Flyout { if (this.height_ !== flyoutHeight) { for (let i = 0, block; (block = blocks[i]); i++) { - if (block.flyoutRect_) { - this.moveRectToBlock_(block.flyoutRect_, block); + if (this.rectMap_.has(block)) { + this.moveRectToBlock_(this.rectMap_.get(block), block); } } diff --git a/core/flyout_vertical.js b/core/flyout_vertical.js index 546124eeb..80a6d61d5 100644 --- a/core/flyout_vertical.js +++ b/core/flyout_vertical.js @@ -350,8 +350,8 @@ class VerticalFlyout extends Flyout { } block.moveBy(newX - oldX, 0); } - if (block.flyoutRect_) { - this.moveRectToBlock_(block.flyoutRect_, block); + if (this.rectMap_.has(block)) { + this.moveRectToBlock_(this.rectMap_.get(block), block); } } if (this.RTL) { diff --git a/core/mutator.js b/core/mutator.js index 0794e32ca..9b6b2c806 100644 --- a/core/mutator.js +++ b/core/mutator.js @@ -367,11 +367,9 @@ class Mutator extends Icon { // Save the initial connections, then listen for further changes. if (this.block_.saveConnections) { const thisRootBlock = this.rootBlock_; - const mutatorBlock = - /** @type {{saveConnections: function(!Block)}} */ (this.block_); - mutatorBlock.saveConnections(this.rootBlock_); + this.block_.saveConnections(thisRootBlock); this.sourceListener_ = function() { - mutatorBlock.saveConnections(thisRootBlock); + this.block_.saveConnections(thisRootBlock); }; this.block_.workspace.addChangeListener(this.sourceListener_); } diff --git a/core/procedures.js b/core/procedures.js index 308b1fff7..d7041f46d 100644 --- a/core/procedures.js +++ b/core/procedures.js @@ -27,6 +27,8 @@ const {Block} = goog.requireType('Blockly.Block'); /* eslint-disable-next-line no-unused-vars */ const {BubbleOpen} = goog.requireType('Blockly.Events.BubbleOpen'); /* eslint-disable-next-line no-unused-vars */ +const {BlockSvg} = goog.requireType('Blockly.BlockSvg'); +/* eslint-disable-next-line no-unused-vars */ const {Field} = goog.requireType('Blockly.Field'); const {Msg} = goog.require('Blockly.Msg'); const {Names} = goog.require('Blockly.Names'); @@ -162,8 +164,9 @@ const isNameUsed = function(name, workspace, opt_exclude) { if (blocks[i] === opt_exclude) { continue; } - if (blocks[i].getProcedureDef) { - const procedureBlock = /** @type {!ProcedureBlock} */ (blocks[i]); + // Assume it is a procedure block so we can check. + const procedureBlock = /** @type {!ProcedureBlock} */ (blocks[i]); + if (procedureBlock.getProcedureDef) { const procName = procedureBlock.getProcedureDef(); if (Names.equals(procName[0], name)) { return true; @@ -193,8 +196,9 @@ const rename = function(name) { // Rename any callers. const blocks = this.getSourceBlock().workspace.getAllBlocks(false); for (let i = 0; i < blocks.length; i++) { - if (blocks[i].renameProcedure) { - const procedureBlock = /** @type {!ProcedureBlock} */ (blocks[i]); + // Assume it is a procedure so we can check. + const procedureBlock = /** @type {!ProcedureBlock} */ (blocks[i]); + if (procedureBlock.renameProcedure) { procedureBlock.renameProcedure( /** @type {string} */ (oldName), legalName); } @@ -335,13 +339,13 @@ const mutatorOpenListener = function(e) { return; } const workspaceId = /** @type {string} */ (bubbleEvent.workspaceId); - const block = - Workspace.getById(workspaceId).getBlockById(bubbleEvent.blockId); + const block = /** @type {!BlockSvg} */ + (Workspace.getById(workspaceId).getBlockById(bubbleEvent.blockId)); const type = block.type; if (type !== 'procedures_defnoreturn' && type !== 'procedures_defreturn') { return; } - const workspace = block.mutator.getWorkspace(); + const workspace = /** @type {!WorkspaceSvg} */ (block.mutator.getWorkspace()); updateMutatorFlyout(workspace); workspace.addChangeListener(mutatorChangeListener); }; @@ -376,8 +380,9 @@ const getCallers = function(name, workspace) { const blocks = workspace.getAllBlocks(false); // Iterate through every block and check the name. for (let i = 0; i < blocks.length; i++) { - if (blocks[i].getProcedureCall) { - const procedureBlock = /** @type {!ProcedureBlock} */ (blocks[i]); + // Assume it is a procedure block so we can check. + const procedureBlock = /** @type {!ProcedureBlock} */ (blocks[i]); + if (procedureBlock.getProcedureCall) { const procName = procedureBlock.getProcedureCall(); // Procedure name may be null if the block is only half-built. if (procName && Names.equals(procName, name)) { @@ -433,8 +438,9 @@ const getDefinition = function(name, workspace) { // rely on getProcedureDef. const blocks = workspace.getAllBlocks(false); for (let i = 0; i < blocks.length; i++) { - if (blocks[i].getProcedureDef) { - const procedureBlock = /** @type {!ProcedureBlock} */ (blocks[i]); + // Assume it is a procedure block so we can check. + const procedureBlock = /** @type {!ProcedureBlock} */ (blocks[i]); + if (procedureBlock.getProcedureDef) { const tuple = procedureBlock.getProcedureDef(); if (tuple && Names.equals(tuple[0], name)) { return blocks[i]; // Can't use procedureBlock var due to type check. diff --git a/core/rendered_connection.js b/core/rendered_connection.js index 56010451a..4b0634deb 100644 --- a/core/rendered_connection.js +++ b/core/rendered_connection.js @@ -53,6 +53,9 @@ class RenderedConnection extends Connection { constructor(source, type) { super(source, type); + /** @type {!BlockSvg} */ + this.sourceBlock_; + /** * Connection database for connections of this type on the current * workspace. @@ -139,7 +142,7 @@ class RenderedConnection extends Connection { /** * Move the block(s) belonging to the connection to a point where they don't * visually interfere with the specified connection. - * @param {!Connection} staticConnection The connection to move away + * @param {!RenderedConnection} staticConnection The connection to move away * from. * @package */ @@ -436,7 +439,8 @@ class RenderedConnection extends Connection { setTimeout(function() { if (!block.isDisposed() && !block.getParent()) { eventUtils.setGroup(group); - this.bumpAwayFrom(otherConnection); + this.bumpAwayFrom( + /** @type {!RenderedConnection} */ (otherConnection)); eventUtils.setGroup(false); } }.bind(this), config.bumpDelay); @@ -452,15 +456,18 @@ class RenderedConnection extends Connection { */ disconnectInternal_(parentBlock, childBlock) { super.disconnectInternal_(parentBlock, childBlock); + const renderedParent = /** @type {!BlockSvg} */ (parentBlock); + const renderedChild = /** @type {!BlockSvg} */ (childBlock); + // Rerender the parent so that it may reflow. - if (parentBlock.rendered) { - parentBlock.render(); + if (renderedParent.rendered) { + renderedParent.render(); } - if (childBlock.rendered) { - childBlock.updateDisabled(); - childBlock.render(); + if (renderedChild.rendered) { + renderedChild.updateDisabled(); + renderedChild.render(); // Reset visibility, since the child is now a top block. - childBlock.getSvgRoot().style.display = 'block'; + renderedChild.getSvgRoot().style.display = 'block'; } } @@ -506,9 +513,12 @@ class RenderedConnection extends Connection { connect_(childConnection) { super.connect_(childConnection); + const renderedChildConnection = /** @type {!RenderedConnection} */ + (childConnection); + const parentConnection = this; const parentBlock = parentConnection.getSourceBlock(); - const childBlock = childConnection.getSourceBlock(); + const childBlock = renderedChildConnection.getSourceBlock(); const parentRendered = parentBlock.rendered; const childRendered = childBlock.rendered; diff --git a/core/renderers/common/i_path_object.js b/core/renderers/common/i_path_object.js index d8388e715..06939bb3c 100644 --- a/core/renderers/common/i_path_object.js +++ b/core/renderers/common/i_path_object.js @@ -19,7 +19,7 @@ goog.module('Blockly.blockRendering.IPathObject'); /* eslint-disable-next-line no-unused-vars */ -const {Block} = goog.requireType('Blockly.Block'); +const {BlockSvg} = goog.requireType('Blockly.BlockSvg'); /* eslint-disable-next-line no-unused-vars */ const {ConstantProvider} = goog.requireType('Blockly.blockRendering.ConstantProvider'); /* eslint-disable-next-line no-unused-vars */ @@ -78,7 +78,7 @@ IPathObject.prototype.setPath; /** * Apply the stored colours to the block's path, taking into account whether * the paths belong to a shadow block. - * @param {!Block} block The source block. + * @param {!BlockSvg} block The source block. * @package */ IPathObject.prototype.applyColour; diff --git a/core/renderers/common/path_object.js b/core/renderers/common/path_object.js index 712e16bde..3ffa21a0a 100644 --- a/core/renderers/common/path_object.js +++ b/core/renderers/common/path_object.js @@ -18,7 +18,7 @@ goog.module('Blockly.blockRendering.PathObject'); const dom = goog.require('Blockly.utils.dom'); /* eslint-disable-next-line no-unused-vars */ -const {Block} = goog.requireType('Blockly.Block'); +const {BlockSvg} = goog.requireType('Blockly.BlockSvg'); /* eslint-disable-next-line no-unused-vars */ const {Connection} = goog.requireType('Blockly.Connection'); /* eslint-disable-next-line no-unused-vars */ @@ -144,7 +144,7 @@ class PathObject { /** * Apply the stored colours to the block's path, taking into account whether * the paths belong to a shadow block. - * @param {!Block} block The source block. + * @param {!BlockSvg} block The source block. * @package */ applyColour(block) { diff --git a/core/serialization/blocks.js b/core/serialization/blocks.js index 150ea865f..2e3b76bbd 100644 --- a/core/serialization/blocks.js +++ b/core/serialization/blocks.js @@ -23,6 +23,8 @@ const serializationRegistry = goog.require('Blockly.serialization.registry'); const {BadConnectionCheck, MissingBlockType, MissingConnection, RealChildOfShadow} = goog.require('Blockly.serialization.exceptions'); /* eslint-disable-next-line no-unused-vars */ const {Block} = goog.requireType('Blockly.Block'); +/* eslint-disable-next-line no-unused-vars */ +const {BlockSvg} = goog.requireType('Blockly.BlockSvg'); // eslint-disable-next-line no-unused-vars const {Connection} = goog.requireType('Blockly.Connection'); // eslint-disable-next-line no-unused-vars @@ -350,9 +352,10 @@ const appendInternal = function(state, workspace, { // Adding connections to the connection db is expensive. This defers that // operation to decrease load time. if (workspace.rendered) { + const blockSvg = /** @type {!BlockSvg} */ (block); setTimeout(() => { - if (!block.disposed) { - block.setConnectionTracking(true); + if (!blockSvg.disposed) { + blockSvg.setConnectionTracking(true); } }, 1); } @@ -513,9 +516,10 @@ const loadIcons = function(block, state) { block.setCommentText(comment['text']); block.commentModel.pinned = comment['pinned']; block.commentModel.size = new Size(comment['width'], comment['height']); - if (comment['pinned'] && block.getCommentIcon && !block.isInFlyout) { + if (comment['pinned'] && block.rendered && !block.isInFlyout) { // Give the block a chance to be positioned and rendered before showing. - setTimeout(() => block.getCommentIcon().setVisible(true), 1); + const blockSvg = /** @type {!BlockSvg} */ (block); + setTimeout(() => blockSvg.getCommentIcon().setVisible(true), 1); } } }; @@ -607,12 +611,13 @@ const loadConnection = function(connection, connectionState) { */ const initBlock = function(block, rendered) { if (rendered) { + const blockSvg = /** @type {!BlockSvg} */ (block); // Adding connections to the connection db is expensive. This defers that // operation to decrease load time. - block.setConnectionTracking(false); + blockSvg.setConnectionTracking(false); - block.initSvg(); - block.render(false); + blockSvg.initSvg(); + blockSvg.render(false); } else { block.initModel(); } diff --git a/core/workspace_svg.js b/core/workspace_svg.js index 28849b0c3..f95e61eb3 100644 --- a/core/workspace_svg.js +++ b/core/workspace_svg.js @@ -1563,14 +1563,14 @@ class WorkspaceSvg extends Workspace { let blockX = 0; let blockY = 0; if (xmlBlock) { - block = Xml.domToBlock(xmlBlock, this); + block = /** @type {!BlockSvg} */ (Xml.domToBlock(xmlBlock, this)); blockX = parseInt(xmlBlock.getAttribute('x'), 10); if (this.RTL) { blockX = -blockX; } blockY = parseInt(xmlBlock.getAttribute('y'), 10); } else if (jsonBlock) { - block = blocks.append(jsonBlock, this); + block = /** @type {!BlockSvg} */ (blocks.append(jsonBlock, this)); blockX = jsonBlock['x'] || 10; if (this.RTL) { blockX = this.getWidth() - blockX; @@ -2425,6 +2425,16 @@ class WorkspaceSvg extends Workspace { return /** @type {BlockSvg} */ (super.getBlockById(id)); } + /** + * Find all blocks in workspace. Blocks are optionally sorted + * by position; top to bottom (with slight LTR or RTL bias). + * @param {boolean} ordered Sort the list if true. + * @return {!Array} Array of blocks. + */ + getAllBlocks(ordered) { + return /** @type {!Array} */ (super.getAllBlocks(ordered)); + } + /** * Finds the top-level blocks and returns them. Blocks are optionally sorted * by position; top to bottom (with slight LTR or RTL bias). diff --git a/core/xml.js b/core/xml.js index f9c8b1c31..217b910f0 100644 --- a/core/xml.js +++ b/core/xml.js @@ -21,6 +21,8 @@ const utilsXml = goog.require('Blockly.utils.xml'); /* eslint-disable-next-line no-unused-vars */ const {Block} = goog.requireType('Blockly.Block'); /* eslint-disable-next-line no-unused-vars */ +const {BlockSvg} = goog.requireType('Blockly.BlockSvg'); +/* eslint-disable-next-line no-unused-vars */ const {Connection} = goog.requireType('Blockly.Connection'); /* eslint-disable-next-line no-unused-vars */ const {Field} = goog.requireType('Blockly.Field'); @@ -599,10 +601,10 @@ const domToBlock = function(xmlBlock, workspace) { try { topBlock = domToBlockHeadless(xmlBlock, workspace); // Generate list of all blocks. - const blocks = topBlock.getDescendants(false); if (workspace.rendered) { - // Wait to track connections to speed up assembly. - topBlock.setConnectionTracking(false); + const topBlockSvg = /** @type {!BlockSvg} */ (topBlock); + const blocks = topBlock.getDescendants(false); + topBlockSvg.setConnectionTracking(false); // Render each block. for (let i = blocks.length - 1; i >= 0; i--) { blocks[i].initSvg(); @@ -613,15 +615,16 @@ const domToBlock = function(xmlBlock, workspace) { // Populating the connection database may be deferred until after the // blocks have rendered. setTimeout(function() { - if (!topBlock.disposed) { - topBlock.setConnectionTracking(true); + if (!topBlockSvg.disposed) { + topBlockSvg.setConnectionTracking(true); } }, 1); - topBlock.updateDisabled(); + topBlockSvg.updateDisabled(); // Allow the scrollbars to resize and move based on the new contents. // TODO(@picklesrus): #387. Remove when domToBlock avoids resizing. workspace.resizeContents(); } else { + const blocks = topBlock.getDescendants(false); for (let i = blocks.length - 1; i >= 0; i--) { blocks[i].initModel(); } @@ -778,8 +781,9 @@ const applyCommentTagNodes = function(xmlChildren, block) { } if (pinned && block.getCommentIcon && !block.isInFlyout) { + const blockSvg = /** @type {BlockSvg} */ (block); setTimeout(function() { - block.getCommentIcon().setVisible(true); + blockSvg.getCommentIcon().setVisible(true); }, 1); } } @@ -953,8 +957,11 @@ const domToBlockHeadless = function( applyNextTagNodes(xmlChildNameMap.next, workspace, block); if (shouldCallInitSvg) { - // InitSvg needs to be called after variable fields are loaded. - block.initSvg(); + // This shouldn't even be called here + // (ref: https://github.com/google/blockly/pull/4296#issuecomment-884226021 + // But the XML serializer/deserializer is iceboxed so I'm not going to fix + // it. + (/** @type {!BlockSvg} */ (block)).initSvg(); } const inline = xmlBlock.getAttribute('inline'); diff --git a/scripts/gulpfiles/chunks.json b/scripts/gulpfiles/chunks.json index 72c0d27c8..789b9fa3a 100644 --- a/scripts/gulpfiles/chunks.json +++ b/scripts/gulpfiles/chunks.json @@ -253,13 +253,13 @@ "./core/extensions.js", "./core/block.js", "./core/utils/string.js", - "./core/utils/object.js", "./core/dialog.js", "./core/utils/xml.js", "./core/events/events_var_base.js", "./core/events/events_var_create.js", "./core/variable_model.js", "./core/variables.js", + "./core/utils/object.js", "./core/events/events_abstract.js", "./core/registry.js", "./core/events/utils.js", diff --git a/tests/deps.js b/tests/deps.js index 3d6cad703..24df7a3c0 100644 --- a/tests/deps.js +++ b/tests/deps.js @@ -12,7 +12,7 @@ goog.addDependency('../../core/block.js', ['Blockly.Block'], ['Blockly.ASTNode', goog.addDependency('../../core/block_animations.js', ['Blockly.blockAnimations'], ['Blockly.utils.Svg', 'Blockly.utils.dom'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/block_drag_surface.js', ['Blockly.BlockDragSurfaceSvg'], ['Blockly.utils.Coordinate', 'Blockly.utils.Svg', 'Blockly.utils.dom', 'Blockly.utils.svgMath'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/block_dragger.js', ['Blockly.BlockDragger'], ['Blockly.Events.BlockDrag', 'Blockly.Events.BlockMove', 'Blockly.Events.utils', 'Blockly.IBlockDragger', 'Blockly.InsertionMarkerManager', 'Blockly.blockAnimations', 'Blockly.bumpObjects', 'Blockly.common', 'Blockly.registry', 'Blockly.utils.Coordinate', 'Blockly.utils.dom'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/block_svg.js', ['Blockly.BlockSvg'], ['Blockly.ASTNode', 'Blockly.Block', 'Blockly.ConnectionType', 'Blockly.ContextMenu', 'Blockly.ContextMenuRegistry', 'Blockly.Events.BlockMove', 'Blockly.Events.Selected', 'Blockly.Events.utils', 'Blockly.FieldLabel', 'Blockly.IASTNodeLocationSvg', 'Blockly.IBoundedElement', 'Blockly.ICopyable', 'Blockly.IDraggable', 'Blockly.MarkerManager', 'Blockly.Msg', 'Blockly.RenderedConnection', 'Blockly.TabNavigateCursor', 'Blockly.Tooltip', 'Blockly.Touch', 'Blockly.blockAnimations', 'Blockly.browserEvents', 'Blockly.common', 'Blockly.config', 'Blockly.constants', 'Blockly.internalConstants', 'Blockly.serialization.blocks', 'Blockly.utils.Coordinate', 'Blockly.utils.Rect', 'Blockly.utils.Svg', 'Blockly.utils.dom', 'Blockly.utils.object', 'Blockly.utils.svgMath', 'Blockly.utils.userAgent'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/block_svg.js', ['Blockly.BlockSvg'], ['Blockly.ASTNode', 'Blockly.Block', 'Blockly.ConnectionType', 'Blockly.ContextMenu', 'Blockly.ContextMenuRegistry', 'Blockly.Events.BlockMove', 'Blockly.Events.Selected', 'Blockly.Events.utils', 'Blockly.FieldLabel', 'Blockly.IASTNodeLocationSvg', 'Blockly.IBoundedElement', 'Blockly.ICopyable', 'Blockly.IDraggable', 'Blockly.MarkerManager', 'Blockly.Msg', 'Blockly.RenderedConnection', 'Blockly.TabNavigateCursor', 'Blockly.Tooltip', 'Blockly.Touch', 'Blockly.blockAnimations', 'Blockly.browserEvents', 'Blockly.common', 'Blockly.config', 'Blockly.constants', 'Blockly.internalConstants', 'Blockly.serialization.blocks', 'Blockly.utils.Coordinate', 'Blockly.utils.Rect', 'Blockly.utils.Svg', 'Blockly.utils.dom', 'Blockly.utils.svgMath', 'Blockly.utils.userAgent'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/blockly.js', ['Blockly'], ['Blockly.ASTNode', 'Blockly.BasicCursor', 'Blockly.Block', 'Blockly.BlockDragSurfaceSvg', 'Blockly.BlockDragger', 'Blockly.BlockSvg', 'Blockly.BlocklyOptions', 'Blockly.Bubble', 'Blockly.BubbleDragger', 'Blockly.CollapsibleToolboxCategory', 'Blockly.Comment', 'Blockly.ComponentManager', 'Blockly.Connection', 'Blockly.ConnectionChecker', 'Blockly.ConnectionDB', 'Blockly.ConnectionType', 'Blockly.ContextMenu', 'Blockly.ContextMenuItems', 'Blockly.ContextMenuRegistry', 'Blockly.Css', 'Blockly.Cursor', 'Blockly.DeleteArea', 'Blockly.DragTarget', 'Blockly.DropDownDiv', 'Blockly.Events', 'Blockly.Events.BlockCreate', 'Blockly.Events.FinishedLoading', 'Blockly.Events.Ui', 'Blockly.Events.UiBase', 'Blockly.Events.VarCreate', 'Blockly.Extensions', 'Blockly.Field', 'Blockly.FieldAngle', 'Blockly.FieldCheckbox', 'Blockly.FieldColour', 'Blockly.FieldDropdown', 'Blockly.FieldImage', 'Blockly.FieldLabel', 'Blockly.FieldLabelSerializable', 'Blockly.FieldMultilineInput', 'Blockly.FieldNumber', 'Blockly.FieldTextInput', 'Blockly.FieldVariable', 'Blockly.Flyout', 'Blockly.FlyoutButton', 'Blockly.FlyoutMetricsManager', 'Blockly.Generator', 'Blockly.Gesture', 'Blockly.Grid', 'Blockly.HorizontalFlyout', 'Blockly.IASTNodeLocation', 'Blockly.IASTNodeLocationSvg', 'Blockly.IASTNodeLocationWithBlock', 'Blockly.IAutoHideable', 'Blockly.IBlockDragger', 'Blockly.IBoundedElement', 'Blockly.IBubble', 'Blockly.ICollapsibleToolboxItem', 'Blockly.IComponent', 'Blockly.IConnectionChecker', 'Blockly.IContextMenu', 'Blockly.ICopyable', 'Blockly.IDeletable', 'Blockly.IDeleteArea', 'Blockly.IDragTarget', 'Blockly.IDraggable', 'Blockly.IFlyout', 'Blockly.IKeyboardAccessible', 'Blockly.IMetricsManager', 'Blockly.IMovable', 'Blockly.IPositionable', 'Blockly.IRegistrable', 'Blockly.IRegistrableField', 'Blockly.ISelectable', 'Blockly.ISelectableToolboxItem', 'Blockly.IStyleable', 'Blockly.IToolbox', 'Blockly.IToolboxItem', 'Blockly.Icon', 'Blockly.Input', 'Blockly.InsertionMarkerManager', 'Blockly.Marker', 'Blockly.MarkerManager', 'Blockly.Menu', 'Blockly.MenuItem', 'Blockly.MetricsManager', 'Blockly.Msg', 'Blockly.Mutator', 'Blockly.Names', 'Blockly.Options', 'Blockly.Procedures', 'Blockly.RenderedConnection', 'Blockly.Scrollbar', 'Blockly.ScrollbarPair', 'Blockly.ShortcutItems', 'Blockly.ShortcutRegistry', 'Blockly.TabNavigateCursor', 'Blockly.Theme', 'Blockly.ThemeManager', 'Blockly.Themes', 'Blockly.Toolbox', 'Blockly.ToolboxCategory', 'Blockly.ToolboxItem', 'Blockly.ToolboxSeparator', 'Blockly.Tooltip', 'Blockly.Touch', 'Blockly.TouchGesture', 'Blockly.Trashcan', 'Blockly.VariableMap', 'Blockly.VariableModel', 'Blockly.Variables', 'Blockly.VariablesDynamic', 'Blockly.VerticalFlyout', 'Blockly.Warning', 'Blockly.WidgetDiv', 'Blockly.Workspace', 'Blockly.WorkspaceAudio', 'Blockly.WorkspaceComment', 'Blockly.WorkspaceCommentSvg', 'Blockly.WorkspaceDragSurfaceSvg', 'Blockly.WorkspaceDragger', 'Blockly.WorkspaceSvg', 'Blockly.Xml', 'Blockly.ZoomControls', 'Blockly.blockAnimations', 'Blockly.blockRendering', 'Blockly.blocks', 'Blockly.browserEvents', 'Blockly.bumpObjects', 'Blockly.clipboard', 'Blockly.common', 'Blockly.config', 'Blockly.constants', 'Blockly.dialog', 'Blockly.fieldRegistry', 'Blockly.geras', 'Blockly.inject', 'Blockly.inputTypes', 'Blockly.internalConstants', 'Blockly.minimalist', 'Blockly.registry', 'Blockly.serialization.ISerializer', 'Blockly.serialization.blocks', 'Blockly.serialization.exceptions', 'Blockly.serialization.priorities', 'Blockly.serialization.registry', 'Blockly.serialization.variables', 'Blockly.serialization.workspaces', 'Blockly.thrasos', 'Blockly.uiPosition', 'Blockly.utils', 'Blockly.utils.colour', 'Blockly.utils.deprecation', 'Blockly.utils.global', 'Blockly.utils.svgMath', 'Blockly.utils.toolbox', 'Blockly.zelos'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/blockly_options.js', ['Blockly.BlocklyOptions'], [], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/blocks.js', ['Blockly.blocks'], [], {'lang': 'es6', 'module': 'goog'}); diff --git a/tests/mocha/extensions_test.js b/tests/mocha/extensions_test.js index d4aebf38e..d7846bb81 100644 --- a/tests/mocha/extensions_test.js +++ b/tests/mocha/extensions_test.js @@ -244,8 +244,8 @@ suite('Extensions', function() { // Make sure all of the functions were installed correctly. chai.assert.equal(block.domToMutation(), 'domToMutationFn'); chai.assert.equal(block.mutationToDom(), 'mutationToDomFn'); - chai.assert.isFalse(Object.prototype.hasOwnProperty.call(block, 'compose')); - chai.assert.isFalse(Object.prototype.hasOwnProperty.call(block, 'decompose')); + chai.assert.isUndefined(block['compose']); + chai.assert.isUndefined(block['decompose']); }); }); }); From 9ba2571a38dcf7bbdece8b42051f326caddf4af4 Mon Sep 17 00:00:00 2001 From: alschmiedt Date: Mon, 28 Feb 2022 17:59:28 -0800 Subject: [PATCH 090/128] deprecate: the debug renderer (#5961) * deprecate: the debug renderer * chore: run format * chore: remove @deprecated for functions still used in core --- core/renderers/common/block_rendering.js | 12 +++++++++--- core/renderers/common/debug.js | 15 +++++++++++++++ 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/core/renderers/common/block_rendering.js b/core/renderers/common/block_rendering.js index c98a31c76..44ffaaace 100644 --- a/core/renderers/common/block_rendering.js +++ b/core/renderers/common/block_rendering.js @@ -56,11 +56,13 @@ const {Types} = goog.require('Blockly.blockRendering.Types'); * @return {boolean} Whether the debugger is turned on. * @alias Blockly.blockRendering.isDebuggerEnabled * @package + * @deprecated */ const isDebuggerEnabled = function() { deprecation.warn( 'Blockly.blockRendering.isDebuggerEnabled()', 'September 2021', - 'September 2022', 'Blockly.blockRendering.debug.isDebuggerEnabled()'); + 'September 2022', + 'the debug renderer in @blockly/dev-tools (See https://www.npmjs.com/package/@blockly/dev-tools.)'); return debug.isDebuggerEnabled(); }; exports.isDebuggerEnabled = isDebuggerEnabled; @@ -91,11 +93,13 @@ exports.unregister = unregister; * Turn on the blocks debugger. * @package * @alias Blockly.blockRendering.startDebugger + * @deprecated */ const startDebugger = function() { deprecation.warn( 'Blockly.blockRendering.startDebugger()', 'September 2021', - 'September 2022', 'Blockly.blockRendering.debug.startDebugger()'); + 'September 2022', + 'the debug renderer in @blockly/dev-tools (See https://www.npmjs.com/package/@blockly/dev-tools.)'); debug.startDebugger(); }; exports.startDebugger = startDebugger; @@ -104,11 +108,13 @@ exports.startDebugger = startDebugger; * Turn off the blocks debugger. * @package * @alias Blockly.blockRendering.stopDebugger + * @deprecated */ const stopDebugger = function() { deprecation.warn( 'Blockly.blockRendering.stopDebugger()', 'September 2021', - 'September 2022', 'Blockly.blockRendering.debug.stopDebugger()'); + 'September 2022', + 'the debug renderer in @blockly/dev-tools (See https://www.npmjs.com/package/@blockly/dev-tools.)'); debug.stopDebugger(); }; exports.stopDebugger = stopDebugger; diff --git a/core/renderers/common/debug.js b/core/renderers/common/debug.js index e8b2d9aea..d62c27063 100644 --- a/core/renderers/common/debug.js +++ b/core/renderers/common/debug.js @@ -15,6 +15,8 @@ */ goog.module('Blockly.blockRendering.debug'); +const deprecation = goog.require('Blockly.utils.deprecation'); + /** * Whether or not the debugger is turned on. @@ -28,6 +30,11 @@ let useDebugger = false; * @package */ const isDebuggerEnabled = function() { + deprecation.warn( + 'Blockly.blockRendering.debug.isDebuggerEnabled()', 'February 2022', + 'September 2022', + 'the debug renderer in @blockly/dev-tools (See https://www.npmjs.com/package/@blockly/dev-tools.)'); + return useDebugger; }; exports.isDebuggerEnabled = isDebuggerEnabled; @@ -38,6 +45,10 @@ exports.isDebuggerEnabled = isDebuggerEnabled; * @alias Blockly.blockRendering.debug.startDebugger */ const startDebugger = function() { + deprecation.warn( + 'Blockly.blockRendering.debug.startDebugger()', 'February 2022', + 'September 2022', + 'the debug renderer in @blockly/dev-tools (See https://www.npmjs.com/package/@blockly/dev-tools.)'); useDebugger = true; }; exports.startDebugger = startDebugger; @@ -48,6 +59,10 @@ exports.startDebugger = startDebugger; * @alias Blockly.blockRendering.debug.stopDebugger */ const stopDebugger = function() { + deprecation.warn( + 'Blockly.blockRendering.debug.stopDebugger()', 'February 2022', + 'September 2022', + 'the debug renderer in @blockly/dev-tools (See https://www.npmjs.com/package/@blockly/dev-tools.)'); useDebugger = false; }; exports.stopDebugger = stopDebugger; From 88334bea80aa26c08705f16aba5e79dd708158f9 Mon Sep 17 00:00:00 2001 From: Christopher Allen Date: Tue, 1 Mar 2022 16:30:58 +0000 Subject: [PATCH 091/128] fix(tests): Enable --debug for test:compile:advanced; fix some errors (#5959) * Enable the --debug flag when running the buildAdvancedCompilationTest gulp task. * Migrate test/compile/main.js to goog.module. * Use more selective goog.requires. * Reduces compiled size from ~400k to ~370k. * @suppress "extra" requires needed for side effects. --- package.json | 2 +- tests/compile/main.js | 30 ++++++++++++++++++++++-------- 2 files changed, 23 insertions(+), 9 deletions(-) diff --git a/package.json b/package.json index 88cc6c0ef..149e38a61 100644 --- a/package.json +++ b/package.json @@ -51,7 +51,7 @@ "test": "tests/run_all_tests.sh", "test:generators": "tests/scripts/run_generators.sh", "test:mocha:interactive": "http-server ./ -o /tests/mocha/index.html -c-1", - "test:compile:advanced": "gulp buildAdvancedCompilationTest", + "test:compile:advanced": "gulp buildAdvancedCompilationTest --debug", "typings": "gulp typings", "updateGithubPages": "gulp gitUpdateGithubPages" }, diff --git a/tests/compile/main.js b/tests/compile/main.js index 586f4ce36..b5d20a770 100644 --- a/tests/compile/main.js +++ b/tests/compile/main.js @@ -4,19 +4,33 @@ * SPDX-License-Identifier: Apache-2.0 */ -goog.provide('Main'); +goog.module('Main'); + // Core // Either require 'Blockly.requires', or just the components you use: -goog.require('Blockly'); +/* eslint-disable-next-line no-unused-vars */ +const {BlocklyOptions} = goog.requireType('Blockly.BlocklyOptions'); +const {inject} = goog.require('Blockly.inject'); +/** @suppress {extraRequire} */ goog.require('Blockly.geras.Renderer'); +/** @suppress {extraRequire} */ goog.require('Blockly.VerticalFlyout'); // Blocks -goog.require('Blockly.libraryBlocks'); +/** @suppress {extraRequire} */ +goog.require('Blockly.libraryBlocks.logic'); +/** @suppress {extraRequire} */ +goog.require('Blockly.libraryBlocks.loops'); +/** @suppress {extraRequire} */ +goog.require('Blockly.libraryBlocks.math'); +/** @suppress {extraRequire} */ +goog.require('Blockly.libraryBlocks.texts'); +/** @suppress {extraRequire} */ goog.require('Blockly.libraryBlocks.testBlocks'); -Main.init = function() { - Blockly.inject('blocklyDiv', { - 'toolbox': document.getElementById('toolbox') - }); + +function init() { + inject('blocklyDiv', /** @type {BlocklyOptions} */ ({ + 'toolbox': document.getElementById('toolbox') + })); }; -window.addEventListener('load', Main.init); +window.addEventListener('load', init); From 2a0e54759dcd4b00e543ffd45ad2ed570ca7177c Mon Sep 17 00:00:00 2001 From: Beka Westberg Date: Tue, 1 Mar 2022 15:15:29 -0800 Subject: [PATCH 092/128] Revert "fix(tests): Enable --debug for test:compile:advanced; fix some errors (#5959)" This reverts commit 88334bea80aa26c08705f16aba5e79dd708158f9. --- package.json | 2 +- tests/compile/main.js | 30 ++++++++---------------------- 2 files changed, 9 insertions(+), 23 deletions(-) diff --git a/package.json b/package.json index 149e38a61..88cc6c0ef 100644 --- a/package.json +++ b/package.json @@ -51,7 +51,7 @@ "test": "tests/run_all_tests.sh", "test:generators": "tests/scripts/run_generators.sh", "test:mocha:interactive": "http-server ./ -o /tests/mocha/index.html -c-1", - "test:compile:advanced": "gulp buildAdvancedCompilationTest --debug", + "test:compile:advanced": "gulp buildAdvancedCompilationTest", "typings": "gulp typings", "updateGithubPages": "gulp gitUpdateGithubPages" }, diff --git a/tests/compile/main.js b/tests/compile/main.js index b5d20a770..586f4ce36 100644 --- a/tests/compile/main.js +++ b/tests/compile/main.js @@ -4,33 +4,19 @@ * SPDX-License-Identifier: Apache-2.0 */ -goog.module('Main'); - +goog.provide('Main'); // Core // Either require 'Blockly.requires', or just the components you use: -/* eslint-disable-next-line no-unused-vars */ -const {BlocklyOptions} = goog.requireType('Blockly.BlocklyOptions'); -const {inject} = goog.require('Blockly.inject'); -/** @suppress {extraRequire} */ +goog.require('Blockly'); goog.require('Blockly.geras.Renderer'); -/** @suppress {extraRequire} */ goog.require('Blockly.VerticalFlyout'); // Blocks -/** @suppress {extraRequire} */ -goog.require('Blockly.libraryBlocks.logic'); -/** @suppress {extraRequire} */ -goog.require('Blockly.libraryBlocks.loops'); -/** @suppress {extraRequire} */ -goog.require('Blockly.libraryBlocks.math'); -/** @suppress {extraRequire} */ -goog.require('Blockly.libraryBlocks.texts'); -/** @suppress {extraRequire} */ +goog.require('Blockly.libraryBlocks'); goog.require('Blockly.libraryBlocks.testBlocks'); - -function init() { - inject('blocklyDiv', /** @type {BlocklyOptions} */ ({ - 'toolbox': document.getElementById('toolbox') - })); +Main.init = function() { + Blockly.inject('blocklyDiv', { + 'toolbox': document.getElementById('toolbox') + }); }; -window.addEventListener('load', init); +window.addEventListener('load', Main.init); From b34db5bd01f7b532ebabc80264ca9fc804a76c75 Mon Sep 17 00:00:00 2001 From: gpfernandezflorio Date: Thu, 3 Mar 2022 09:48:03 -0300 Subject: [PATCH 093/128] fix(blocks): correct the callType_ of procedures_defreturn (#5974) Fixes a bug introduced in PR #5736. --- blocks/procedures.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/blocks/procedures.js b/blocks/procedures.js index eed3a718b..d9de9e098 100644 --- a/blocks/procedures.js +++ b/blocks/procedures.js @@ -443,7 +443,6 @@ const PROCEDURE_DEF_COMMON = { } } }, - callType_: 'procedures_callnoreturn', }; blocks['procedures_defnoreturn'] = { @@ -486,6 +485,7 @@ blocks['procedures_defnoreturn'] = { getProcedureDef: function() { return [this.getFieldValue('NAME'), this.arguments_, false]; }, + callType_: 'procedures_callnoreturn', }; blocks['procedures_defreturn'] = { @@ -531,6 +531,7 @@ blocks['procedures_defreturn'] = { getProcedureDef: function() { return [this.getFieldValue('NAME'), this.arguments_, true]; }, + callType_: 'procedures_callreturn', }; blocks['procedures_mutatorcontainer'] = { From 8058df2a71dcecdc1190ae1d6f5dcccfafc980e8 Mon Sep 17 00:00:00 2001 From: Beka Westberg Date: Thu, 3 Mar 2022 10:52:39 -0800 Subject: [PATCH 094/128] fix: custom block context menus (#5976) * fix: custom block context menus * fix: move rendered-specific properties back into BlockSvg --- core/block.js | 25 ------------------------- core/block_svg.js | 14 +++++++++++--- tests/deps.js | 2 +- 3 files changed, 12 insertions(+), 29 deletions(-) diff --git a/core/block.js b/core/block.js index 134ce88ab..1cf13246e 100644 --- a/core/block.js +++ b/core/block.js @@ -162,31 +162,6 @@ class Block { */ this.loadExtraState = undefined; - /** - * An optional method called by the default mutator UI which allows the - * block to "explode" itself into smaller sub blocks. This function should - * return a "top block" which is the main block in the mutator workspace - * that sub-blocks connect to. - * @type {undefined|?function():!Block} - */ - this.decompose = undefined; - - /** - * An optional method called by the deafult mutator UI which allows the - * block to configure itself based on the configuration of sub-blocks in - * the mutator workspace. This function should accept the "top block" which - * was returned by `decompose` as a paramter. - * @type {undefined|?function(!Block)} - */ - this.compose = undefined; - - /** - * An optional method called by the default mutator UI which gives the block - * a chance to save information about what child blocks are connected to - * what mutated connections. - * @type {undefined|?function(!Block)} - */ - this.saveConnections = undefined; /** * An optional property for suppressing adding STATEMENT_PREFIX and diff --git a/core/block_svg.js b/core/block_svg.js index 3b81d63f8..cc1e66289 100644 --- a/core/block_svg.js +++ b/core/block_svg.js @@ -110,7 +110,7 @@ class BlockSvg extends Block { * mutation dialog button and UI to appear. * @type {undefined|?function(WorkspaceSvg):!BlockSvg} */ - this.decompose = undefined; + this.decompose = this.decompose; /** * An optional method called when a mutator dialog saves its content. @@ -119,13 +119,21 @@ class BlockSvg extends Block { * method for the default mutation dialog button and UI to appear. * @type {undefined|?function(!BlockSvg)} */ - this.compose = undefined; + this.compose = this.compose; + + /** + * An optional method called by the default mutator UI which gives the block + * a chance to save information about what child blocks are connected to + * what mutated connections. + * @type {undefined|?function(!BlockSvg)} + */ + this.saveConnections = this.saveConnections; /** * An optional method for defining custom block context menu items. * @type {undefined|?function(!Array)} */ - this.customContextMenu = undefined; + this.customContextMenu = this.customContextMenu; /** * An property used internally to reference the block's rendering debugger. diff --git a/tests/deps.js b/tests/deps.js index 24df7a3c0..ef4b6e87f 100644 --- a/tests/deps.js +++ b/tests/deps.js @@ -143,7 +143,7 @@ goog.addDependency('../../core/registry.js', ['Blockly.registry'], [], {'lang': goog.addDependency('../../core/rendered_connection.js', ['Blockly.RenderedConnection'], ['Blockly.Connection', 'Blockly.ConnectionType', 'Blockly.Events.utils', 'Blockly.common', 'Blockly.config', 'Blockly.internalConstants', 'Blockly.utils.Coordinate', 'Blockly.utils.Svg', 'Blockly.utils.dom', 'Blockly.utils.svgMath', 'Blockly.utils.svgPaths'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/renderers/common/block_rendering.js', ['Blockly.blockRendering'], ['Blockly.blockRendering.BottomRow', 'Blockly.blockRendering.Connection', 'Blockly.blockRendering.ConstantProvider', 'Blockly.blockRendering.Debug', 'Blockly.blockRendering.Drawer', 'Blockly.blockRendering.ExternalValueInput', 'Blockly.blockRendering.Field', 'Blockly.blockRendering.Hat', 'Blockly.blockRendering.IPathObject', 'Blockly.blockRendering.Icon', 'Blockly.blockRendering.InRowSpacer', 'Blockly.blockRendering.InlineInput', 'Blockly.blockRendering.InputConnection', 'Blockly.blockRendering.InputRow', 'Blockly.blockRendering.JaggedEdge', 'Blockly.blockRendering.MarkerSvg', 'Blockly.blockRendering.Measurable', 'Blockly.blockRendering.NextConnection', 'Blockly.blockRendering.OutputConnection', 'Blockly.blockRendering.PathObject', 'Blockly.blockRendering.PreviousConnection', 'Blockly.blockRendering.RenderInfo', 'Blockly.blockRendering.Renderer', 'Blockly.blockRendering.RoundCorner', 'Blockly.blockRendering.Row', 'Blockly.blockRendering.SpacerRow', 'Blockly.blockRendering.SquareCorner', 'Blockly.blockRendering.StatementInput', 'Blockly.blockRendering.TopRow', 'Blockly.blockRendering.Types', 'Blockly.blockRendering.debug', 'Blockly.registry', 'Blockly.utils.deprecation'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/renderers/common/constants.js', ['Blockly.blockRendering.ConstantProvider'], ['Blockly.ConnectionType', 'Blockly.utils.Svg', 'Blockly.utils.colour', 'Blockly.utils.dom', 'Blockly.utils.object', 'Blockly.utils.parsing', 'Blockly.utils.svgPaths', 'Blockly.utils.userAgent'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../core/renderers/common/debug.js', ['Blockly.blockRendering.debug'], [], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../core/renderers/common/debug.js', ['Blockly.blockRendering.debug'], ['Blockly.utils.deprecation'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/renderers/common/debugger.js', ['Blockly.blockRendering.Debug'], ['Blockly.ConnectionType', 'Blockly.FieldLabel', 'Blockly.blockRendering.Field', 'Blockly.blockRendering.InputConnection', 'Blockly.blockRendering.Types', 'Blockly.utils.Svg', 'Blockly.utils.dom'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/renderers/common/drawer.js', ['Blockly.blockRendering.Drawer'], ['Blockly.blockRendering.Connection', 'Blockly.blockRendering.Types', 'Blockly.blockRendering.debug', 'Blockly.utils.svgPaths'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../core/renderers/common/i_path_object.js', ['Blockly.blockRendering.IPathObject'], [], {'lang': 'es6', 'module': 'goog'}); From 6841ccc99fdbcc5f6d5a63bb36cb3b6ebd2be246 Mon Sep 17 00:00:00 2001 From: Maribeth Bottorff Date: Thu, 3 Mar 2022 17:23:02 -0800 Subject: [PATCH 095/128] feat: Allow developers to set a custom tooltip rendering function. (#5956) * refactor: refactor tooltip show method * refactor: make Tooltip a class that is accessed via a singleton * revert: "refactor: make Tooltip a class that is accessed via a singleton" This reverts commit b3d543cc3560fbe44b16ac8085e8d6cb141f8dbe. * feat: add the ability to set a custom tooltip function * fix: check for null where it matters for types * feat: Add a test for the custom tooltip function * fix: fix formatting * fix: format test * fix: remove unnecessary teardown call in test --- core/tooltip.js | 171 +++++++++++++++++++++++++----------- tests/mocha/tooltip_test.js | 71 +++++++++++---- 2 files changed, 175 insertions(+), 67 deletions(-) diff --git a/core/tooltip.js b/core/tooltip.js index e06e9b9d2..e3e32b92e 100644 --- a/core/tooltip.js +++ b/core/tooltip.js @@ -4,23 +4,15 @@ * SPDX-License-Identifier: Apache-2.0 */ -/** - * @fileoverview Library to create tooltips for Blockly. - * First, call init() after onload. - * Second, set the 'tooltip' property on any SVG element that needs a tooltip. - * If the tooltip is a string, then that message will be displayed. - * If the tooltip is an SVG element, then that object's tooltip will be used. - * Third, call bindMouseEvents(e) passing the SVG element. - */ 'use strict'; /** * Library to create tooltips for Blockly. - * First, call init() after onload. + * First, call createDom() after onload. * Second, set the 'tooltip' property on any SVG element that needs a tooltip. - * If the tooltip is a string, then that message will be displayed. - * If the tooltip is an SVG element, then that object's tooltip will be used. - * Third, call bindMouseEvents(e) passing the SVG element. + * If the tooltip is a string, or a function that returns a string, that message + * will be displayed. If the tooltip is an SVG element, then that object's + * tooltip will be used. Third, call bindMouseEvents(e) passing the SVG element. * @namespace Blockly.Tooltip */ goog.module('Blockly.Tooltip'); @@ -42,6 +34,46 @@ const deprecation = goog.require('Blockly.utils.deprecation'); let TipInfo; exports.TipInfo = TipInfo; +/** + * A function that renders custom tooltip UI. + * 1st parameter: the div element to render content into. + * 2nd parameter: the element being moused over (i.e., the element for which the + * tooltip should be shown). + * @typedef {function(!Element, !Element)} + * @alias Blockly.Tooltip.CustomTooltip + */ +let CustomTooltip; +exports.CustomTooltip = CustomTooltip; + +/** + * An optional function that renders custom tooltips into the provided DIV. If + * this is defined, the function will be called instead of rendering the default + * tooltip UI. + * @type {!CustomTooltip|undefined} + */ +let customTooltip = undefined; + +/** + * Sets a custom function that will be called if present instead of the default + * tooltip UI. + * @param {!CustomTooltip} customFn A custom tooltip used to render an alternate + * tooltip UI. + * @alias Blockly.Tooltip.setCustomTooltip + */ +const setCustomTooltip = function(customFn) { + customTooltip = customFn; +}; +exports.setCustomTooltip = setCustomTooltip; + +/** + * Gets the custom tooltip function. + * @returns {!CustomTooltip|undefined} The custom tooltip function, if defined. + */ +const getCustomTooltip = function() { + return customTooltip; +}; +exports.getCustomTooltip = getCustomTooltip; + /** * Is a tooltip currently showing? * @type {boolean} @@ -409,6 +441,76 @@ const unblock = function() { }; exports.unblock = unblock; +/** + * Renders the tooltip content into the tooltip div. + */ +const renderContent = function() { + if (!DIV || !element) { + // This shouldn't happen, but if it does, we can't render. + return; + } + if (typeof customTooltip === 'function') { + customTooltip(DIV, element); + } else { + renderDefaultContent(); + } +}; + +/** + * Renders the default tooltip UI. + */ +const renderDefaultContent = function() { + let tip = getTooltipOfObject(element); + tip = blocklyString.wrap(tip, LIMIT); + // Create new text, line by line. + const lines = tip.split('\n'); + for (let i = 0; i < lines.length; i++) { + const div = document.createElement('div'); + div.appendChild(document.createTextNode(lines[i])); + DIV.appendChild(div); + } +}; + +/** + * Gets the coordinates for the tooltip div, taking into account the edges of + * the screen to prevent showing the tooltip offscreen. + * @param {boolean} rtl True if the tooltip should be in right-to-left layout. + * @returns {{x: number, y: number}} Coordinates at which the tooltip div should + * be placed. + */ +const getPosition = function(rtl) { + // Position the tooltip just below the cursor. + const windowWidth = document.documentElement.clientWidth; + const windowHeight = document.documentElement.clientHeight; + + let anchorX = lastX; + if (rtl) { + anchorX -= OFFSET_X + DIV.offsetWidth; + } else { + anchorX += OFFSET_X; + } + + let anchorY = lastY + OFFSET_Y; + if (anchorY + DIV.offsetHeight > windowHeight + window.scrollY) { + // Falling off the bottom of the screen; shift the tooltip up. + anchorY -= DIV.offsetHeight + 2 * OFFSET_Y; + } + + if (rtl) { + // Prevent falling off left edge in RTL mode. + anchorX = Math.max(MARGINS - window.scrollX, anchorX); + } else { + if (anchorX + DIV.offsetWidth > + windowWidth + window.scrollX - 2 * MARGINS) { + // Falling off the right edge of the screen; + // clamp the tooltip on the edge. + anchorX = windowWidth - DIV.offsetWidth - 2 * MARGINS; + } + } + + return {x: anchorX, y: anchorY}; +}; + /** * Create the tooltip and show it. */ @@ -423,46 +525,17 @@ const show = function() { } // Erase all existing text. DIV.textContent = ''; - let tip = getTooltipOfObject(element); - tip = blocklyString.wrap(tip, LIMIT); - // Create new text, line by line. - const lines = tip.split('\n'); - for (let i = 0; i < lines.length; i++) { - const div = document.createElement('div'); - div.appendChild(document.createTextNode(lines[i])); - DIV.appendChild(div); - } - const rtl = /** @type {{RTL: boolean}} */ (element).RTL; - const windowWidth = document.documentElement.clientWidth; - const windowHeight = document.documentElement.clientHeight; + + // Add new content. + renderContent(); + // Display the tooltip. + const rtl = /** @type {{RTL: boolean}} */ (element).RTL; DIV.style.direction = rtl ? 'rtl' : 'ltr'; DIV.style.display = 'block'; visible = true; - // Move the tooltip to just below the cursor. - let anchorX = lastX; - if (rtl) { - anchorX -= OFFSET_X + DIV.offsetWidth; - } else { - anchorX += OFFSET_X; - } - let anchorY = lastY + OFFSET_Y; - if (anchorY + DIV.offsetHeight > windowHeight + window.scrollY) { - // Falling off the bottom of the screen; shift the tooltip up. - anchorY -= DIV.offsetHeight + 2 * OFFSET_Y; - } - if (rtl) { - // Prevent falling off left edge in RTL mode. - anchorX = Math.max(MARGINS - window.scrollX, anchorX); - } else { - if (anchorX + DIV.offsetWidth > - windowWidth + window.scrollX - 2 * MARGINS) { - // Falling off the right edge of the screen; - // clamp the tooltip on the edge. - anchorX = windowWidth - DIV.offsetWidth - 2 * MARGINS; - } - } - DIV.style.top = anchorY + 'px'; - DIV.style.left = anchorX + 'px'; + const {x, y} = getPosition(rtl); + DIV.style.left = x + 'px'; + DIV.style.top = y + 'px'; }; diff --git a/tests/mocha/tooltip_test.js b/tests/mocha/tooltip_test.js index a2c5bb216..7c9cc8bf3 100644 --- a/tests/mocha/tooltip_test.js +++ b/tests/mocha/tooltip_test.js @@ -13,32 +13,63 @@ suite('Tooltip', function() { setup(function() { sharedTestSetup.call(this); this.workspace = new Blockly.Workspace(); + + Blockly.defineBlocksWithJsonArray([ + { + 'type': 'test_block', + 'message0': '%1', + 'args0': [ + { + 'type': 'field_input', + 'name': 'FIELD', + }, + ], + }, + ]); }); teardown(function() { + delete Blockly.Blocks['test_block']; sharedTestTeardown.call(this); }); - suite('set/getTooltip', function() { + suite('Custom Tooltip', function() { setup(function() { - Blockly.defineBlocksWithJsonArray([ - { - "type": "test_block", - "message0": "%1", - "args0": [ - { - "type": "field_input", - "name": "FIELD", - }, - ], - }, - ]); + this.renderedWorkspace = Blockly.inject('blocklyDiv', {}); }); teardown(function() { - delete Blockly.Blocks["test_block"]; + workspaceTeardown.call(this, this.renderedWorkspace); }); + test('Custom function is called', function() { + // Custom tooltip function is registered and should be called when mouse + // events are fired. + let wasCalled = false; + const customFn = function() { + wasCalled = true; + }; + Blockly.Tooltip.setCustomTooltip(customFn); + + this.block = this.renderedWorkspace.newBlock('test_block'); + this.block.setTooltip('Test Tooltip'); + + // Fire pointer events directly on the relevant SVG. + // Note the 'pointerover', due to the events registered through + // Blockly.browserEvents.bind being registered as pointer events rather + // than mouse events. Mousemove event is registered directly on the + // element rather than through browserEvents. + this.block.pathObject.svgPath.dispatchEvent( + new MouseEvent('pointerover')); + this.block.pathObject.svgPath.dispatchEvent(new MouseEvent('mousemove')); + this.clock.runAll(); + + chai.assert.isTrue( + wasCalled, 'Expected custom tooltip function to have been called'); + }); + }); + + suite('set/getTooltip', function() { const tooltipText = 'testTooltip'; function assertTooltip(obj) { @@ -97,7 +128,8 @@ suite('Tooltip', function() { test('Function returning object', function() { setFunctionReturningObjectTooltip(this.block); - chai.assert.throws(this.block.getTooltip.bind(this.block), + chai.assert.throws( + this.block.getTooltip.bind(this.block), 'Tooltip function must return a string.'); }); @@ -136,7 +168,8 @@ suite('Tooltip', function() { test('Function returning object', function() { setFunctionReturningObjectTooltip(this.block); - chai.assert.throws(this.block.getTooltip.bind(this.block), + chai.assert.throws( + this.block.getTooltip.bind(this.block), 'Tooltip function must return a string.'); }); @@ -169,7 +202,8 @@ suite('Tooltip', function() { test('Function returning object', function() { setFunctionReturningObjectTooltip(this.field); - chai.assert.throws(this.field.getTooltip.bind(this.field), + chai.assert.throws( + this.field.getTooltip.bind(this.field), 'Tooltip function must return a string.'); }); @@ -215,7 +249,8 @@ suite('Tooltip', function() { test('Function returning object', function() { setFunctionReturningObjectTooltip(this.field); - chai.assert.throws(this.field.getTooltip.bind(this.field), + chai.assert.throws( + this.field.getTooltip.bind(this.field), 'Tooltip function must return a string.'); }); From 2edd22811752f05e16c68d593e5d1b809e24ed25 Mon Sep 17 00:00:00 2001 From: Beka Westberg Date: Fri, 4 Mar 2022 13:10:03 -0800 Subject: [PATCH 096/128] fix: move test helpers from samples into core (#5969) * fix: move core test helpers into new directory * fix: add test helpers to core and convert to goog modules * fix: change tests to use local helpers * fix: change local tests to use chai asserts * fix: skip field tests in serializer b/c test blocks are unavailable * fix: rename some helper files * fix: rename some helper modules * fix: split block helpers into code gen and serialization * fix: split block defs into new helper file * fix: split warning helpers into new file * fix: split user input helpers into new file * fix: split event helpers into a new file * fix: split variable helper into new file * fix: move remaining test helpers to new setup-teardown file * fix: rename setup and teardown module * fix: cleanup from rebase * fix: undo accidental rename * fix: lint? * fix: bad toolbox definitions namespace * fix: fixup warning helpers * fix: remove inclusion of dev-tools in mocha tests * move to modules, but break mocha * fix: run mocha as a module * fix: lint --- tests/deps.mocha.js | 131 ++-- tests/mocha/.eslintrc.json | 9 +- tests/mocha/astnode_test.js | 8 +- tests/mocha/block_change_event_test.js | 3 +- tests/mocha/block_create_event_test.js | 3 +- tests/mocha/block_test.js | 6 +- tests/mocha/comment_test.js | 3 +- tests/mocha/connection_checker_test.js | 2 +- tests/mocha/connection_db_test.js | 2 +- tests/mocha/connection_test.js | 3 +- tests/mocha/contextmenu_items_test.js | 2 +- tests/mocha/cursor_test.js | 2 +- tests/mocha/dropdowndiv_test.js | 2 +- tests/mocha/event_test.js | 6 +- tests/mocha/extensions_test.js | 2 +- tests/mocha/field_angle_test.js | 24 +- tests/mocha/field_checkbox_test.js | 18 +- tests/mocha/field_colour_test.js | 22 +- tests/mocha/field_dropdown_test.js | 20 +- tests/mocha/field_image_test.js | 17 +- tests/mocha/field_label_serializable_test.js | 20 +- tests/mocha/field_label_test.js | 20 +- tests/mocha/field_multilineinput_test.js | 23 +- tests/mocha/field_number_test.js | 29 +- tests/mocha/field_registry_test.js | 3 +- tests/mocha/field_test.js | 3 +- tests/mocha/field_textinput_test.js | 24 +- tests/mocha/field_variable_test.js | 20 +- tests/mocha/flyout_test.js | 4 +- tests/mocha/generator_test.js | 2 +- tests/mocha/gesture_test.js | 5 +- tests/mocha/index.html | 3 +- tests/mocha/input_test.js | 2 +- tests/mocha/insertion_marker_test.js | 2 +- tests/mocha/jso_deserialization_test.js | 3 +- tests/mocha/jso_serialization_test.js | 3 +- tests/mocha/json_test.js | 3 +- tests/mocha/keydown_test.js | 4 +- tests/mocha/logic_ternary_test.js | 5 +- tests/mocha/metrics_test.js | 2 +- tests/mocha/mutator_test.js | 3 +- tests/mocha/names_test.js | 2 +- tests/mocha/procedures_test.js | 7 +- tests/mocha/registry_test.js | 3 +- tests/mocha/serializer_test.js | 12 +- tests/mocha/shortcut_registry_test.js | 3 +- tests/mocha/test_helpers.js | 717 ------------------ tests/mocha/test_helpers/block_definitions.js | 178 +++++ tests/mocha/test_helpers/code_generation.js | 115 +++ tests/mocha/test_helpers/common.js | 108 +++ tests/mocha/test_helpers/events.js | 199 +++++ tests/mocha/test_helpers/fields.js | 276 +++++++ .../procedures.js} | 14 +- tests/mocha/test_helpers/serialization.js | 130 ++++ tests/mocha/test_helpers/setup_teardown.js | 202 +++++ .../toolbox_definitions.js} | 35 +- tests/mocha/test_helpers/user_input.js | 65 ++ tests/mocha/test_helpers/variables.js | 24 + tests/mocha/test_helpers/warnings.js | 84 ++ .../workspace.js} | 9 +- tests/mocha/theme_test.js | 3 +- tests/mocha/toolbox_test.js | 5 +- tests/mocha/tooltip_test.js | 2 +- tests/mocha/trashcan_test.js | 5 +- tests/mocha/utils_test.js | 2 +- tests/mocha/variable_map_test.js | 3 +- tests/mocha/variable_model_test.js | 2 +- tests/mocha/variables_test.js | 2 +- tests/mocha/widget_div_test.js | 2 +- tests/mocha/workspace_comment_test.js | 2 +- tests/mocha/workspace_svg_test.js | 7 +- tests/mocha/workspace_test.js | 5 +- tests/mocha/xml_test.js | 3 +- tests/mocha/zoom_controls_test.js | 4 +- 74 files changed, 1713 insertions(+), 985 deletions(-) delete mode 100644 tests/mocha/test_helpers.js create mode 100644 tests/mocha/test_helpers/block_definitions.js create mode 100644 tests/mocha/test_helpers/code_generation.js create mode 100644 tests/mocha/test_helpers/common.js create mode 100644 tests/mocha/test_helpers/events.js create mode 100644 tests/mocha/test_helpers/fields.js rename tests/mocha/{procedures_test_helpers.js => test_helpers/procedures.js} (91%) create mode 100644 tests/mocha/test_helpers/serialization.js create mode 100644 tests/mocha/test_helpers/setup_teardown.js rename tests/mocha/{toolbox_helper.js => test_helpers/toolbox_definitions.js} (86%) create mode 100644 tests/mocha/test_helpers/user_input.js create mode 100644 tests/mocha/test_helpers/variables.js create mode 100644 tests/mocha/test_helpers/warnings.js rename tests/mocha/{workspace_helpers.js => test_helpers/workspace.js} (99%) diff --git a/tests/deps.mocha.js b/tests/deps.mocha.js index a686fdda7..f2d550157 100644 --- a/tests/deps.mocha.js +++ b/tests/deps.mocha.js @@ -1,64 +1,73 @@ goog.addDependency('../../tests/mocha/.mocharc.js', [], []); -goog.addDependency('../../tests/mocha/astnode_test.js', ['Blockly.test.astNode'], ['Blockly.ASTNode', 'Blockly.test.helpers'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../tests/mocha/block_change_event_test.js', ['Blockly.test.blockChangeEvent'], ['Blockly.test.helpers'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../tests/mocha/block_create_event_test.js', ['Blockly.test.blockCreateEvent'], ['Blockly.Events.utils', 'Blockly.test.helpers'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../tests/mocha/astnode_test.js', ['Blockly.test.astNode'], ['Blockly.ASTNode', 'Blockly.test.helpers.setupTeardown'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../tests/mocha/block_change_event_test.js', ['Blockly.test.blockChangeEvent'], ['Blockly.test.helpers.blockDefinitions', 'Blockly.test.helpers.setupTeardown'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../tests/mocha/block_create_event_test.js', ['Blockly.test.blockCreateEvent'], ['Blockly.Events.utils', 'Blockly.test.helpers.events', 'Blockly.test.helpers.setupTeardown'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../tests/mocha/block_json_test.js', ['Blockly.test.blockJson'], ['Blockly.Input'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../tests/mocha/block_test.js', ['Blockly.test.blocks'], ['Blockly.ConnectionType', 'Blockly.Events.utils', 'Blockly.blocks', 'Blockly.test.helpers'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../tests/mocha/comment_test.js', ['Blockly.test.comments'], ['Blockly.Events.utils', 'Blockly.test.helpers'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../tests/mocha/connection_checker_test.js', ['Blockly.test.connectionChecker'], ['Blockly.ConnectionType', 'Blockly.test.helpers'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../tests/mocha/connection_db_test.js', ['Blockly.test.connectionDb'], ['Blockly.ConnectionType', 'Blockly.test.helpers'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../tests/mocha/connection_test.js', ['Blockly.test.connection'], ['Blockly.test.helpers'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../tests/mocha/contextmenu_items_test.js', ['Blockly.test.contextMenuItem'], ['Blockly.test.helpers'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../tests/mocha/cursor_test.js', ['Blockly.test.cursor'], ['Blockly.ASTNode', 'Blockly.test.helpers'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../tests/mocha/dropdowndiv_test.js', ['Blockly.test.dropdown'], ['Blockly.test.helpers'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../tests/mocha/event_test.js', ['Blockly.test.event'], ['Blockly.ASTNode', 'Blockly.Events.utils', 'Blockly.WorkspaceComment', 'Blockly.test.helpers'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../tests/mocha/extensions_test.js', ['Blockly.test.extensions'], ['Blockly.test.helpers'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../tests/mocha/field_angle_test.js', ['Blockly.test.fieldAngle'], ['Blockly.test.helpers'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../tests/mocha/field_checkbox_test.js', ['Blockly.test.fieldCheckbox'], ['Blockly.test.helpers'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../tests/mocha/field_colour_test.js', ['Blockly.test.fieldColour'], ['Blockly.test.helpers'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../tests/mocha/field_dropdown_test.js', ['Blockly.test.fieldDropdown'], ['Blockly.test.helpers'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../tests/mocha/field_image_test.js', ['Blockly.test.fieldImage'], ['Blockly.test.helpers'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../tests/mocha/field_label_serializable_test.js', ['Blockly.test.fieldLabelSerialization'], ['Blockly.test.helpers'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../tests/mocha/field_label_test.js', ['Blockly.test.fieldLabel'], ['Blockly.test.helpers'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../tests/mocha/field_multilineinput_test.js', ['Blockly.test.fieldMultiline'], ['Blockly.test.helpers'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../tests/mocha/field_number_test.js', ['Blockly.test.fieldNumber'], ['Blockly.test.helpers'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../tests/mocha/field_registry_test.js', ['Blockly.test.fieldRegistry'], ['Blockly.test.helpers'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../tests/mocha/field_test.js', ['Blockly.test.fieldTest'], ['Blockly.test.helpers'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../tests/mocha/field_textinput_test.js', ['Blockly.test.fieldTextInput'], ['Blockly.test.helpers'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../tests/mocha/field_variable_test.js', ['Blockly.test.fieldVariable'], ['Blockly.test.helpers'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../tests/mocha/flyout_test.js', ['Blockly.test.flyout'], ['Blockly.test.helpers', 'Blockly.test.toolboxHelpers'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../tests/mocha/generator_test.js', ['Blockly.test.generator'], ['Blockly.Dart', 'Blockly.JavaScript', 'Blockly.Lua', 'Blockly.PHP', 'Blockly.Python', 'Blockly.test.helpers'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../tests/mocha/gesture_test.js', ['Blockly.test.gesture'], ['Blockly.Events.utils', 'Blockly.test.helpers'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../tests/mocha/input_test.js', ['Blockly.test.input'], ['Blockly.test.helpers'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../tests/mocha/insertion_marker_test.js', ['Blockly.test.insertionMarker'], ['Blockly.test.helpers'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../tests/mocha/jso_deserialization_test.js', ['Blockly.test.jsoDeserialization'], ['Blockly.Events.utils', 'Blockly.test.helpers'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../tests/mocha/jso_serialization_test.js', ['Blockly.test.jsoSerialization'], ['Blockly.test.helpers'], {'lang': 'es8', 'module': 'goog'}); -goog.addDependency('../../tests/mocha/json_test.js', ['Blockly.test.json'], ['Blockly.test.helpers'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../tests/mocha/keydown_test.js', ['Blockly.test.keydown'], ['Blockly.test.helpers'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../tests/mocha/logic_ternary_test.js', ['Blockly.test.logicTernary'], ['Blockly.Events.utils', 'Blockly.test.helpers'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../tests/mocha/metrics_test.js', ['Blockly.test.metrics'], ['Blockly.test.helpers'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../tests/mocha/mutator_test.js', ['Blockly.test.mutator'], ['Blockly.test.helpers'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../tests/mocha/names_test.js', ['Blockly.test.names'], ['Blockly.test.helpers'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../tests/mocha/procedures_test.js', ['Blockly.test.procedures'], ['Blockly', 'Blockly.Msg', 'Blockly.test.helpers', 'Blockly.test.procedureHelpers'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../tests/mocha/procedures_test_helpers.js', ['Blockly.test.procedureHelpers'], ['Blockly.ConnectionType'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../tests/mocha/registry_test.js', ['Blockly.test.registry'], ['Blockly.test.helpers'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../tests/mocha/block_test.js', ['Blockly.test.blocks'], ['Blockly.ConnectionType', 'Blockly.Events.utils', 'Blockly.blocks', 'Blockly.test.helpers.blockDefinitions', 'Blockly.test.helpers.setupTeardown', 'Blockly.test.helpers.warnings'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../tests/mocha/comment_test.js', ['Blockly.test.comments'], ['Blockly.Events.utils', 'Blockly.test.helpers.events', 'Blockly.test.helpers.setupTeardown'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../tests/mocha/connection_checker_test.js', ['Blockly.test.connectionChecker'], ['Blockly.ConnectionType', 'Blockly.test.helpers.setupTeardown'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../tests/mocha/connection_db_test.js', ['Blockly.test.connectionDb'], ['Blockly.ConnectionType', 'Blockly.test.helpers.setupTeardown'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../tests/mocha/connection_test.js', ['Blockly.test.connection'], ['Blockly.test.helpers.blockDefinitions', 'Blockly.test.helpers.setupTeardown'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../tests/mocha/contextmenu_items_test.js', ['Blockly.test.contextMenuItem'], ['Blockly.test.helpers.setupTeardown'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../tests/mocha/cursor_test.js', ['Blockly.test.cursor'], ['Blockly.ASTNode', 'Blockly.test.helpers.setupTeardown'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../tests/mocha/dropdowndiv_test.js', ['Blockly.test.dropdown'], ['Blockly.test.helpers.setupTeardown'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../tests/mocha/event_test.js', ['Blockly.test.event'], ['Blockly.ASTNode', 'Blockly.Events.utils', 'Blockly.WorkspaceComment', 'Blockly.test.helpers.events', 'Blockly.test.helpers.setupTeardown', 'Blockly.test.helpers.variables'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../tests/mocha/extensions_test.js', ['Blockly.test.extensions'], ['Blockly.test.helpers.setupTeardown'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../tests/mocha/field_angle_test.js', ['Blockly.test.fieldAngle'], ['Blockly.test.helpers.blockDefinitions', 'Blockly.test.helpers.fields', 'Blockly.test.helpers.setupTeardown'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../tests/mocha/field_checkbox_test.js', ['Blockly.test.fieldCheckbox'], ['Blockly.test.helpers.blockDefinitions', 'Blockly.test.helpers.fields', 'Blockly.test.helpers.setupTeardown'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../tests/mocha/field_colour_test.js', ['Blockly.test.fieldColour'], ['Blockly.test.helpers.blockDefinitions', 'Blockly.test.helpers.fields', 'Blockly.test.helpers.setupTeardown'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../tests/mocha/field_dropdown_test.js', ['Blockly.test.fieldDropdown'], ['Blockly.test.helpers.blockDefinitions', 'Blockly.test.helpers.fields', 'Blockly.test.helpers.setupTeardown'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../tests/mocha/field_image_test.js', ['Blockly.test.fieldImage'], ['Blockly.test.helpers.fields', 'Blockly.test.helpers.setupTeardown'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../tests/mocha/field_label_serializable_test.js', ['Blockly.test.fieldLabelSerialization'], ['Blockly.test.helpers.blockDefinitions', 'Blockly.test.helpers.fields', 'Blockly.test.helpers.setupTeardown'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../tests/mocha/field_label_test.js', ['Blockly.test.fieldLabel'], ['Blockly.test.helpers.blockDefinitions', 'Blockly.test.helpers.fields', 'Blockly.test.helpers.setupTeardown'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../tests/mocha/field_multilineinput_test.js', ['Blockly.test.fieldMultiline'], ['Blockly.test.helpers.blockDefinitions', 'Blockly.test.helpers.codeGeneration', 'Blockly.test.helpers.fields', 'Blockly.test.helpers.setupTeardown'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../tests/mocha/field_number_test.js', ['Blockly.test.fieldNumber'], ['Blockly.test.helpers.blockDefinitions', 'Blockly.test.helpers.common', 'Blockly.test.helpers.fields', 'Blockly.test.helpers.setupTeardown'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../tests/mocha/field_registry_test.js', ['Blockly.test.fieldRegistry'], ['Blockly.test.helpers.setupTeardown', 'Blockly.test.helpers.warnings'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../tests/mocha/field_test.js', ['Blockly.test.fieldTest'], ['Blockly.test.helpers.setupTeardown', 'Blockly.test.helpers.warnings'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../tests/mocha/field_textinput_test.js', ['Blockly.test.fieldTextInput'], ['Blockly.test.helpers.blockDefinitions', 'Blockly.test.helpers.fields', 'Blockly.test.helpers.setupTeardown'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../tests/mocha/field_variable_test.js', ['Blockly.test.fieldVariable'], ['Blockly.test.helpers.blockDefinitions', 'Blockly.test.helpers.fields', 'Blockly.test.helpers.setupTeardown'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../tests/mocha/flyout_test.js', ['Blockly.test.flyout'], ['Blockly.test.helpers.setupTeardown', 'Blockly.test.helpers.toolboxDefinitions'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../tests/mocha/generator_test.js', ['Blockly.test.generator'], ['Blockly.Dart', 'Blockly.JavaScript', 'Blockly.Lua', 'Blockly.PHP', 'Blockly.Python', 'Blockly.test.helpers.setupTeardown'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../tests/mocha/gesture_test.js', ['Blockly.test.gesture'], ['Blockly.Events.utils', 'Blockly.test.helpers.blockDefinitions', 'Blockly.test.helpers.events', 'Blockly.test.helpers.setupTeardown', 'Blockly.test.helpers.userInput'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../tests/mocha/input_test.js', ['Blockly.test.input'], ['Blockly.test.helpers.setupTeardown'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../tests/mocha/insertion_marker_test.js', ['Blockly.test.insertionMarker'], ['Blockly.test.helpers.setupTeardown'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../tests/mocha/jso_deserialization_test.js', ['Blockly.test.jsoDeserialization'], ['Blockly.Events.utils', 'Blockly.test.helpers.events', 'Blockly.test.helpers.setupTeardown'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../tests/mocha/jso_serialization_test.js', ['Blockly.test.jsoSerialization'], ['Blockly.test.helpers.blockDefinitions', 'Blockly.test.helpers.setupTeardown'], {'lang': 'es8', 'module': 'goog'}); +goog.addDependency('../../tests/mocha/json_test.js', ['Blockly.test.json'], ['Blockly.test.helpers.setupTeardown', 'Blockly.test.helpers.warnings'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../tests/mocha/keydown_test.js', ['Blockly.test.keydown'], ['Blockly.test.helpers.blockDefinitions', 'Blockly.test.helpers.setupTeardown', 'Blockly.test.helpers.userInput'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../tests/mocha/logic_ternary_test.js', ['Blockly.test.logicTernary'], ['Blockly.Events.utils', 'Blockly.test.helpers.serialization', 'Blockly.test.helpers.setupTeardown'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../tests/mocha/metrics_test.js', ['Blockly.test.metrics'], ['Blockly.test.helpers.setupTeardown'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../tests/mocha/mutator_test.js', ['Blockly.test.mutator'], ['Blockly.test.helpers.blockDefinitions', 'Blockly.test.helpers.setupTeardown'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../tests/mocha/names_test.js', ['Blockly.test.names'], ['Blockly.test.helpers.setupTeardown'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../tests/mocha/procedures_test.js', ['Blockly.test.procedures'], ['Blockly', 'Blockly.Msg', 'Blockly.test.helpers.procedures', 'Blockly.test.helpers.serialization', 'Blockly.test.helpers.setupTeardown'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../tests/mocha/registry_test.js', ['Blockly.test.registry'], ['Blockly.test.helpers.setupTeardown', 'Blockly.test.helpers.warnings'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../tests/mocha/run_mocha_tests_in_browser.js', [], [], {'lang': 'es8'}); -goog.addDependency('../../tests/mocha/serializer_test.js', ['Blockly.test.serialization'], ['Blockly.test.helpers'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../tests/mocha/shortcut_registry_test.js', ['Blockly.test.shortcutRegistry'], ['Blockly.test.helpers'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../tests/mocha/test_helpers.js', ['Blockly.test.helpers'], ['Blockly.Events.utils', 'Blockly.blocks', 'Blockly.utils.KeyCodes'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../tests/mocha/theme_test.js', ['Blockly.test.theme'], ['Blockly.Events.utils', 'Blockly.test.helpers'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../tests/mocha/toolbox_helper.js', ['Blockly.test.toolboxHelpers'], [], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../tests/mocha/toolbox_test.js', ['Blockly.test.toolbox'], ['Blockly.test.helpers', 'Blockly.test.toolboxHelpers'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../tests/mocha/tooltip_test.js', ['Blockly.test.tooltip'], ['Blockly.test.helpers'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../tests/mocha/trashcan_test.js', ['Blockly.test.trashcan'], ['Blockly.Events.utils', 'Blockly.test.helpers'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../tests/mocha/utils_test.js', ['Blockly.test.utils'], ['Blockly.test.helpers'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../tests/mocha/variable_map_test.js', ['Blockly.test.variableMap'], ['Blockly.test.helpers'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../tests/mocha/variable_model_test.js', ['Blockly.test.variableModel'], ['Blockly.test.helpers'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../tests/mocha/variables_test.js', ['Blockly.test.variables'], ['Blockly.test.helpers'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../tests/mocha/widget_div_test.js', ['Blockly.test.widgetDiv'], ['Blockly.test.helpers'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../tests/mocha/workspace_comment_test.js', ['Blockly.test.workspaceComment'], ['Blockly.WorkspaceComment', 'Blockly.test.helpers'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../tests/mocha/workspace_helpers.js', ['Blockly.test.workspaceHelpers'], ['Blockly.Events.utils', 'Blockly.test.helpers'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../tests/mocha/workspace_svg_test.js', ['Blockly.test.workspaceSvg'], ['Blockly.Events.utils', 'Blockly.test.helpers', 'Blockly.test.workspaceHelpers'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../tests/mocha/workspace_test.js', ['Blockly.test.workspace'], ['Blockly.test.helpers', 'Blockly.test.workspaceHelpers'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../tests/mocha/xml_test.js', ['Blockly.test.xml'], ['Blockly.test.helpers'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../tests/mocha/zoom_controls_test.js', ['Blockly.test.zoomControls'], ['Blockly.Events.utils', 'Blockly.test.helpers'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../tests/mocha/serializer_test.js', ['Blockly.test.serialization'], ['Blockly.test.helpers.common', 'Blockly.test.helpers.setupTeardown'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../tests/mocha/shortcut_registry_test.js', ['Blockly.test.shortcutRegistry'], ['Blockly.test.helpers.setupTeardown', 'Blockly.test.helpers.userInput'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../tests/mocha/test_helpers/block_definitions.js', ['Blockly.test.helpers.blockDefinitions'], [], {'lang': 'es6', 'module': 'es6'}); +goog.addDependency('../../tests/mocha/test_helpers/code_generation.js', ['Blockly.test.helpers.codeGeneration'], ['Blockly.test.helpers.common'], {'lang': 'es6', 'module': 'es6'}); +goog.addDependency('../../tests/mocha/test_helpers/common.js', ['Blockly.test.helpers.common'], [], {'lang': 'es6', 'module': 'es6'}); +goog.addDependency('../../tests/mocha/test_helpers/events.js', ['Blockly.test.helpers.events'], [], {'lang': 'es6', 'module': 'es6'}); +goog.addDependency('../../tests/mocha/test_helpers/fields.js', ['Blockly.test.helpers.fields'], ['Blockly.test.helpers.common'], {'lang': 'es6', 'module': 'es6'}); +goog.addDependency('../../tests/mocha/test_helpers/procedures.js', ['Blockly.test.helpers.procedures'], ['Blockly.ConnectionType'], {'lang': 'es6', 'module': 'es6'}); +goog.addDependency('../../tests/mocha/test_helpers/serialization.js', ['Blockly.test.helpers.serialization'], ['Blockly.test.helpers.common'], {'lang': 'es6', 'module': 'es6'}); +goog.addDependency('../../tests/mocha/test_helpers/setup_teardown.js', ['Blockly.test.helpers.setupTeardown'], ['Blockly.Events.utils', 'Blockly.blocks'], {'lang': 'es6', 'module': 'es6'}); +goog.addDependency('../../tests/mocha/test_helpers/toolbox_definitions.js', ['Blockly.test.helpers.toolboxDefinitions'], [], {'lang': 'es6', 'module': 'es6'}); +goog.addDependency('../../tests/mocha/test_helpers/user_input.js', ['Blockly.test.helpers.userInput'], ['Blockly.utils.KeyCodes'], {'lang': 'es6', 'module': 'es6'}); +goog.addDependency('../../tests/mocha/test_helpers/variables.js', ['Blockly.test.helpers.variables'], [], {'lang': 'es6', 'module': 'es6'}); +goog.addDependency('../../tests/mocha/test_helpers/warnings.js', ['Blockly.test.helpers.warnings'], [], {'lang': 'es6', 'module': 'es6'}); +goog.addDependency('../../tests/mocha/test_helpers/workspace.js', ['Blockly.test.helpers.workspace'], ['Blockly.Events.utils', 'Blockly.test.helpers.setupTeardown', 'Blockly.test.helpers.variables', 'Blockly.test.helpers.warnings'], {'lang': 'es6', 'module': 'es6'}); +goog.addDependency('../../tests/mocha/theme_test.js', ['Blockly.test.theme'], ['Blockly.Events.utils', 'Blockly.test.helpers.events', 'Blockly.test.helpers.setupTeardown'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../tests/mocha/toolbox_test.js', ['Blockly.test.toolbox'], ['Blockly.test.helpers.blockDefinitions', 'Blockly.test.helpers.setupTeardown', 'Blockly.test.helpers.toolboxDefinitions'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../tests/mocha/tooltip_test.js', ['Blockly.test.tooltip'], ['Blockly.test.helpers.setupTeardown'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../tests/mocha/trashcan_test.js', ['Blockly.test.trashcan'], ['Blockly.Events.utils', 'Blockly.test.helpers.blockDefinitions', 'Blockly.test.helpers.events', 'Blockly.test.helpers.setupTeardown', 'Blockly.test.helpers.userInput'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../tests/mocha/utils_test.js', ['Blockly.test.utils'], ['Blockly.test.helpers.setupTeardown'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../tests/mocha/variable_map_test.js', ['Blockly.test.variableMap'], ['Blockly.test.helpers.setupTeardown', 'Blockly.test.helpers.variables'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../tests/mocha/variable_model_test.js', ['Blockly.test.variableModel'], ['Blockly.test.helpers.setupTeardown'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../tests/mocha/variables_test.js', ['Blockly.test.variables'], ['Blockly.test.helpers.setupTeardown'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../tests/mocha/widget_div_test.js', ['Blockly.test.widgetDiv'], ['Blockly.test.helpers.setupTeardown'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../tests/mocha/workspace_comment_test.js', ['Blockly.test.workspaceComment'], ['Blockly.WorkspaceComment', 'Blockly.test.helpers.setupTeardown'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../tests/mocha/workspace_svg_test.js', ['Blockly.test.workspaceSvg'], ['Blockly.Events.utils', 'Blockly.test.helpers.blockDefinitions', 'Blockly.test.helpers.events', 'Blockly.test.helpers.setupTeardown', 'Blockly.test.helpers.variables', 'Blockly.test.helpers.workspace'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../tests/mocha/workspace_test.js', ['Blockly.test.workspace'], ['Blockly.test.helpers.setupTeardown', 'Blockly.test.helpers.variables', 'Blockly.test.helpers.workspace'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../tests/mocha/xml_test.js', ['Blockly.test.xml'], ['Blockly.test.helpers.setupTeardown', 'Blockly.test.helpers.variables'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../tests/mocha/zoom_controls_test.js', ['Blockly.test.zoomControls'], ['Blockly.Events.utils', 'Blockly.test.helpers.events', 'Blockly.test.helpers.setupTeardown', 'Blockly.test.helpers.userInput'], {'lang': 'es6', 'module': 'goog'}); diff --git a/tests/mocha/.eslintrc.json b/tests/mocha/.eslintrc.json index c42c50c20..bf87ec0bd 100644 --- a/tests/mocha/.eslintrc.json +++ b/tests/mocha/.eslintrc.json @@ -1,18 +1,21 @@ { + "parserOptions": { + "sourceType": "module" + }, "env": { "browser": true, "mocha": true }, "globals": { "chai": false, - "sinon": false, - "testHelpers": true + "sinon": false }, "rules": { "no-unused-vars": ["off"], // Allow uncommented helper functions in tests. "require-jsdoc": ["off"], - "prefer-rest-params": ["off"] + "prefer-rest-params": ["off"], + "no-invalid-this": ["off"] }, "extends": "../../.eslintrc.json" } diff --git a/tests/mocha/astnode_test.js b/tests/mocha/astnode_test.js index e370d4dd7..1a15dfb62 100644 --- a/tests/mocha/astnode_test.js +++ b/tests/mocha/astnode_test.js @@ -7,10 +7,11 @@ goog.module('Blockly.test.astNode'); const {ASTNode} = goog.require('Blockly.ASTNode'); -const {sharedTestSetup, sharedTestTeardown, workspaceTeardown} = goog.require('Blockly.test.helpers'); +const {sharedTestSetup, sharedTestTeardown, workspaceTeardown} = goog.require('Blockly.test.helpers.setupTeardown'); suite('ASTNode', function() { + console.log('1/a'); setup(function() { sharedTestSetup.call(this); Blockly.defineBlocksWithJsonArray([{ @@ -100,7 +101,9 @@ suite('ASTNode', function() { }); suite('HelperFunctions', function() { + console.log('2'); test('findNextForInput_', function() { + console.log('3'); const input = this.blocks.statementInput1.inputList[0]; const input2 = this.blocks.statementInput1.inputList[1]; const connection = input.connection; @@ -169,6 +172,7 @@ suite('ASTNode', function() { }); suite('NavigationFunctions', function() { + console.log('b'); setup(function() { Blockly.defineBlocksWithJsonArray([{ "type": "top_connection", @@ -319,7 +323,9 @@ suite('ASTNode', function() { workspaceTeardown.call(this, this.singleBlockWorkspace); }); + console.log('c'); test('fromPreviousToBlock', function() { + console.log('d'); const prevConnection = this.blocks.statementInput1.previousConnection; const node = ASTNode.createConnectionNode(prevConnection); const nextNode = node.next(); diff --git a/tests/mocha/block_change_event_test.js b/tests/mocha/block_change_event_test.js index e4e3f49cf..6cfbca578 100644 --- a/tests/mocha/block_change_event_test.js +++ b/tests/mocha/block_change_event_test.js @@ -6,7 +6,8 @@ goog.module('Blockly.test.blockChangeEvent'); -const {defineMutatorBlocks, sharedTestSetup, sharedTestTeardown} = goog.require('Blockly.test.helpers'); +const {sharedTestSetup, sharedTestTeardown} = goog.require('Blockly.test.helpers.setupTeardown'); +const {defineMutatorBlocks} = goog.require('Blockly.test.helpers.blockDefinitions'); suite('Block Change Event', function() { diff --git a/tests/mocha/block_create_event_test.js b/tests/mocha/block_create_event_test.js index 69debed96..475991908 100644 --- a/tests/mocha/block_create_event_test.js +++ b/tests/mocha/block_create_event_test.js @@ -6,8 +6,9 @@ goog.module('Blockly.test.blockCreateEvent'); +const {assertEventFired} = goog.require('Blockly.test.helpers.events'); const eventUtils = goog.require('Blockly.Events.utils'); -const {assertEventFired, sharedTestSetup, sharedTestTeardown} = goog.require('Blockly.test.helpers'); +const {sharedTestSetup, sharedTestTeardown} = goog.require('Blockly.test.helpers.setupTeardown'); suite('Block Create Event', function() { diff --git a/tests/mocha/block_test.js b/tests/mocha/block_test.js index 36cc583d9..13e515534 100644 --- a/tests/mocha/block_test.js +++ b/tests/mocha/block_test.js @@ -6,10 +6,12 @@ goog.module('Blockly.test.blocks'); -const eventUtils = goog.require('Blockly.Events.utils'); const {Blocks} = goog.require('Blockly.blocks'); const {ConnectionType} = goog.require('Blockly.ConnectionType'); -const {createDeprecationWarningStub, createRenderedBlock, sharedTestSetup, sharedTestTeardown, workspaceTeardown} = goog.require('Blockly.test.helpers'); +const {createDeprecationWarningStub} = goog.require('Blockly.test.helpers.warnings'); +const {createRenderedBlock} = goog.require('Blockly.test.helpers.blockDefinitions'); +const eventUtils = goog.require('Blockly.Events.utils'); +const {sharedTestSetup, sharedTestTeardown, workspaceTeardown} = goog.require('Blockly.test.helpers.setupTeardown'); suite('Blocks', function() { diff --git a/tests/mocha/comment_test.js b/tests/mocha/comment_test.js index 94a496637..afee012f6 100644 --- a/tests/mocha/comment_test.js +++ b/tests/mocha/comment_test.js @@ -6,8 +6,9 @@ goog.module('Blockly.test.comments'); +const {assertEventFired} = goog.require('Blockly.test.helpers.events'); const eventUtils = goog.require('Blockly.Events.utils'); -const {assertEventFired, sharedTestSetup, sharedTestTeardown} = goog.require('Blockly.test.helpers'); +const {sharedTestSetup, sharedTestTeardown} = goog.require('Blockly.test.helpers.setupTeardown'); suite('Comments', function() { diff --git a/tests/mocha/connection_checker_test.js b/tests/mocha/connection_checker_test.js index 53582daaf..523fecfcc 100644 --- a/tests/mocha/connection_checker_test.js +++ b/tests/mocha/connection_checker_test.js @@ -7,7 +7,7 @@ goog.module('Blockly.test.connectionChecker'); const {ConnectionType} = goog.require('Blockly.ConnectionType'); -const {sharedTestSetup, sharedTestTeardown} = goog.require('Blockly.test.helpers'); +const {sharedTestSetup, sharedTestTeardown} = goog.require('Blockly.test.helpers.setupTeardown'); suite('Connection checker', function() { diff --git a/tests/mocha/connection_db_test.js b/tests/mocha/connection_db_test.js index 83ec64663..cdc343bd5 100644 --- a/tests/mocha/connection_db_test.js +++ b/tests/mocha/connection_db_test.js @@ -7,7 +7,7 @@ goog.module('Blockly.test.connectionDb'); const {ConnectionType} = goog.require('Blockly.ConnectionType'); -const {sharedTestSetup, sharedTestTeardown} = goog.require('Blockly.test.helpers'); +const {sharedTestSetup, sharedTestTeardown} = goog.require('Blockly.test.helpers.setupTeardown'); suite('Connection Database', function() { diff --git a/tests/mocha/connection_test.js b/tests/mocha/connection_test.js index 24e763683..37bca1240 100644 --- a/tests/mocha/connection_test.js +++ b/tests/mocha/connection_test.js @@ -6,7 +6,8 @@ goog.module('Blockly.test.connection'); -const {assertSingleDeprecationWarningCall, createDeprecationWarningStub, createGenUidStubWithReturns, defineRowBlock, defineStatementBlock, defineStackBlock, sharedTestSetup, sharedTestTeardown, workspaceTeardown} = goog.require('Blockly.test.helpers'); +const {createGenUidStubWithReturns, sharedTestSetup, sharedTestTeardown, workspaceTeardown} = goog.require('Blockly.test.helpers.setupTeardown'); +const {defineRowBlock, defineStatementBlock, defineStackBlock} = goog.require('Blockly.test.helpers.blockDefinitions'); suite('Connection', function() { diff --git a/tests/mocha/contextmenu_items_test.js b/tests/mocha/contextmenu_items_test.js index 1c82072e7..c9b9b8127 100644 --- a/tests/mocha/contextmenu_items_test.js +++ b/tests/mocha/contextmenu_items_test.js @@ -6,7 +6,7 @@ goog.module('Blockly.test.contextMenuItem'); -const {sharedTestSetup, sharedTestTeardown, workspaceTeardown} = goog.require('Blockly.test.helpers'); +const {sharedTestSetup, sharedTestTeardown, workspaceTeardown} = goog.require('Blockly.test.helpers.setupTeardown'); suite('Context Menu Items', function() { diff --git a/tests/mocha/cursor_test.js b/tests/mocha/cursor_test.js index a86268d87..77b22470a 100644 --- a/tests/mocha/cursor_test.js +++ b/tests/mocha/cursor_test.js @@ -6,7 +6,7 @@ goog.module('Blockly.test.cursor'); -const {sharedTestSetup, sharedTestTeardown} = goog.require('Blockly.test.helpers'); +const {sharedTestSetup, sharedTestTeardown} = goog.require('Blockly.test.helpers.setupTeardown'); const {ASTNode} = goog.require('Blockly.ASTNode'); diff --git a/tests/mocha/dropdowndiv_test.js b/tests/mocha/dropdowndiv_test.js index c45aee795..6cd8dca53 100644 --- a/tests/mocha/dropdowndiv_test.js +++ b/tests/mocha/dropdowndiv_test.js @@ -6,7 +6,7 @@ goog.module('Blockly.test.dropdown'); -const {sharedTestSetup, sharedTestTeardown} = goog.require('Blockly.test.helpers'); +const {sharedTestSetup, sharedTestTeardown} = goog.require('Blockly.test.helpers.setupTeardown'); suite('DropDownDiv', function() { diff --git a/tests/mocha/event_test.js b/tests/mocha/event_test.js index 70ae131b7..2b57b8a98 100644 --- a/tests/mocha/event_test.js +++ b/tests/mocha/event_test.js @@ -6,9 +6,11 @@ goog.module('Blockly.test.event'); -const eventUtils = goog.require('Blockly.Events.utils'); -const {assertEventEquals, assertNthCallEventArgEquals, assertVariableValues, createFireChangeListenerSpy, createGenUidStubWithReturns, sharedTestSetup, sharedTestTeardown, workspaceTeardown} = goog.require('Blockly.test.helpers'); const {ASTNode} = goog.require('Blockly.ASTNode'); +const {assertEventEquals, assertNthCallEventArgEquals, createFireChangeListenerSpy} = goog.require('Blockly.test.helpers.events'); +const {assertVariableValues} = goog.require('Blockly.test.helpers.variables'); +const {createGenUidStubWithReturns, sharedTestSetup, sharedTestTeardown, workspaceTeardown} = goog.require('Blockly.test.helpers.setupTeardown'); +const eventUtils = goog.require('Blockly.Events.utils'); goog.require('Blockly.WorkspaceComment'); diff --git a/tests/mocha/extensions_test.js b/tests/mocha/extensions_test.js index d7846bb81..6c2873ff1 100644 --- a/tests/mocha/extensions_test.js +++ b/tests/mocha/extensions_test.js @@ -6,7 +6,7 @@ goog.module('Blockly.test.extensions'); -const {sharedTestSetup, sharedTestTeardown} = goog.require('Blockly.test.helpers'); +const {sharedTestSetup, sharedTestTeardown} = goog.require('Blockly.test.helpers.setupTeardown'); suite('Extensions', function() { diff --git a/tests/mocha/field_angle_test.js b/tests/mocha/field_angle_test.js index 2d3736e67..1639eb206 100644 --- a/tests/mocha/field_angle_test.js +++ b/tests/mocha/field_angle_test.js @@ -6,7 +6,9 @@ goog.module('Blockly.test.fieldAngle'); -const {createTestBlock, defineRowBlock, sharedTestSetup, sharedTestTeardown, workspaceTeardown} = goog.require('Blockly.test.helpers'); +const {assertFieldValue, runConstructorSuiteTests, runFromJsonSuiteTests, runSetValueTests} = goog.require('Blockly.test.helpers.fields'); +const {createTestBlock, defineRowBlock} = goog.require('Blockly.test.helpers.blockDefinitions'); +const {sharedTestSetup, sharedTestTeardown, workspaceTeardown} = goog.require('Blockly.test.helpers.setupTeardown'); suite('Angle Fields', function() { @@ -60,7 +62,7 @@ suite('Angle Fields', function() { * @param {FieldTemplate} field The field to check. */ const assertFieldDefault = function(field) { - testHelpers.assertFieldValue(field, defaultFieldValue); + assertFieldValue(field, defaultFieldValue); }; /** * Asserts that the field properties are correct based on the test case. @@ -68,14 +70,14 @@ suite('Angle Fields', function() { * @param {!FieldValueTestCase} testCase The test case. */ const validTestCaseAssertField = function(field, testCase) { - testHelpers.assertFieldValue(field, testCase.expectedValue); + assertFieldValue(field, testCase.expectedValue); }; - testHelpers.runConstructorSuiteTests( + runConstructorSuiteTests( Blockly.FieldAngle, validValueTestCases, invalidValueTestCases, validTestCaseAssertField, assertFieldDefault); - testHelpers.runFromJsonSuiteTests( + runFromJsonSuiteTests( Blockly.FieldAngle, validValueTestCases, invalidValueTestCases, validTestCaseAssertField, assertFieldDefault); @@ -84,12 +86,12 @@ suite('Angle Fields', function() { setup(function() { this.field = new Blockly.FieldAngle(); }); - testHelpers.runSetValueTests( + runSetValueTests( validValueTestCases, invalidValueTestCases, defaultFieldValue); test('With source block', function() { this.field.setSourceBlock(createTestBlock()); this.field.setValue(2.5); - testHelpers.assertFieldValue(this.field, 2.5); + assertFieldValue(this.field, 2.5); }); }); suite('Value -> New Value', function() { @@ -97,12 +99,12 @@ suite('Angle Fields', function() { setup(function() { this.field = new Blockly.FieldAngle(initialValue); }); - testHelpers.runSetValueTests( + runSetValueTests( validValueTestCases, invalidValueTestCases, initialValue); test('With source block', function() { this.field.setSourceBlock(createTestBlock()); this.field.setValue(2.5); - testHelpers.assertFieldValue(this.field, 2.5); + assertFieldValue(this.field, 2.5); }); }); }); @@ -142,12 +144,12 @@ suite('Angle Fields', function() { this.field.isBeingEdited_ = true; this.field.htmlInput_.value = String(suiteInfo.value); this.field.onHtmlInputChange_(null); - testHelpers.assertFieldValue( + assertFieldValue( this.field, suiteInfo.expectedValue, String(suiteInfo.value)); }); test('When Not Editing', function() { this.field.setValue(suiteInfo.value); - testHelpers.assertFieldValue(this.field, suiteInfo.expectedValue); + assertFieldValue(this.field, suiteInfo.expectedValue); }); }); }); diff --git a/tests/mocha/field_checkbox_test.js b/tests/mocha/field_checkbox_test.js index 2c6b8eeb2..5de565984 100644 --- a/tests/mocha/field_checkbox_test.js +++ b/tests/mocha/field_checkbox_test.js @@ -6,7 +6,9 @@ goog.module('Blockly.test.fieldCheckbox'); -const {defineRowBlock, sharedTestSetup, sharedTestTeardown, workspaceTeardown} = goog.require('Blockly.test.helpers'); +const {assertFieldValue, runConstructorSuiteTests, runFromJsonSuiteTests, runSetValueTests} = goog.require('Blockly.test.helpers.fields'); +const {sharedTestSetup, sharedTestTeardown, workspaceTeardown} = goog.require('Blockly.test.helpers.setupTeardown'); +const {defineRowBlock} = goog.require('Blockly.test.helpers.blockDefinitions'); suite('Checkbox Fields', function() { @@ -61,7 +63,7 @@ suite('Checkbox Fields', function() { * @param {!Blockly.FieldCheckbox} field The field to check. */ const assertFieldDefault = function(field) { - testHelpers.assertFieldValue( + assertFieldValue( field, defaultFieldValue, defaultFieldValue.toLowerCase()); }; /** @@ -70,15 +72,15 @@ suite('Checkbox Fields', function() { * @param {!FieldValueTestCase} testCase The test case. */ const validTestCaseAssertField = function(field, testCase) { - testHelpers.assertFieldValue( + assertFieldValue( field, testCase.expectedValue, testCase.expectedValue.toLowerCase()); }; - testHelpers.runConstructorSuiteTests( + runConstructorSuiteTests( Blockly.FieldCheckbox, validValueTestCases, invalidValueTestCases, validTestCaseAssertField, assertFieldDefault); - testHelpers.runFromJsonSuiteTests( + runFromJsonSuiteTests( Blockly.FieldCheckbox, validValueTestCases, invalidValueTestCases, validTestCaseAssertField, assertFieldDefault); @@ -87,14 +89,14 @@ suite('Checkbox Fields', function() { setup(function() { this.field = new Blockly.FieldCheckbox('TRUE'); }); - testHelpers.runSetValueTests( + runSetValueTests( validValueTestCases, invalidValueTestCases, 'TRUE', 'true'); }); suite('False -> New Value', function() { setup(function() { this.field = new Blockly.FieldCheckbox('FALSE'); }); - testHelpers.runSetValueTests( + runSetValueTests( validValueTestCases, invalidValueTestCases, 'FALSE', 'false'); }); }); @@ -131,7 +133,7 @@ suite('Checkbox Fields', function() { }); test('New Value', function() { this.field.setValue(suiteInfo.value); - testHelpers.assertFieldValue( + assertFieldValue( this.field, suiteInfo.expectedValue, String(suiteInfo.expectedValue).toLowerCase()); }); diff --git a/tests/mocha/field_colour_test.js b/tests/mocha/field_colour_test.js index 97fd27c96..eb0389702 100644 --- a/tests/mocha/field_colour_test.js +++ b/tests/mocha/field_colour_test.js @@ -6,7 +6,9 @@ goog.module('Blockly.test.fieldColour'); -const {createTestBlock, defineRowBlock, sharedTestSetup, sharedTestTeardown, workspaceTeardown} = goog.require('Blockly.test.helpers'); +const {assertFieldValue, runConstructorSuiteTests, runFromJsonSuiteTests, runSetValueTests} = goog.require('Blockly.test.helpers.fields'); +const {createTestBlock, defineRowBlock} = goog.require('Blockly.test.helpers.blockDefinitions'); +const {sharedTestSetup, sharedTestTeardown, workspaceTeardown} = goog.require('Blockly.test.helpers.setupTeardown'); suite('Colour Fields', function() { @@ -87,7 +89,7 @@ suite('Colour Fields', function() { * @param {FieldTemplate} field The field to check. */ const assertFieldDefault = function(field) { - testHelpers.assertFieldValue(field, defaultFieldValue, defaultTextValue); + assertFieldValue(field, defaultFieldValue, defaultTextValue); }; /** * Asserts that the field properties are correct based on the test case. @@ -95,15 +97,15 @@ suite('Colour Fields', function() { * @param {!FieldValueTestCase} testCase The test case. */ const validTestCaseAssertField = function(field, testCase) { - testHelpers.assertFieldValue( + assertFieldValue( field, testCase.expectedValue, testCase.expectedText); }; - testHelpers.runConstructorSuiteTests( + runConstructorSuiteTests( Blockly.FieldColour, validValueTestCases, invalidValueTestCases, validTestCaseAssertField, assertFieldDefault); - testHelpers.runFromJsonSuiteTests( + runFromJsonSuiteTests( Blockly.FieldColour, validValueTestCases, invalidValueTestCases, validTestCaseAssertField, assertFieldDefault); @@ -112,25 +114,25 @@ suite('Colour Fields', function() { setup(function() { this.field = new Blockly.FieldColour(); }); - testHelpers.runSetValueTests( + runSetValueTests( validValueTestCases, invalidValueTestCases, defaultFieldValue, defaultTextValue); test('With source block', function() { this.field.setSourceBlock(createTestBlock()); this.field.setValue('#bcbcbc'); - testHelpers.assertFieldValue(this.field, '#bcbcbc', '#bcbcbc'); + assertFieldValue(this.field, '#bcbcbc', '#bcbcbc'); }); }); suite('Value -> New Value', function() { setup(function() { this.field = new Blockly.FieldColour('#aaaaaa'); }); - testHelpers.runSetValueTests( + runSetValueTests( validValueTestCases, invalidValueTestCases, '#aaaaaa', '#aaa'); test('With source block', function() { this.field.setSourceBlock(createTestBlock()); this.field.setValue('#bcbcbc'); - testHelpers.assertFieldValue(this.field, '#bcbcbc', '#bcbcbc'); + assertFieldValue(this.field, '#bcbcbc', '#bcbcbc'); }); }); }); @@ -161,7 +163,7 @@ suite('Colour Fields', function() { }); test('New Value', function() { this.field.setValue(suiteInfo.value); - testHelpers.assertFieldValue( + assertFieldValue( this.field, suiteInfo.expectedValue, suiteInfo.expectedText); }); }); diff --git a/tests/mocha/field_dropdown_test.js b/tests/mocha/field_dropdown_test.js index 11b517b6e..1b67525f4 100644 --- a/tests/mocha/field_dropdown_test.js +++ b/tests/mocha/field_dropdown_test.js @@ -6,7 +6,9 @@ goog.module('Blockly.test.fieldDropdown'); -const {createTestBlock, defineRowBlock, sharedTestSetup, sharedTestTeardown, workspaceTeardown} = goog.require('Blockly.test.helpers'); +const {assertFieldValue, runConstructorSuiteTests, runFromJsonSuiteTests, runSetValueTests} = goog.require('Blockly.test.helpers.fields'); +const {createTestBlock, defineRowBlock} = goog.require('Blockly.test.helpers.blockDefinitions'); +const {sharedTestSetup, sharedTestTeardown, workspaceTeardown} = goog.require('Blockly.test.helpers.setupTeardown'); suite('Dropdown Fields', function() { @@ -74,14 +76,14 @@ suite('Dropdown Fields', function() { * @param {!FieldValueTestCase} testCase The test case. */ const validTestCaseAssertField = function(field, testCase) { - testHelpers.assertFieldValue(field, testCase.expectedValue, testCase.expectedText); + assertFieldValue(field, testCase.expectedValue, testCase.expectedText); }; - testHelpers.runConstructorSuiteTests( + runConstructorSuiteTests( Blockly.FieldDropdown, validValueCreationTestCases, invalidValueCreationTestCases, validTestCaseAssertField); - testHelpers.runFromJsonSuiteTests( + runFromJsonSuiteTests( Blockly.FieldDropdown, validValueCreationTestCases, invalidValueCreationTestCases, validTestCaseAssertField); @@ -107,12 +109,12 @@ suite('Dropdown Fields', function() { this.field = new Blockly.FieldDropdown( [['a', 'A'], ['b', 'B'], ['c', 'C']]); }); - testHelpers.runSetValueTests( + runSetValueTests( validValueSetValueTestCases, invalidValueSetValueTestCases, 'A', 'a'); test('With source block', function() { this.field.setSourceBlock(createTestBlock()); this.field.setValue('B'); - testHelpers.assertFieldValue(this.field, 'B', 'b'); + assertFieldValue(this.field, 'B', 'b'); }); }); @@ -133,7 +135,7 @@ suite('Dropdown Fields', function() { }); test('New Value', function() { this.dropdownField.setValue('1B'); - testHelpers.assertFieldValue(this.dropdownField, '1A', '1a'); + assertFieldValue(this.dropdownField, '1A', '1a'); }); }); suite('Force 1s Validator', function() { @@ -144,7 +146,7 @@ suite('Dropdown Fields', function() { }); test('New Value', function() { this.dropdownField.setValue('2B'); - testHelpers.assertFieldValue(this.dropdownField, '1B', '1b'); + assertFieldValue(this.dropdownField, '1B', '1b'); }); }); suite('Returns Undefined Validator', function() { @@ -153,7 +155,7 @@ suite('Dropdown Fields', function() { }); test('New Value', function() { this.dropdownField.setValue('1B'); - testHelpers.assertFieldValue(this.dropdownField, '1B', '1b'); + assertFieldValue(this.dropdownField, '1B', '1b'); }); }); }); diff --git a/tests/mocha/field_image_test.js b/tests/mocha/field_image_test.js index fcc68fd67..62826398a 100644 --- a/tests/mocha/field_image_test.js +++ b/tests/mocha/field_image_test.js @@ -6,7 +6,8 @@ goog.module('Blockly.test.fieldImage'); -const {sharedTestSetup, sharedTestTeardown} = goog.require('Blockly.test.helpers'); +const {assertFieldValue, runConstructorSuiteTests, runFromJsonSuiteTests, runSetValueTests} = goog.require('Blockly.test.helpers.fields'); +const {sharedTestSetup, sharedTestTeardown} = goog.require('Blockly.test.helpers.setupTeardown'); suite('Image Fields', function() { @@ -56,14 +57,14 @@ suite('Image Fields', function() { * @param {!FieldValueTestCase} testCase The test case. */ const validTestCaseAssertField = function(field, testCase) { - testHelpers.assertFieldValue(field, testCase.expectedValue, testCase.expectedText); + assertFieldValue(field, testCase.expectedValue, testCase.expectedText); }; - testHelpers.runConstructorSuiteTests( + runConstructorSuiteTests( Blockly.FieldImage, validValueCreationTestCases, invalidValueTestCases, validTestCaseAssertField); - testHelpers.runFromJsonSuiteTests( + runFromJsonSuiteTests( Blockly.FieldImage, validValueCreationTestCases, invalidValueTestCases, validTestCaseAssertField); @@ -80,7 +81,7 @@ suite('Image Fields', function() { setup(function() { this.field = new Blockly.FieldImage('src', 1, 1, 'alt'); }); - testHelpers.runSetValueTests( + runSetValueTests( validValueSetValueTestCases, invalidValueTestCases, 'src', 'alt'); }); @@ -126,15 +127,15 @@ suite('Image Fields', function() { }); test('Null', function() { this.imageField.setAlt(null); - testHelpers.assertFieldValue(this.imageField, 'src', ''); + assertFieldValue(this.imageField, 'src', ''); }); test('Empty String', function() { this.imageField.setAlt(''); - testHelpers.assertFieldValue(this.imageField, 'src', ''); + assertFieldValue(this.imageField, 'src', ''); }); test('Good Alt', function() { this.imageField.setAlt('newAlt'); - testHelpers.assertFieldValue(this.imageField, 'src', 'newAlt'); + assertFieldValue(this.imageField, 'src', 'newAlt'); }); }); test('JS Configuration - Simple', function() { diff --git a/tests/mocha/field_label_serializable_test.js b/tests/mocha/field_label_serializable_test.js index 212173b2a..b5ba42824 100644 --- a/tests/mocha/field_label_serializable_test.js +++ b/tests/mocha/field_label_serializable_test.js @@ -6,7 +6,9 @@ goog.module('Blockly.test.fieldLabelSerialization'); -const {createTestBlock, defineRowBlock, sharedTestSetup, sharedTestTeardown, workspaceTeardown} = goog.require('Blockly.test.helpers'); +const {assertFieldValue, runConstructorSuiteTests, runFromJsonSuiteTests, runSetValueTests} = goog.require('Blockly.test.helpers.fields'); +const {sharedTestSetup, sharedTestTeardown, workspaceTeardown} = goog.require('Blockly.test.helpers.setupTeardown'); +const {createTestBlock, defineRowBlock} = goog.require('Blockly.test.helpers.blockDefinitions'); suite('Label Serializable Fields', function() { @@ -53,7 +55,7 @@ suite('Label Serializable Fields', function() { * @param {!Blockly.FieldLabelSerializable} field The field to check. */ const assertFieldDefault = function(field) { - testHelpers.assertFieldValue(field, defaultFieldValue); + assertFieldValue(field, defaultFieldValue); }; /** * Asserts that the field properties are correct based on the test case. @@ -61,14 +63,14 @@ suite('Label Serializable Fields', function() { * @param {!FieldValueTestCase} testCase The test case. */ const validTestCaseAssertField = function(field, testCase) { - testHelpers.assertFieldValue(field, testCase.expectedValue); + assertFieldValue(field, testCase.expectedValue); }; - testHelpers.runConstructorSuiteTests( + runConstructorSuiteTests( Blockly.FieldLabelSerializable, validValueTestCases, invalidValueTestCases, validTestCaseAssertField, assertFieldDefault); - testHelpers.runFromJsonSuiteTests( + runFromJsonSuiteTests( Blockly.FieldLabelSerializable, validValueTestCases, invalidValueTestCases, validTestCaseAssertField, assertFieldDefault); @@ -77,12 +79,12 @@ suite('Label Serializable Fields', function() { setup(function() { this.field = new Blockly.FieldLabelSerializable(); }); - testHelpers.runSetValueTests( + runSetValueTests( validValueTestCases, invalidValueTestCases, defaultFieldValue); test('With source block', function() { this.field.setSourceBlock(createTestBlock()); this.field.setValue('value'); - testHelpers.assertFieldValue(this.field, 'value'); + assertFieldValue(this.field, 'value'); }); }); suite('Value -> New Value', function() { @@ -90,12 +92,12 @@ suite('Label Serializable Fields', function() { setup(function() { this.field = new Blockly.FieldLabelSerializable(initialValue); }); - testHelpers.runSetValueTests( + runSetValueTests( validValueTestCases, invalidValueTestCases, initialValue); test('With source block', function() { this.field.setSourceBlock(createTestBlock()); this.field.setValue('value'); - testHelpers.assertFieldValue(this.field, 'value'); + assertFieldValue(this.field, 'value'); }); }); }); diff --git a/tests/mocha/field_label_test.js b/tests/mocha/field_label_test.js index 52fedef90..62f088b96 100644 --- a/tests/mocha/field_label_test.js +++ b/tests/mocha/field_label_test.js @@ -6,7 +6,9 @@ goog.module('Blockly.test.fieldLabel'); -const {createTestBlock, sharedTestSetup, sharedTestTeardown} = goog.require('Blockly.test.helpers'); +const {assertFieldValue, runConstructorSuiteTests, runFromJsonSuiteTests, runSetValueTests} = goog.require('Blockly.test.helpers.fields'); +const {sharedTestSetup, sharedTestTeardown} = goog.require('Blockly.test.helpers.setupTeardown'); +const {createTestBlock} = goog.require('Blockly.test.helpers.blockDefinitions'); suite('Label Fields', function() { @@ -53,7 +55,7 @@ suite('Label Fields', function() { * @param {!Blockly.FieldLabel} field The field to check. */ const assertFieldDefault = function(field) { - testHelpers.assertFieldValue(field, defaultFieldValue); + assertFieldValue(field, defaultFieldValue); }; /** * Asserts that the field properties are correct based on the test case. @@ -61,14 +63,14 @@ suite('Label Fields', function() { * @param {!FieldValueTestCase} testCase The test case. */ const validTestCaseAssertField = function(field, testCase) { - testHelpers.assertFieldValue(field, testCase.expectedValue); + assertFieldValue(field, testCase.expectedValue); }; - testHelpers.runConstructorSuiteTests( + runConstructorSuiteTests( Blockly.FieldLabel, validValueTestCases, invalidValueTestCases, validTestCaseAssertField, assertFieldDefault); - testHelpers.runFromJsonSuiteTests( + runFromJsonSuiteTests( Blockly.FieldLabel, validValueTestCases, invalidValueTestCases, validTestCaseAssertField, assertFieldDefault); @@ -77,12 +79,12 @@ suite('Label Fields', function() { setup(function() { this.field = new Blockly.FieldLabel(); }); - testHelpers.runSetValueTests( + runSetValueTests( validValueTestCases, invalidValueTestCases, defaultFieldValue); test('With source block', function() { this.field.setSourceBlock(createTestBlock()); this.field.setValue('value'); - testHelpers.assertFieldValue(this.field, 'value'); + assertFieldValue(this.field, 'value'); }); }); suite('Value -> New Value', function() { @@ -90,12 +92,12 @@ suite('Label Fields', function() { setup(function() { this.field = new Blockly.FieldLabel(initialValue); }); - testHelpers.runSetValueTests( + runSetValueTests( validValueTestCases, invalidValueTestCases, initialValue); test('With source block', function() { this.field.setSourceBlock(createTestBlock()); this.field.setValue('value'); - testHelpers.assertFieldValue(this.field, 'value'); + assertFieldValue(this.field, 'value'); }); }); }); diff --git a/tests/mocha/field_multilineinput_test.js b/tests/mocha/field_multilineinput_test.js index 8283df431..6096384fe 100644 --- a/tests/mocha/field_multilineinput_test.js +++ b/tests/mocha/field_multilineinput_test.js @@ -6,7 +6,10 @@ goog.module('Blockly.test.fieldMultiline'); -const {createTestBlock, defineRowBlock, sharedTestSetup, sharedTestTeardown, workspaceTeardown} = goog.require('Blockly.test.helpers'); +const {assertFieldValue, runConstructorSuiteTests, runFromJsonSuiteTests, runSetValueTests} = goog.require('Blockly.test.helpers.fields'); +const {createTestBlock, defineRowBlock} = goog.require('Blockly.test.helpers.blockDefinitions'); +const {sharedTestSetup, sharedTestTeardown, workspaceTeardown} = goog.require('Blockly.test.helpers.setupTeardown'); +const {runCodeGenerationTestSuites} = goog.require('Blockly.test.helpers.codeGeneration'); suite('Multiline Input Fields', function() { @@ -55,7 +58,7 @@ suite('Multiline Input Fields', function() { * @param {!Blockly.FieldMultilineInput} field The field to check. */ const assertFieldDefault = function(field) { - testHelpers.assertFieldValue(field, defaultFieldValue); + assertFieldValue(field, defaultFieldValue); }; /** * Asserts that the field properties are correct based on the test case. @@ -63,14 +66,14 @@ suite('Multiline Input Fields', function() { * @param {!FieldValueTestCase} testCase The test case. */ const validTestCaseAssertField = function(field, testCase) { - testHelpers.assertFieldValue(field, testCase.expectedValue); + assertFieldValue(field, testCase.expectedValue); }; - testHelpers.runConstructorSuiteTests( + runConstructorSuiteTests( Blockly.FieldMultilineInput, validValueTestCases, invalidValueTestCases, validTestCaseAssertField, assertFieldDefault); - testHelpers.runFromJsonSuiteTests( + runFromJsonSuiteTests( Blockly.FieldMultilineInput, validValueTestCases, invalidValueTestCases, validTestCaseAssertField, assertFieldDefault); @@ -79,12 +82,12 @@ suite('Multiline Input Fields', function() { setup(function() { this.field = new Blockly.FieldMultilineInput(); }); - testHelpers.runSetValueTests( + runSetValueTests( validValueTestCases, invalidValueTestCases, defaultFieldValue); test('With source block', function() { this.field.setSourceBlock(createTestBlock()); this.field.setValue('value'); - testHelpers.assertFieldValue(this.field, 'value'); + assertFieldValue(this.field, 'value'); }); }); suite('Value -> New Value', function() { @@ -92,12 +95,12 @@ suite('Multiline Input Fields', function() { setup(function() { this.field = new Blockly.FieldMultilineInput(initialValue); }); - testHelpers.runSetValueTests( + runSetValueTests( validValueTestCases, invalidValueTestCases, initialValue); test('With source block', function() { this.field.setSourceBlock(createTestBlock()); this.field.setValue('value'); - testHelpers.assertFieldValue(this.field, 'value'); + assertFieldValue(this.field, 'value'); }); }); }); @@ -156,7 +159,7 @@ suite('Multiline Input Fields', function() { createBlock: createBlockFn('bark bark\n bark bark bark\n bark bar bark bark\n')}, ]}, ]; - testHelpers.runCodeGenerationTestSuites(testSuites); + runCodeGenerationTestSuites(testSuites); }); suite('Serialization', function() { diff --git a/tests/mocha/field_number_test.js b/tests/mocha/field_number_test.js index 379bb5b83..fd23cc661 100644 --- a/tests/mocha/field_number_test.js +++ b/tests/mocha/field_number_test.js @@ -6,7 +6,10 @@ goog.module('Blockly.test.fieldNumber'); -const {defineRowBlock, sharedTestSetup, sharedTestTeardown, workspaceTeardown} = goog.require('Blockly.test.helpers'); +const {assertFieldValue, runConstructorSuiteTests, runFromJsonSuiteTests, runSetValueTests} = goog.require('Blockly.test.helpers.fields'); +const {defineRowBlock} = goog.require('Blockly.test.helpers.blockDefinitions'); +const {sharedTestSetup, sharedTestTeardown, workspaceTeardown} = goog.require('Blockly.test.helpers.setupTeardown'); +const {runTestCases} = goog.require('Blockly.test.helpers.common'); suite('Number Fields', function() { @@ -64,7 +67,7 @@ suite('Number Fields', function() { */ function assertNumberField(field, expectedMin, expectedMax, expectedPrecision, expectedValue) { - testHelpers.assertFieldValue(field, expectedValue); + assertFieldValue(field, expectedValue); chai.assert.equal(field.getMin(), expectedMin, 'Min'); chai.assert.equal(field.getMax(), expectedMax, 'Max'); chai.assert.equal( @@ -88,11 +91,11 @@ suite('Number Fields', function() { testCase.expectedValue, testCase.expectedValue); }; - testHelpers.runConstructorSuiteTests( + runConstructorSuiteTests( Blockly.FieldNumber, validValueTestCases, invalidValueTestCases, validTestCaseAssertField, assertFieldDefault); - testHelpers.runFromJsonSuiteTests( + runFromJsonSuiteTests( Blockly.FieldNumber, validValueTestCases, invalidValueTestCases, validTestCaseAssertField, assertFieldDefault); @@ -101,7 +104,7 @@ suite('Number Fields', function() { setup(function() { this.field = new Blockly.FieldNumber(); }); - testHelpers.runSetValueTests( + runSetValueTests( validValueTestCases, invalidValueTestCases, defaultFieldValue); }); suite('Value -> New Value', function() { @@ -109,7 +112,7 @@ suite('Number Fields', function() { setup(function() { this.field = new Blockly.FieldNumber(initialValue); }); - testHelpers.runSetValueTests( + runSetValueTests( validValueTestCases, invalidValueTestCases, initialValue); }); suite('Constraints', function() { @@ -127,11 +130,11 @@ suite('Number Fields', function() { expectedValue: 123}, ]; suite('Precision', function() { - testHelpers.runTestCases(testCases, function(testCase) { + runTestCases(testCases, function(testCase) { return function() { const field = Blockly.FieldNumber.fromJson(testCase.json); field.setValue(testCase.value); - testHelpers.assertFieldValue(field, testCase.expectedValue); + assertFieldValue(field, testCase.expectedValue); }; }); test('Null', function() { @@ -144,7 +147,7 @@ suite('Number Fields', function() { const field = Blockly.FieldNumber.fromJson(testCase.json); testCase.values.forEach(function(value, i) { field.setValue(value); - testHelpers.assertFieldValue( + assertFieldValue( field, testCase.expectedValues[i]); }); }; @@ -158,7 +161,7 @@ suite('Number Fields', function() { {title: '+10', json: {min: 10}, values: [-20, 0, 20], expectedValues: [10, 10, 20]}, ]; - testHelpers.runTestCases(testCases, setValueBoundsTestFn); + runTestCases(testCases, setValueBoundsTestFn); test('Null', function() { const field = Blockly.FieldNumber.fromJson({min: null}); chai.assert.equal(field.getMin(), -Infinity); @@ -173,7 +176,7 @@ suite('Number Fields', function() { {title: '+10', json: {max: 10}, values: [-20, 0, 20], expectedValues: [-20, 0, 10]}, ]; - testHelpers.runTestCases(testCases, setValueBoundsTestFn); + runTestCases(testCases, setValueBoundsTestFn); test('Null', function() { const field = Blockly.FieldNumber.fromJson({max: null}); chai.assert.equal(field.getMax(), Infinity); @@ -217,12 +220,12 @@ suite('Number Fields', function() { this.field.isBeingEdited_ = true; this.field.htmlInput_.value = String(suiteInfo.value); this.field.onHtmlInputChange_(null); - testHelpers.assertFieldValue( + assertFieldValue( this.field, suiteInfo.expectedValue, String(suiteInfo.value)); }); test('When Not Editing', function() { this.field.setValue(suiteInfo.value); - testHelpers.assertFieldValue(this.field, suiteInfo.expectedValue); + assertFieldValue(this.field, suiteInfo.expectedValue); }); }); }); diff --git a/tests/mocha/field_registry_test.js b/tests/mocha/field_registry_test.js index 0df2f6bd0..394081365 100644 --- a/tests/mocha/field_registry_test.js +++ b/tests/mocha/field_registry_test.js @@ -6,7 +6,8 @@ goog.module('Blockly.test.fieldRegistry'); -const {createDeprecationWarningStub, sharedTestSetup, sharedTestTeardown} = goog.require('Blockly.test.helpers'); +const {createDeprecationWarningStub} = goog.require('Blockly.test.helpers.warnings'); +const {sharedTestSetup, sharedTestTeardown} = goog.require('Blockly.test.helpers.setupTeardown'); suite('Field Registry', function() { diff --git a/tests/mocha/field_test.js b/tests/mocha/field_test.js index 0ba6a9e98..4d1887aa0 100644 --- a/tests/mocha/field_test.js +++ b/tests/mocha/field_test.js @@ -6,7 +6,8 @@ goog.module('Blockly.test.fieldTest'); -const {addBlockTypeToCleanup, addMessageToCleanup, createDeprecationWarningStub, sharedTestSetup, sharedTestTeardown, workspaceTeardown} = goog.require('Blockly.test.helpers'); +const {addBlockTypeToCleanup, addMessageToCleanup, sharedTestSetup, sharedTestTeardown, workspaceTeardown} = goog.require('Blockly.test.helpers.setupTeardown'); +const {createDeprecationWarningStub} = goog.require('Blockly.test.helpers.warnings'); suite('Abstract Fields', function() { diff --git a/tests/mocha/field_textinput_test.js b/tests/mocha/field_textinput_test.js index d95e31204..efd01d702 100644 --- a/tests/mocha/field_textinput_test.js +++ b/tests/mocha/field_textinput_test.js @@ -6,7 +6,9 @@ goog.module('Blockly.test.fieldTextInput'); -const {createTestBlock, defineRowBlock, sharedTestSetup, sharedTestTeardown, workspaceTeardown} = goog.require('Blockly.test.helpers'); +const {assertFieldValue, runConstructorSuiteTests, runFromJsonSuiteTests, runSetValueTests} = goog.require('Blockly.test.helpers.fields'); +const {createTestBlock, defineRowBlock} = goog.require('Blockly.test.helpers.blockDefinitions'); +const {sharedTestSetup, sharedTestTeardown, workspaceTeardown} = goog.require('Blockly.test.helpers.setupTeardown'); suite('Text Input Fields', function() { @@ -53,7 +55,7 @@ suite('Text Input Fields', function() { * @param {!Blockly.FieldTextInput} field The field to check. */ const assertFieldDefault = function(field) { - testHelpers.assertFieldValue(field, defaultFieldValue); + assertFieldValue(field, defaultFieldValue); }; /** * Asserts that the field properties are correct based on the test case. @@ -61,14 +63,14 @@ suite('Text Input Fields', function() { * @param {!FieldValueTestCase} testCase The test case. */ const validTestCaseAssertField = function(field, testCase) { - testHelpers.assertFieldValue(field, testCase.expectedValue); + assertFieldValue(field, testCase.expectedValue); }; - testHelpers.runConstructorSuiteTests( + runConstructorSuiteTests( Blockly.FieldTextInput, validValueTestCases, invalidValueTestCases, validTestCaseAssertField, assertFieldDefault); - testHelpers.runFromJsonSuiteTests( + runFromJsonSuiteTests( Blockly.FieldTextInput, validValueTestCases, invalidValueTestCases, validTestCaseAssertField, assertFieldDefault); @@ -77,12 +79,12 @@ suite('Text Input Fields', function() { setup(function() { this.field = new Blockly.FieldTextInput(); }); - testHelpers.runSetValueTests( + runSetValueTests( validValueTestCases, invalidValueTestCases, defaultFieldValue); test('With source block', function() { this.field.setSourceBlock(createTestBlock()); this.field.setValue('value'); - testHelpers.assertFieldValue(this.field, 'value'); + assertFieldValue(this.field, 'value'); }); }); suite('Value -> New Value', function() { @@ -90,12 +92,12 @@ suite('Text Input Fields', function() { setup(function() { this.field = new Blockly.FieldTextInput(initialValue); }); - testHelpers.runSetValueTests( + runSetValueTests( validValueTestCases, invalidValueTestCases, initialValue); test('With source block', function() { this.field.setSourceBlock(createTestBlock()); this.field.setValue('value'); - testHelpers.assertFieldValue(this.field, 'value'); + assertFieldValue(this.field, 'value'); }); }); }); @@ -136,12 +138,12 @@ suite('Text Input Fields', function() { this.field.isBeingEdited_ = true; this.field.htmlInput_.value = suiteInfo.value; this.field.onHtmlInputChange_(null); - testHelpers.assertFieldValue( + assertFieldValue( this.field, suiteInfo.expectedValue, suiteInfo.value); }); test('When Not Editing', function() { this.field.setValue(suiteInfo.value); - testHelpers.assertFieldValue(this.field, suiteInfo.expectedValue); + assertFieldValue(this.field, suiteInfo.expectedValue); }); }); }); diff --git a/tests/mocha/field_variable_test.js b/tests/mocha/field_variable_test.js index 4a93ccf41..2eafb6f42 100644 --- a/tests/mocha/field_variable_test.js +++ b/tests/mocha/field_variable_test.js @@ -6,7 +6,9 @@ goog.module('Blockly.test.fieldVariable'); -const {createGenUidStubWithReturns, createTestBlock, defineRowBlock, sharedTestSetup, sharedTestTeardown, workspaceTeardown} = goog.require('Blockly.test.helpers'); +const {assertFieldValue, runConstructorSuiteTests, runFromJsonSuiteTests, runSetValueTests} = goog.require('Blockly.test.helpers.fields'); +const {createGenUidStubWithReturns, sharedTestSetup, sharedTestTeardown, workspaceTeardown} = goog.require('Blockly.test.helpers.setupTeardown'); +const {createTestBlock, defineRowBlock} = goog.require('Blockly.test.helpers.blockDefinitions'); suite('Variable Fields', function() { @@ -83,7 +85,7 @@ suite('Variable Fields', function() { * @param {!Blockly.FieldVariable} field The field to check. */ const assertFieldDefault = function(field) { - testHelpers.assertFieldValue(field, FAKE_ID, defaultFieldName); + assertFieldValue(field, FAKE_ID, defaultFieldName); }; /** * Asserts that the field properties are correct based on the test case. @@ -91,15 +93,15 @@ suite('Variable Fields', function() { * @param {!FieldValueTestCase} testCase The test case. */ const validTestCaseAssertField = function(field, testCase) { - testHelpers.assertFieldValue(field, FAKE_ID, testCase.expectedText); + assertFieldValue(field, FAKE_ID, testCase.expectedText); }; - testHelpers.runConstructorSuiteTests( + runConstructorSuiteTests( Blockly.FieldVariable, validValueCreationTestCases, invalidValueCreationTestCases, validTestCaseAssertField, assertFieldDefault, customCreateWithJs); - testHelpers.runFromJsonSuiteTests( + runFromJsonSuiteTests( Blockly.FieldVariable, validValueCreationTestCases, invalidValueCreationTestCases, validTestCaseAssertField, assertFieldDefault, customCreateWithJson); @@ -149,7 +151,7 @@ suite('Variable Fields', function() { teardown(function() { console.warn = this.nativeConsoleWarn; }); - testHelpers.runSetValueTests(validValueTestCases, invalidValueTestCases, + runSetValueTests(validValueTestCases, invalidValueTestCases, FAKE_ID, defaultFieldName); }); @@ -215,7 +217,7 @@ suite('Variable Fields', function() { }); test('New Value', function() { this.variableField.setValue('id2'); - testHelpers.assertFieldValue(this.variableField, 'id1', 'name1'); + assertFieldValue(this.variableField, 'id1', 'name1'); }); }); suite('Force \'id\' ID Validator', function() { @@ -228,7 +230,7 @@ suite('Variable Fields', function() { // Must create the var so that the field doesn't throw an error. this.workspace.createVariable('thing2', null, 'other2'); this.variableField.setValue('other2'); - testHelpers.assertFieldValue(this.variableField, 'id2', 'name2'); + assertFieldValue(this.variableField, 'id2', 'name2'); }); }); suite('Returns Undefined Validator', function() { @@ -237,7 +239,7 @@ suite('Variable Fields', function() { }); test('New Value', function() { this.variableField.setValue('id2'); - testHelpers.assertFieldValue(this.variableField, 'id2', 'name2'); + assertFieldValue(this.variableField, 'id2', 'name2'); }); }); }); diff --git a/tests/mocha/flyout_test.js b/tests/mocha/flyout_test.js index 8f3e56693..8fbc38659 100644 --- a/tests/mocha/flyout_test.js +++ b/tests/mocha/flyout_test.js @@ -6,8 +6,8 @@ goog.module('Blockly.test.flyout'); -const {defineStackBlock, sharedTestSetup, sharedTestTeardown, workspaceTeardown} = goog.require('Blockly.test.helpers'); -const {getBasicToolbox, getChildItem, getCollapsibleItem, getDeeplyNestedJSON, getInjectedToolbox, getNonCollapsibleItem, getProperSimpleJson, getSeparator, getSimpleJson, getXmlArray} = goog.require('Blockly.test.toolboxHelpers'); +const {defineStackBlock, sharedTestSetup, sharedTestTeardown, workspaceTeardown} = goog.require('Blockly.test.helpers.setupTeardown'); +const {getBasicToolbox, getChildItem, getCollapsibleItem, getDeeplyNestedJSON, getInjectedToolbox, getNonCollapsibleItem, getProperSimpleJson, getSeparator, getSimpleJson, getXmlArray} = goog.require('Blockly.test.helpers.toolboxDefinitions'); suite('Flyout', function() { diff --git a/tests/mocha/generator_test.js b/tests/mocha/generator_test.js index 2231263d2..4167d44f6 100644 --- a/tests/mocha/generator_test.js +++ b/tests/mocha/generator_test.js @@ -11,7 +11,7 @@ goog.require('Blockly.JavaScript'); goog.require('Blockly.Lua'); goog.require('Blockly.PHP'); goog.require('Blockly.Python'); -const {sharedTestSetup, sharedTestTeardown} = goog.require('Blockly.test.helpers'); +const {sharedTestSetup, sharedTestTeardown} = goog.require('Blockly.test.helpers.setupTeardown'); suite('Generator', function() { diff --git a/tests/mocha/gesture_test.js b/tests/mocha/gesture_test.js index 16a6cadda..6e21287de 100644 --- a/tests/mocha/gesture_test.js +++ b/tests/mocha/gesture_test.js @@ -6,8 +6,11 @@ goog.module('Blockly.test.gesture'); +const {assertEventFired, assertEventNotFired} = goog.require('Blockly.test.helpers.events'); +const {defineBasicBlockWithField} = goog.require('Blockly.test.helpers.blockDefinitions'); +const {dispatchPointerEvent} = goog.require('Blockly.test.helpers.userInput'); const eventUtils = goog.require('Blockly.Events.utils'); -const {assertEventFired, assertEventNotFired, defineBasicBlockWithField, dispatchPointerEvent, sharedTestSetup, sharedTestTeardown} = goog.require('Blockly.test.helpers'); +const {sharedTestSetup, sharedTestTeardown} = goog.require('Blockly.test.helpers.setupTeardown'); suite('Gesture', function() { diff --git a/tests/mocha/index.html b/tests/mocha/index.html index 7d734de53..d4d403314 100644 --- a/tests/mocha/index.html +++ b/tests/mocha/index.html @@ -24,7 +24,6 @@ - @@ -173,10 +173,16 @@ diff --git a/tests/mocha/run_mocha_tests_in_browser.js b/tests/mocha/run_mocha_tests_in_browser.js index d4dc83fbe..217c9992b 100644 --- a/tests/mocha/run_mocha_tests_in_browser.js +++ b/tests/mocha/run_mocha_tests_in_browser.js @@ -61,8 +61,18 @@ async function runMochaTestsInBrowser() { const elem = await browser.$('#failureCount'); const numOfFailure = await elem.getAttribute('tests_failed'); + if (numOfFailure > 0) { + console.log('============Blockly Mocha Test Failures================') + const failureMessagesEls = await browser.$$('#failureMessages p'); + if (!failureMessagesEls.length) { + console.log('There is at least one test failure, but no messages reported. Mocha may be failing because no tests are being run.'); + } + for (let el of failureMessagesEls) { + console.log(await el.getText()); + } + } + console.log('============Blockly Mocha Test Summary================='); - console.log(numOfFailure); console.log(numOfFailure + ' tests failed'); console.log('============Blockly Mocha Test Summary================='); if (parseInt(numOfFailure) !== 0) { From c1004be1f24debe1df1566e6067cf2f6769d51aa Mon Sep 17 00:00:00 2001 From: Beka Westberg Date: Tue, 8 Mar 2022 07:21:06 -0800 Subject: [PATCH 099/128] fix: convert the common renderer to an ES6 class (#5978) * fix: run conversion script on renderer * fix: cleanup from conversion script * fix: format --- core/renderers/common/renderer.js | 480 +++++++++++++++--------------- 1 file changed, 241 insertions(+), 239 deletions(-) diff --git a/core/renderers/common/renderer.js b/core/renderers/common/renderer.js index da754653f..39b57aec6 100644 --- a/core/renderers/common/renderer.js +++ b/core/renderers/common/renderer.js @@ -47,257 +47,259 @@ const {WorkspaceSvg} = goog.requireType('Blockly.WorkspaceSvg'); /** * The base class for a block renderer. - * @param {string} name The renderer name. - * @package - * @constructor * @implements {IRegistrable} - * @alias Blockly.blockRendering.Renderer */ -const Renderer = function(name) { +class Renderer { /** - * The renderer name. - * @type {string} + * @param {string} name The renderer name. + * @package + * @alias Blockly.blockRendering.Renderer + */ + constructor(name) { + /** + * The renderer name. + * @type {string} + * @package + */ + this.name = name; + + /** + * The renderer's constant provider. + * @type {ConstantProvider} + * @private + */ + this.constants_ = null; + + /** + * Rendering constant overrides, passed in through options. + * @type {?Object} + * @package + */ + this.overrides = null; + } + + /** + * Gets the class name that identifies this renderer. + * @return {string} The CSS class name. * @package */ - this.name = name; + getClassName() { + return this.name + '-renderer'; + } /** - * The renderer's constant provider. - * @type {ConstantProvider} - * @private - */ - this.constants_ = null; - - /** - * Rendering constant overrides, passed in through options. - * @type {?Object} + * Initialize the renderer. + * @param {!Theme} theme The workspace theme object. + * @param {Object=} opt_rendererOverrides Rendering constant overrides. * @package */ - this.overrides = null; -}; - -/** - * Gets the class name that identifies this renderer. - * @return {string} The CSS class name. - * @package - */ -Renderer.prototype.getClassName = function() { - return this.name + '-renderer'; -}; - -/** - * Initialize the renderer. - * @param {!Theme} theme The workspace theme object. - * @param {Object=} opt_rendererOverrides Rendering constant overrides. - * @package - */ -Renderer.prototype.init = function(theme, opt_rendererOverrides) { - this.constants_ = this.makeConstants_(); - if (opt_rendererOverrides) { - this.overrides = opt_rendererOverrides; - object.mixin(this.constants_, opt_rendererOverrides); - } - this.constants_.setTheme(theme); - this.constants_.init(); -}; - -/** - * Create any DOM elements that this renderer needs. - * @param {!SVGElement} svg The root of the workspace's SVG. - * @param {!Theme} theme The workspace theme object. - * @package - */ -Renderer.prototype.createDom = function(svg, theme) { - this.constants_.createDom( - svg, this.name + '-' + theme.name, - '.' + this.getClassName() + '.' + theme.getClassName()); -}; - -/** - * Refresh the renderer after a theme change. - * @param {!SVGElement} svg The root of the workspace's SVG. - * @param {!Theme} theme The workspace theme object. - * @package - */ -Renderer.prototype.refreshDom = function(svg, theme) { - const previousConstants = this.getConstants(); - previousConstants.dispose(); - this.constants_ = this.makeConstants_(); - if (this.overrides) { - object.mixin(this.constants_, this.overrides); - } - // Ensure the constant provider's random identifier does not change. - this.constants_.randomIdentifier = previousConstants.randomIdentifier; - this.constants_.setTheme(theme); - this.constants_.init(); - this.createDom(svg, theme); -}; - -/** - * Dispose of this renderer. - * Delete all DOM elements that this renderer and its constants created. - * @package - */ -Renderer.prototype.dispose = function() { - if (this.constants_) { - this.constants_.dispose(); - } -}; - -/** - * Create a new instance of the renderer's constant provider. - * @return {!ConstantProvider} The constant provider. - * @protected - */ -Renderer.prototype.makeConstants_ = function() { - return new ConstantProvider(); -}; - -/** - * Create a new instance of the renderer's render info object. - * @param {!BlockSvg} block The block to measure. - * @return {!RenderInfo} The render info object. - * @protected - */ -Renderer.prototype.makeRenderInfo_ = function(block) { - return new RenderInfo(this, block); -}; - -/** - * Create a new instance of the renderer's drawer. - * @param {!BlockSvg} block The block to render. - * @param {!RenderInfo} info An object containing all - * information needed to render this block. - * @return {!Drawer} The drawer. - * @protected - */ -Renderer.prototype.makeDrawer_ = function(block, info) { - return new Drawer(block, info); -}; - -/** - * Create a new instance of the renderer's debugger. - * @return {!Debug} The renderer debugger. - * @suppress {strictModuleDepCheck} Debug renderer only included in playground. - * @protected - */ -Renderer.prototype.makeDebugger_ = function() { - const {Debug} = goog.module.get('Blockly.blockRendering.Debug'); - if (!Debug) { - throw Error('Missing require for Blockly.blockRendering.Debug'); - } - return new Debug(this.getConstants()); -}; - -/** - * Create a new instance of the renderer's marker drawer. - * @param {!WorkspaceSvg} workspace The workspace the marker belongs to. - * @param {!Marker} marker The marker. - * @return {!MarkerSvg} The object in charge of drawing - * the marker. - * @package - */ -Renderer.prototype.makeMarkerDrawer = function(workspace, marker) { - return new MarkerSvg(workspace, this.getConstants(), marker); -}; - -/** - * Create a new instance of a renderer path object. - * @param {!SVGElement} root The root SVG element. - * @param {!Theme.BlockStyle} style The style object to use for - * colouring. - * @return {!IPathObject} The renderer path object. - * @package - */ -Renderer.prototype.makePathObject = function(root, style) { - return new PathObject( - root, style, /** @type {!ConstantProvider} */ (this.constants_)); -}; - -/** - * Get the current renderer's constant provider. We assume that when this is - * called, the renderer has already been initialized. - * @return {!ConstantProvider} The constant provider. - * @package - */ -Renderer.prototype.getConstants = function() { - return /** @type {!ConstantProvider} */ (this.constants_); -}; - -/** - * Determine whether or not to highlight a connection. - * @param {Connection} _conn The connection to determine whether or not - * to highlight. - * @return {boolean} True if we should highlight the connection. - * @package - */ -Renderer.prototype.shouldHighlightConnection = function(_conn) { - return true; -}; - -/** - * Checks if an orphaned block can connect to the "end" of the topBlock's - * block-clump. If the clump is a row the end is the last input. If the clump - * is a stack, the end is the last next connection. If the clump is neither, - * then this returns false. - * @param {!BlockSvg} topBlock The top block of the block clump we want to try - * and connect to. - * @param {!BlockSvg} orphanBlock The orphan block that wants to find - * a home. - * @param {number} localType The type of the connection being dragged. - * @return {boolean} Whether there is a home for the orphan or not. - * @package - */ -Renderer.prototype.orphanCanConnectAtEnd = function( - topBlock, orphanBlock, localType) { - const orphanConnection = - (localType === ConnectionType.OUTPUT_VALUE ? - orphanBlock.outputConnection : - orphanBlock.previousConnection); - return !!Connection.getConnectionForOrphanedConnection( - /** @type {!Block} **/ (topBlock), - /** @type {!Connection} **/ (orphanConnection)); -}; - -/** - * Chooses a connection preview method based on the available connection, the - * current dragged connection, and the block being dragged. - * @param {!RenderedConnection} closest The available connection. - * @param {!RenderedConnection} local The connection currently being - * dragged. - * @param {!BlockSvg} topBlock The block currently being dragged. - * @return {!InsertionMarkerManager.PREVIEW_TYPE} The preview type - * to display. - * @package - */ -Renderer.prototype.getConnectionPreviewMethod = function( - closest, local, topBlock) { - if (local.type === ConnectionType.OUTPUT_VALUE || - local.type === ConnectionType.PREVIOUS_STATEMENT) { - if (!closest.isConnected() || - this.orphanCanConnectAtEnd( - topBlock, - /** @type {!BlockSvg} */ (closest.targetBlock()), local.type)) { - return InsertionMarkerManager.PREVIEW_TYPE.INSERTION_MARKER; + init(theme, opt_rendererOverrides) { + this.constants_ = this.makeConstants_(); + if (opt_rendererOverrides) { + this.overrides = opt_rendererOverrides; + object.mixin(this.constants_, opt_rendererOverrides); } - return InsertionMarkerManager.PREVIEW_TYPE.REPLACEMENT_FADE; + this.constants_.setTheme(theme); + this.constants_.init(); } - return InsertionMarkerManager.PREVIEW_TYPE.INSERTION_MARKER; -}; - -/** - * Render the block. - * @param {!BlockSvg} block The block to render. - * @package - */ -Renderer.prototype.render = function(block) { - if (debug.isDebuggerEnabled() && !block.renderingDebugger) { - block.renderingDebugger = this.makeDebugger_(); + /** + * Create any DOM elements that this renderer needs. + * @param {!SVGElement} svg The root of the workspace's SVG. + * @param {!Theme} theme The workspace theme object. + * @package + */ + createDom(svg, theme) { + this.constants_.createDom( + svg, this.name + '-' + theme.name, + '.' + this.getClassName() + '.' + theme.getClassName()); } - const info = this.makeRenderInfo_(block); - info.measure(); - this.makeDrawer_(block, info).draw(); -}; + + /** + * Refresh the renderer after a theme change. + * @param {!SVGElement} svg The root of the workspace's SVG. + * @param {!Theme} theme The workspace theme object. + * @package + */ + refreshDom(svg, theme) { + const previousConstants = this.getConstants(); + previousConstants.dispose(); + this.constants_ = this.makeConstants_(); + if (this.overrides) { + object.mixin(this.constants_, this.overrides); + } + // Ensure the constant provider's random identifier does not change. + this.constants_.randomIdentifier = previousConstants.randomIdentifier; + this.constants_.setTheme(theme); + this.constants_.init(); + this.createDom(svg, theme); + } + + /** + * Dispose of this renderer. + * Delete all DOM elements that this renderer and its constants created. + * @package + */ + dispose() { + if (this.constants_) { + this.constants_.dispose(); + } + } + + /** + * Create a new instance of the renderer's constant provider. + * @return {!ConstantProvider} The constant provider. + * @protected + */ + makeConstants_() { + return new ConstantProvider(); + } + + /** + * Create a new instance of the renderer's render info object. + * @param {!BlockSvg} block The block to measure. + * @return {!RenderInfo} The render info object. + * @protected + */ + makeRenderInfo_(block) { + return new RenderInfo(this, block); + } + + /** + * Create a new instance of the renderer's drawer. + * @param {!BlockSvg} block The block to render. + * @param {!RenderInfo} info An object containing all + * information needed to render this block. + * @return {!Drawer} The drawer. + * @protected + */ + makeDrawer_(block, info) { + return new Drawer(block, info); + } + + /** + * Create a new instance of the renderer's debugger. + * @return {!Debug} The renderer debugger. + * @suppress {strictModuleDepCheck} Debug renderer only included in + * playground. + * @protected + */ + makeDebugger_() { + const {Debug} = goog.module.get('Blockly.blockRendering.Debug'); + if (!Debug) { + throw Error('Missing require for Blockly.blockRendering.Debug'); + } + return new Debug(this.getConstants()); + } + + /** + * Create a new instance of the renderer's marker drawer. + * @param {!WorkspaceSvg} workspace The workspace the marker belongs to. + * @param {!Marker} marker The marker. + * @return {!MarkerSvg} The object in charge of drawing + * the marker. + * @package + */ + makeMarkerDrawer(workspace, marker) { + return new MarkerSvg(workspace, this.getConstants(), marker); + } + + /** + * Create a new instance of a renderer path object. + * @param {!SVGElement} root The root SVG element. + * @param {!Theme.BlockStyle} style The style object to use for + * colouring. + * @return {!IPathObject} The renderer path object. + * @package + */ + makePathObject(root, style) { + return new PathObject( + root, style, /** @type {!ConstantProvider} */ (this.constants_)); + } + + /** + * Get the current renderer's constant provider. We assume that when this is + * called, the renderer has already been initialized. + * @return {!ConstantProvider} The constant provider. + * @package + */ + getConstants() { + return /** @type {!ConstantProvider} */ (this.constants_); + } + + /** + * Determine whether or not to highlight a connection. + * @param {Connection} _conn The connection to determine whether or not + * to highlight. + * @return {boolean} True if we should highlight the connection. + * @package + */ + shouldHighlightConnection(_conn) { + return true; + } + + /** + * Checks if an orphaned block can connect to the "end" of the topBlock's + * block-clump. If the clump is a row the end is the last input. If the clump + * is a stack, the end is the last next connection. If the clump is neither, + * then this returns false. + * @param {!BlockSvg} topBlock The top block of the block clump we want to try + * and connect to. + * @param {!BlockSvg} orphanBlock The orphan block that wants to find + * a home. + * @param {number} localType The type of the connection being dragged. + * @return {boolean} Whether there is a home for the orphan or not. + * @package + */ + orphanCanConnectAtEnd(topBlock, orphanBlock, localType) { + const orphanConnection = + (localType === ConnectionType.OUTPUT_VALUE ? + orphanBlock.outputConnection : + orphanBlock.previousConnection); + return !!Connection.getConnectionForOrphanedConnection( + /** @type {!Block} **/ (topBlock), + /** @type {!Connection} **/ (orphanConnection)); + } + + /** + * Chooses a connection preview method based on the available connection, the + * current dragged connection, and the block being dragged. + * @param {!RenderedConnection} closest The available connection. + * @param {!RenderedConnection} local The connection currently being + * dragged. + * @param {!BlockSvg} topBlock The block currently being dragged. + * @return {!InsertionMarkerManager.PREVIEW_TYPE} The preview type + * to display. + * @package + */ + getConnectionPreviewMethod(closest, local, topBlock) { + if (local.type === ConnectionType.OUTPUT_VALUE || + local.type === ConnectionType.PREVIOUS_STATEMENT) { + if (!closest.isConnected() || + this.orphanCanConnectAtEnd( + topBlock, + /** @type {!BlockSvg} */ (closest.targetBlock()), local.type)) { + return InsertionMarkerManager.PREVIEW_TYPE.INSERTION_MARKER; + } + return InsertionMarkerManager.PREVIEW_TYPE.REPLACEMENT_FADE; + } + + return InsertionMarkerManager.PREVIEW_TYPE.INSERTION_MARKER; + } + + /** + * Render the block. + * @param {!BlockSvg} block The block to render. + * @package + */ + render(block) { + if (debug.isDebuggerEnabled() && !block.renderingDebugger) { + block.renderingDebugger = this.makeDebugger_(); + } + const info = this.makeRenderInfo_(block); + info.measure(); + this.makeDrawer_(block, info).draw(); + } +} exports.Renderer = Renderer; From e11b5834e5e4e8fe991be32afb08eafa7c8adffd Mon Sep 17 00:00:00 2001 From: Christopher Allen Date: Tue, 8 Mar 2022 23:20:19 +0000 Subject: [PATCH 100/128] fix(tests): Enable `--debug` for `test:compile:advanced`; fix some errors (and demote the rest to warnings) (#5983) * refactor(tests): Migrate tests/compile/main.js to goog.module * feat(tests): Enable --debug for test:compile:advanced; demote errors * Enable the --debug flag when running the buildAdvancedCompilationTest gulp task. * Remove partialAlias diagnostic group from `JSC_ERROR`, demoting JSC_PARTIAL_NAMESPACE to warning. Reverts "Revert 'fix(tests): Enable --debug for test:compile:advanced; fix some errors (#5959)'". --- package.json | 2 +- scripts/gulpfiles/build_tasks.js | 2 +- tests/compile/main.js | 30 ++++++++++++++++++++++-------- 3 files changed, 24 insertions(+), 10 deletions(-) diff --git a/package.json b/package.json index 88cc6c0ef..149e38a61 100644 --- a/package.json +++ b/package.json @@ -51,7 +51,7 @@ "test": "tests/run_all_tests.sh", "test:generators": "tests/scripts/run_generators.sh", "test:mocha:interactive": "http-server ./ -o /tests/mocha/index.html -c-1", - "test:compile:advanced": "gulp buildAdvancedCompilationTest", + "test:compile:advanced": "gulp buildAdvancedCompilationTest --debug", "typings": "gulp typings", "updateGithubPages": "gulp gitUpdateGithubPages" }, diff --git a/scripts/gulpfiles/build_tasks.js b/scripts/gulpfiles/build_tasks.js index b95cb7c52..b0dd9af2b 100644 --- a/scripts/gulpfiles/build_tasks.js +++ b/scripts/gulpfiles/build_tasks.js @@ -209,7 +209,7 @@ var JSCOMP_ERROR = [ 'moduleLoad', 'msgDescriptions', 'nonStandardJsDocs', - 'partialAlias', + // 'partialAlias', // Don't want this to be an error yet; only warning. // 'polymer', // Not applicable. // 'reportUnknownTypes', // VERY verbose. // 'strictCheckTypes', // Use --strict to enable. diff --git a/tests/compile/main.js b/tests/compile/main.js index 586f4ce36..b5d20a770 100644 --- a/tests/compile/main.js +++ b/tests/compile/main.js @@ -4,19 +4,33 @@ * SPDX-License-Identifier: Apache-2.0 */ -goog.provide('Main'); +goog.module('Main'); + // Core // Either require 'Blockly.requires', or just the components you use: -goog.require('Blockly'); +/* eslint-disable-next-line no-unused-vars */ +const {BlocklyOptions} = goog.requireType('Blockly.BlocklyOptions'); +const {inject} = goog.require('Blockly.inject'); +/** @suppress {extraRequire} */ goog.require('Blockly.geras.Renderer'); +/** @suppress {extraRequire} */ goog.require('Blockly.VerticalFlyout'); // Blocks -goog.require('Blockly.libraryBlocks'); +/** @suppress {extraRequire} */ +goog.require('Blockly.libraryBlocks.logic'); +/** @suppress {extraRequire} */ +goog.require('Blockly.libraryBlocks.loops'); +/** @suppress {extraRequire} */ +goog.require('Blockly.libraryBlocks.math'); +/** @suppress {extraRequire} */ +goog.require('Blockly.libraryBlocks.texts'); +/** @suppress {extraRequire} */ goog.require('Blockly.libraryBlocks.testBlocks'); -Main.init = function() { - Blockly.inject('blocklyDiv', { - 'toolbox': document.getElementById('toolbox') - }); + +function init() { + inject('blocklyDiv', /** @type {BlocklyOptions} */ ({ + 'toolbox': document.getElementById('toolbox') + })); }; -window.addEventListener('load', Main.init); +window.addEventListener('load', init); From 3740d51089d59bab2a4a86b1a08ba0fd35fdbf82 Mon Sep 17 00:00:00 2001 From: Rachel Fenichel Date: Tue, 8 Mar 2022 16:00:31 -0800 Subject: [PATCH 101/128] chore: makes types of divs more specific (#5988) * chore: cast to a more specific type when creating a div * chore: make types more specific for divs * chore: format --- core/dropdowndiv.js | 12 ++++++------ core/inject.js | 3 ++- core/menu.js | 2 +- core/menuitem.js | 11 +++++++---- core/toolbox/category.js | 29 ++++++++++++++++------------ core/toolbox/collapsible_category.js | 9 +++++---- core/toolbox/separator.js | 11 ++++++----- core/toolbox/toolbox.js | 22 +++++++++++---------- core/tooltip.js | 10 +++++----- core/utils/dom.js | 4 ++-- core/widgetdiv.js | 8 ++++---- 11 files changed, 67 insertions(+), 54 deletions(-) diff --git a/core/dropdowndiv.js b/core/dropdowndiv.js index 9c4661bae..bd6e8afea 100644 --- a/core/dropdowndiv.js +++ b/core/dropdowndiv.js @@ -103,19 +103,19 @@ let themeClassName = ''; /** * The content element. - * @type {!Element} + * @type {!HTMLDivElement} */ let div; /** * The content element. - * @type {!Element} + * @type {!HTMLDivElement} */ let content; /** * The arrow element. - * @type {!Element} + * @type {!HTMLDivElement} */ let arrow; @@ -177,16 +177,16 @@ const createDom = function() { if (div) { return; // Already created. } - div = document.createElement('div'); + div = /** @type {!HTMLDivElement} */ (document.createElement('div')); div.className = 'blocklyDropDownDiv'; const parentDiv = common.getParentContainer() || document.body; parentDiv.appendChild(div); - content = document.createElement('div'); + content = /** @type {!HTMLDivElement} */ (document.createElement('div')); content.className = 'blocklyDropDownContent'; div.appendChild(content); - arrow = document.createElement('div'); + arrow = /** @type {!HTMLDivElement} */ (document.createElement('div')); arrow.className = 'blocklyDropDownArrow'; div.appendChild(arrow); diff --git a/core/inject.js b/core/inject.js index 6911bf4f8..6c7094428 100644 --- a/core/inject.js +++ b/core/inject.js @@ -59,7 +59,8 @@ const inject = function(container, opt_options) { } const options = new Options(opt_options || (/** @type {!BlocklyOptions} */ ({}))); - const subContainer = document.createElement('div'); + const subContainer = + /** @type {!HTMLDivElement} */ (document.createElement('div')); subContainer.className = 'injectionDiv'; subContainer.tabIndex = 0; aria.setState(subContainer, aria.State.LABEL, Msg['WORKSPACE_ARIA_LABEL']); diff --git a/core/menu.js b/core/menu.js index b4e3e1377..b1b90a7e8 100644 --- a/core/menu.js +++ b/core/menu.js @@ -98,7 +98,7 @@ const Menu = class { /** * The menu's root DOM element. - * @type {?Element} + * @type {?HTMLDivElement} * @private */ this.element_ = null; diff --git a/core/menuitem.js b/core/menuitem.js index 8d86ab1ab..b4bd2ed30 100644 --- a/core/menuitem.js +++ b/core/menuitem.js @@ -54,7 +54,7 @@ const MenuItem = class { /** * The DOM element for the menu item. - * @type {?Element} + * @type {?HTMLDivElement} * @private */ this.element_ = null; @@ -107,7 +107,8 @@ const MenuItem = class { * @return {!Element} Completed DOM. */ createDom() { - const element = document.createElement('div'); + const element = + /** @type {!HTMLDivElement} */ (document.createElement('div')); element.id = idGenerator.getNextUniqueId(); this.element_ = element; @@ -121,11 +122,13 @@ const MenuItem = class { '') + (this.rightToLeft_ ? 'blocklyMenuItemRtl goog-menuitem-rtl ' : ''); - const content = document.createElement('div'); + const content = + /** @type {!HTMLDivElement} */ (document.createElement('div')); content.className = 'blocklyMenuItemContent goog-menuitem-content'; // Add a checkbox for checkable menu items. if (this.checkable_) { - const checkbox = document.createElement('div'); + const checkbox = + /** @type {!HTMLDivElement} */ (document.createElement('div')); checkbox.className = 'blocklyMenuItemCheckbox goog-menuitem-checkbox'; content.appendChild(checkbox); } diff --git a/core/toolbox/category.js b/core/toolbox/category.js index ddb202bbf..47165b637 100644 --- a/core/toolbox/category.js +++ b/core/toolbox/category.js @@ -67,21 +67,21 @@ class ToolboxCategory extends ToolboxItem { /** * The html container for the category. - * @type {?Element} + * @type {?HTMLDivElement} * @protected */ this.htmlDiv_ = null; /** * The html element for the category row. - * @type {?Element} + * @type {?HTMLDivElement} * @protected */ this.rowDiv_ = null; /** * The html element that holds children elements of the category row. - * @type {?Element} + * @type {?HTMLDivElement} * @protected */ this.rowContents_ = null; @@ -204,16 +204,18 @@ class ToolboxCategory extends ToolboxItem { /** * Creates the DOM for the category. - * @return {!Element} The parent element for the category. + * @return {!HTMLDivElement} The parent element for the category. * @protected */ createDom_() { this.htmlDiv_ = this.createContainer_(); aria.setRole(this.htmlDiv_, aria.Role.TREEITEM); aria.setState( - /** @type {!Element} */ (this.htmlDiv_), aria.State.SELECTED, false); + /** @type {!HTMLDivElement} */ (this.htmlDiv_), aria.State.SELECTED, + false); aria.setState( - /** @type {!Element} */ (this.htmlDiv_), aria.State.LEVEL, this.level_); + /** @type {!HTMLDivElement} */ (this.htmlDiv_), aria.State.LEVEL, + this.level_); this.rowDiv_ = this.createRowContainer_(); this.rowDiv_.style.pointerEvents = 'auto'; @@ -240,11 +242,12 @@ class ToolboxCategory extends ToolboxItem { /** * Creates the container that holds the row and any subcategories. - * @return {!Element} The div that holds the icon and the label. + * @return {!HTMLDivElement} The div that holds the icon and the label. * @protected */ createContainer_() { - const container = document.createElement('div'); + const container = + /** @type {!HTMLDivElement} */ (document.createElement('div')); dom.addClass(container, this.cssConfig_['container']); return container; } @@ -252,11 +255,12 @@ class ToolboxCategory extends ToolboxItem { /** * Creates the parent of the contents container. All clicks will happen on * this div. - * @return {!Element} The div that holds the contents container. + * @return {!HTMLDivElement} The div that holds the contents container. * @protected */ createRowContainer_() { - const rowDiv = document.createElement('div'); + const rowDiv = + /** @type {!HTMLDivElement} */ (document.createElement('div')); dom.addClass(rowDiv, this.cssConfig_['row']); let nestedPadding = ToolboxCategory.nestedPadding * this.getLevel(); nestedPadding = nestedPadding.toString() + 'px'; @@ -268,11 +272,12 @@ class ToolboxCategory extends ToolboxItem { /** * Creates the container for the label and icon. * This is necessary so we can set all subcategory pointer events to none. - * @return {!Element} The div that holds the icon and the label. + * @return {!HTMLDivElement} The div that holds the icon and the label. * @protected */ createRowContentsContainer_() { - const contentsContainer = document.createElement('div'); + const contentsContainer = + /** @type {!HTMLDivElement} */ (document.createElement('div')); dom.addClass(contentsContainer, this.cssConfig_['rowcontentcontainer']); return contentsContainer; } diff --git a/core/toolbox/collapsible_category.js b/core/toolbox/collapsible_category.js index 3281e8771..032a3f6c2 100644 --- a/core/toolbox/collapsible_category.js +++ b/core/toolbox/collapsible_category.js @@ -47,7 +47,7 @@ class CollapsibleToolboxCategory extends ToolboxCategory { /** * Container for any child categories. - * @type {?Element} + * @type {?HTMLDivElement} * @protected */ this.subcategoriesDiv_ = null; @@ -170,11 +170,12 @@ class CollapsibleToolboxCategory extends ToolboxCategory { /** * Create the DOM for all subcategories. * @param {!Array} subcategories The subcategories. - * @return {!Element} The div holding all the subcategories. + * @return {!HTMLDivElement} The div holding all the subcategories. * @protected */ createSubCategoriesDom_(subcategories) { - const contentsContainer = document.createElement('div'); + const contentsContainer = + /** @type {!HTMLDivElement} */ (document.createElement('div')); dom.addClass(contentsContainer, this.cssConfig_['contents']); for (let i = 0; i < subcategories.length; i++) { @@ -207,7 +208,7 @@ class CollapsibleToolboxCategory extends ToolboxCategory { this.closeIcon_(this.iconDom_); } aria.setState( - /** @type {!Element} */ (this.htmlDiv_), aria.State.EXPANDED, + /** @type {!HTMLDivElement} */ (this.htmlDiv_), aria.State.EXPANDED, isExpanded); this.parentToolbox_.handleToolboxItemResize(); diff --git a/core/toolbox/separator.js b/core/toolbox/separator.js index ae6c38673..9759286d1 100644 --- a/core/toolbox/separator.js +++ b/core/toolbox/separator.js @@ -48,7 +48,7 @@ class ToolboxSeparator extends ToolboxItem { this.cssConfig_ = {'container': 'blocklyTreeSeparator'}; /** - * @type {?Element} + * @type {?HTMLDivElement} * @private */ this.htmlDiv_ = null; @@ -66,11 +66,12 @@ class ToolboxSeparator extends ToolboxItem { /** * Creates the DOM for a separator. - * @return {!Element} The parent element for the separator. + * @return {!HTMLDivElement} The parent element for the separator. * @protected */ createDom_() { - const container = document.createElement('div'); + const container = + /** @type {!HTMLDivElement} */ (document.createElement('div')); dom.addClass(container, this.cssConfig_['container']); this.htmlDiv_ = container; return container; @@ -80,14 +81,14 @@ class ToolboxSeparator extends ToolboxItem { * @override */ getDiv() { - return /** @type {!Element} */ (this.htmlDiv_); + return /** @type {!HTMLDivElement} */ (this.htmlDiv_); } /** * @override */ dispose() { - dom.removeNode(/** @type {!Element} */ (this.htmlDiv_)); + dom.removeNode(/** @type {!HTMLDivElement} */ (this.htmlDiv_)); } } diff --git a/core/toolbox/toolbox.js b/core/toolbox/toolbox.js index 8219099f4..01181e82f 100644 --- a/core/toolbox/toolbox.js +++ b/core/toolbox/toolbox.js @@ -107,13 +107,13 @@ class Toolbox extends DeleteArea { /** * The html container for the toolbox. - * @type {?Element} + * @type {?HTMLDivElement} */ this.HtmlDiv = null; /** * The html container for the contents of a toolbox. - * @type {?Element} + * @type {?HTMLDivElement} * @protected */ this.contentsDiv_ = null; @@ -241,7 +241,7 @@ class Toolbox extends DeleteArea { /** * Creates the DOM for the toolbox. * @param {!WorkspaceSvg} workspace The workspace this toolbox is on. - * @return {!Element} The HTML container for the toolbox. + * @return {!HTMLDivElement} The HTML container for the toolbox. * @protected */ createDom_(workspace) { @@ -262,11 +262,12 @@ class Toolbox extends DeleteArea { /** * Creates the container div for the toolbox. - * @return {!Element} The HTML container for the toolbox. + * @return {!HTMLDivElement} The HTML container for the toolbox. * @protected */ createContainer_() { - const toolboxContainer = document.createElement('div'); + const toolboxContainer = + /** @type {!HTMLDivElement} */ (document.createElement('div')); toolboxContainer.setAttribute('layout', this.isHorizontal() ? 'h' : 'v'); dom.addClass(toolboxContainer, 'blocklyToolboxDiv'); dom.addClass(toolboxContainer, 'blocklyNonSelectable'); @@ -276,11 +277,12 @@ class Toolbox extends DeleteArea { /** * Creates the container for all the contents in the toolbox. - * @return {!Element} The HTML container for the toolbox contents. + * @return {!HTMLDivElement} The HTML container for the toolbox contents. * @protected */ createContentsContainer_() { - const contentsContainer = document.createElement('div'); + const contentsContainer = + /** @type {!HTMLDivElement} */ (document.createElement('div')); dom.addClass(contentsContainer, 'blocklyToolboxContents'); if (this.isHorizontal()) { contentsContainer.style.flexDirection = 'row'; @@ -290,9 +292,9 @@ class Toolbox extends DeleteArea { /** * Adds event listeners to the toolbox container div. - * @param {!Element} container The HTML container for the toolbox. - * @param {!Element} contentsContainer The HTML container for the contents - * of the toolbox. + * @param {!HTMLDivElement} container The HTML container for the toolbox. + * @param {!HTMLDivElement} contentsContainer The HTML container for the + * contents of the toolbox. * @protected */ attachEvents_(container, contentsContainer) { diff --git a/core/tooltip.js b/core/tooltip.js index e3e32b92e..2d7105f65 100644 --- a/core/tooltip.js +++ b/core/tooltip.js @@ -192,13 +192,13 @@ exports.MARGINS = MARGINS; /** * The HTML container. Set once by createDom. - * @type {Element} + * @type {?HTMLDivElement} */ let DIV = null; /** * Returns the HTML tooltip container. - * @returns {Element} The HTML tooltip container. + * @returns {?HTMLDivElement} The HTML tooltip container. * @alias Blockly.Tooltip.getDiv */ const getDiv = function() { @@ -210,7 +210,7 @@ Object.defineProperties(exports, { /** * The HTML container. Set once by createDom. * @name Blockly.Tooltip.DIV - * @type {Element} + * @type {HTMLDivElement} * @deprecated Use Blockly.Tooltip.getDiv() and .setDiv(). * (September 2021) * @suppress {checkTypes} @@ -274,7 +274,7 @@ const createDom = function() { return; // Already created. } // Create an HTML container for popup overlays (e.g. editor widgets). - DIV = document.createElement('div'); + DIV = /** @type {!HTMLDivElement} */ (document.createElement('div')); DIV.className = 'blocklyTooltipDiv'; const container = common.getParentContainer() || document.body; container.appendChild(DIV); @@ -465,7 +465,7 @@ const renderDefaultContent = function() { // Create new text, line by line. const lines = tip.split('\n'); for (let i = 0; i < lines.length; i++) { - const div = document.createElement('div'); + const div = /** @type {!HTMLDivElement} */ (document.createElement('div')); div.appendChild(document.createTextNode(lines[i])); DIV.appendChild(div); } diff --git a/core/utils/dom.js b/core/utils/dom.js index 73ece81ac..e97ebf5c1 100644 --- a/core/utils/dom.js +++ b/core/utils/dom.js @@ -403,11 +403,11 @@ const measureFontMetrics = function(text, fontSize, fontWeight, fontFamily) { span.style.font = fontWeight + ' ' + fontSize + ' ' + fontFamily; span.textContent = text; - const block = document.createElement('div'); + const block = /** @type {!HTMLDivElement} */ (document.createElement('div')); block.style.width = '1px'; block.style.height = 0; - const div = document.createElement('div'); + const div = /** @type {!HTMLDivElement} */ (document.createElement('div')); div.setAttribute('style', 'position: fixed; top: 0; left: 0; display: flex;'); div.appendChild(span); div.appendChild(block); diff --git a/core/widgetdiv.js b/core/widgetdiv.js index da900e4fa..b7fe045b5 100644 --- a/core/widgetdiv.js +++ b/core/widgetdiv.js @@ -56,13 +56,13 @@ let themeClassName = ''; /** * The HTML container for popup overlays (e.g. editor widgets). - * @type {?Element} + * @type {?HTMLDivElement} */ let DIV; /** * Returns the HTML container for editor widgets. - * @return {?Element} The editor widget container. + * @return {?HTMLDivElement} The editor widget container. * @alias Blockly.WidgetDiv.getDiv */ const getDiv = function() { @@ -72,7 +72,7 @@ exports.getDiv = getDiv; /** * Allows unit tests to reset the div. - * @param {?Element} newDiv The new value for the DIV field. + * @param {?HTMLDivElement} newDiv The new value for the DIV field. * @alias Blockly.WidgetDiv.testOnly_setDiv * @ignore */ @@ -109,7 +109,7 @@ const createDom = function() { return; // Already created. } - DIV = document.createElement('div'); + DIV = /** @type {!HTMLDivElement} */ (document.createElement('div')); DIV.className = 'blocklyWidgetDiv'; const container = common.getParentContainer() || document.body; container.appendChild(DIV); From 01d45972d4df8b5e4afa4a19d93defb8961fea57 Mon Sep 17 00:00:00 2001 From: Beka Westberg Date: Wed, 9 Mar 2022 07:38:37 -0800 Subject: [PATCH 102/128] fix: revert converting test helpers to es modules (#5982) * Revert "fix: lint" This reverts commit 050956d105c96a1e5e4697dd46094cfc1d016816. * Revert "fix: run mocha as a module" This reverts commit 4dac25ae9915b6a3eb144f1230d274cb18a69e68. * Revert "move to modules, but break mocha" This reverts commit 220d7bbd1d2069964cb4d5efab96c2aed32483fd. --- tests/deps.mocha.js | 26 +++++++------- tests/mocha/.eslintrc.json | 6 +--- tests/mocha/astnode_test.js | 6 ---- tests/mocha/index.html | 2 +- tests/mocha/test_helpers/block_definitions.js | 23 +++++++----- tests/mocha/test_helpers/code_generation.js | 11 +++--- tests/mocha/test_helpers/common.js | 14 +++++--- tests/mocha/test_helpers/events.js | 17 +++++---- tests/mocha/test_helpers/fields.js | 20 +++++++---- tests/mocha/test_helpers/procedures.js | 14 +++++--- tests/mocha/test_helpers/serialization.js | 8 +++-- tests/mocha/test_helpers/setup_teardown.js | 20 +++++++---- .../mocha/test_helpers/toolbox_definitions.js | 35 ++++++++++++------- tests/mocha/test_helpers/user_input.js | 11 +++--- tests/mocha/test_helpers/variables.js | 5 +-- tests/mocha/test_helpers/warnings.js | 20 +++++++---- tests/mocha/test_helpers/workspace.js | 5 +-- 17 files changed, 146 insertions(+), 97 deletions(-) diff --git a/tests/deps.mocha.js b/tests/deps.mocha.js index f2d550157..c43d84e13 100644 --- a/tests/deps.mocha.js +++ b/tests/deps.mocha.js @@ -44,19 +44,19 @@ goog.addDependency('../../tests/mocha/registry_test.js', ['Blockly.test.registry goog.addDependency('../../tests/mocha/run_mocha_tests_in_browser.js', [], [], {'lang': 'es8'}); goog.addDependency('../../tests/mocha/serializer_test.js', ['Blockly.test.serialization'], ['Blockly.test.helpers.common', 'Blockly.test.helpers.setupTeardown'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../tests/mocha/shortcut_registry_test.js', ['Blockly.test.shortcutRegistry'], ['Blockly.test.helpers.setupTeardown', 'Blockly.test.helpers.userInput'], {'lang': 'es6', 'module': 'goog'}); -goog.addDependency('../../tests/mocha/test_helpers/block_definitions.js', ['Blockly.test.helpers.blockDefinitions'], [], {'lang': 'es6', 'module': 'es6'}); -goog.addDependency('../../tests/mocha/test_helpers/code_generation.js', ['Blockly.test.helpers.codeGeneration'], ['Blockly.test.helpers.common'], {'lang': 'es6', 'module': 'es6'}); -goog.addDependency('../../tests/mocha/test_helpers/common.js', ['Blockly.test.helpers.common'], [], {'lang': 'es6', 'module': 'es6'}); -goog.addDependency('../../tests/mocha/test_helpers/events.js', ['Blockly.test.helpers.events'], [], {'lang': 'es6', 'module': 'es6'}); -goog.addDependency('../../tests/mocha/test_helpers/fields.js', ['Blockly.test.helpers.fields'], ['Blockly.test.helpers.common'], {'lang': 'es6', 'module': 'es6'}); -goog.addDependency('../../tests/mocha/test_helpers/procedures.js', ['Blockly.test.helpers.procedures'], ['Blockly.ConnectionType'], {'lang': 'es6', 'module': 'es6'}); -goog.addDependency('../../tests/mocha/test_helpers/serialization.js', ['Blockly.test.helpers.serialization'], ['Blockly.test.helpers.common'], {'lang': 'es6', 'module': 'es6'}); -goog.addDependency('../../tests/mocha/test_helpers/setup_teardown.js', ['Blockly.test.helpers.setupTeardown'], ['Blockly.Events.utils', 'Blockly.blocks'], {'lang': 'es6', 'module': 'es6'}); -goog.addDependency('../../tests/mocha/test_helpers/toolbox_definitions.js', ['Blockly.test.helpers.toolboxDefinitions'], [], {'lang': 'es6', 'module': 'es6'}); -goog.addDependency('../../tests/mocha/test_helpers/user_input.js', ['Blockly.test.helpers.userInput'], ['Blockly.utils.KeyCodes'], {'lang': 'es6', 'module': 'es6'}); -goog.addDependency('../../tests/mocha/test_helpers/variables.js', ['Blockly.test.helpers.variables'], [], {'lang': 'es6', 'module': 'es6'}); -goog.addDependency('../../tests/mocha/test_helpers/warnings.js', ['Blockly.test.helpers.warnings'], [], {'lang': 'es6', 'module': 'es6'}); -goog.addDependency('../../tests/mocha/test_helpers/workspace.js', ['Blockly.test.helpers.workspace'], ['Blockly.Events.utils', 'Blockly.test.helpers.setupTeardown', 'Blockly.test.helpers.variables', 'Blockly.test.helpers.warnings'], {'lang': 'es6', 'module': 'es6'}); +goog.addDependency('../../tests/mocha/test_helpers/block_definitions.js', ['Blockly.test.helpers.blockDefinitions'], [], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../tests/mocha/test_helpers/code_generation.js', ['Blockly.test.helpers.codeGeneration'], ['Blockly.test.helpers.common'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../tests/mocha/test_helpers/common.js', ['Blockly.test.helpers.common'], [], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../tests/mocha/test_helpers/events.js', ['Blockly.test.helpers.events'], [], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../tests/mocha/test_helpers/fields.js', ['Blockly.test.helpers.fields'], ['Blockly.test.helpers.common'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../tests/mocha/test_helpers/procedures.js', ['Blockly.test.helpers.procedures'], ['Blockly.ConnectionType'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../tests/mocha/test_helpers/serialization.js', ['Blockly.test.helpers.serialization'], ['Blockly.test.helpers.common'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../tests/mocha/test_helpers/setup_teardown.js', ['Blockly.test.helpers.setupTeardown'], ['Blockly.Events.utils', 'Blockly.blocks'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../tests/mocha/test_helpers/toolbox_definitions.js', ['Blockly.test.helpers.toolboxDefinitions'], [], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../tests/mocha/test_helpers/user_input.js', ['Blockly.test.helpers.userInput'], ['Blockly.utils.KeyCodes'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../tests/mocha/test_helpers/variables.js', ['Blockly.test.helpers.variables'], [], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../tests/mocha/test_helpers/warnings.js', ['Blockly.test.helpers.warnings'], [], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../tests/mocha/test_helpers/workspace.js', ['Blockly.test.helpers.workspace'], ['Blockly.Events.utils', 'Blockly.test.helpers.setupTeardown', 'Blockly.test.helpers.variables', 'Blockly.test.helpers.warnings'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../tests/mocha/theme_test.js', ['Blockly.test.theme'], ['Blockly.Events.utils', 'Blockly.test.helpers.events', 'Blockly.test.helpers.setupTeardown'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../tests/mocha/toolbox_test.js', ['Blockly.test.toolbox'], ['Blockly.test.helpers.blockDefinitions', 'Blockly.test.helpers.setupTeardown', 'Blockly.test.helpers.toolboxDefinitions'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../tests/mocha/tooltip_test.js', ['Blockly.test.tooltip'], ['Blockly.test.helpers.setupTeardown'], {'lang': 'es6', 'module': 'goog'}); diff --git a/tests/mocha/.eslintrc.json b/tests/mocha/.eslintrc.json index bf87ec0bd..8ebf31ae6 100644 --- a/tests/mocha/.eslintrc.json +++ b/tests/mocha/.eslintrc.json @@ -1,7 +1,4 @@ { - "parserOptions": { - "sourceType": "module" - }, "env": { "browser": true, "mocha": true @@ -14,8 +11,7 @@ "no-unused-vars": ["off"], // Allow uncommented helper functions in tests. "require-jsdoc": ["off"], - "prefer-rest-params": ["off"], - "no-invalid-this": ["off"] + "prefer-rest-params": ["off"] }, "extends": "../../.eslintrc.json" } diff --git a/tests/mocha/astnode_test.js b/tests/mocha/astnode_test.js index 1a15dfb62..f974f3ea8 100644 --- a/tests/mocha/astnode_test.js +++ b/tests/mocha/astnode_test.js @@ -11,7 +11,6 @@ const {sharedTestSetup, sharedTestTeardown, workspaceTeardown} = goog.require('B suite('ASTNode', function() { - console.log('1/a'); setup(function() { sharedTestSetup.call(this); Blockly.defineBlocksWithJsonArray([{ @@ -101,9 +100,7 @@ suite('ASTNode', function() { }); suite('HelperFunctions', function() { - console.log('2'); test('findNextForInput_', function() { - console.log('3'); const input = this.blocks.statementInput1.inputList[0]; const input2 = this.blocks.statementInput1.inputList[1]; const connection = input.connection; @@ -172,7 +169,6 @@ suite('ASTNode', function() { }); suite('NavigationFunctions', function() { - console.log('b'); setup(function() { Blockly.defineBlocksWithJsonArray([{ "type": "top_connection", @@ -323,9 +319,7 @@ suite('ASTNode', function() { workspaceTeardown.call(this, this.singleBlockWorkspace); }); - console.log('c'); test('fromPreviousToBlock', function() { - console.log('d'); const prevConnection = this.blocks.statementInput1.previousConnection; const node = ASTNode.createConnectionNode(prevConnection); const nextNode = node.next(); diff --git a/tests/mocha/index.html b/tests/mocha/index.html index 694d5215a..3d1cfaa9c 100644 --- a/tests/mocha/index.html +++ b/tests/mocha/index.html @@ -172,7 +172,7 @@ - From 5ee94e223b676239a1e89f05d53f3157c1abe195 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 17 Mar 2022 10:58:00 -0700 Subject: [PATCH 113/128] chore(deps): bump webdriverio from 7.16.16 to 7.17.4 (#5992) Bumps [webdriverio](https://github.com/webdriverio/webdriverio) from 7.16.16 to 7.17.4. - [Release notes](https://github.com/webdriverio/webdriverio/releases) - [Changelog](https://github.com/webdriverio/webdriverio/blob/main/CHANGELOG.md) - [Commits](https://github.com/webdriverio/webdriverio/compare/v7.16.16...v7.17.4) --- updated-dependencies: - dependency-name: webdriverio dependency-type: direct:development update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- package-lock.json | 553 +++++++++++++++++++++++++++++----------------- 1 file changed, 354 insertions(+), 199 deletions(-) diff --git a/package-lock.json b/package-lock.json index ca12dd890..6565fbb26 100644 --- a/package-lock.json +++ b/package-lock.json @@ -994,32 +994,48 @@ "resolved": "https://registry.npmjs.org/@wdio/protocols/-/protocols-7.16.7.tgz", "integrity": "sha512-Wv40pNQcLiPzQ3o98Mv4A8T1EBQ6k4khglz/e2r16CTm+F3DDYh8eLMAsU5cgnmuwwDKX1EyOiFwieykBn5MCg==", "dev": true, + "peer": true, "engines": { "node": ">=12.0.0" } }, "node_modules/@wdio/repl": { - "version": "7.16.14", - "resolved": "https://registry.npmjs.org/@wdio/repl/-/repl-7.16.14.tgz", - "integrity": "sha512-Ezih0Y+lsGkKv3H3U56hdWgZiQGA3VaAYguSLd9+g1xbQq+zMKqSmfqECD9bAy+OgCCiVTRstES6lHZxJVPhAg==", + "version": "7.17.3", + "resolved": "https://registry.npmjs.org/@wdio/repl/-/repl-7.17.3.tgz", + "integrity": "sha512-ZX4dYnoOb9NC3IQFhva4B7FCoVx9v7CIG7g5W4bX/un5Xfyz3Fne1vGP9Aku15nyIaXRSCzuV6vpT/5KR6q6Hg==", "dev": true, "dependencies": { - "@wdio/utils": "7.16.14" + "@wdio/utils": "7.17.3" }, "engines": { "node": ">=12.0.0" } }, "node_modules/@wdio/repl/node_modules/@types/node": { - "version": "17.0.14", - "resolved": "https://registry.npmjs.org/@types/node/-/node-17.0.14.tgz", - "integrity": "sha512-SbjLmERksKOGzWzPNuW7fJM7fk3YXVTFiZWB/Hs99gwhk+/dnrQRPBQjPW9aO+fi1tAffi9PrwFvsmOKmDTyng==", + "version": "17.0.21", + "resolved": "https://registry.npmjs.org/@types/node/-/node-17.0.21.tgz", + "integrity": "sha512-DBZCJbhII3r90XbQxI8Y9IjjiiOGlZ0Hr32omXIZvwwZ7p4DMMXGrKXVyPfuoBOri9XNtL0UK69jYIBIsRX3QQ==", "dev": true }, + "node_modules/@wdio/repl/node_modules/@wdio/logger": { + "version": "7.17.3", + "resolved": "https://registry.npmjs.org/@wdio/logger/-/logger-7.17.3.tgz", + "integrity": "sha512-hpvJDsJMX8G/8gXHOEipxkQPjojjA+BRCZqCvZRLCVpWm2JB7tBoMzu9sUJXcpSkY03b94KAd4EwNA2uNAf9aQ==", + "dev": true, + "dependencies": { + "chalk": "^4.0.0", + "loglevel": "^1.6.0", + "loglevel-plugin-prefix": "^0.8.4", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=12.0.0" + } + }, "node_modules/@wdio/repl/node_modules/@wdio/types": { - "version": "7.16.14", - "resolved": "https://registry.npmjs.org/@wdio/types/-/types-7.16.14.tgz", - "integrity": "sha512-AyNI9iBSos9xWBmiFAF3sBs6AJXO/55VppU/eeF4HRdbZMtMarnvMuahM+jlUrA3vJSmDW+ufelG0MT//6vrnw==", + "version": "7.17.3", + "resolved": "https://registry.npmjs.org/@wdio/types/-/types-7.17.3.tgz", + "integrity": "sha512-j8kYdaMl4NFRS8M1bFDuEa3GMbUZbLQY7i6XEnJSetyW0GyMDLlzwcfXI4DdX85+3JbO5624UGKxVsQcuA7T3A==", "dev": true, "dependencies": { "@types/node": "^17.0.4", @@ -1030,13 +1046,13 @@ } }, "node_modules/@wdio/repl/node_modules/@wdio/utils": { - "version": "7.16.14", - "resolved": "https://registry.npmjs.org/@wdio/utils/-/utils-7.16.14.tgz", - "integrity": "sha512-wwin8nVpIlhmXJkq6GJw9aDDzgLOJKgXTcEua0T2sdXjoW78u5Ly/GZrFXTjMGhacFvoZfitTrjyfyy4CxMVvw==", + "version": "7.17.3", + "resolved": "https://registry.npmjs.org/@wdio/utils/-/utils-7.17.3.tgz", + "integrity": "sha512-20bGTCmgBNVKa2BJs3B5kxbsryjhfEOoKDnFjZ/rAVZYT1t1sg0e/W+vRfamd++NqTaIHOY/IKGEFiEnCw5nXw==", "dev": true, "dependencies": { - "@wdio/logger": "7.16.0", - "@wdio/types": "7.16.14", + "@wdio/logger": "7.17.3", + "@wdio/types": "7.17.3", "p-iteration": "^1.1.8" }, "engines": { @@ -3334,18 +3350,18 @@ } }, "node_modules/devtools": { - "version": "7.16.16", - "resolved": "https://registry.npmjs.org/devtools/-/devtools-7.16.16.tgz", - "integrity": "sha512-M0kzkuSgfEhpqIis3gdtWsNjn/HQ+vRAmEzDnbYx/7FfjFxhSv1d+rOOT20pvd60soItMYpsOova1igACEGkGQ==", + "version": "7.17.3", + "resolved": "https://registry.npmjs.org/devtools/-/devtools-7.17.3.tgz", + "integrity": "sha512-y5O+z+q7cUuAKMY9ZNGexbb62MUimKAJX7OkFecix2Fl9+YFSmAQUUtHWrTt9qFkw5NJNMdiXZhQvk+JdfRygw==", "dev": true, "dependencies": { "@types/node": "^17.0.4", "@types/ua-parser-js": "^0.7.33", - "@wdio/config": "7.16.16", - "@wdio/logger": "7.16.0", - "@wdio/protocols": "7.16.7", - "@wdio/types": "7.16.14", - "@wdio/utils": "7.16.14", + "@wdio/config": "7.17.3", + "@wdio/logger": "7.17.3", + "@wdio/protocols": "7.17.3", + "@wdio/types": "7.17.3", + "@wdio/utils": "7.17.3", "chrome-launcher": "^0.15.0", "edge-paths": "^2.1.0", "puppeteer-core": "^13.1.3", @@ -3358,9 +3374,9 @@ } }, "node_modules/devtools-protocol": { - "version": "0.0.973690", - "resolved": "https://registry.npmjs.org/devtools-protocol/-/devtools-protocol-0.0.973690.tgz", - "integrity": "sha512-myh3hSFp0YWa2GED11PmbLhV4dv9RdO7YUz27XJrbQLnP5bMbZL6dfOOILTHO57yH0kX5GfuOZBsg/4NamfPvQ==", + "version": "0.0.979353", + "resolved": "https://registry.npmjs.org/devtools-protocol/-/devtools-protocol-0.0.979353.tgz", + "integrity": "sha512-/A7o8FU5n4i2WN/RH6opBbteawPbNgyKmmyl6Ts4zpQ5FVq/cGe2K/qGr8t80BLVu8KynTckHbdpaLCwxzRyFA==", "dev": true }, "node_modules/devtools/node_modules/@types/node": { @@ -3370,13 +3386,13 @@ "dev": true }, "node_modules/devtools/node_modules/@wdio/config": { - "version": "7.16.16", - "resolved": "https://registry.npmjs.org/@wdio/config/-/config-7.16.16.tgz", - "integrity": "sha512-K/ObPuo6Da2liz++OKOIfbdpFwI7UWiFcBylfJkCYbweuXCoW1aUqlKI6rmKPwCH9Uqr/RHWu6p8eo0zWe6xVA==", + "version": "7.17.3", + "resolved": "https://registry.npmjs.org/@wdio/config/-/config-7.17.3.tgz", + "integrity": "sha512-MSWCsx0w1EbxbwOD8ykTxHqgx208CWoz9n4oWHx7Q1APfetqWFLM4O7K8cdZS1gV4IvH4EAV9807L91K8r0JNw==", "dev": true, "dependencies": { - "@wdio/logger": "7.16.0", - "@wdio/types": "7.16.14", + "@wdio/logger": "7.17.3", + "@wdio/types": "7.17.3", "deepmerge": "^4.0.0", "glob": "^7.1.2" }, @@ -3384,10 +3400,34 @@ "node": ">=12.0.0" } }, + "node_modules/devtools/node_modules/@wdio/logger": { + "version": "7.17.3", + "resolved": "https://registry.npmjs.org/@wdio/logger/-/logger-7.17.3.tgz", + "integrity": "sha512-hpvJDsJMX8G/8gXHOEipxkQPjojjA+BRCZqCvZRLCVpWm2JB7tBoMzu9sUJXcpSkY03b94KAd4EwNA2uNAf9aQ==", + "dev": true, + "dependencies": { + "chalk": "^4.0.0", + "loglevel": "^1.6.0", + "loglevel-plugin-prefix": "^0.8.4", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/devtools/node_modules/@wdio/protocols": { + "version": "7.17.3", + "resolved": "https://registry.npmjs.org/@wdio/protocols/-/protocols-7.17.3.tgz", + "integrity": "sha512-DxVRil2uMDOshk0gMOrmemC9uEZuB5Dv4bJX/ozZwXPV9AHd6oJqUrsF/fs8bT9+4AWkE58yqsRBFc/pt7sFMw==", + "dev": true, + "engines": { + "node": ">=12.0.0" + } + }, "node_modules/devtools/node_modules/@wdio/types": { - "version": "7.16.14", - "resolved": "https://registry.npmjs.org/@wdio/types/-/types-7.16.14.tgz", - "integrity": "sha512-AyNI9iBSos9xWBmiFAF3sBs6AJXO/55VppU/eeF4HRdbZMtMarnvMuahM+jlUrA3vJSmDW+ufelG0MT//6vrnw==", + "version": "7.17.3", + "resolved": "https://registry.npmjs.org/@wdio/types/-/types-7.17.3.tgz", + "integrity": "sha512-j8kYdaMl4NFRS8M1bFDuEa3GMbUZbLQY7i6XEnJSetyW0GyMDLlzwcfXI4DdX85+3JbO5624UGKxVsQcuA7T3A==", "dev": true, "dependencies": { "@types/node": "^17.0.4", @@ -3398,13 +3438,13 @@ } }, "node_modules/devtools/node_modules/@wdio/utils": { - "version": "7.16.14", - "resolved": "https://registry.npmjs.org/@wdio/utils/-/utils-7.16.14.tgz", - "integrity": "sha512-wwin8nVpIlhmXJkq6GJw9aDDzgLOJKgXTcEua0T2sdXjoW78u5Ly/GZrFXTjMGhacFvoZfitTrjyfyy4CxMVvw==", + "version": "7.17.3", + "resolved": "https://registry.npmjs.org/@wdio/utils/-/utils-7.17.3.tgz", + "integrity": "sha512-20bGTCmgBNVKa2BJs3B5kxbsryjhfEOoKDnFjZ/rAVZYT1t1sg0e/W+vRfamd++NqTaIHOY/IKGEFiEnCw5nXw==", "dev": true, "dependencies": { - "@wdio/logger": "7.16.0", - "@wdio/types": "7.16.14", + "@wdio/logger": "7.17.3", + "@wdio/types": "7.17.3", "p-iteration": "^1.1.8" }, "engines": { @@ -9448,14 +9488,14 @@ } }, "node_modules/puppeteer-core": { - "version": "13.4.0", - "resolved": "https://registry.npmjs.org/puppeteer-core/-/puppeteer-core-13.4.0.tgz", - "integrity": "sha512-TcGT5Qgq9tgI0msFrIhq70N1+WrnGowjn0hc4vtzEIizJETXOZVrQZVWy051lO/nxEVGyqRXHwtpWjv4/fRbUw==", + "version": "13.5.1", + "resolved": "https://registry.npmjs.org/puppeteer-core/-/puppeteer-core-13.5.1.tgz", + "integrity": "sha512-dobVqWjV34ilyfQHR3BBnCYaekBYTi5MgegEYBRYd3s3uFy8jUpZEEWbaFjG9ETm+LGzR5Lmr0aF6LLuHtiuCg==", "dev": true, "dependencies": { "cross-fetch": "3.1.5", "debug": "4.3.3", - "devtools-protocol": "0.0.960912", + "devtools-protocol": "0.0.969999", "extract-zip": "2.0.1", "https-proxy-agent": "5.0.0", "pkg-dir": "4.2.0", @@ -9471,9 +9511,9 @@ } }, "node_modules/puppeteer-core/node_modules/devtools-protocol": { - "version": "0.0.960912", - "resolved": "https://registry.npmjs.org/devtools-protocol/-/devtools-protocol-0.0.960912.tgz", - "integrity": "sha512-I3hWmV9rWHbdnUdmMKHF2NuYutIM2kXz2mdXW8ha7TbRlGTVs+PF+PsB5QWvpCek4Fy9B+msiispCfwlhG5Sqg==", + "version": "0.0.969999", + "resolved": "https://registry.npmjs.org/devtools-protocol/-/devtools-protocol-0.0.969999.tgz", + "integrity": "sha512-6GfzuDWU0OFAuOvBokXpXPLxjOJ5DZ157Ue3sGQQM3LgAamb8m0R0ruSfN0DDu+XG5XJgT50i6zZ/0o8RglreQ==", "dev": true }, "node_modules/puppeteer-core/node_modules/ws": { @@ -11921,19 +11961,19 @@ } }, "node_modules/webdriver": { - "version": "7.16.16", - "resolved": "https://registry.npmjs.org/webdriver/-/webdriver-7.16.16.tgz", - "integrity": "sha512-x8UoG9k/P8KDrfSh1pOyNevt9tns3zexoMxp9cKnyA/7HYSErhZYTLGlgxscAXLtQG41cMH/Ba/oBmOx7Hgd8w==", + "version": "7.17.3", + "resolved": "https://registry.npmjs.org/webdriver/-/webdriver-7.17.3.tgz", + "integrity": "sha512-E1V/IKYjJoVjK9zhHfSCWeqORhgNlDuYydykm0h+CchEhMSgTmtTH/LYfXSx4myXzobdlIg6xhE7Jv7XPjSkAA==", "dev": true, "dependencies": { "@types/node": "^17.0.4", - "@wdio/config": "7.16.16", - "@wdio/logger": "7.16.0", - "@wdio/protocols": "7.16.7", - "@wdio/types": "7.16.14", - "@wdio/utils": "7.16.14", + "@wdio/config": "7.17.3", + "@wdio/logger": "7.17.3", + "@wdio/protocols": "7.17.3", + "@wdio/types": "7.17.3", + "@wdio/utils": "7.17.3", "got": "^11.0.2", - "ky": "^0.29.0", + "ky": "^0.30.0", "lodash.merge": "^4.6.1" }, "engines": { @@ -11947,13 +11987,13 @@ "dev": true }, "node_modules/webdriver/node_modules/@wdio/config": { - "version": "7.16.16", - "resolved": "https://registry.npmjs.org/@wdio/config/-/config-7.16.16.tgz", - "integrity": "sha512-K/ObPuo6Da2liz++OKOIfbdpFwI7UWiFcBylfJkCYbweuXCoW1aUqlKI6rmKPwCH9Uqr/RHWu6p8eo0zWe6xVA==", + "version": "7.17.3", + "resolved": "https://registry.npmjs.org/@wdio/config/-/config-7.17.3.tgz", + "integrity": "sha512-MSWCsx0w1EbxbwOD8ykTxHqgx208CWoz9n4oWHx7Q1APfetqWFLM4O7K8cdZS1gV4IvH4EAV9807L91K8r0JNw==", "dev": true, "dependencies": { - "@wdio/logger": "7.16.0", - "@wdio/types": "7.16.14", + "@wdio/logger": "7.17.3", + "@wdio/types": "7.17.3", "deepmerge": "^4.0.0", "glob": "^7.1.2" }, @@ -11961,10 +12001,34 @@ "node": ">=12.0.0" } }, + "node_modules/webdriver/node_modules/@wdio/logger": { + "version": "7.17.3", + "resolved": "https://registry.npmjs.org/@wdio/logger/-/logger-7.17.3.tgz", + "integrity": "sha512-hpvJDsJMX8G/8gXHOEipxkQPjojjA+BRCZqCvZRLCVpWm2JB7tBoMzu9sUJXcpSkY03b94KAd4EwNA2uNAf9aQ==", + "dev": true, + "dependencies": { + "chalk": "^4.0.0", + "loglevel": "^1.6.0", + "loglevel-plugin-prefix": "^0.8.4", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/webdriver/node_modules/@wdio/protocols": { + "version": "7.17.3", + "resolved": "https://registry.npmjs.org/@wdio/protocols/-/protocols-7.17.3.tgz", + "integrity": "sha512-DxVRil2uMDOshk0gMOrmemC9uEZuB5Dv4bJX/ozZwXPV9AHd6oJqUrsF/fs8bT9+4AWkE58yqsRBFc/pt7sFMw==", + "dev": true, + "engines": { + "node": ">=12.0.0" + } + }, "node_modules/webdriver/node_modules/@wdio/types": { - "version": "7.16.14", - "resolved": "https://registry.npmjs.org/@wdio/types/-/types-7.16.14.tgz", - "integrity": "sha512-AyNI9iBSos9xWBmiFAF3sBs6AJXO/55VppU/eeF4HRdbZMtMarnvMuahM+jlUrA3vJSmDW+ufelG0MT//6vrnw==", + "version": "7.17.3", + "resolved": "https://registry.npmjs.org/@wdio/types/-/types-7.17.3.tgz", + "integrity": "sha512-j8kYdaMl4NFRS8M1bFDuEa3GMbUZbLQY7i6XEnJSetyW0GyMDLlzwcfXI4DdX85+3JbO5624UGKxVsQcuA7T3A==", "dev": true, "dependencies": { "@types/node": "^17.0.4", @@ -11975,13 +12039,13 @@ } }, "node_modules/webdriver/node_modules/@wdio/utils": { - "version": "7.16.14", - "resolved": "https://registry.npmjs.org/@wdio/utils/-/utils-7.16.14.tgz", - "integrity": "sha512-wwin8nVpIlhmXJkq6GJw9aDDzgLOJKgXTcEua0T2sdXjoW78u5Ly/GZrFXTjMGhacFvoZfitTrjyfyy4CxMVvw==", + "version": "7.17.3", + "resolved": "https://registry.npmjs.org/@wdio/utils/-/utils-7.17.3.tgz", + "integrity": "sha512-20bGTCmgBNVKa2BJs3B5kxbsryjhfEOoKDnFjZ/rAVZYT1t1sg0e/W+vRfamd++NqTaIHOY/IKGEFiEnCw5nXw==", "dev": true, "dependencies": { - "@wdio/logger": "7.16.0", - "@wdio/types": "7.16.14", + "@wdio/logger": "7.17.3", + "@wdio/types": "7.17.3", "p-iteration": "^1.1.8" }, "engines": { @@ -11989,9 +12053,9 @@ } }, "node_modules/webdriver/node_modules/ky": { - "version": "0.29.0", - "resolved": "https://registry.npmjs.org/ky/-/ky-0.29.0.tgz", - "integrity": "sha512-01TBSOqlHmLfcQhHseugGHLxPtU03OyZWaLDWt5MfzCkijG6xWFvAQPhKVn0cR2MMjYvBP9keQ8A3+rQEhLO5g==", + "version": "0.30.0", + "resolved": "https://registry.npmjs.org/ky/-/ky-0.30.0.tgz", + "integrity": "sha512-X/u76z4JtDVq10u1JA5UQfatPxgPaVDMYTrgHyiTpGN2z4TMEJkIHsoSBBSg9SWZEIXTKsi9kHgiQ9o3Y/4yog==", "dev": true, "engines": { "node": ">=12" @@ -12001,25 +12065,25 @@ } }, "node_modules/webdriverio": { - "version": "7.16.16", - "resolved": "https://registry.npmjs.org/webdriverio/-/webdriverio-7.16.16.tgz", - "integrity": "sha512-caPaEWyuD3Qoa7YkW4xCCQA4v9Pa9wmhFGPvNZh3ERtjMCNi8L/XXOdkekWNZmFh3tY0kFguBj7+fAwSY7HAGw==", + "version": "7.17.4", + "resolved": "https://registry.npmjs.org/webdriverio/-/webdriverio-7.17.4.tgz", + "integrity": "sha512-p7u2q7NJL7Et8FdSroq/Ltoi3KkKxERE79Srh9lFr6yRNPFqb46dJf/g4nljLhburnGkbNdYN15JWgyWYnnj9g==", "dev": true, "dependencies": { "@types/aria-query": "^5.0.0", "@types/node": "^17.0.4", - "@wdio/config": "7.16.16", - "@wdio/logger": "7.16.0", - "@wdio/protocols": "7.16.7", - "@wdio/repl": "7.16.14", - "@wdio/types": "7.16.14", - "@wdio/utils": "7.16.14", + "@wdio/config": "7.17.3", + "@wdio/logger": "7.17.3", + "@wdio/protocols": "7.17.3", + "@wdio/repl": "7.17.3", + "@wdio/types": "7.17.3", + "@wdio/utils": "7.17.3", "archiver": "^5.0.0", "aria-query": "^5.0.0", "css-shorthand-properties": "^1.1.1", "css-value": "^0.0.1", - "devtools": "7.16.16", - "devtools-protocol": "^0.0.973690", + "devtools": "7.17.3", + "devtools-protocol": "^0.0.979353", "fs-extra": "^10.0.0", "get-port": "^5.1.1", "grapheme-splitter": "^1.0.2", @@ -12033,26 +12097,26 @@ "resq": "^1.9.1", "rgb2hex": "0.2.5", "serialize-error": "^8.0.0", - "webdriver": "7.16.16" + "webdriver": "7.17.3" }, "engines": { "node": ">=12.0.0" } }, "node_modules/webdriverio/node_modules/@types/node": { - "version": "17.0.14", - "resolved": "https://registry.npmjs.org/@types/node/-/node-17.0.14.tgz", - "integrity": "sha512-SbjLmERksKOGzWzPNuW7fJM7fk3YXVTFiZWB/Hs99gwhk+/dnrQRPBQjPW9aO+fi1tAffi9PrwFvsmOKmDTyng==", + "version": "17.0.21", + "resolved": "https://registry.npmjs.org/@types/node/-/node-17.0.21.tgz", + "integrity": "sha512-DBZCJbhII3r90XbQxI8Y9IjjiiOGlZ0Hr32omXIZvwwZ7p4DMMXGrKXVyPfuoBOri9XNtL0UK69jYIBIsRX3QQ==", "dev": true }, "node_modules/webdriverio/node_modules/@wdio/config": { - "version": "7.16.16", - "resolved": "https://registry.npmjs.org/@wdio/config/-/config-7.16.16.tgz", - "integrity": "sha512-K/ObPuo6Da2liz++OKOIfbdpFwI7UWiFcBylfJkCYbweuXCoW1aUqlKI6rmKPwCH9Uqr/RHWu6p8eo0zWe6xVA==", + "version": "7.17.3", + "resolved": "https://registry.npmjs.org/@wdio/config/-/config-7.17.3.tgz", + "integrity": "sha512-MSWCsx0w1EbxbwOD8ykTxHqgx208CWoz9n4oWHx7Q1APfetqWFLM4O7K8cdZS1gV4IvH4EAV9807L91K8r0JNw==", "dev": true, "dependencies": { - "@wdio/logger": "7.16.0", - "@wdio/types": "7.16.14", + "@wdio/logger": "7.17.3", + "@wdio/types": "7.17.3", "deepmerge": "^4.0.0", "glob": "^7.1.2" }, @@ -12060,10 +12124,34 @@ "node": ">=12.0.0" } }, + "node_modules/webdriverio/node_modules/@wdio/logger": { + "version": "7.17.3", + "resolved": "https://registry.npmjs.org/@wdio/logger/-/logger-7.17.3.tgz", + "integrity": "sha512-hpvJDsJMX8G/8gXHOEipxkQPjojjA+BRCZqCvZRLCVpWm2JB7tBoMzu9sUJXcpSkY03b94KAd4EwNA2uNAf9aQ==", + "dev": true, + "dependencies": { + "chalk": "^4.0.0", + "loglevel": "^1.6.0", + "loglevel-plugin-prefix": "^0.8.4", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/webdriverio/node_modules/@wdio/protocols": { + "version": "7.17.3", + "resolved": "https://registry.npmjs.org/@wdio/protocols/-/protocols-7.17.3.tgz", + "integrity": "sha512-DxVRil2uMDOshk0gMOrmemC9uEZuB5Dv4bJX/ozZwXPV9AHd6oJqUrsF/fs8bT9+4AWkE58yqsRBFc/pt7sFMw==", + "dev": true, + "engines": { + "node": ">=12.0.0" + } + }, "node_modules/webdriverio/node_modules/@wdio/types": { - "version": "7.16.14", - "resolved": "https://registry.npmjs.org/@wdio/types/-/types-7.16.14.tgz", - "integrity": "sha512-AyNI9iBSos9xWBmiFAF3sBs6AJXO/55VppU/eeF4HRdbZMtMarnvMuahM+jlUrA3vJSmDW+ufelG0MT//6vrnw==", + "version": "7.17.3", + "resolved": "https://registry.npmjs.org/@wdio/types/-/types-7.17.3.tgz", + "integrity": "sha512-j8kYdaMl4NFRS8M1bFDuEa3GMbUZbLQY7i6XEnJSetyW0GyMDLlzwcfXI4DdX85+3JbO5624UGKxVsQcuA7T3A==", "dev": true, "dependencies": { "@types/node": "^17.0.4", @@ -12074,13 +12162,13 @@ } }, "node_modules/webdriverio/node_modules/@wdio/utils": { - "version": "7.16.14", - "resolved": "https://registry.npmjs.org/@wdio/utils/-/utils-7.16.14.tgz", - "integrity": "sha512-wwin8nVpIlhmXJkq6GJw9aDDzgLOJKgXTcEua0T2sdXjoW78u5Ly/GZrFXTjMGhacFvoZfitTrjyfyy4CxMVvw==", + "version": "7.17.3", + "resolved": "https://registry.npmjs.org/@wdio/utils/-/utils-7.17.3.tgz", + "integrity": "sha512-20bGTCmgBNVKa2BJs3B5kxbsryjhfEOoKDnFjZ/rAVZYT1t1sg0e/W+vRfamd++NqTaIHOY/IKGEFiEnCw5nXw==", "dev": true, "dependencies": { - "@wdio/logger": "7.16.0", - "@wdio/types": "7.16.14", + "@wdio/logger": "7.17.3", + "@wdio/types": "7.17.3", "p-iteration": "^1.1.8" }, "engines": { @@ -13299,27 +13387,40 @@ "version": "7.16.7", "resolved": "https://registry.npmjs.org/@wdio/protocols/-/protocols-7.16.7.tgz", "integrity": "sha512-Wv40pNQcLiPzQ3o98Mv4A8T1EBQ6k4khglz/e2r16CTm+F3DDYh8eLMAsU5cgnmuwwDKX1EyOiFwieykBn5MCg==", - "dev": true + "dev": true, + "peer": true }, "@wdio/repl": { - "version": "7.16.14", - "resolved": "https://registry.npmjs.org/@wdio/repl/-/repl-7.16.14.tgz", - "integrity": "sha512-Ezih0Y+lsGkKv3H3U56hdWgZiQGA3VaAYguSLd9+g1xbQq+zMKqSmfqECD9bAy+OgCCiVTRstES6lHZxJVPhAg==", + "version": "7.17.3", + "resolved": "https://registry.npmjs.org/@wdio/repl/-/repl-7.17.3.tgz", + "integrity": "sha512-ZX4dYnoOb9NC3IQFhva4B7FCoVx9v7CIG7g5W4bX/un5Xfyz3Fne1vGP9Aku15nyIaXRSCzuV6vpT/5KR6q6Hg==", "dev": true, "requires": { - "@wdio/utils": "7.16.14" + "@wdio/utils": "7.17.3" }, "dependencies": { "@types/node": { - "version": "17.0.14", - "resolved": "https://registry.npmjs.org/@types/node/-/node-17.0.14.tgz", - "integrity": "sha512-SbjLmERksKOGzWzPNuW7fJM7fk3YXVTFiZWB/Hs99gwhk+/dnrQRPBQjPW9aO+fi1tAffi9PrwFvsmOKmDTyng==", + "version": "17.0.21", + "resolved": "https://registry.npmjs.org/@types/node/-/node-17.0.21.tgz", + "integrity": "sha512-DBZCJbhII3r90XbQxI8Y9IjjiiOGlZ0Hr32omXIZvwwZ7p4DMMXGrKXVyPfuoBOri9XNtL0UK69jYIBIsRX3QQ==", "dev": true }, + "@wdio/logger": { + "version": "7.17.3", + "resolved": "https://registry.npmjs.org/@wdio/logger/-/logger-7.17.3.tgz", + "integrity": "sha512-hpvJDsJMX8G/8gXHOEipxkQPjojjA+BRCZqCvZRLCVpWm2JB7tBoMzu9sUJXcpSkY03b94KAd4EwNA2uNAf9aQ==", + "dev": true, + "requires": { + "chalk": "^4.0.0", + "loglevel": "^1.6.0", + "loglevel-plugin-prefix": "^0.8.4", + "strip-ansi": "^6.0.0" + } + }, "@wdio/types": { - "version": "7.16.14", - "resolved": "https://registry.npmjs.org/@wdio/types/-/types-7.16.14.tgz", - "integrity": "sha512-AyNI9iBSos9xWBmiFAF3sBs6AJXO/55VppU/eeF4HRdbZMtMarnvMuahM+jlUrA3vJSmDW+ufelG0MT//6vrnw==", + "version": "7.17.3", + "resolved": "https://registry.npmjs.org/@wdio/types/-/types-7.17.3.tgz", + "integrity": "sha512-j8kYdaMl4NFRS8M1bFDuEa3GMbUZbLQY7i6XEnJSetyW0GyMDLlzwcfXI4DdX85+3JbO5624UGKxVsQcuA7T3A==", "dev": true, "requires": { "@types/node": "^17.0.4", @@ -13327,13 +13428,13 @@ } }, "@wdio/utils": { - "version": "7.16.14", - "resolved": "https://registry.npmjs.org/@wdio/utils/-/utils-7.16.14.tgz", - "integrity": "sha512-wwin8nVpIlhmXJkq6GJw9aDDzgLOJKgXTcEua0T2sdXjoW78u5Ly/GZrFXTjMGhacFvoZfitTrjyfyy4CxMVvw==", + "version": "7.17.3", + "resolved": "https://registry.npmjs.org/@wdio/utils/-/utils-7.17.3.tgz", + "integrity": "sha512-20bGTCmgBNVKa2BJs3B5kxbsryjhfEOoKDnFjZ/rAVZYT1t1sg0e/W+vRfamd++NqTaIHOY/IKGEFiEnCw5nXw==", "dev": true, "requires": { - "@wdio/logger": "7.16.0", - "@wdio/types": "7.16.14", + "@wdio/logger": "7.17.3", + "@wdio/types": "7.17.3", "p-iteration": "^1.1.8" } } @@ -15122,18 +15223,18 @@ "dev": true }, "devtools": { - "version": "7.16.16", - "resolved": "https://registry.npmjs.org/devtools/-/devtools-7.16.16.tgz", - "integrity": "sha512-M0kzkuSgfEhpqIis3gdtWsNjn/HQ+vRAmEzDnbYx/7FfjFxhSv1d+rOOT20pvd60soItMYpsOova1igACEGkGQ==", + "version": "7.17.3", + "resolved": "https://registry.npmjs.org/devtools/-/devtools-7.17.3.tgz", + "integrity": "sha512-y5O+z+q7cUuAKMY9ZNGexbb62MUimKAJX7OkFecix2Fl9+YFSmAQUUtHWrTt9qFkw5NJNMdiXZhQvk+JdfRygw==", "dev": true, "requires": { "@types/node": "^17.0.4", "@types/ua-parser-js": "^0.7.33", - "@wdio/config": "7.16.16", - "@wdio/logger": "7.16.0", - "@wdio/protocols": "7.16.7", - "@wdio/types": "7.16.14", - "@wdio/utils": "7.16.14", + "@wdio/config": "7.17.3", + "@wdio/logger": "7.17.3", + "@wdio/protocols": "7.17.3", + "@wdio/types": "7.17.3", + "@wdio/utils": "7.17.3", "chrome-launcher": "^0.15.0", "edge-paths": "^2.1.0", "puppeteer-core": "^13.1.3", @@ -15149,21 +15250,39 @@ "dev": true }, "@wdio/config": { - "version": "7.16.16", - "resolved": "https://registry.npmjs.org/@wdio/config/-/config-7.16.16.tgz", - "integrity": "sha512-K/ObPuo6Da2liz++OKOIfbdpFwI7UWiFcBylfJkCYbweuXCoW1aUqlKI6rmKPwCH9Uqr/RHWu6p8eo0zWe6xVA==", + "version": "7.17.3", + "resolved": "https://registry.npmjs.org/@wdio/config/-/config-7.17.3.tgz", + "integrity": "sha512-MSWCsx0w1EbxbwOD8ykTxHqgx208CWoz9n4oWHx7Q1APfetqWFLM4O7K8cdZS1gV4IvH4EAV9807L91K8r0JNw==", "dev": true, "requires": { - "@wdio/logger": "7.16.0", - "@wdio/types": "7.16.14", + "@wdio/logger": "7.17.3", + "@wdio/types": "7.17.3", "deepmerge": "^4.0.0", "glob": "^7.1.2" } }, + "@wdio/logger": { + "version": "7.17.3", + "resolved": "https://registry.npmjs.org/@wdio/logger/-/logger-7.17.3.tgz", + "integrity": "sha512-hpvJDsJMX8G/8gXHOEipxkQPjojjA+BRCZqCvZRLCVpWm2JB7tBoMzu9sUJXcpSkY03b94KAd4EwNA2uNAf9aQ==", + "dev": true, + "requires": { + "chalk": "^4.0.0", + "loglevel": "^1.6.0", + "loglevel-plugin-prefix": "^0.8.4", + "strip-ansi": "^6.0.0" + } + }, + "@wdio/protocols": { + "version": "7.17.3", + "resolved": "https://registry.npmjs.org/@wdio/protocols/-/protocols-7.17.3.tgz", + "integrity": "sha512-DxVRil2uMDOshk0gMOrmemC9uEZuB5Dv4bJX/ozZwXPV9AHd6oJqUrsF/fs8bT9+4AWkE58yqsRBFc/pt7sFMw==", + "dev": true + }, "@wdio/types": { - "version": "7.16.14", - "resolved": "https://registry.npmjs.org/@wdio/types/-/types-7.16.14.tgz", - "integrity": "sha512-AyNI9iBSos9xWBmiFAF3sBs6AJXO/55VppU/eeF4HRdbZMtMarnvMuahM+jlUrA3vJSmDW+ufelG0MT//6vrnw==", + "version": "7.17.3", + "resolved": "https://registry.npmjs.org/@wdio/types/-/types-7.17.3.tgz", + "integrity": "sha512-j8kYdaMl4NFRS8M1bFDuEa3GMbUZbLQY7i6XEnJSetyW0GyMDLlzwcfXI4DdX85+3JbO5624UGKxVsQcuA7T3A==", "dev": true, "requires": { "@types/node": "^17.0.4", @@ -15171,13 +15290,13 @@ } }, "@wdio/utils": { - "version": "7.16.14", - "resolved": "https://registry.npmjs.org/@wdio/utils/-/utils-7.16.14.tgz", - "integrity": "sha512-wwin8nVpIlhmXJkq6GJw9aDDzgLOJKgXTcEua0T2sdXjoW78u5Ly/GZrFXTjMGhacFvoZfitTrjyfyy4CxMVvw==", + "version": "7.17.3", + "resolved": "https://registry.npmjs.org/@wdio/utils/-/utils-7.17.3.tgz", + "integrity": "sha512-20bGTCmgBNVKa2BJs3B5kxbsryjhfEOoKDnFjZ/rAVZYT1t1sg0e/W+vRfamd++NqTaIHOY/IKGEFiEnCw5nXw==", "dev": true, "requires": { - "@wdio/logger": "7.16.0", - "@wdio/types": "7.16.14", + "@wdio/logger": "7.17.3", + "@wdio/types": "7.17.3", "p-iteration": "^1.1.8" } }, @@ -15190,9 +15309,9 @@ } }, "devtools-protocol": { - "version": "0.0.973690", - "resolved": "https://registry.npmjs.org/devtools-protocol/-/devtools-protocol-0.0.973690.tgz", - "integrity": "sha512-myh3hSFp0YWa2GED11PmbLhV4dv9RdO7YUz27XJrbQLnP5bMbZL6dfOOILTHO57yH0kX5GfuOZBsg/4NamfPvQ==", + "version": "0.0.979353", + "resolved": "https://registry.npmjs.org/devtools-protocol/-/devtools-protocol-0.0.979353.tgz", + "integrity": "sha512-/A7o8FU5n4i2WN/RH6opBbteawPbNgyKmmyl6Ts4zpQ5FVq/cGe2K/qGr8t80BLVu8KynTckHbdpaLCwxzRyFA==", "dev": true }, "diff": { @@ -20039,14 +20158,14 @@ "integrity": "sha512-XRsRjdf+j5ml+y/6GKHPZbrF/8p2Yga0JPtdqTIY2Xe5ohJPD9saDJJLPvp9+NSBprVvevdXZybnj2cv8OEd0A==" }, "puppeteer-core": { - "version": "13.4.0", - "resolved": "https://registry.npmjs.org/puppeteer-core/-/puppeteer-core-13.4.0.tgz", - "integrity": "sha512-TcGT5Qgq9tgI0msFrIhq70N1+WrnGowjn0hc4vtzEIizJETXOZVrQZVWy051lO/nxEVGyqRXHwtpWjv4/fRbUw==", + "version": "13.5.1", + "resolved": "https://registry.npmjs.org/puppeteer-core/-/puppeteer-core-13.5.1.tgz", + "integrity": "sha512-dobVqWjV34ilyfQHR3BBnCYaekBYTi5MgegEYBRYd3s3uFy8jUpZEEWbaFjG9ETm+LGzR5Lmr0aF6LLuHtiuCg==", "dev": true, "requires": { "cross-fetch": "3.1.5", "debug": "4.3.3", - "devtools-protocol": "0.0.960912", + "devtools-protocol": "0.0.969999", "extract-zip": "2.0.1", "https-proxy-agent": "5.0.0", "pkg-dir": "4.2.0", @@ -20059,9 +20178,9 @@ }, "dependencies": { "devtools-protocol": { - "version": "0.0.960912", - "resolved": "https://registry.npmjs.org/devtools-protocol/-/devtools-protocol-0.0.960912.tgz", - "integrity": "sha512-I3hWmV9rWHbdnUdmMKHF2NuYutIM2kXz2mdXW8ha7TbRlGTVs+PF+PsB5QWvpCek4Fy9B+msiispCfwlhG5Sqg==", + "version": "0.0.969999", + "resolved": "https://registry.npmjs.org/devtools-protocol/-/devtools-protocol-0.0.969999.tgz", + "integrity": "sha512-6GfzuDWU0OFAuOvBokXpXPLxjOJ5DZ157Ue3sGQQM3LgAamb8m0R0ruSfN0DDu+XG5XJgT50i6zZ/0o8RglreQ==", "dev": true }, "ws": { @@ -22075,19 +22194,19 @@ } }, "webdriver": { - "version": "7.16.16", - "resolved": "https://registry.npmjs.org/webdriver/-/webdriver-7.16.16.tgz", - "integrity": "sha512-x8UoG9k/P8KDrfSh1pOyNevt9tns3zexoMxp9cKnyA/7HYSErhZYTLGlgxscAXLtQG41cMH/Ba/oBmOx7Hgd8w==", + "version": "7.17.3", + "resolved": "https://registry.npmjs.org/webdriver/-/webdriver-7.17.3.tgz", + "integrity": "sha512-E1V/IKYjJoVjK9zhHfSCWeqORhgNlDuYydykm0h+CchEhMSgTmtTH/LYfXSx4myXzobdlIg6xhE7Jv7XPjSkAA==", "dev": true, "requires": { "@types/node": "^17.0.4", - "@wdio/config": "7.16.16", - "@wdio/logger": "7.16.0", - "@wdio/protocols": "7.16.7", - "@wdio/types": "7.16.14", - "@wdio/utils": "7.16.14", + "@wdio/config": "7.17.3", + "@wdio/logger": "7.17.3", + "@wdio/protocols": "7.17.3", + "@wdio/types": "7.17.3", + "@wdio/utils": "7.17.3", "got": "^11.0.2", - "ky": "^0.29.0", + "ky": "^0.30.0", "lodash.merge": "^4.6.1" }, "dependencies": { @@ -22098,21 +22217,39 @@ "dev": true }, "@wdio/config": { - "version": "7.16.16", - "resolved": "https://registry.npmjs.org/@wdio/config/-/config-7.16.16.tgz", - "integrity": "sha512-K/ObPuo6Da2liz++OKOIfbdpFwI7UWiFcBylfJkCYbweuXCoW1aUqlKI6rmKPwCH9Uqr/RHWu6p8eo0zWe6xVA==", + "version": "7.17.3", + "resolved": "https://registry.npmjs.org/@wdio/config/-/config-7.17.3.tgz", + "integrity": "sha512-MSWCsx0w1EbxbwOD8ykTxHqgx208CWoz9n4oWHx7Q1APfetqWFLM4O7K8cdZS1gV4IvH4EAV9807L91K8r0JNw==", "dev": true, "requires": { - "@wdio/logger": "7.16.0", - "@wdio/types": "7.16.14", + "@wdio/logger": "7.17.3", + "@wdio/types": "7.17.3", "deepmerge": "^4.0.0", "glob": "^7.1.2" } }, + "@wdio/logger": { + "version": "7.17.3", + "resolved": "https://registry.npmjs.org/@wdio/logger/-/logger-7.17.3.tgz", + "integrity": "sha512-hpvJDsJMX8G/8gXHOEipxkQPjojjA+BRCZqCvZRLCVpWm2JB7tBoMzu9sUJXcpSkY03b94KAd4EwNA2uNAf9aQ==", + "dev": true, + "requires": { + "chalk": "^4.0.0", + "loglevel": "^1.6.0", + "loglevel-plugin-prefix": "^0.8.4", + "strip-ansi": "^6.0.0" + } + }, + "@wdio/protocols": { + "version": "7.17.3", + "resolved": "https://registry.npmjs.org/@wdio/protocols/-/protocols-7.17.3.tgz", + "integrity": "sha512-DxVRil2uMDOshk0gMOrmemC9uEZuB5Dv4bJX/ozZwXPV9AHd6oJqUrsF/fs8bT9+4AWkE58yqsRBFc/pt7sFMw==", + "dev": true + }, "@wdio/types": { - "version": "7.16.14", - "resolved": "https://registry.npmjs.org/@wdio/types/-/types-7.16.14.tgz", - "integrity": "sha512-AyNI9iBSos9xWBmiFAF3sBs6AJXO/55VppU/eeF4HRdbZMtMarnvMuahM+jlUrA3vJSmDW+ufelG0MT//6vrnw==", + "version": "7.17.3", + "resolved": "https://registry.npmjs.org/@wdio/types/-/types-7.17.3.tgz", + "integrity": "sha512-j8kYdaMl4NFRS8M1bFDuEa3GMbUZbLQY7i6XEnJSetyW0GyMDLlzwcfXI4DdX85+3JbO5624UGKxVsQcuA7T3A==", "dev": true, "requires": { "@types/node": "^17.0.4", @@ -22120,44 +22257,44 @@ } }, "@wdio/utils": { - "version": "7.16.14", - "resolved": "https://registry.npmjs.org/@wdio/utils/-/utils-7.16.14.tgz", - "integrity": "sha512-wwin8nVpIlhmXJkq6GJw9aDDzgLOJKgXTcEua0T2sdXjoW78u5Ly/GZrFXTjMGhacFvoZfitTrjyfyy4CxMVvw==", + "version": "7.17.3", + "resolved": "https://registry.npmjs.org/@wdio/utils/-/utils-7.17.3.tgz", + "integrity": "sha512-20bGTCmgBNVKa2BJs3B5kxbsryjhfEOoKDnFjZ/rAVZYT1t1sg0e/W+vRfamd++NqTaIHOY/IKGEFiEnCw5nXw==", "dev": true, "requires": { - "@wdio/logger": "7.16.0", - "@wdio/types": "7.16.14", + "@wdio/logger": "7.17.3", + "@wdio/types": "7.17.3", "p-iteration": "^1.1.8" } }, "ky": { - "version": "0.29.0", - "resolved": "https://registry.npmjs.org/ky/-/ky-0.29.0.tgz", - "integrity": "sha512-01TBSOqlHmLfcQhHseugGHLxPtU03OyZWaLDWt5MfzCkijG6xWFvAQPhKVn0cR2MMjYvBP9keQ8A3+rQEhLO5g==", + "version": "0.30.0", + "resolved": "https://registry.npmjs.org/ky/-/ky-0.30.0.tgz", + "integrity": "sha512-X/u76z4JtDVq10u1JA5UQfatPxgPaVDMYTrgHyiTpGN2z4TMEJkIHsoSBBSg9SWZEIXTKsi9kHgiQ9o3Y/4yog==", "dev": true } } }, "webdriverio": { - "version": "7.16.16", - "resolved": "https://registry.npmjs.org/webdriverio/-/webdriverio-7.16.16.tgz", - "integrity": "sha512-caPaEWyuD3Qoa7YkW4xCCQA4v9Pa9wmhFGPvNZh3ERtjMCNi8L/XXOdkekWNZmFh3tY0kFguBj7+fAwSY7HAGw==", + "version": "7.17.4", + "resolved": "https://registry.npmjs.org/webdriverio/-/webdriverio-7.17.4.tgz", + "integrity": "sha512-p7u2q7NJL7Et8FdSroq/Ltoi3KkKxERE79Srh9lFr6yRNPFqb46dJf/g4nljLhburnGkbNdYN15JWgyWYnnj9g==", "dev": true, "requires": { "@types/aria-query": "^5.0.0", "@types/node": "^17.0.4", - "@wdio/config": "7.16.16", - "@wdio/logger": "7.16.0", - "@wdio/protocols": "7.16.7", - "@wdio/repl": "7.16.14", - "@wdio/types": "7.16.14", - "@wdio/utils": "7.16.14", + "@wdio/config": "7.17.3", + "@wdio/logger": "7.17.3", + "@wdio/protocols": "7.17.3", + "@wdio/repl": "7.17.3", + "@wdio/types": "7.17.3", + "@wdio/utils": "7.17.3", "archiver": "^5.0.0", "aria-query": "^5.0.0", "css-shorthand-properties": "^1.1.1", "css-value": "^0.0.1", - "devtools": "7.16.16", - "devtools-protocol": "^0.0.973690", + "devtools": "7.17.3", + "devtools-protocol": "^0.0.979353", "fs-extra": "^10.0.0", "get-port": "^5.1.1", "grapheme-splitter": "^1.0.2", @@ -22171,31 +22308,49 @@ "resq": "^1.9.1", "rgb2hex": "0.2.5", "serialize-error": "^8.0.0", - "webdriver": "7.16.16" + "webdriver": "7.17.3" }, "dependencies": { "@types/node": { - "version": "17.0.14", - "resolved": "https://registry.npmjs.org/@types/node/-/node-17.0.14.tgz", - "integrity": "sha512-SbjLmERksKOGzWzPNuW7fJM7fk3YXVTFiZWB/Hs99gwhk+/dnrQRPBQjPW9aO+fi1tAffi9PrwFvsmOKmDTyng==", + "version": "17.0.21", + "resolved": "https://registry.npmjs.org/@types/node/-/node-17.0.21.tgz", + "integrity": "sha512-DBZCJbhII3r90XbQxI8Y9IjjiiOGlZ0Hr32omXIZvwwZ7p4DMMXGrKXVyPfuoBOri9XNtL0UK69jYIBIsRX3QQ==", "dev": true }, "@wdio/config": { - "version": "7.16.16", - "resolved": "https://registry.npmjs.org/@wdio/config/-/config-7.16.16.tgz", - "integrity": "sha512-K/ObPuo6Da2liz++OKOIfbdpFwI7UWiFcBylfJkCYbweuXCoW1aUqlKI6rmKPwCH9Uqr/RHWu6p8eo0zWe6xVA==", + "version": "7.17.3", + "resolved": "https://registry.npmjs.org/@wdio/config/-/config-7.17.3.tgz", + "integrity": "sha512-MSWCsx0w1EbxbwOD8ykTxHqgx208CWoz9n4oWHx7Q1APfetqWFLM4O7K8cdZS1gV4IvH4EAV9807L91K8r0JNw==", "dev": true, "requires": { - "@wdio/logger": "7.16.0", - "@wdio/types": "7.16.14", + "@wdio/logger": "7.17.3", + "@wdio/types": "7.17.3", "deepmerge": "^4.0.0", "glob": "^7.1.2" } }, + "@wdio/logger": { + "version": "7.17.3", + "resolved": "https://registry.npmjs.org/@wdio/logger/-/logger-7.17.3.tgz", + "integrity": "sha512-hpvJDsJMX8G/8gXHOEipxkQPjojjA+BRCZqCvZRLCVpWm2JB7tBoMzu9sUJXcpSkY03b94KAd4EwNA2uNAf9aQ==", + "dev": true, + "requires": { + "chalk": "^4.0.0", + "loglevel": "^1.6.0", + "loglevel-plugin-prefix": "^0.8.4", + "strip-ansi": "^6.0.0" + } + }, + "@wdio/protocols": { + "version": "7.17.3", + "resolved": "https://registry.npmjs.org/@wdio/protocols/-/protocols-7.17.3.tgz", + "integrity": "sha512-DxVRil2uMDOshk0gMOrmemC9uEZuB5Dv4bJX/ozZwXPV9AHd6oJqUrsF/fs8bT9+4AWkE58yqsRBFc/pt7sFMw==", + "dev": true + }, "@wdio/types": { - "version": "7.16.14", - "resolved": "https://registry.npmjs.org/@wdio/types/-/types-7.16.14.tgz", - "integrity": "sha512-AyNI9iBSos9xWBmiFAF3sBs6AJXO/55VppU/eeF4HRdbZMtMarnvMuahM+jlUrA3vJSmDW+ufelG0MT//6vrnw==", + "version": "7.17.3", + "resolved": "https://registry.npmjs.org/@wdio/types/-/types-7.17.3.tgz", + "integrity": "sha512-j8kYdaMl4NFRS8M1bFDuEa3GMbUZbLQY7i6XEnJSetyW0GyMDLlzwcfXI4DdX85+3JbO5624UGKxVsQcuA7T3A==", "dev": true, "requires": { "@types/node": "^17.0.4", @@ -22203,13 +22358,13 @@ } }, "@wdio/utils": { - "version": "7.16.14", - "resolved": "https://registry.npmjs.org/@wdio/utils/-/utils-7.16.14.tgz", - "integrity": "sha512-wwin8nVpIlhmXJkq6GJw9aDDzgLOJKgXTcEua0T2sdXjoW78u5Ly/GZrFXTjMGhacFvoZfitTrjyfyy4CxMVvw==", + "version": "7.17.3", + "resolved": "https://registry.npmjs.org/@wdio/utils/-/utils-7.17.3.tgz", + "integrity": "sha512-20bGTCmgBNVKa2BJs3B5kxbsryjhfEOoKDnFjZ/rAVZYT1t1sg0e/W+vRfamd++NqTaIHOY/IKGEFiEnCw5nXw==", "dev": true, "requires": { - "@wdio/logger": "7.16.0", - "@wdio/types": "7.16.14", + "@wdio/logger": "7.17.3", + "@wdio/types": "7.17.3", "p-iteration": "^1.1.8" } }, From 152f0172708a4938cea07838c63cf3ea35f32b89 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 17 Mar 2022 10:59:00 -0700 Subject: [PATCH 114/128] chore(deps): bump google-closure-deps from 20220104.0.0 to 20220202.0.0 (#5965) Bumps [google-closure-deps](https://github.com/google/closure-library) from 20220104.0.0 to 20220202.0.0. - [Release notes](https://github.com/google/closure-library/releases) - [Commits](https://github.com/google/closure-library/compare/v20220104...v20220202) --- updated-dependencies: - dependency-name: google-closure-deps dependency-type: direct:development update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- package-lock.json | 14 +++++++------- package.json | 2 +- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/package-lock.json b/package-lock.json index 6565fbb26..5967bf2ef 100644 --- a/package-lock.json +++ b/package-lock.json @@ -24,7 +24,7 @@ "eslint": "^8.4.1", "eslint-config-google": "^0.14.0", "google-closure-compiler": "^20220301.0.0", - "google-closure-deps": "^20220104.0.0", + "google-closure-deps": "^20220202.0.0", "gulp": "^4.0.2", "gulp-clang-format": "^1.0.27", "gulp-concat": "^2.6.1", @@ -5287,9 +5287,9 @@ } }, "node_modules/google-closure-deps": { - "version": "20220104.0.0", - "resolved": "https://registry.npmjs.org/google-closure-deps/-/google-closure-deps-20220104.0.0.tgz", - "integrity": "sha512-FylwKqY3QbirbYnjCHtsIJG46XrVHFVXddANP/bmqqBeoJipX377bT3v4UqBNP+kPWv2uFlP/sfUdyVq0S65Ng==", + "version": "20220202.0.0", + "resolved": "https://registry.npmjs.org/google-closure-deps/-/google-closure-deps-20220202.0.0.tgz", + "integrity": "sha512-cPE4GbWRn4ix92UFE1nbjJpQw3eQ/1fGjjMDJG8mghhBEiBBXzBZUEpPALrpdEy9ZYgOdaRAr9UqAN35jfmy8g==", "dev": true, "dependencies": { "minimatch": "^3.0.4", @@ -16767,9 +16767,9 @@ "optional": true }, "google-closure-deps": { - "version": "20220104.0.0", - "resolved": "https://registry.npmjs.org/google-closure-deps/-/google-closure-deps-20220104.0.0.tgz", - "integrity": "sha512-FylwKqY3QbirbYnjCHtsIJG46XrVHFVXddANP/bmqqBeoJipX377bT3v4UqBNP+kPWv2uFlP/sfUdyVq0S65Ng==", + "version": "20220202.0.0", + "resolved": "https://registry.npmjs.org/google-closure-deps/-/google-closure-deps-20220202.0.0.tgz", + "integrity": "sha512-cPE4GbWRn4ix92UFE1nbjJpQw3eQ/1fGjjMDJG8mghhBEiBBXzBZUEpPALrpdEy9ZYgOdaRAr9UqAN35jfmy8g==", "dev": true, "requires": { "minimatch": "^3.0.4", diff --git a/package.json b/package.json index 506410e4c..cba9bc93d 100644 --- a/package.json +++ b/package.json @@ -78,7 +78,7 @@ "eslint": "^8.4.1", "eslint-config-google": "^0.14.0", "google-closure-compiler": "^20220301.0.0", - "google-closure-deps": "^20220104.0.0", + "google-closure-deps": "^20220202.0.0", "gulp": "^4.0.2", "gulp-clang-format": "^1.0.27", "gulp-concat": "^2.6.1", From f344f9a89e71d033bd23d3ded2a073b74e09f1d7 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 17 Mar 2022 11:02:16 -0700 Subject: [PATCH 115/128] chore(deps): bump @blockly/dev-tools from 3.0.6 to 3.0.7 (#5963) Bumps [@blockly/dev-tools](https://github.com/google/blockly-samples/tree/HEAD/plugins/dev-tools) from 3.0.6 to 3.0.7. - [Release notes](https://github.com/google/blockly-samples/releases) - [Commits](https://github.com/google/blockly-samples/commits/@blockly/dev-tools@3.0.7/plugins/dev-tools) --- updated-dependencies: - dependency-name: "@blockly/dev-tools" dependency-type: direct:development update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- package-lock.json | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/package-lock.json b/package-lock.json index 5967bf2ef..90af7fb1d 100644 --- a/package-lock.json +++ b/package-lock.json @@ -167,9 +167,9 @@ } }, "node_modules/@blockly/dev-tools": { - "version": "3.0.6", - "resolved": "https://registry.npmjs.org/@blockly/dev-tools/-/dev-tools-3.0.6.tgz", - "integrity": "sha512-0JqbdZ0CfJ0ZbHXdUKfhlqyZ3QnKgAsBq5PV469e57VGgSFSWgc+1FKmn0CpBP2f5b7R/oTQQCtYfW7xsuFNbQ==", + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/@blockly/dev-tools/-/dev-tools-3.0.7.tgz", + "integrity": "sha512-s55teQLYNKOtWZIngce2WFy052CrEGPMfhRzQgFKlrTfVafr+iZc+E4MTIY1J9R2Zw5uKnfxULV8LfNrwcH+fA==", "dev": true, "dependencies": { "@blockly/block-test": "^2.0.4", @@ -12692,9 +12692,9 @@ "requires": {} }, "@blockly/dev-tools": { - "version": "3.0.6", - "resolved": "https://registry.npmjs.org/@blockly/dev-tools/-/dev-tools-3.0.6.tgz", - "integrity": "sha512-0JqbdZ0CfJ0ZbHXdUKfhlqyZ3QnKgAsBq5PV469e57VGgSFSWgc+1FKmn0CpBP2f5b7R/oTQQCtYfW7xsuFNbQ==", + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/@blockly/dev-tools/-/dev-tools-3.0.7.tgz", + "integrity": "sha512-s55teQLYNKOtWZIngce2WFy052CrEGPMfhRzQgFKlrTfVafr+iZc+E4MTIY1J9R2Zw5uKnfxULV8LfNrwcH+fA==", "dev": true, "requires": { "@blockly/block-test": "^2.0.4", From cefb5055369a392bb40ba4f1f654fcfa6d8c7c5b Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 17 Mar 2022 13:33:53 -0700 Subject: [PATCH 116/128] chore(deps): bump @wdio/selenium-standalone-service (#6006) Bumps [@wdio/selenium-standalone-service](https://github.com/webdriverio/webdriverio) from 7.16.16 to 7.18.0. - [Release notes](https://github.com/webdriverio/webdriverio/releases) - [Changelog](https://github.com/webdriverio/webdriverio/blob/main/CHANGELOG.md) - [Commits](https://github.com/webdriverio/webdriverio/compare/v7.16.16...v7.18.0) --- updated-dependencies: - dependency-name: "@wdio/selenium-standalone-service" dependency-type: direct:development update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- package-lock.json | 85 +++++++++++++++++++++++++++++++---------------- 1 file changed, 57 insertions(+), 28 deletions(-) diff --git a/package-lock.json b/package-lock.json index 90af7fb1d..617762bf3 100644 --- a/package-lock.json +++ b/package-lock.json @@ -979,6 +979,7 @@ "resolved": "https://registry.npmjs.org/@wdio/logger/-/logger-7.16.0.tgz", "integrity": "sha512-/6lOGb2Iow5eSsy7RJOl1kCwsP4eMlG+/QKro5zUJsuyNJSQXf2ejhpkzyKWLgQbHu83WX6cM1014AZuLkzoQg==", "dev": true, + "peer": true, "dependencies": { "chalk": "^4.0.0", "loglevel": "^1.6.0", @@ -1060,17 +1061,17 @@ } }, "node_modules/@wdio/selenium-standalone-service": { - "version": "7.16.16", - "resolved": "https://registry.npmjs.org/@wdio/selenium-standalone-service/-/selenium-standalone-service-7.16.16.tgz", - "integrity": "sha512-RPjwTNfIHE53RmtQY0ZV6Bwh+rDfMz79fmwX0WHRVOoPIcjRV68UctGjU3pQInOwrDyyP7ztLnFFEYLhOYZRfQ==", + "version": "7.18.0", + "resolved": "https://registry.npmjs.org/@wdio/selenium-standalone-service/-/selenium-standalone-service-7.18.0.tgz", + "integrity": "sha512-Tl+GB45oYsnL5zP5xQU245Uhcm3IFL7XP3x7nIsUj7VHzWPSvMB4Hib90CnNiTd2pY1AUC8q+2rlS1M1jZq3VQ==", "dev": true, "dependencies": { "@types/fs-extra": "^9.0.1", "@types/node": "^17.0.4", "@types/selenium-standalone": "^7.0.0", - "@wdio/config": "7.16.16", - "@wdio/logger": "7.16.0", - "@wdio/types": "7.16.14", + "@wdio/config": "7.18.0", + "@wdio/logger": "7.17.3", + "@wdio/types": "7.18.0", "fs-extra": "^10.0.0", "selenium-standalone": "^8.0.3" }, @@ -1088,13 +1089,13 @@ "dev": true }, "node_modules/@wdio/selenium-standalone-service/node_modules/@wdio/config": { - "version": "7.16.16", - "resolved": "https://registry.npmjs.org/@wdio/config/-/config-7.16.16.tgz", - "integrity": "sha512-K/ObPuo6Da2liz++OKOIfbdpFwI7UWiFcBylfJkCYbweuXCoW1aUqlKI6rmKPwCH9Uqr/RHWu6p8eo0zWe6xVA==", + "version": "7.18.0", + "resolved": "https://registry.npmjs.org/@wdio/config/-/config-7.18.0.tgz", + "integrity": "sha512-pXv4MWfMFSOXU6eJRbJuHcP0hN9sOyRzEpHNgMk6hsDpzqSKFp2Rg4fYrlmvYJILrM6PxTfylVz9gwP4QWOsdA==", "dev": true, "dependencies": { - "@wdio/logger": "7.16.0", - "@wdio/types": "7.16.14", + "@wdio/logger": "7.17.3", + "@wdio/types": "7.18.0", "deepmerge": "^4.0.0", "glob": "^7.1.2" }, @@ -1102,10 +1103,25 @@ "node": ">=12.0.0" } }, + "node_modules/@wdio/selenium-standalone-service/node_modules/@wdio/logger": { + "version": "7.17.3", + "resolved": "https://registry.npmjs.org/@wdio/logger/-/logger-7.17.3.tgz", + "integrity": "sha512-hpvJDsJMX8G/8gXHOEipxkQPjojjA+BRCZqCvZRLCVpWm2JB7tBoMzu9sUJXcpSkY03b94KAd4EwNA2uNAf9aQ==", + "dev": true, + "dependencies": { + "chalk": "^4.0.0", + "loglevel": "^1.6.0", + "loglevel-plugin-prefix": "^0.8.4", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=12.0.0" + } + }, "node_modules/@wdio/selenium-standalone-service/node_modules/@wdio/types": { - "version": "7.16.14", - "resolved": "https://registry.npmjs.org/@wdio/types/-/types-7.16.14.tgz", - "integrity": "sha512-AyNI9iBSos9xWBmiFAF3sBs6AJXO/55VppU/eeF4HRdbZMtMarnvMuahM+jlUrA3vJSmDW+ufelG0MT//6vrnw==", + "version": "7.18.0", + "resolved": "https://registry.npmjs.org/@wdio/types/-/types-7.18.0.tgz", + "integrity": "sha512-GZO5gmobbAOGln4+edAsyPbeLes4I6ZCa0iBn/KVM72y8cvHH+L2ojLsDvzd6Pn/g79zDjEUpBH7BgkDplj8lg==", "dev": true, "dependencies": { "@types/node": "^17.0.4", @@ -13376,6 +13392,7 @@ "resolved": "https://registry.npmjs.org/@wdio/logger/-/logger-7.16.0.tgz", "integrity": "sha512-/6lOGb2Iow5eSsy7RJOl1kCwsP4eMlG+/QKro5zUJsuyNJSQXf2ejhpkzyKWLgQbHu83WX6cM1014AZuLkzoQg==", "dev": true, + "peer": true, "requires": { "chalk": "^4.0.0", "loglevel": "^1.6.0", @@ -13441,17 +13458,17 @@ } }, "@wdio/selenium-standalone-service": { - "version": "7.16.16", - "resolved": "https://registry.npmjs.org/@wdio/selenium-standalone-service/-/selenium-standalone-service-7.16.16.tgz", - "integrity": "sha512-RPjwTNfIHE53RmtQY0ZV6Bwh+rDfMz79fmwX0WHRVOoPIcjRV68UctGjU3pQInOwrDyyP7ztLnFFEYLhOYZRfQ==", + "version": "7.18.0", + "resolved": "https://registry.npmjs.org/@wdio/selenium-standalone-service/-/selenium-standalone-service-7.18.0.tgz", + "integrity": "sha512-Tl+GB45oYsnL5zP5xQU245Uhcm3IFL7XP3x7nIsUj7VHzWPSvMB4Hib90CnNiTd2pY1AUC8q+2rlS1M1jZq3VQ==", "dev": true, "requires": { "@types/fs-extra": "^9.0.1", "@types/node": "^17.0.4", "@types/selenium-standalone": "^7.0.0", - "@wdio/config": "7.16.16", - "@wdio/logger": "7.16.0", - "@wdio/types": "7.16.14", + "@wdio/config": "7.18.0", + "@wdio/logger": "7.17.3", + "@wdio/types": "7.18.0", "fs-extra": "^10.0.0", "selenium-standalone": "^8.0.3" }, @@ -13463,21 +13480,33 @@ "dev": true }, "@wdio/config": { - "version": "7.16.16", - "resolved": "https://registry.npmjs.org/@wdio/config/-/config-7.16.16.tgz", - "integrity": "sha512-K/ObPuo6Da2liz++OKOIfbdpFwI7UWiFcBylfJkCYbweuXCoW1aUqlKI6rmKPwCH9Uqr/RHWu6p8eo0zWe6xVA==", + "version": "7.18.0", + "resolved": "https://registry.npmjs.org/@wdio/config/-/config-7.18.0.tgz", + "integrity": "sha512-pXv4MWfMFSOXU6eJRbJuHcP0hN9sOyRzEpHNgMk6hsDpzqSKFp2Rg4fYrlmvYJILrM6PxTfylVz9gwP4QWOsdA==", "dev": true, "requires": { - "@wdio/logger": "7.16.0", - "@wdio/types": "7.16.14", + "@wdio/logger": "7.17.3", + "@wdio/types": "7.18.0", "deepmerge": "^4.0.0", "glob": "^7.1.2" } }, + "@wdio/logger": { + "version": "7.17.3", + "resolved": "https://registry.npmjs.org/@wdio/logger/-/logger-7.17.3.tgz", + "integrity": "sha512-hpvJDsJMX8G/8gXHOEipxkQPjojjA+BRCZqCvZRLCVpWm2JB7tBoMzu9sUJXcpSkY03b94KAd4EwNA2uNAf9aQ==", + "dev": true, + "requires": { + "chalk": "^4.0.0", + "loglevel": "^1.6.0", + "loglevel-plugin-prefix": "^0.8.4", + "strip-ansi": "^6.0.0" + } + }, "@wdio/types": { - "version": "7.16.14", - "resolved": "https://registry.npmjs.org/@wdio/types/-/types-7.16.14.tgz", - "integrity": "sha512-AyNI9iBSos9xWBmiFAF3sBs6AJXO/55VppU/eeF4HRdbZMtMarnvMuahM+jlUrA3vJSmDW+ufelG0MT//6vrnw==", + "version": "7.18.0", + "resolved": "https://registry.npmjs.org/@wdio/types/-/types-7.18.0.tgz", + "integrity": "sha512-GZO5gmobbAOGln4+edAsyPbeLes4I6ZCa0iBn/KVM72y8cvHH+L2ojLsDvzd6Pn/g79zDjEUpBH7BgkDplj8lg==", "dev": true, "requires": { "@types/node": "^17.0.4", From e502eaa6e1c88b2bb34e9a87917a15098b81cfa3 Mon Sep 17 00:00:00 2001 From: Beka Westberg Date: Fri, 18 Mar 2022 11:06:24 -0700 Subject: [PATCH 117/128] fix: incorrect module for event data in renamings database (#6012) --- scripts/migration/renamings.json5 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/migration/renamings.json5 b/scripts/migration/renamings.json5 index 4935f9a36..2d456384d 100644 --- a/scripts/migration/renamings.json5 +++ b/scripts/migration/renamings.json5 @@ -92,7 +92,7 @@ oldName: 'Blockly', exports: { // bind/unbind events functions. See PR #4642 - EventData: {newModule: 'Blockly.eventHandling', newExport: 'Data'}, + EventData: {newModule: 'Blockly.browserEvents', newExport: 'Data'}, bindEvent_: {newModule: 'Blockly.browserEvents', newExport: 'bind'}, unbindEvent_: {newModule: 'Blockly.browserEvents', newExport: 'unbind'}, bindEventWithChecks_: { From 85ce3b82c6c32e8a2a1608c6d604262ea0e5c38d Mon Sep 17 00:00:00 2001 From: YAMADA Yutaka <77612853+yamadayutaka@users.noreply.github.com> Date: Mon, 21 Mar 2022 23:51:51 +0900 Subject: [PATCH 118/128] fix: comments not being restored when dragging (#6011) * fix comment deserialization * add restore comment test * Fix comment. * fix: Modify test structure. --- core/serialization/blocks.js | 9 +- tests/deps.mocha.js | 1 + tests/mocha/comment_deserialization_test.js | 117 ++++++++++++++++++++ tests/mocha/index.html | 1 + 4 files changed, 126 insertions(+), 2 deletions(-) create mode 100644 tests/mocha/comment_deserialization_test.js diff --git a/core/serialization/blocks.js b/core/serialization/blocks.js index 2e3b76bbd..6aabb08ee 100644 --- a/core/serialization/blocks.js +++ b/core/serialization/blocks.js @@ -514,8 +514,13 @@ const loadIcons = function(block, state) { const comment = state['icons']['comment']; if (comment) { block.setCommentText(comment['text']); - block.commentModel.pinned = comment['pinned']; - block.commentModel.size = new Size(comment['width'], comment['height']); + // Load if saved. (Cleaned unnecessary attributes when in the trashcan.) + if ('pinned' in comment) { + block.commentModel.pinned = comment['pinned']; + } + if ('width' in comment && 'height' in comment) { + block.commentModel.size = new Size(comment['width'], comment['height']); + } if (comment['pinned'] && block.rendered && !block.isInFlyout) { // Give the block a chance to be positioned and rendered before showing. const blockSvg = /** @type {!BlockSvg} */ (block); diff --git a/tests/deps.mocha.js b/tests/deps.mocha.js index c43d84e13..ba58a1b31 100644 --- a/tests/deps.mocha.js +++ b/tests/deps.mocha.js @@ -4,6 +4,7 @@ goog.addDependency('../../tests/mocha/block_change_event_test.js', ['Blockly.tes goog.addDependency('../../tests/mocha/block_create_event_test.js', ['Blockly.test.blockCreateEvent'], ['Blockly.Events.utils', 'Blockly.test.helpers.events', 'Blockly.test.helpers.setupTeardown'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../tests/mocha/block_json_test.js', ['Blockly.test.blockJson'], ['Blockly.Input'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../tests/mocha/block_test.js', ['Blockly.test.blocks'], ['Blockly.ConnectionType', 'Blockly.Events.utils', 'Blockly.blocks', 'Blockly.test.helpers.blockDefinitions', 'Blockly.test.helpers.setupTeardown', 'Blockly.test.helpers.warnings'], {'lang': 'es6', 'module': 'goog'}); +goog.addDependency('../../tests/mocha/comment_deserialization_test.js', ['Blockly.test.commentDeserialization'], ['Blockly.test.helpers.setupTeardown', 'Blockly.test.helpers.userInput'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../tests/mocha/comment_test.js', ['Blockly.test.comments'], ['Blockly.Events.utils', 'Blockly.test.helpers.events', 'Blockly.test.helpers.setupTeardown'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../tests/mocha/connection_checker_test.js', ['Blockly.test.connectionChecker'], ['Blockly.ConnectionType', 'Blockly.test.helpers.setupTeardown'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../tests/mocha/connection_db_test.js', ['Blockly.test.connectionDb'], ['Blockly.ConnectionType', 'Blockly.test.helpers.setupTeardown'], {'lang': 'es6', 'module': 'goog'}); diff --git a/tests/mocha/comment_deserialization_test.js b/tests/mocha/comment_deserialization_test.js new file mode 100644 index 000000000..f3eb48dc5 --- /dev/null +++ b/tests/mocha/comment_deserialization_test.js @@ -0,0 +1,117 @@ +/** + * @license + * Copyright 2022 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ + +goog.module('Blockly.test.commentDeserialization'); + +const {sharedTestSetup, sharedTestTeardown} = goog.require('Blockly.test.helpers.setupTeardown'); +const {simulateClick} = goog.require('Blockly.test.helpers.userInput'); + + +suite('Comment Deserialization', function() { + setup(function() { + sharedTestSetup.call(this); + Blockly.defineBlocksWithJsonArray([ + { + "type": "empty_block", + "message0": "", + "args0": [], + }, + ]); + const toolboxXml = ` + + + + test toolbox text + + + + `; + this.workspace = Blockly.inject('blocklyDiv', { + comments: true, + scrollbars: true, + trashcan: true, + maxTrashcanContents: Infinity, + toolbox: Blockly.Xml.textToDom(toolboxXml), + }); + }); + teardown(function() { + sharedTestTeardown.call(this); + }); + suite('Pattern', function() { + teardown(function() { + // Delete all blocks. + this.workspace.clear(); + }); + function createBlock(workspace) { + const block = Blockly.Xml.domToBlock(Blockly.Xml.textToDom( + '' + ), workspace); + block.setCommentText('test text'); + return block; + } + function assertComment(workspace, text) { + // Show comment. + const block = workspace.getAllBlocks()[0]; + block.comment.setVisible(true); + // Check comment bubble size. + const comment = block.getCommentIcon(); + const bubbleSize = comment.getBubbleSize(); + chai.assert.isNotNaN(bubbleSize.width); + chai.assert.isNotNaN(bubbleSize.height); + // Check comment text. + chai.assert.equal(comment.textarea_.value, text); + } + test('Trashcan', function() { + // Create block. + this.block = createBlock(this.workspace); + // Delete block. + this.block.checkAndDelete(); + chai.assert.equal(this.workspace.getAllBlocks().length, 0); + // Open trashcan. + simulateClick(this.workspace.trashcan.svgGroup_); + // Place from trashcan. + simulateClick(this.workspace.trashcan.flyout.svgGroup_.querySelector('.blocklyDraggable')); + chai.assert.equal(this.workspace.getAllBlocks().length, 1); + // Check comment. + assertComment(this.workspace, 'test text'); + }); + test('Undo', function() { + // Create block. + this.block = createBlock(this.workspace); + // Delete block. + this.block.checkAndDelete(); + chai.assert.equal(this.workspace.getAllBlocks().length, 0); + // Undo. + this.workspace.undo(false); + chai.assert.equal(this.workspace.getAllBlocks().length, 1); + // Check comment. + assertComment(this.workspace, 'test text'); + }); + test('Redo', function() { + // Create block. + this.block = createBlock(this.workspace); + // Undo & undo. + this.workspace.undo(false); + this.workspace.undo(false); + chai.assert.equal(this.workspace.getAllBlocks().length, 0); + // Redo & redo. + this.workspace.undo(true); + this.workspace.undo(true); + chai.assert.equal(this.workspace.getAllBlocks().length, 1); + // Check comment. + assertComment(this.workspace, 'test text'); + }); + test('Toolbox', function() { + // Place from toolbox. + const toolbox = this.workspace.getToolbox(); + simulateClick(toolbox.HtmlDiv.querySelector('.blocklyTreeRow')); + simulateClick(toolbox.getFlyout().svgGroup_.querySelector('.blocklyDraggable')); + chai.assert.equal(this.workspace.getAllBlocks().length, 1); + // Check comment. + assertComment(this.workspace, 'test toolbox text'); + }); + }); +}); diff --git a/tests/mocha/index.html b/tests/mocha/index.html index 1891821b2..27edd9d6a 100644 --- a/tests/mocha/index.html +++ b/tests/mocha/index.html @@ -60,6 +60,7 @@ goog.require('Blockly.test.blockJson'); goog.require('Blockly.test.blocks'); goog.require('Blockly.test.comments'); + goog.require('Blockly.test.commentDeserialization'); goog.require('Blockly.test.connectionChecker'); goog.require('Blockly.test.connectionDb'); goog.require('Blockly.test.connection'); From 243fc52a96e1089aad89ff6b642c6605d8f71afd Mon Sep 17 00:00:00 2001 From: alschmiedt Date: Mon, 21 Mar 2022 08:43:46 -0700 Subject: [PATCH 119/128] fix: opening/closing the mutators (#6000) --- core/mutator.js | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/core/mutator.js b/core/mutator.js index fc9391d36..08b36533e 100644 --- a/core/mutator.js +++ b/core/mutator.js @@ -366,8 +366,10 @@ class Mutator extends Icon { if (this.block_.saveConnections) { const thisRootBlock = this.rootBlock_; this.block_.saveConnections(thisRootBlock); - this.sourceListener_ = function() { - this.block_.saveConnections(thisRootBlock); + this.sourceListener_ = () => { + if (this.block_) { + this.block_.saveConnections(thisRootBlock); + } }; this.block_.workspace.addChangeListener(this.sourceListener_); } From 9d62f92a2ffddac6fb5fcb3c3fa7405250b4f47d Mon Sep 17 00:00:00 2001 From: Christopher Allen Date: Mon, 21 Mar 2022 20:10:48 +0000 Subject: [PATCH 120/128] refactor(build): Prepare UMD wrapper generation for transition to ES modules (#5993) * fix(build): Correctly handle out-of-order chunks It turns out that closure-calculate-chunks does not guarantee that calculated chunks will be output in the same order as the entrypoints, so modify getChunkOptions so that it no longer makes that assumption. * refactor(build): Introduce NAMESPACE_PROPERTY; rename NAMESPACE_OBJECT Rename the constant NAMESPACE_OBJECT to NAMESPACE_VARIABLE to better explain its actual meaning, and introduce NAMESPACE_PROPERTY to specify what property the namespace object will be stored in (and change the previous value, "internal_", to "__namespace__" to reduce the chance of conflicts with properties created by the output of Closure Compiler). * refactor(build): Always save namespace object on chunk exports object This is so that chunks whose parent chunk is not the root chunk (chunks[0]) can obtain the namespace object. (See following commit.) * fix(build): Correct handling of chunk dependencies Previously getChunkOptions and chunkWrapper incorrectly assumed that a chunk could have more than one dependency. In fact, each chunk can have only a single dependency, which is its parent chunk. It is used only to retrieve the namespace object, which is saved on to the exports object for the chunk so that any child chunk(s) can obtain it. Update getChunkOptions and chunkWrapper (making the latter longer but more readable) accordingly. * refactor(build): Rename/repurpose chunk.exports -> .reexport And remove chunk.importAs, since it was no longer being used anywhere. * fix: remove unnecessary s from reexports Co-authored-by: alschmiedt --- scripts/gulpfiles/build_tasks.js | 155 +++++++++++++++++-------------- 1 file changed, 87 insertions(+), 68 deletions(-) diff --git a/scripts/gulpfiles/build_tasks.js b/scripts/gulpfiles/build_tasks.js index 678c9ab4c..47b324164 100644 --- a/scripts/gulpfiles/build_tasks.js +++ b/scripts/gulpfiles/build_tasks.js @@ -61,7 +61,16 @@ const CHUNK_CACHE_FILE = 'scripts/gulpfiles/chunks.json' * wrapper argument, but as it will appear many times in the compiled * output it is preferable that it be short. */ -const NAMESPACE_OBJECT = '$'; +const NAMESPACE_VARIABLE = '$'; + +/** + * Property that will be used to store the value of the namespace + * object on each chunk's exported object. This is so that dependent + * chunks can retrieve the namespace object and thereby access modules + * defined in the parent chunk (or it's parent, etc.). This should be + * chosen so as to not collide with any exported name. + */ +const NAMESPACE_PROPERTY = '__namespace__'; /** * A list of chunks. Order matters: later chunks can depend on @@ -73,25 +82,16 @@ const NAMESPACE_OBJECT = '$'; * will be written to. * - .entry: the source .js file which is the entrypoint for the * chunk. - * - .exports: a variable or property that will (prefixed with - * NAMESPACE_OBJECT) be returned from the factory function and which - * (sans prefix) will be set in the global scope to that returned - * value if the module is loaded in a browser. - * - .importAs: the name that this chunk's exports object will be - * given when passed to the factory function of other chunks that - * depend on it. (Needs to be distinct from .exports since (e.g.) - * "Blockly.libraryBlocks" is not a valid variable name.) - * - .factoryPreamble: code to override the default wrapper factory - * function preamble. - * - .factoryPostamble: code to override the default wrapper factory - * function postabmle. + * - .reexport: if running in a browser, save the chunk's exports + * object at this location in the global namespace. * * The function getChunkOptions will, after running * closure-calculate-chunks, update each chunk to add the following * properties: * - * - .dependencies: a list of the chunks the chunk depends upon. - * - .wrapper: the chunk wrapper. + * - .parent: the parent chunk of the given chunk. Typically + * chunks[0], except for chunk[0].parent which will be null. + * - .wrapper: the generated chunk wrapper. * * Output files will be named .js. */ @@ -99,55 +99,40 @@ const chunks = [ { name: 'blockly', entry: 'core/blockly.js', - exports: 'Blockly', - importAs: 'Blockly', - factoryPreamble: `const ${NAMESPACE_OBJECT}={};`, - factoryPostamble: - `${NAMESPACE_OBJECT}.Blockly.internal_=${NAMESPACE_OBJECT};`, + reexport: 'Blockly', }, { name: 'blocks', entry: 'blocks/blocks.js', - exports: 'Blockly.libraryBlocks', - importAs: 'libraryBlocks', + reexport: 'Blockly.libraryBlocks', }, { name: 'javascript', entry: 'generators/javascript/all.js', - exports: 'Blockly.JavaScript', + reexport: 'Blockly.JavaScript', }, { name: 'python', entry: 'generators/python/all.js', - exports: 'Blockly.Python', + reexport: 'Blockly.Python', }, { name: 'php', entry: 'generators/php/all.js', - exports: 'Blockly.PHP', + reexport: 'Blockly.PHP', }, { name: 'lua', entry: 'generators/lua/all.js', - exports: 'Blockly.Lua', + reexport: 'Blockly.Lua', }, { name: 'dart', entry: 'generators/dart/all.js', - exports: 'Blockly.Dart', + reexport: 'Blockly.Dart', } ]; -/** - * The default factory function premable. - */ -const FACTORY_PREAMBLE = `const ${NAMESPACE_OBJECT}=Blockly.internal_;`; - -/** - * The default factory function postamble. - */ -const FACTORY_POSTAMBLE = ''; - const licenseRegex = `\\/\\*\\* \\* @license \\* (Copyright \\d+ (Google LLC|Massachusetts Institute of Technology)) @@ -356,13 +341,40 @@ function buildLangfiles(done) { * Definition. */ function chunkWrapper(chunk) { - const fileNames = chunk.dependencies.map( - d => JSON.stringify(`./${d.name}${COMPILED_SUFFIX}.js`)); - const amdDeps = fileNames.join(', '); - const cjsDeps = fileNames.map(f => `require(${f})`).join(', '); - const browserDeps = - chunk.dependencies.map(d => `root.${d.exports}`).join(', '); - const factoryParams = chunk.dependencies.map(d => d.importAs).join(', '); + // Each chunk can have only a single dependency, which is its parent + // chunk. It is used only to retrieve the namespace object, which + // is saved on to the exports object for the chunk so that any child + // chunk(s) can obtain it. + + // JavaScript expressions for the amd, cjs and browser dependencies. + let amdDepsExpr = ''; + let cjsDepsExpr = ''; + let browserDepsExpr = ''; + // Arguments for the factory function. + let factoryArgs = ''; + // Expression to get or create the namespace object. + let namespaceExpr = `{}`; + + if (chunk.parent) { + const parentFilename = + JSON.stringify(`./${chunk.parent.name}${COMPILED_SUFFIX}.js`); + amdDepsExpr = parentFilename; + cjsDepsExpr = `require(${parentFilename})`; + browserDepsExpr = `root.${chunk.parent.reexport}`; + factoryArgs = '__parent__'; + namespaceExpr = `${factoryArgs}.${NAMESPACE_PROPERTY}`; + } + + // Expression that evaluates the the value of the exports object for + // the specified chunk. For now we guess the name that is created + // by the module's goog.module.delcareLegacyNamespace call based on + // chunk.reexport. + const exportsExpression = `${NAMESPACE_VARIABLE}.${chunk.reexport}`; + // In near future we might try to guess the internally-generated + // name for the ES module's exports object. + // const exportsExpression = + // 'module$' + chunk.entry.replace(/\.m?js$/, '').replace(/\//g, '$'); + // Note that when loading in a browser the base of the exported path // (e.g. Blockly.blocks.all - see issue #5932) might not exist @@ -374,18 +386,18 @@ function chunkWrapper(chunk) { /* eslint-disable */ ;(function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD - define([${amdDeps}], factory); + define([${amdDepsExpr}], factory); } else if (typeof exports === 'object') { // Node.js - module.exports = factory(${cjsDeps}); + module.exports = factory(${cjsDepsExpr}); } else { // Browser - var factoryExports = factory(${browserDeps}); - root.${chunk.exports} = factoryExports; + var factoryExports = factory(${browserDepsExpr}); + root.${chunk.reexport} = factoryExports; } -}(this, function(${factoryParams}) { -${chunk.factoryPreamble || FACTORY_PREAMBLE} +}(this, function(${factoryArgs}) { +var ${NAMESPACE_VARIABLE}=${namespaceExpr}; %output% -${chunk.factoryPostamble || FACTORY_POSTAMBLE} -return ${NAMESPACE_OBJECT}.${chunk.exports}; +${exportsExpression}.${NAMESPACE_PROPERTY}=${NAMESPACE_VARIABLE}; +return ${exportsExpression}; })); `; }; @@ -459,26 +471,33 @@ function getChunkOptions() { // This is designed to be passed directly as-is as the options // object to the Closure Compiler node API, but we want to replace // the unhelpful entry-point based chunk names (let's call these - // "nicknames") with the ones from chunks. Luckily they will be in - // the same order that the entry points were supplied in - i.e., - // they correspond 1:1 with the entries in chunks. + // "nicknames") with the ones from chunks. Unforutnately there's no + // guarnatee they will be in the same order that the entry points + // were supplied in (though it happens to work out that way if no + // chunk depends on any chunk but the first), so we look for + // one of the entrypoints amongst the files in each chunk. const chunkByNickname = Object.create(null); - let jsFiles = rawOptions.js; - const chunkList = rawOptions.chunk.map((element, index) => { - const [nickname, numJsFiles, dependencyNicks] = element.split(':'); - const chunk = chunks[index]; + const jsFiles = rawOptions.js.slice(); // Will be modified via .splice! + const chunkList = rawOptions.chunk.map((element) => { + const [nickname, numJsFiles, parentNick] = element.split(':'); - // Replace nicknames with our names. + // Get array of files for just this chunk. + const chunkFiles = jsFiles.splice(0, numJsFiles); + + // Figure out which chunk this is by looking for one of the + // known chunk entrypoints in chunkFiles. N.B.: O(n*m). :-( + const chunk = chunks.find( + chunk => chunkFiles.find(f => f.endsWith('/' + chunk.entry))); + if (!chunk) throw new Error('Unable to identify chunk'); + + // Replace nicknames with the names we chose. chunkByNickname[nickname] = chunk; - if (!dependencyNicks) { // Chunk has no dependencies. - chunk.dependencies = []; + if (!parentNick) { // Chunk has no parent. + chunk.parent = null; return `${chunk.name}:${numJsFiles}`; } - chunk.dependencies = - dependencyNicks.split(',').map(nick => chunkByNickname[nick]); - const dependencyNames = - chunk.dependencies.map(dependency => dependency.name).join(','); - return `${chunk.name}:${numJsFiles}:${dependencyNames}`; + chunk.parent = chunkByNickname[parentNick]; + return `${chunk.name}:${numJsFiles}:${chunk.parent.name}`; }); // Generate a chunk wrapper for each chunk. @@ -577,7 +596,7 @@ function buildCompiled() { define: 'Blockly.VERSION="' + packageJson.version + '"', chunk: chunkOptions.chunk, chunk_wrapper: chunkOptions.chunk_wrapper, - rename_prefix_namespace: NAMESPACE_OBJECT, + rename_prefix_namespace: NAMESPACE_VARIABLE, // Don't supply the list of source files in chunkOptions.js as an // option to Closure Compiler; instead feed them as input via gulp.src. }; From 7abf3de910a35e1a6086a3243570627a41e73339 Mon Sep 17 00:00:00 2001 From: Beka Westberg Date: Mon, 21 Mar 2022 14:12:47 -0700 Subject: [PATCH 121/128] fix: playground test blocks, text area listeners, and show/hide buttons (#6015) --- tests/playground.html | 24 +++++++++++++++++------- 1 file changed, 17 insertions(+), 7 deletions(-) diff --git a/tests/playground.html b/tests/playground.html index 67489339d..44255cb2e 100644 --- a/tests/playground.html +++ b/tests/playground.html @@ -7,6 +7,7 @@ + - - + + - - - +
diff --git a/tests/playgrounds/prepare.js b/tests/playgrounds/prepare.js index 8b9d534cb..d428b9524 100644 --- a/tests/playgrounds/prepare.js +++ b/tests/playgrounds/prepare.js @@ -70,16 +70,30 @@ }); `); } else { + // The below code is necessary for a few reasons: + // - We need an absolute path instead of relative path because the + // advanced_playground the and regular playground are in different folders. + // - We need to get the root directory for blockly because it is + // different for github.io, appspot and local. + const files = [ + 'blockly_compressed.js', + 'msg/messages.js', + 'blocks_compressed.js', + 'dart_compressed.js', + 'javascript_compressed.js', + 'lua_compressed.js', + 'php_compressed.js', + 'python_compressed.js', + ]; + // We need to load Blockly in compiled mode. + const hostName = window.location.host.replaceAll('.', '\\.'); + const matches = new RegExp(hostName + '\\/(.*)tests').exec(window.location.href); + const root = matches && matches[1] ? matches[1] : ''; // Load blockly_compressed.js et al. using '); - document.write(''); - document.write(''); - document.write(''); - document.write(''); - document.write(''); - document.write(''); - document.write(''); + for (let i = 0; i < files.length; i++) { + document.write(''); + } } })(); diff --git a/tests/themes/test_themes.js b/tests/themes/test_themes.js index 30792ae9e..ad42d50af 100644 --- a/tests/themes/test_themes.js +++ b/tests/themes/test_themes.js @@ -5,24 +5,22 @@ */ 'use strict'; -goog.provide('Blockly.TestThemes'); - /** * A theme with classic colours but enables start hats. */ -Blockly.Themes.TestHats = Blockly.Theme.defineTheme('testhats', { +const TestHatsTheme = Blockly.Theme.defineTheme('testhats', { 'base': Blockly.Themes.Classic }); -Blockly.Themes.TestHats.setStartHats(true); +TestHatsTheme.setStartHats(true); /** * A theme with classic colours but a different font. */ -Blockly.Themes.TestFont = Blockly.Theme.defineTheme('testfont', { +const TestFontTheme = Blockly.Theme.defineTheme('testfont', { 'base': Blockly.Themes.Classic }); -Blockly.Themes.TestFont.setFontStyle({ +TestFontTheme.setFontStyle({ 'family': '"Times New Roman", Times, serif', 'weight': null, // Use default font-weight 'size': 16 @@ -33,9 +31,9 @@ Blockly.Themes.TestFont.setFontStyle({ * @type {!Object} * @private */ -Blockly.Themes.testThemes_ = { - 'Test Hats': Blockly.Themes.TestHats, - 'Test Font': Blockly.Themes.TestFont +const testThemes_ = { + 'Test Hats': TestHatsTheme, + 'Test Font': TestFontTheme }; /** @@ -45,7 +43,7 @@ Blockly.Themes.testThemes_ = { * @package */ function getTestTheme(value) { - return Blockly.Themes.testThemes_[value]; + return testThemes_[value]; } /** @@ -54,7 +52,7 @@ function getTestTheme(value) { */ function populateTestThemes() { var themeChanger = document.getElementById('themeChanger'); - var keys = Object.keys(Blockly.Themes.testThemes_); + var keys = Object.keys(testThemes_); for (var i = 0, key; (key = keys[i]); i++) { var option = document.createElement('option'); option.setAttribute('value', key); From 2c15d002ababcba7f34c526c05f231735e3e0169 Mon Sep 17 00:00:00 2001 From: Maribeth Bottorff Date: Thu, 24 Mar 2022 15:05:38 -0700 Subject: [PATCH 125/128] fix: export Blockly.Names.NameType and Blockly.Input.Align correctly (#6030) * fix: make NameType available externally * fix: export Input.Align --- core/input.js | 27 +++++++++++++++------------ core/names.js | 4 ++++ 2 files changed, 19 insertions(+), 12 deletions(-) diff --git a/core/input.js b/core/input.js index 256f3ab8e..4427a5204 100644 --- a/core/input.js +++ b/core/input.js @@ -31,18 +31,6 @@ const {inputTypes} = goog.require('Blockly.inputTypes'); goog.require('Blockly.FieldLabel'); -/** - * Enum for alignment of inputs. - * @enum {number} - * @alias Blockly.Input.Align - */ -const Align = { - LEFT: -1, - CENTRE: 0, - RIGHT: 1, -}; -exports.Align = Align; - /** * Class for an input with an optional field. * @alias Blockly.Input @@ -329,4 +317,19 @@ class Input { } } +/** + * Enum for alignment of inputs. + * @enum {number} + * @alias Blockly.Input.Align + */ +const Align = { + LEFT: -1, + CENTRE: 0, + RIGHT: 1, +}; +exports.Align = Align; + +// Add Align to Input so that `Blockly.Input.Align` is publicly accessible. +Input.Align = Align; + exports.Input = Input; diff --git a/core/names.js b/core/names.js index afe4c7292..8424a417b 100644 --- a/core/names.js +++ b/core/names.js @@ -277,6 +277,10 @@ const NameType = { }; exports.NameType = NameType; +// We have to export NameType here so that it is accessible under the old name +// `Blockly.Names.NameType` +Names.NameType = NameType; + /** * Constant to separate developer variable names from user-defined variable * names when running generators. From ca6e590101d511a8d98a5c5438af32ff6749e020 Mon Sep 17 00:00:00 2001 From: Aaron Dodson Date: Fri, 25 Mar 2022 08:27:08 -0700 Subject: [PATCH 126/128] fix: Fix downloading screenshots on the playground. (#6025) * fix: Fix downloading screenshots on the playground. * fix: Resolve lint warning about unused variable. --- tests/playground.html | 3 ++- tests/playgrounds/advanced_playground.html | 2 +- tests/playgrounds/screenshot.js | 2 +- 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/tests/playground.html b/tests/playground.html index 44255cb2e..7a555392f 100644 --- a/tests/playground.html +++ b/tests/playground.html @@ -7,6 +7,7 @@ +